diff --git a/DEPS b/DEPS index 94177eff4..3f8303b 100644 --- a/DEPS +++ b/DEPS
@@ -251,7 +251,7 @@ # luci-go CIPD package version. # Make sure the revision is uploaded by infra-packagers builder. # https://ci.chromium.org/p/infra-internal/g/infra-packagers/console - 'luci_go': 'git_revision:9b6501cd8b61afbb92c76207dfd2594606a4b4d1', + 'luci_go': 'git_revision:c893d7a542f324fe7c1a63c83e57ccea23631ffe', # This can be overridden, e.g. with custom_vars, to build clang from HEAD # instead of downloading the prebuilt pinned revision. @@ -308,23 +308,23 @@ # 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': 'a454bfcdca9d2e023965d1d9f02d4c17b894caaf', + 'skia_revision': 'f3f2e87572c1540efcb5fcdc0577a5ac1d4a83d7', # 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': '5f70181253a9031d1b4b8f94c79631f53f7caede', + 'v8_revision': '81548eeb2d168bf576ee74db3ab6c18cf378b431', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling ANGLE # and whatever else without interference from each other. - 'angle_revision': 'c19ec9481a70f42fea14c908361460ac0f4a3557', + 'angle_revision': '2b3c8aaf1a9326592b4b931784ef9fb31eca5551', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling SwiftShader # and whatever else without interference from each other. - 'swiftshader_revision': '782eb8546f758d66ec3e52e75517bd257065195b', + 'swiftshader_revision': '8e7ad8bdf906f6e2706b4797728340d582f60c46', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling PDFium # and whatever else without interference from each other. - 'pdfium_revision': '61f2c1da3e14411fc48764cc6d6c41a4c2859490', + 'pdfium_revision': 'a88c2be5a04367a7d56c389a038ffb5c12872c47', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling BoringSSL # and whatever else without interference from each other. @@ -335,7 +335,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling Fuchsia sdk # and whatever else without interference from each other. - 'fuchsia_version': 'version:9.20221005.2.1', + 'fuchsia_version': 'version:9.20221006.5.1', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling google-toolbox-for-mac # and whatever else without interference from each other. @@ -379,7 +379,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': '0c709a95edc3ce3dd640c4b9925e97c6b4596488', + 'catapult_revision': '6cc3b1e4ab164b9b31e1b86a8ec2dc2e1e2f8b98', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling libFuzzer # and whatever else without interference from each other. @@ -387,7 +387,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': 'd2100753f35a46d015277cd82325173d6f8eb3dd', + 'devtools_frontend_revision': 'e24bc6f45caddd883af3be6ac5de0d8c53e9e4eb', # 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. @@ -423,11 +423,11 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. - 'dawn_revision': 'd71caf7f58a47325977390326bfe7064d9289dbe', + 'dawn_revision': '39e4d0df3f8033ca1ad63803b55eccda3b9de7d8', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. - 'quiche_revision': '3a819a7a4f5d34eacc5797864c335de65618b118', + 'quiche_revision': 'bae24053c94bd1ae6b264bb55a583037b5eccc5d', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling ios_webkit # and whatever else without interference from each other. @@ -443,7 +443,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling libavif # and whatever else without interference from each other. - 'libavif_revision': 'cd0bb358f83d01867f0fa53079470043618c9af5', + 'libavif_revision': '7aaada8e3e301da23342dde9be67eb505e918843', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling nearby # and whatever else without interference from each other. @@ -459,6 +459,10 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. + 'cros_components_revision': 'a0979aacb8744f42ed7abd966a6b0ac7578a73e9', + # Three lines of non-changing comments so that + # the commit queue can handle CLs rolling feed + # and whatever else without interference from each other. 'resultdb_version': 'git_revision:6cc18e2763e180929d70c786b419c1f8e6bcc66c', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed @@ -823,7 +827,7 @@ }, 'src/ios/third_party/edo/src': { - 'url': Var('chromium_git') + '/external/github.com/google/eDistantObject.git' + '@' + 'e571ad687b91d53f0fc38be9a87d3d5b3873dca7', + 'url': Var('chromium_git') + '/external/github.com/google/eDistantObject.git' + '@' + '904c99f0237920066a507129b0266080db3fda11', 'condition': 'checkout_ios', }, @@ -993,7 +997,7 @@ 'packages': [ { 'package': 'chromium/third_party/androidx', - 'version': '0yLHxVsHQ9H_tPonOZy5XMCLMOvQ1j-pcw7UypcoL8MC', + 'version': 'atg_0ThGWvR5eLea-pNZ9TXpiJFZXXui8vMSiVekrroC', }, ], 'condition': 'checkout_android', @@ -1070,7 +1074,7 @@ 'packages': [ { 'package': 'chromium/third_party/android_build_tools/manifest_merger', - 'version': '0cYQOUjN8K9fAtfcm6Vwi30XcO6mPJU_5v4-pUkBg0sC', + 'version': 'bUREd_PkCqlp2ww6zmyOLGf0jhqgbnf6GT4V1xkAZ10C', }, ], 'condition': 'checkout_android', @@ -1236,13 +1240,13 @@ }, 'src/third_party/depot_tools': - Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + '99c8282eb5b28dc33a352b3f17755d1891bfeec2', + Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + 'c9127e51dcc18a2c91968af10ba6303cf9a5abd4', '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' + '@' + '4c0b2dda2feb3b7f034c7de98143fdc50666bd51', + 'url': 'https://chrome-internal.googlesource.com/devtools/devtools-internal.git' + '@' + 'b8bdc32e47e5f7f72c0dad0b0f52f4e0a0f12117', 'condition': 'checkout_src_internal', }, @@ -1471,6 +1475,9 @@ 'src/third_party/ukey2/src': Var('chromium_git') + '/external/github.com/google/ukey2.git' + '@' + Var('ukey2_revision'), + 'src/third_party/cros_components': + Var('chromium_git') + '/external/google3/cros_components.git' + '@' + Var('cros_components_revision'), + # Userspace interface to kernel DRM services. 'src/third_party/libdrm/src': { 'url': Var('chromium_git') + '/chromiumos/third_party/libdrm.git' + '@' + '56f81e6776c1c100c3f627b2c1feb9dcae2aad3c', @@ -1654,7 +1661,7 @@ }, 'src/third_party/perfetto': - Var('android_git') + '/platform/external/perfetto.git' + '@' + 'f6f851f265bdd96022f4c4af1bfd4fae6385db5e', + Var('android_git') + '/platform/external/perfetto.git' + '@' + '6f9968b593b7f806a59655e7fa1f3682b5c2f5aa', 'src/third_party/perl': { 'url': Var('chromium_git') + '/chromium/deps/perl.git' + '@' + '6f3e5028eb65d0b4c5fdd792106ac4c84eee1eb3', @@ -1708,7 +1715,7 @@ 'packages': [ { 'package': 'chromium/third_party/r8', - 'version': 'IgKfK01VX-GA1mjxpHqq-7kL9VDb5qlXZnSW0Jtl6cAC', + 'version': 'eY1JQSP1ngqJAq0m54TQZX2a2XY51h0EsqqZJZwmn-MC', }, ], 'condition': 'checkout_android', @@ -1799,7 +1806,7 @@ 'dep_type': 'cipd', }, - 'src/third_party/vulkan-deps': '{chromium_git}/vulkan-deps@8c5393022c35f41c10f17be56bf33503faa66b9f', + 'src/third_party/vulkan-deps': '{chromium_git}/vulkan-deps@1172dba338881bb88803651e0f05885d9987335a', 'src/third_party/vulkan_memory_allocator': Var('chromium_git') + '/external/github.com/GPUOpen-LibrariesAndSDKs/VulkanMemoryAllocator.git' + '@' + 'ebe84bec02c041d28f902da0214bf442743fc907', @@ -1839,7 +1846,7 @@ Var('chromium_git') + '/external/github.com/gpuweb/cts.git' + '@' + 'f0dacbbf2cde8826f3c0fea86f60a7f639af5e03', 'src/third_party/webrtc': - Var('webrtc_git') + '/src.git' + '@' + '767898c0481d510ffdc55ac3ae39f3f448d09b41', + Var('webrtc_git') + '/src.git' + '@' + 'b15faaa2640d137d6341b09fd3670813e3aaf99e', # 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. @@ -1866,7 +1873,7 @@ 'packages': [ { 'package': 'skia/tools/goldctl/linux-amd64', - 'version': 'vvnmipanCNz0xZWcZxMxqF8Dm17k5IzoIIuSAxayctEC', + 'version': 'pnprsw4_qiLaFOB3waX424Uaz5zX3MSh6Iz5A3OwpR8C', }, ], 'dep_type': 'cipd', @@ -1876,7 +1883,7 @@ 'packages': [ { 'package': 'skia/tools/goldctl/windows-amd64', - 'version': 'mMto2aiE2BsVX1RoY_FYEPJ7ph496TgwksEHvbcwQJsC', + 'version': 'wEIMZs5miJMkTVDLFMkQjh4dJWrLB4k8VQDU4aUPSwYC', }, ], 'dep_type': 'cipd', @@ -1887,7 +1894,7 @@ 'packages': [ { 'package': 'skia/tools/goldctl/mac-amd64', - 'version': 'IvvIkJXPEctNxoRBIUUUuHSJN0vsFTR9XgTza8JoCngC', + 'version': 'qMTthZODlW9LCvkQX3upPhaL6t3VwQcYrs9cDYwP75oC', }, ], 'dep_type': 'cipd', @@ -1898,7 +1905,7 @@ 'packages': [ { 'package': 'skia/tools/goldctl/mac-arm64', - 'version': 'PobY7qdsILEzxp0nSF8_mIJNJpPQiFs2mtNqOXLZlAYC', + 'version': '3NLkdA7AHyUKOEdv0Dc16lTUNJN9FjFkDIzVXthPsDkC', }, ], 'dep_type': 'cipd', @@ -1909,7 +1916,7 @@ Var('chromium_git') + '/v8/v8.git' + '@' + Var('v8_revision'), 'src-internal': { - 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@b0e9a406ec24c11187a58385e070b8c928890578', + 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@655d080a8cb39b75d297f41a6358f7eaccbdaa0a', 'condition': 'checkout_src_internal', }, @@ -1961,7 +1968,7 @@ 'packages': [ { 'package': 'chromeos_internal/apps/projector_app/app', - 'version': 'faFro1J-dIJrVViFlAE9jnKYFZowDuVnIxoVib5-71wC', + 'version': '607zEl7pDlNSc7SJfDva-RdOPPrDWN67_XANjw-VutcC', }, ], 'condition': 'checkout_chromeos and checkout_src_internal',
diff --git a/android_webview/browser/aw_autofill_client.cc b/android_webview/browser/aw_autofill_client.cc index 996e201..858f7828 100644 --- a/android_webview/browser/aw_autofill_client.cc +++ b/android_webview/browser/aw_autofill_client.cc
@@ -61,7 +61,7 @@ } PrefService* AwAutofillClient::GetPrefs() { - return const_cast<PrefService*>(base::as_const(*this).GetPrefs()); + return const_cast<PrefService*>(std::as_const(*this).GetPrefs()); } const PrefService* AwAutofillClient::GetPrefs() const {
diff --git a/ash/BUILD.gn b/ash/BUILD.gn index 37ba5b6c..7f338d5 100644 --- a/ash/BUILD.gn +++ b/ash/BUILD.gn
@@ -1031,6 +1031,8 @@ "style/style_util.h", "style/style_viewer/system_ui_components_grid_view.cc", "style/style_viewer/system_ui_components_grid_view.h", + "style/style_viewer/system_ui_components_style_viewer_view.cc", + "style/style_viewer/system_ui_components_style_viewer_view.h", "style/system_shadow.cc", "style/system_shadow.h", "style/system_shadow_on_nine_patch_layer.cc", @@ -2330,9 +2332,6 @@ "//ash/quick_pair/ui", "//ash/services/multidevice_setup/public/mojom", "//ash/services/nearby/public/cpp", - "//ash/services/quick_pair", - "//ash/services/quick_pair/public/cpp", - "//ash/services/quick_pair/public/mojom", "//ash/services/recording", "//ash/services/recording/public/mojom", "//ash/style", @@ -2378,6 +2377,9 @@ "//chromeos/ash/services/hotspot_config/public/mojom", "//chromeos/ash/services/libassistant/public/cpp:structs", "//chromeos/ash/services/libassistant/public/mojom", + "//chromeos/ash/services/quick_pair", + "//chromeos/ash/services/quick_pair/public/cpp", + "//chromeos/ash/services/quick_pair/public/mojom", "//chromeos/components/quick_answers/public/cpp:prefs", "//chromeos/components/sensors:buildflags", "//chromeos/components/sensors:sensors", @@ -3481,6 +3483,8 @@ "system/tray/system_nudge_label.h", "test/ash_pixel_diff_test_helper.cc", "test/ash_pixel_diff_test_helper.h", + "test/ash_pixel_diff_util.cc", + "test/ash_pixel_diff_util.h", "utility/haptics_tracking_test_input_controller.cc", "utility/haptics_tracking_test_input_controller.h",
diff --git a/ash/app_list/views/app_list_view_pixeltest.cc b/ash/app_list/views/app_list_view_pixeltest.cc index aed35c0..bd3eba6 100644 --- a/ash/app_list/views/app_list_view_pixeltest.cc +++ b/ash/app_list/views/app_list_view_pixeltest.cc
@@ -4,8 +4,10 @@ #include "ash/app_list/test/app_list_test_helper.h" #include "ash/app_list/views/app_list_bubble_apps_page.h" +#include "ash/app_list/views/app_list_bubble_view.h" #include "ash/app_list/views/search_box_view.h" -#include "ash/shell.h" +#include "ash/shelf/shelf.h" +#include "ash/shelf/shelf_navigation_widget.h" #include "ash/test/ash_pixel_diff_test_helper.h" #include "ash/test/ash_pixel_test_init_params.h" #include "ash/test/ash_test_base.h" @@ -51,8 +53,10 @@ /*num_apps=*/2, AppListTestHelper::IconColorType::kAlternativeColor, /*set_name=*/true); ShowAppListAndHideCursor(); - EXPECT_TRUE(GetPixelDiffer()->ComparePrimaryFullScreen( - GetParam() ? "bubble_launcher_basics_rtl" : "bubble_launcher_basics")); + EXPECT_TRUE(GetPixelDiffer()->CompareUiComponentsOnPrimaryScreen( + GetParam() ? "bubble_launcher_basics_rtl" : "bubble_launcher_basics", + GetAppListTestHelper()->GetBubbleView(), + GetPrimaryShelf()->navigation_widget())); } // Verifies that the app list gradient zones work as expected. @@ -69,9 +73,11 @@ scroll_view->ScrollToPosition(scroll_view->vertical_scroll_bar(), /*position=*/20); - EXPECT_TRUE(GetPixelDiffer()->ComparePrimaryFullScreen( + EXPECT_TRUE(GetPixelDiffer()->CompareUiComponentsOnPrimaryScreen( GetParam() ? "bubble_launcher_gradient_zone_rtl" - : "bubble_launcher_gradient_zone")); + : "bubble_launcher_gradient_zone", + GetAppListTestHelper()->GetBubbleView(), + GetPrimaryShelf()->navigation_widget())); } } // namespace ash
diff --git a/ash/app_list/views/app_list_view_unittest.cc b/ash/app_list/views/app_list_view_unittest.cc index e042ee8..adfe1f8 100644 --- a/ash/app_list/views/app_list_view_unittest.cc +++ b/ash/app_list/views/app_list_view_unittest.cc
@@ -74,9 +74,6 @@ constexpr int kInitialItems = 34; -constexpr int kMaxItemsPerFolderPage = AppListFolderView::kMaxFolderColumns * - AppListFolderView::kMaxPagedFolderRows; - // Constants used for for testing app list layout in fullscreen state: // The app list grid vertical inset - the height of the view fadeout area. constexpr int kGridVerticalInset = 16; @@ -1069,53 +1066,6 @@ TestFocusTraversal(backward_view_list, ui::VKEY_UP, false); } -// Tests the vertical focus traversal in FULLSCREEN_ALL_APPS state in the second -// page within folder. ProductivityLauncher does not use pages for folders. -TEST_F(AppListViewPeekingFocusTest, - VerticalFocusTraversalInSecondPageOfFolder) { - Show(); - - // Open the folder. - folder_item_view()->RequestFocus(); - SimulateKeyPress(ui::VKEY_RETURN, false); - EXPECT_TRUE(contents_view()->apps_container_view()->IsInFolderView()); - - // Select the second page. - ASSERT_FALSE(features::IsProductivityLauncherEnabled()); - static_cast<PagedAppsGridView*>(app_list_folder_view()->items_grid_view()) - ->pagination_model() - ->SelectPage(1, false /* animate */); - - std::vector<views::View*> forward_view_list; - const views::ViewModelT<AppListItemView>* view_model = - app_list_folder_view()->items_grid_view()->view_model(); - for (size_t i = kMaxItemsPerFolderPage; i < view_model->view_size(); - i += app_list_folder_view()->items_grid_view()->cols()) { - forward_view_list.push_back(view_model->view_at(i)); - } - forward_view_list.push_back( - app_list_folder_view()->folder_header_view()->GetFolderNameViewForTest()); - forward_view_list.push_back(search_box_view()->search_box()); - forward_view_list.push_back(view_model->view_at(0)); - - // Test traversal triggered by down. - TestFocusTraversal(forward_view_list, ui::VKEY_DOWN, false); - - std::vector<views::View*> backward_view_list; - backward_view_list.push_back(view_model->view_at(0)); - backward_view_list.push_back(search_box_view()->search_box()); - backward_view_list.push_back( - app_list_folder_view()->folder_header_view()->GetFolderNameViewForTest()); - for (size_t i = view_model->view_size() - 1; i < view_model->view_size(); - i -= app_list_folder_view()->items_grid_view()->cols()) { - backward_view_list.push_back(view_model->view_at(i)); - } - backward_view_list.push_back(search_box_view()->search_box()); - - // Test traversal triggered by up. - TestFocusTraversal(backward_view_list, ui::VKEY_UP, false); -} - // Tests that focus changes update the search box text. TEST_F(AppListViewFocusTest, SearchBoxTextUpdatesOnResultFocus) { Show(); @@ -2790,30 +2740,5 @@ expected_updated_item_size, /*has_recent_apps=*/true); } -// Tests that page switching in folder doesn't record AppListPageSwitcherSource -// metric. ProductivityLauncher does not use pages in folders. -TEST_F(AppListViewPeekingFocusTest, PageSwitchingNotRecordingMetric) { - base::HistogramTester histogram_tester; - Show(); - - histogram_tester.ExpectTotalCount("Apps.AppListPageSwitcherSource", 0); - // Open the folder. - folder_item_view()->RequestFocus(); - SimulateKeyPress(ui::VKEY_RETURN, false); - ASSERT_TRUE(contents_view()->apps_container_view()->IsInFolderView()); - - // Create a fling to the left so the folder view changes page. - constexpr float kFlingVelocityForChangingPage = 850.0f; - gfx::Point location = app_list_folder_view()->bounds().CenterPoint(); - ui::GestureEventDetails details = ui::GestureEventDetails( - ui::ET_SCROLL_FLING_START, -kFlingVelocityForChangingPage, 0); - ui::GestureEvent event = ui::GestureEvent( - location.x(), location.y(), ui::EF_NONE, base::TimeTicks::Now(), details); - app_list_folder_view()->items_grid_view()->OnGestureEvent(&event); - - ASSERT_TRUE(event.handled()); - histogram_tester.ExpectTotalCount("Apps.AppListPageSwitcherSource", 0); -} - } // namespace } // namespace ash
diff --git a/ash/app_list/views/apps_grid_view_unittest.cc b/ash/app_list/views/apps_grid_view_unittest.cc index 68e127af..edd24e6 100644 --- a/ash/app_list/views/apps_grid_view_unittest.cc +++ b/ash/app_list/views/apps_grid_view_unittest.cc
@@ -85,10 +85,6 @@ namespace { constexpr int kNumOfSuggestedApps = 3; - -constexpr size_t kMaxItemsPerFolderPage = - AppListFolderView::kMaxFolderColumns * - AppListFolderView::kMaxPagedFolderRows; constexpr size_t kMaxItemsInFolder = 48; class ShelfItemFactoryFake : public ShelfModel::ShelfItemFactory { @@ -1182,47 +1178,6 @@ one_row_folder_view.size()); } -TEST_F(AppsGridViewTest, AddItemsToFolderShouldUpdateBounds) { - // Populate two folders with different number of apps. - AppListFolderItem* folder_1 = model_->CreateAndPopulateFolderWithApps(2); - model_->CreateAndPopulateFolderWithApps(4); - - // Record the bounds of the folder view with 4 items in it. - AppsGridView* items_grid_view = app_list_folder_view()->items_grid_view(); - test_api_->PressItemAt(1); - EXPECT_TRUE(GetAppListTestHelper()->IsInFolderView()); - gfx::Rect two_rows_folder_view = items_grid_view->GetBoundsInScreen(); - app_list_folder_view()->CloseFolderPage(); - - // Record the bounds of the folder view with 2 items in it and keep the folder - // view open for further testing. - test_api_->PressItemAt(0); - EXPECT_TRUE(GetAppListTestHelper()->IsInFolderView()); - gfx::Rect one_row_folder_view = items_grid_view->GetBoundsInScreen(); - EXPECT_NE(one_row_folder_view.size(), two_rows_folder_view.size()); - - // Add an item to the folder so that there are two rows in the folder view. - model_->AddItemToFolder(model_->CreateItem("Extra 1"), folder_1->id()); - EXPECT_TRUE(GetAppListTestHelper()->IsInFolderView()); - items_grid_view->GetWidget()->LayoutRootViewIfNecessary(); - EXPECT_EQ(items_grid_view->GetBoundsInScreen().size(), - two_rows_folder_view.size()); - app_list_folder_view()->CloseFolderPage(); - - // Create a folder with a full page of apps. Add an item to the folder should - // not change the size of the folder view. - AppListFolderItem* folder_full = - model_->CreateAndPopulateFolderWithApps(kMaxItemsPerFolderPage); - test_api_->PressItemAt(2); - EXPECT_TRUE(GetAppListTestHelper()->IsInFolderView()); - gfx::Rect full_folder_view = items_grid_view->GetBoundsInScreen(); - - model_->AddItemToFolder(model_->CreateItem("Extra 2"), folder_full->id()); - EXPECT_EQ(items_grid_view->GetBoundsInScreen().size(), - full_folder_view.size()); - app_list_folder_view()->CloseFolderPage(); -} - TEST_P(AppsGridViewClamshellAndTabletTest, AddItemsToFolderShouldUpdateBounds) { // Populate two folders with different number of apps. AppListFolderItem* folder_1 = model_->CreateAndPopulateFolderWithApps(2); @@ -1250,10 +1205,10 @@ two_rows_folder_view.size()); app_list_folder_view()->CloseFolderPage(); - // Create a folder with a full page of apps. Add an item to the folder should + // Create and add an almost full folder. Add an item to the folder should // not change the size of the folder view. AppListFolderItem* folder_full = - model_->CreateAndPopulateFolderWithApps(kMaxItemsPerFolderPage); + model_->CreateAndPopulateFolderWithApps(kMaxItemsInFolder - 1); test_api_->PressItemAt(2); EXPECT_TRUE(GetAppListTestHelper()->IsInFolderView()); gfx::Rect full_folder_view = items_grid_view->GetBoundsInScreen(); @@ -1265,7 +1220,7 @@ } TEST_P(AppsGridViewTabletTest, ScrollDownShouldNotExitFolder) { - const size_t kTotalItems = kMaxItemsPerFolderPage; + const size_t kTotalItems = kMaxItemsInFolder; model_->CreateAndPopulateFolderWithApps(kTotalItems); EXPECT_EQ(1u, model_->top_level_item_list()->item_count()); EXPECT_EQ(AppListFolderItem::kItemType, @@ -1659,9 +1614,9 @@ EXPECT_EQ(1, GetHapticTickEventsCount()); } -TEST_F(AppsGridViewTest, CheckFolderWithMultiplePagesContents) { +TEST_F(AppsGridViewTest, CheckFolderWithMultipleItemsContents) { // Creates a folder item. - const size_t kTotalItems = kMaxItemsPerFolderPage; + const size_t kTotalItems = kMaxItemsInFolder; AppListFolderItem* folder_item = model_->CreateAndPopulateFolderWithApps(kTotalItems); @@ -1742,7 +1697,7 @@ TEST_P(AppsGridViewDragTest, MouseDragItemOutOfFolder) { // Creates a folder item. - const size_t kTotalItems = kMaxItemsPerFolderPage; + const size_t kTotalItems = kMaxItemsInFolder; AppListFolderItem* folder_item = model_->CreateAndPopulateFolderWithApps(kTotalItems); test_api_->Update(); @@ -3752,7 +3707,7 @@ } TEST_P(AppsGridViewDragTest, DragAndPinNotInitiallyVisibleFolderItemToShelf) { - model_->CreateAndPopulateFolderWithApps(2 * kMaxItemsPerFolderPage); + model_->CreateAndPopulateFolderWithApps(kMaxItemsInFolder); UpdateLayout(); // Open the folder. @@ -4174,7 +4129,7 @@ TEST_F(AppsGridViewTest, PopulateAppsGridWithAFolder) { // Creates a folder item. - const size_t kTotalItems = kMaxItemsPerFolderPage; + const size_t kTotalItems = kMaxItemsInFolder; AppListFolderItem* folder_item = model_->CreateAndPopulateFolderWithApps(kTotalItems); @@ -4187,7 +4142,8 @@ model_->top_level_item_list()->item_at(0)->GetItemType()); EXPECT_EQ(kTotalItems, folder_item->ChildItemCount()); EXPECT_EQ(4, folder_apps_grid_view()->cols()); - EXPECT_EQ(16u, AppsGridViewTestApi(folder_apps_grid_view()).TilesPerPage(0)); + EXPECT_EQ(kTotalItems, + AppsGridViewTestApi(folder_apps_grid_view()).TilesPerPage(0)); EXPECT_EQ(1, GetTotalPages(folder_apps_grid_view())); EXPECT_EQ(0, GetSelectedPage(folder_apps_grid_view())); EXPECT_TRUE(folder_apps_grid_view()->IsInFolder()); @@ -4725,7 +4681,7 @@ ASSERT_TRUE(paged_apps_grid_view_); // Creates a folder item and open it. - const size_t kTotalItems = kMaxItemsPerFolderPage; + const size_t kTotalItems = kMaxItemsInFolder; model_->CreateAndPopulateFolderWithApps(kTotalItems); test_api_->Update(); test_api_->PressItemAt(0);
diff --git a/ash/ash_strings.grd b/ash/ash_strings.grd index 9bced0c..48b8236 100644 --- a/ash/ash_strings.grd +++ b/ash/ash_strings.grd
@@ -5063,6 +5063,9 @@ <message name="IDS_ASH_STATUS_TRAY_SHELF_PARTY_OFF_SUBLABEL" desc="The sub label text shown under the tray menu button when Shelf Party mode is off."> Off </message> + <message name="IDS_ASH_SHELF_ALL_PINNED_ITEMS_ARE_PARTYING" desc="The message that is displayed on the shelf when all pinned items are in Shelf Party (and therefore not shown on the shelf)."> + All pinned items are partying + </message> <!-- Firmware UI notifications --> <message name="IDS_ASH_FIRMWARE_UPDATE_NOTIFICATION_UPDATE_AVAILABLE_TITLE" desc="Notification title to indicate to users that firmware updates are available.">
diff --git a/ash/ash_strings_grd/IDS_ASH_SHELF_ALL_PINNED_ITEMS_ARE_PARTYING.png.sha1 b/ash/ash_strings_grd/IDS_ASH_SHELF_ALL_PINNED_ITEMS_ARE_PARTYING.png.sha1 new file mode 100644 index 0000000..9a9ef37 --- /dev/null +++ b/ash/ash_strings_grd/IDS_ASH_SHELF_ALL_PINNED_ITEMS_ARE_PARTYING.png.sha1
@@ -0,0 +1 @@ +14fa5f6191938b90cbfc76dda3506d6eb3efc06b \ No newline at end of file
diff --git a/ash/components/BUILD.gn b/ash/components/BUILD.gn index 605e6d4..cfa0869 100644 --- a/ash/components/BUILD.gn +++ b/ash/components/BUILD.gn
@@ -27,7 +27,6 @@ "//ash/components/peripheral_notification:unit_tests", "//ash/components/phonehub:unit_tests", "//ash/components/tether:unit_tests", - "//ash/components/tpm:unit_tests", "//ash/components/trial_group:unit_tests", "//ash/strings", "//base/test:test_support",
diff --git a/ash/constants/ash_features.cc b/ash/constants/ash_features.cc index 6db502ba1..c9a7d29 100644 --- a/ash/constants/ash_features.cc +++ b/ash/constants/ash_features.cc
@@ -2111,7 +2111,7 @@ // Guest OS apps. BASE_FEATURE(kArcAndGuestOsFileTasksUseAppService, "ArcAndGuestOsFileTasksUseAppService", - base::FEATURE_DISABLED_BY_DEFAULT); + base::FEATURE_ENABLED_BY_DEFAULT); ////////////////////////////////////////////////////////////////////////////////
diff --git a/ash/quick_pair/DEPS b/ash/quick_pair/DEPS index 49713fb..a31f7ddc 100644 --- a/ash/quick_pair/DEPS +++ b/ash/quick_pair/DEPS
@@ -1,4 +1,5 @@ include_rules = [ + "+chromeos/ash/services/quick_pair", "+components/image_fetcher", "+components/signin/public/identity_manager", "+components/signin/public/base",
diff --git a/ash/quick_pair/common/BUILD.gn b/ash/quick_pair/common/BUILD.gn index 4347790..4ea07d9 100644 --- a/ash/quick_pair/common/BUILD.gn +++ b/ash/quick_pair/common/BUILD.gn
@@ -41,9 +41,9 @@ deps = [ "//ash/constants:constants", - "//ash/services/quick_pair/public/mojom", "//base", "//chromeos/ash/components/feature_usage", + "//chromeos/ash/services/quick_pair/public/mojom", "//components/prefs", "//device/bluetooth", "//device/bluetooth/public/cpp", @@ -65,8 +65,8 @@ deps = [ ":common", - "//ash/services/quick_pair/public/mojom", "//base/test:test_support", + "//chromeos/ash/services/quick_pair/public/mojom", "//components/image_fetcher/core", "//services/network/public/cpp", "//testing/gtest",
diff --git a/ash/quick_pair/common/quick_pair_browser_delegate.h b/ash/quick_pair/common/quick_pair_browser_delegate.h index 86a41b9..e8b1b60a 100644 --- a/ash/quick_pair/common/quick_pair_browser_delegate.h +++ b/ash/quick_pair/common/quick_pair_browser_delegate.h
@@ -5,9 +5,9 @@ #ifndef ASH_QUICK_PAIR_COMMON_QUICK_PAIR_BROWSER_DELEGATE_H_ #define ASH_QUICK_PAIR_COMMON_QUICK_PAIR_BROWSER_DELEGATE_H_ -#include "ash/services/quick_pair/public/mojom/quick_pair_service.mojom-forward.h" #include "base/component_export.h" #include "base/memory/scoped_refptr.h" +#include "chromeos/ash/services/quick_pair/public/mojom/quick_pair_service.mojom-forward.h" #include "mojo/public/cpp/bindings/pending_receiver.h" class PrefService;
diff --git a/ash/quick_pair/fast_pair_handshake/BUILD.gn b/ash/quick_pair/fast_pair_handshake/BUILD.gn index dee2340c..354ede6 100644 --- a/ash/quick_pair/fast_pair_handshake/BUILD.gn +++ b/ash/quick_pair/fast_pair_handshake/BUILD.gn
@@ -33,9 +33,9 @@ "//ash/quick_pair/common", "//ash/quick_pair/proto:fastpair_proto", "//ash/quick_pair/repository", - "//ash/services/quick_pair", - "//ash/services/quick_pair/public/cpp", "//base", + "//chromeos/ash/services/quick_pair", + "//chromeos/ash/services/quick_pair/public/cpp", "//crypto:crypto", "//device/bluetooth", "//third_party/protobuf:protobuf_lite", @@ -60,9 +60,9 @@ deps = [ "//ash/quick_pair/common", - "//ash/services/quick_pair/public/cpp", "//base", "//base/test:test_support", + "//chromeos/ash/services/quick_pair/public/cpp", "//device/bluetooth", "//testing/gtest", ] @@ -83,11 +83,11 @@ ":test_support", "//ash/quick_pair/common", "//ash/quick_pair/repository:test_support", - "//ash/services/quick_pair", - "//ash/services/quick_pair:test_support", - "//ash/services/quick_pair/public/cpp", "//base", "//base/test:test_support", + "//chromeos/ash/services/quick_pair", + "//chromeos/ash/services/quick_pair:test_support", + "//chromeos/ash/services/quick_pair/public/cpp", "//device/bluetooth", "//device/bluetooth:mocks", "//testing/gtest", @@ -100,7 +100,7 @@ ":fast_pair_handshake", "//ash:test_support", "//ash/quick_pair/common", - "//ash/services/quick_pair", "//base", + "//chromeos/ash/services/quick_pair", ] }
diff --git a/ash/quick_pair/fast_pair_handshake/fast_pair_data_encryptor.h b/ash/quick_pair/fast_pair_handshake/fast_pair_data_encryptor.h index 3a26c7074..a7a1392 100644 --- a/ash/quick_pair/fast_pair_handshake/fast_pair_data_encryptor.h +++ b/ash/quick_pair/fast_pair_handshake/fast_pair_data_encryptor.h
@@ -10,9 +10,9 @@ #include <array> -#include "ash/services/quick_pair/public/cpp/decrypted_passkey.h" -#include "ash/services/quick_pair/public/cpp/decrypted_response.h" #include "base/callback.h" +#include "chromeos/ash/services/quick_pair/public/cpp/decrypted_passkey.h" +#include "chromeos/ash/services/quick_pair/public/cpp/decrypted_response.h" #include "third_party/abseil-cpp/absl/types/optional.h" inline constexpr int kBlockSizeBytes = 16;
diff --git a/ash/quick_pair/fast_pair_handshake/fast_pair_data_encryptor_impl.cc b/ash/quick_pair/fast_pair_handshake/fast_pair_data_encryptor_impl.cc index 105e49ab..c1d886c 100644 --- a/ash/quick_pair/fast_pair_handshake/fast_pair_data_encryptor_impl.cc +++ b/ash/quick_pair/fast_pair_handshake/fast_pair_data_encryptor_impl.cc
@@ -14,10 +14,10 @@ #include "ash/quick_pair/proto/fastpair.pb.h" #include "ash/quick_pair/repository/fast_pair/device_metadata.h" #include "ash/quick_pair/repository/fast_pair_repository.h" -#include "ash/services/quick_pair/quick_pair_process.h" #include "base/check.h" #include "base/memory/ptr_util.h" #include "base/notreached.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process.h" namespace ash { namespace quick_pair {
diff --git a/ash/quick_pair/fast_pair_handshake/fast_pair_data_encryptor_impl.h b/ash/quick_pair/fast_pair_handshake/fast_pair_data_encryptor_impl.h index 1dd6739a..7b3d61d1 100644 --- a/ash/quick_pair/fast_pair_handshake/fast_pair_data_encryptor_impl.h +++ b/ash/quick_pair/fast_pair_handshake/fast_pair_data_encryptor_impl.h
@@ -13,9 +13,9 @@ #include "ash/quick_pair/common/device.h" #include "ash/quick_pair/fast_pair_handshake/fast_pair_data_encryptor.h" #include "ash/quick_pair/fast_pair_handshake/fast_pair_key_pair.h" -#include "ash/services/quick_pair/quick_pair_process_manager.h" #include "base/memory/scoped_refptr.h" #include "base/memory/weak_ptr.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process_manager.h" namespace ash { namespace quick_pair {
diff --git a/ash/quick_pair/fast_pair_handshake/fast_pair_data_encryptor_impl_unittest.cc b/ash/quick_pair/fast_pair_handshake/fast_pair_data_encryptor_impl_unittest.cc index 87b05f0..2ae493c 100644 --- a/ash/quick_pair/fast_pair_handshake/fast_pair_data_encryptor_impl_unittest.cc +++ b/ash/quick_pair/fast_pair_handshake/fast_pair_data_encryptor_impl_unittest.cc
@@ -12,11 +12,6 @@ #include "ash/quick_pair/common/protocol.h" #include "ash/quick_pair/fast_pair_handshake/fast_pair_data_encryptor.h" #include "ash/quick_pair/repository/fake_fast_pair_repository.h" -#include "ash/services/quick_pair/fast_pair_data_parser.h" -#include "ash/services/quick_pair/mock_quick_pair_process_manager.h" -#include "ash/services/quick_pair/quick_pair_process.h" -#include "ash/services/quick_pair/quick_pair_process_manager.h" -#include "ash/services/quick_pair/quick_pair_process_manager_impl.h" #include "base/base64.h" #include "base/callback_helpers.h" #include "base/memory/weak_ptr.h" @@ -24,6 +19,11 @@ #include "base/test/bind.h" #include "base/test/gmock_callback_support.h" #include "base/test/task_environment.h" +#include "chromeos/ash/services/quick_pair/fast_pair_data_parser.h" +#include "chromeos/ash/services/quick_pair/mock_quick_pair_process_manager.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process_manager.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process_manager_impl.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/ash/quick_pair/fast_pair_handshake/fast_pair_encryption.cc b/ash/quick_pair/fast_pair_handshake/fast_pair_encryption.cc index de7105c0..53a5abb2 100644 --- a/ash/quick_pair/fast_pair_handshake/fast_pair_encryption.cc +++ b/ash/quick_pair/fast_pair_handshake/fast_pair_encryption.cc
@@ -9,8 +9,8 @@ #include "ash/quick_pair/common/logging.h" #include "ash/quick_pair/fast_pair_handshake/fast_pair_key_pair.h" -#include "ash/services/quick_pair/public/cpp/fast_pair_message_type.h" #include "base/check.h" +#include "chromeos/ash/services/quick_pair/public/cpp/fast_pair_message_type.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/boringssl/src/include/openssl/aes.h" #include "third_party/boringssl/src/include/openssl/base.h"
diff --git a/ash/quick_pair/fast_pair_handshake/fast_pair_encryption_fuzzer.cc b/ash/quick_pair/fast_pair_handshake/fast_pair_encryption_fuzzer.cc index 05ba5f1..07dc8b95 100644 --- a/ash/quick_pair/fast_pair_handshake/fast_pair_encryption_fuzzer.cc +++ b/ash/quick_pair/fast_pair_handshake/fast_pair_encryption_fuzzer.cc
@@ -11,9 +11,9 @@ #include "ash/quick_pair/common/logging.h" #include "ash/quick_pair/fast_pair_handshake/fast_pair_key_pair.h" -#include "ash/services/quick_pair/fast_pair_decryption.h" #include "base/check.h" #include "base/no_destructor.h" +#include "chromeos/ash/services/quick_pair/fast_pair_decryption.h" #include "third_party/boringssl/src/include/openssl/base.h" #include "third_party/boringssl/src/include/openssl/bn.h" #include "third_party/boringssl/src/include/openssl/ec.h"
diff --git a/ash/quick_pair/fast_pair_handshake/fast_pair_handshake_impl.cc b/ash/quick_pair/fast_pair_handshake/fast_pair_handshake_impl.cc index ceb9695..7620aed 100644 --- a/ash/quick_pair/fast_pair_handshake/fast_pair_handshake_impl.cc +++ b/ash/quick_pair/fast_pair_handshake/fast_pair_handshake_impl.cc
@@ -10,8 +10,8 @@ #include "ash/quick_pair/common/protocol.h" #include "ash/quick_pair/fast_pair_handshake/fast_pair_data_encryptor_impl.h" #include "ash/quick_pair/fast_pair_handshake/fast_pair_gatt_service_client_impl.h" -#include "ash/services/quick_pair/public/cpp/decrypted_response.h" #include "base/callback.h" +#include "chromeos/ash/services/quick_pair/public/cpp/decrypted_response.h" #include "device/bluetooth/bluetooth_adapter.h" #include "device/bluetooth/public/cpp/bluetooth_address.h"
diff --git a/ash/quick_pair/fast_pair_handshake/fast_pair_handshake_impl_unittest.cc b/ash/quick_pair/fast_pair_handshake/fast_pair_handshake_impl_unittest.cc index c49a745..6d193d3c 100644 --- a/ash/quick_pair/fast_pair_handshake/fast_pair_handshake_impl_unittest.cc +++ b/ash/quick_pair/fast_pair_handshake/fast_pair_handshake_impl_unittest.cc
@@ -14,13 +14,13 @@ #include "ash/quick_pair/fast_pair_handshake/fast_pair_data_encryptor_impl.h" #include "ash/quick_pair/fast_pair_handshake/fast_pair_gatt_service_client_impl.h" #include "ash/quick_pair/fast_pair_handshake/fast_pair_handshake.h" -#include "ash/services/quick_pair/public/cpp/decrypted_response.h" -#include "ash/services/quick_pair/public/cpp/fast_pair_message_type.h" #include "base/callback_helpers.h" #include "base/memory/scoped_refptr.h" #include "base/test/bind.h" #include "base/test/metrics/histogram_tester.h" #include "base/test/mock_callback.h" +#include "chromeos/ash/services/quick_pair/public/cpp/decrypted_response.h" +#include "chromeos/ash/services/quick_pair/public/cpp/fast_pair_message_type.h" #include "device/bluetooth/bluetooth_adapter.h" #include "device/bluetooth/bluetooth_adapter_factory.h" #include "device/bluetooth/test/mock_bluetooth_adapter.h"
diff --git a/ash/quick_pair/keyed_service/BUILD.gn b/ash/quick_pair/keyed_service/BUILD.gn index f6e0ecc..68395450 100644 --- a/ash/quick_pair/keyed_service/BUILD.gn +++ b/ash/quick_pair/keyed_service/BUILD.gn
@@ -31,11 +31,11 @@ "//ash/quick_pair/repository", "//ash/quick_pair/scanning", "//ash/quick_pair/ui", - "//ash/services/quick_pair", "//base", "//chromeos/ash/services/bluetooth_config", "//chromeos/ash/services/bluetooth_config/public/cpp", "//chromeos/ash/services/bluetooth_config/public/mojom", + "//chromeos/ash/services/quick_pair", "//components/keyed_service/core", "//components/prefs", "//components/user_manager", @@ -68,13 +68,13 @@ "//ash/quick_pair/repository:test_support", "//ash/quick_pair/scanning:test_support", "//ash/quick_pair/ui:test_support", - "//ash/services/quick_pair", - "//ash/services/quick_pair:test_support", "//base", "//base/test:test_support", "//chromeos/ash/services/bluetooth_config", "//chromeos/ash/services/bluetooth_config:test_support", "//chromeos/ash/services/bluetooth_config/public/mojom", + "//chromeos/ash/services/quick_pair", + "//chromeos/ash/services/quick_pair:test_support", "//components/prefs:test_support", "//components/user_manager:test_support", "//device/bluetooth",
diff --git a/ash/quick_pair/keyed_service/battery_update_message_handler_unittest.cc b/ash/quick_pair/keyed_service/battery_update_message_handler_unittest.cc index 9c43c59..b9dc8f39 100644 --- a/ash/quick_pair/keyed_service/battery_update_message_handler_unittest.cc +++ b/ash/quick_pair/keyed_service/battery_update_message_handler_unittest.cc
@@ -16,14 +16,14 @@ #include "ash/quick_pair/message_stream/message_stream_lookup.h" #include "ash/quick_pair/pairing/mock_pairer_broker.h" #include "ash/quick_pair/pairing/pairer_broker.h" -#include "ash/services/quick_pair/fast_pair_data_parser.h" -#include "ash/services/quick_pair/mock_quick_pair_process_manager.h" -#include "ash/services/quick_pair/quick_pair_process.h" -#include "ash/services/quick_pair/quick_pair_process_manager.h" -#include "ash/services/quick_pair/quick_pair_process_manager_impl.h" #include "base/memory/scoped_refptr.h" #include "base/run_loop.h" #include "base/test/task_environment.h" +#include "chromeos/ash/services/quick_pair/fast_pair_data_parser.h" +#include "chromeos/ash/services/quick_pair/mock_quick_pair_process_manager.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process_manager.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process_manager_impl.h" #include "device/bluetooth/bluetooth_adapter_factory.h" #include "device/bluetooth/test/mock_bluetooth_adapter.h" #include "device/bluetooth/test/mock_bluetooth_device.h"
diff --git a/ash/quick_pair/keyed_service/quick_pair_mediator.cc b/ash/quick_pair/keyed_service/quick_pair_mediator.cc index 515b747..e273e0f0 100644 --- a/ash/quick_pair/keyed_service/quick_pair_mediator.cc +++ b/ash/quick_pair/keyed_service/quick_pair_mediator.cc
@@ -30,10 +30,10 @@ #include "ash/quick_pair/scanning/scanner_broker_impl.h" #include "ash/quick_pair/ui/actions.h" #include "ash/quick_pair/ui/ui_broker_impl.h" -#include "ash/services/quick_pair/quick_pair_process.h" -#include "ash/services/quick_pair/quick_pair_process_manager_impl.h" #include "base/threading/thread_task_runner_handle.h" #include "chromeos/ash/services/bluetooth_config/fast_pair_delegate.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process_manager_impl.h" #include "components/prefs/pref_registry_simple.h" namespace ash {
diff --git a/ash/quick_pair/keyed_service/quick_pair_mediator_unittest.cc b/ash/quick_pair/keyed_service/quick_pair_mediator_unittest.cc index f24b1242..733fbad 100644 --- a/ash/quick_pair/keyed_service/quick_pair_mediator_unittest.cc +++ b/ash/quick_pair/keyed_service/quick_pair_mediator_unittest.cc
@@ -32,7 +32,6 @@ #include "ash/quick_pair/scanning/scanner_broker.h" #include "ash/quick_pair/ui/mock_ui_broker.h" #include "ash/quick_pair/ui/ui_broker.h" -#include "ash/services/quick_pair/quick_pair_process_manager_impl.h" #include "ash/test/ash_test_base.h" #include "ash/test/ash_test_helper.h" #include "base/memory/scoped_refptr.h" @@ -41,6 +40,7 @@ #include "chromeos/ash/services/bluetooth_config/fake_adapter_state_controller.h" #include "chromeos/ash/services/bluetooth_config/fake_discovery_session_manager.h" #include "chromeos/ash/services/bluetooth_config/public/mojom/cros_bluetooth_config.mojom.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process_manager_impl.h" #include "components/prefs/pref_registry.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/testing_pref_service.h"
diff --git a/ash/quick_pair/message_stream/BUILD.gn b/ash/quick_pair/message_stream/BUILD.gn index 39b52eaa..74a76300 100644 --- a/ash/quick_pair/message_stream/BUILD.gn +++ b/ash/quick_pair/message_stream/BUILD.gn
@@ -18,10 +18,10 @@ deps = [ "//ash/quick_pair/common", - "//ash/services/quick_pair", - "//ash/services/quick_pair/public/cpp", - "//ash/services/quick_pair/public/mojom", "//base", + "//chromeos/ash/services/quick_pair", + "//chromeos/ash/services/quick_pair/public/cpp", + "//chromeos/ash/services/quick_pair/public/mojom", "//device/bluetooth", "//net", ] @@ -42,11 +42,11 @@ deps = [ "//ash/quick_pair/common", - "//ash/services/quick_pair", - "//ash/services/quick_pair/public/cpp", - "//ash/services/quick_pair/public/mojom", "//base", "//base/test:test_support", + "//chromeos/ash/services/quick_pair", + "//chromeos/ash/services/quick_pair/public/cpp", + "//chromeos/ash/services/quick_pair/public/mojom", "//device/bluetooth", "//device/bluetooth:mocks", "//testing/gtest", @@ -65,10 +65,10 @@ ":message_stream", ":test_support", "//ash/quick_pair/common", - "//ash/services/quick_pair", - "//ash/services/quick_pair:test_support", "//base", "//base/test:test_support", + "//chromeos/ash/services/quick_pair", + "//chromeos/ash/services/quick_pair:test_support", "//device/bluetooth", "//device/bluetooth:mocks", "//mojo/public/cpp/bindings",
diff --git a/ash/quick_pair/message_stream/message_stream.cc b/ash/quick_pair/message_stream/message_stream.cc index 491df5ef..75ec826d 100644 --- a/ash/quick_pair/message_stream/message_stream.cc +++ b/ash/quick_pair/message_stream/message_stream.cc
@@ -6,10 +6,10 @@ #include "ash/quick_pair/common/fast_pair/fast_pair_metrics.h" #include "ash/quick_pair/common/logging.h" -#include "ash/services/quick_pair/quick_pair_process.h" -#include "ash/services/quick_pair/quick_pair_process_manager.h" #include "base/bind.h" #include "base/strings/string_number_conversions.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process_manager.h" #include "device/bluetooth/bluetooth_socket.h" #include "net/base/io_buffer.h"
diff --git a/ash/quick_pair/message_stream/message_stream.h b/ash/quick_pair/message_stream/message_stream.h index 96e1cef..c9ce970 100644 --- a/ash/quick_pair/message_stream/message_stream.h +++ b/ash/quick_pair/message_stream/message_stream.h
@@ -7,12 +7,12 @@ #include <string> -#include "ash/services/quick_pair/quick_pair_process_manager.h" #include "base/containers/circular_deque.h" #include "base/memory/scoped_refptr.h" #include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "base/observer_list_types.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process_manager.h" #include "device/bluetooth/bluetooth_socket.h" #include "third_party/abseil-cpp/absl/types/optional.h"
diff --git a/ash/quick_pair/message_stream/message_stream_unittest.cc b/ash/quick_pair/message_stream/message_stream_unittest.cc index 2295fb2..f01fa62 100644 --- a/ash/quick_pair/message_stream/message_stream_unittest.cc +++ b/ash/quick_pair/message_stream/message_stream_unittest.cc
@@ -8,11 +8,6 @@ #include "ash/quick_pair/common/logging.h" #include "ash/quick_pair/message_stream/fake_bluetooth_socket.h" -#include "ash/services/quick_pair/fast_pair_data_parser.h" -#include "ash/services/quick_pair/mock_quick_pair_process_manager.h" -#include "ash/services/quick_pair/quick_pair_process.h" -#include "ash/services/quick_pair/quick_pair_process_manager.h" -#include "ash/services/quick_pair/quick_pair_process_manager_impl.h" #include "base/callback.h" #include "base/callback_helpers.h" #include "base/memory/scoped_refptr.h" @@ -20,6 +15,11 @@ #include "base/test/metrics/histogram_tester.h" #include "base/test/mock_callback.h" #include "base/test/task_environment.h" +#include "chromeos/ash/services/quick_pair/fast_pair_data_parser.h" +#include "chromeos/ash/services/quick_pair/mock_quick_pair_process_manager.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process_manager.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process_manager_impl.h" #include "device/bluetooth/bluetooth_socket.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/ash/quick_pair/pairing/BUILD.gn b/ash/quick_pair/pairing/BUILD.gn index 523fbac7..a7c85d8 100644 --- a/ash/quick_pair/pairing/BUILD.gn +++ b/ash/quick_pair/pairing/BUILD.gn
@@ -30,9 +30,9 @@ "//ash/quick_pair/message_stream", "//ash/quick_pair/proto:fastpair_proto", "//ash/quick_pair/repository", - "//ash/services/quick_pair", - "//ash/services/quick_pair/public/cpp", "//base", + "//chromeos/ash/services/quick_pair", + "//chromeos/ash/services/quick_pair/public/cpp", "//crypto:crypto", "//device/bluetooth", "//third_party/protobuf:protobuf_lite", @@ -84,11 +84,11 @@ "//ash/quick_pair/proto:fastpair_proto", "//ash/quick_pair/repository:repository", "//ash/quick_pair/repository:test_support", - "//ash/services/quick_pair", - "//ash/services/quick_pair:test_support", - "//ash/services/quick_pair/public/cpp", "//base", "//base/test:test_support", + "//chromeos/ash/services/quick_pair", + "//chromeos/ash/services/quick_pair:test_support", + "//chromeos/ash/services/quick_pair/public/cpp", "//device/bluetooth", "//device/bluetooth:mocks", "//mojo/public/cpp/bindings",
diff --git a/ash/quick_pair/pairing/fast_pair/fast_pair_pairer_impl.cc b/ash/quick_pair/pairing/fast_pair/fast_pair_pairer_impl.cc index 15fb919..c90483ab 100644 --- a/ash/quick_pair/pairing/fast_pair/fast_pair_pairer_impl.cc +++ b/ash/quick_pair/pairing/fast_pair/fast_pair_pairer_impl.cc
@@ -20,12 +20,12 @@ #include "ash/quick_pair/fast_pair_handshake/fast_pair_handshake.h" #include "ash/quick_pair/fast_pair_handshake/fast_pair_handshake_lookup.h" #include "ash/quick_pair/repository/fast_pair_repository.h" -#include "ash/services/quick_pair/public/cpp/fast_pair_message_type.h" #include "ash/session/session_controller_impl.h" #include "ash/shell.h" #include "ash/system/model/system_tray_model.h" #include "base/bind.h" #include "base/callback.h" +#include "chromeos/ash/services/quick_pair/public/cpp/fast_pair_message_type.h" #include "device/bluetooth/bluetooth_adapter.h" #include "device/bluetooth/bluetooth_device.h" #include "device/bluetooth/public/cpp/bluetooth_address.h"
diff --git a/ash/quick_pair/pairing/fast_pair/fast_pair_pairer_impl.h b/ash/quick_pair/pairing/fast_pair/fast_pair_pairer_impl.h index be20f20f..ae02dba 100644 --- a/ash/quick_pair/pairing/fast_pair/fast_pair_pairer_impl.h +++ b/ash/quick_pair/pairing/fast_pair/fast_pair_pairer_impl.h
@@ -9,13 +9,13 @@ #include "ash/quick_pair/fast_pair_handshake/fast_pair_gatt_service_client.h" #include "ash/quick_pair/pairing/fast_pair/fast_pair_pairer.h" #include "ash/quick_pair/proto/fastpair.pb.h" -#include "ash/services/quick_pair/public/cpp/decrypted_passkey.h" -#include "ash/services/quick_pair/public/cpp/decrypted_response.h" #include "base/callback.h" #include "base/memory/scoped_refptr.h" #include "base/memory/weak_ptr.h" #include "base/scoped_observation.h" #include "base/time/time.h" +#include "chromeos/ash/services/quick_pair/public/cpp/decrypted_passkey.h" +#include "chromeos/ash/services/quick_pair/public/cpp/decrypted_response.h" #include "device/bluetooth/bluetooth_device.h" #include "third_party/abseil-cpp/absl/types/optional.h"
diff --git a/ash/quick_pair/pairing/fast_pair/fast_pair_pairer_impl_unittest.cc b/ash/quick_pair/pairing/fast_pair/fast_pair_pairer_impl_unittest.cc index 5959e20..e581aff3 100644 --- a/ash/quick_pair/pairing/fast_pair/fast_pair_pairer_impl_unittest.cc +++ b/ash/quick_pair/pairing/fast_pair/fast_pair_pairer_impl_unittest.cc
@@ -25,9 +25,6 @@ #include "ash/quick_pair/pairing/fast_pair/fast_pair_pairer.h" #include "ash/quick_pair/proto/fastpair.pb.h" #include "ash/quick_pair/repository/fake_fast_pair_repository.h" -#include "ash/services/quick_pair/public/cpp/decrypted_passkey.h" -#include "ash/services/quick_pair/public/cpp/decrypted_response.h" -#include "ash/services/quick_pair/public/cpp/fast_pair_message_type.h" #include "ash/shell.h" #include "ash/test/ash_test_base.h" #include "base/bind.h" @@ -40,6 +37,9 @@ #include "base/test/mock_callback.h" #include "base/test/scoped_feature_list.h" #include "base/test/task_environment.h" +#include "chromeos/ash/services/quick_pair/public/cpp/decrypted_passkey.h" +#include "chromeos/ash/services/quick_pair/public/cpp/decrypted_response.h" +#include "chromeos/ash/services/quick_pair/public/cpp/fast_pair_message_type.h" #include "device/bluetooth/test/mock_bluetooth_adapter.h" #include "device/bluetooth/test/mock_bluetooth_device.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/ash/quick_pair/pairing/retroactive_pairing_detector_unittest.cc b/ash/quick_pair/pairing/retroactive_pairing_detector_unittest.cc index 30b6d6d0..ac04d4f1 100644 --- a/ash/quick_pair/pairing/retroactive_pairing_detector_unittest.cc +++ b/ash/quick_pair/pairing/retroactive_pairing_detector_unittest.cc
@@ -21,17 +21,17 @@ #include "ash/quick_pair/pairing/retroactive_pairing_detector_impl.h" #include "ash/quick_pair/proto/fastpair.pb.h" #include "ash/quick_pair/repository/fake_fast_pair_repository.h" -#include "ash/services/quick_pair/fast_pair_data_parser.h" -#include "ash/services/quick_pair/mock_quick_pair_process_manager.h" -#include "ash/services/quick_pair/quick_pair_process.h" -#include "ash/services/quick_pair/quick_pair_process_manager.h" -#include "ash/services/quick_pair/quick_pair_process_manager_impl.h" #include "ash/shell.h" #include "ash/test/ash_test_base.h" #include "base/memory/scoped_refptr.h" #include "base/run_loop.h" #include "base/test/scoped_feature_list.h" #include "base/test/task_environment.h" +#include "chromeos/ash/services/quick_pair/fast_pair_data_parser.h" +#include "chromeos/ash/services/quick_pair/mock_quick_pair_process_manager.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process_manager.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process_manager_impl.h" #include "device/bluetooth/bluetooth_adapter_factory.h" #include "device/bluetooth/test/mock_bluetooth_adapter.h" #include "device/bluetooth/test/mock_bluetooth_device.h"
diff --git a/ash/quick_pair/repository/BUILD.gn b/ash/quick_pair/repository/BUILD.gn index a7e1b85..b45ca7e9 100644 --- a/ash/quick_pair/repository/BUILD.gn +++ b/ash/quick_pair/repository/BUILD.gn
@@ -47,10 +47,10 @@ deps = [ "//ash/quick_pair/common", "//ash/quick_pair/proto:fastpair_proto", - "//ash/services/quick_pair/public/cpp", "//base", "//chromeos/ash/components/network", "//chromeos/ash/services/bluetooth_config/public/cpp", + "//chromeos/ash/services/quick_pair/public/cpp", "//components/image_fetcher/core", "//components/prefs", "//components/signin/public/identity_manager", @@ -125,10 +125,10 @@ "//ash/quick_pair/common", "//ash/quick_pair/common:test_support", "//ash/quick_pair/proto:fastpair_proto", - "//ash/services/quick_pair/public/cpp", "//base", "//base/test:test_support", "//chromeos/ash/services/bluetooth_config/public/cpp", + "//chromeos/ash/services/quick_pair/public/cpp", "//components/prefs:test_support", "//components/signin/public/identity_manager:test_support", "//crypto",
diff --git a/ash/quick_pair/repository/fast_pair_repository.cc b/ash/quick_pair/repository/fast_pair_repository.cc index 939e46f4..a0a1e3b 100644 --- a/ash/quick_pair/repository/fast_pair_repository.cc +++ b/ash/quick_pair/repository/fast_pair_repository.cc
@@ -7,7 +7,7 @@ #include "ash/quick_pair/common/logging.h" #include "ash/quick_pair/repository/fast_pair/device_metadata_fetcher.h" #include "ash/quick_pair/repository/fast_pair/fast_pair_image_decoder.h" -#include "ash/services/quick_pair/public/cpp/account_key_filter.h" +#include "chromeos/ash/services/quick_pair/public/cpp/account_key_filter.h" #include "components/image_fetcher/core/image_fetcher.h" #include "crypto/sha2.h" #include "device/bluetooth/bluetooth_device.h"
diff --git a/ash/quick_pair/repository/fast_pair_repository_impl.cc b/ash/quick_pair/repository/fast_pair_repository_impl.cc index c7a24dd..1b3f72b 100644 --- a/ash/quick_pair/repository/fast_pair_repository_impl.cc +++ b/ash/quick_pair/repository/fast_pair_repository_impl.cc
@@ -17,7 +17,6 @@ #include "ash/quick_pair/repository/fast_pair/pending_write_store.h" #include "ash/quick_pair/repository/fast_pair/proto_conversions.h" #include "ash/quick_pair/repository/fast_pair/saved_device_registry.h" -#include "ash/services/quick_pair/public/cpp/account_key_filter.h" #include "base/callback_helpers.h" #include "base/memory/scoped_refptr.h" #include "base/strings/string_number_conversions.h" @@ -25,6 +24,7 @@ #include "chromeos/ash/components/network/network_handler.h" #include "chromeos/ash/components/network/network_state_handler.h" #include "chromeos/ash/services/bluetooth_config/public/cpp/device_image_info.h" +#include "chromeos/ash/services/quick_pair/public/cpp/account_key_filter.h" #include "crypto/sha2.h" #include "device/bluetooth/bluetooth_adapter.h" #include "device/bluetooth/bluetooth_adapter_factory.h"
diff --git a/ash/quick_pair/repository/fast_pair_repository_impl_unittest.cc b/ash/quick_pair/repository/fast_pair_repository_impl_unittest.cc index 6f29484..2f8c434 100644 --- a/ash/quick_pair/repository/fast_pair_repository_impl_unittest.cc +++ b/ash/quick_pair/repository/fast_pair_repository_impl_unittest.cc
@@ -17,7 +17,6 @@ #include "ash/quick_pair/repository/fast_pair/pending_write_store.h" #include "ash/quick_pair/repository/fast_pair/proto_conversions.h" #include "ash/quick_pair/repository/fast_pair/saved_device_registry.h" -#include "ash/services/quick_pair/public/cpp/account_key_filter.h" #include "ash/shell.h" #include "ash/test/ash_test_base.h" #include "base/base64.h" @@ -32,6 +31,7 @@ #include "chromeos/ash/components/network/network_handler.h" #include "chromeos/ash/components/network/network_state_handler.h" #include "chromeos/ash/components/network/network_state_test_helper.h" +#include "chromeos/ash/services/quick_pair/public/cpp/account_key_filter.h" #include "components/prefs/testing_pref_service.h" #include "crypto/sha2.h" #include "device/bluetooth/bluetooth_adapter_factory.h"
diff --git a/ash/quick_pair/scanning/BUILD.gn b/ash/quick_pair/scanning/BUILD.gn index 54522c6..4050f58f 100644 --- a/ash/quick_pair/scanning/BUILD.gn +++ b/ash/quick_pair/scanning/BUILD.gn
@@ -29,10 +29,10 @@ "//ash/quick_pair/common", "//ash/quick_pair/fast_pair_handshake", "//ash/quick_pair/repository", - "//ash/services/quick_pair", - "//ash/services/quick_pair/public/cpp", "//base", "//chromeos/ash/components/network", + "//chromeos/ash/services/quick_pair", + "//chromeos/ash/services/quick_pair/public/cpp", "//device/bluetooth", "//device/bluetooth/public/cpp", ] @@ -80,10 +80,10 @@ "//ash/quick_pair/proto:fastpair_proto", "//ash/quick_pair/repository:repository", "//ash/quick_pair/repository:test_support", - "//ash/services/quick_pair", - "//ash/services/quick_pair:test_support", "//base/test:test_support", "//chromeos/ash/components/network:test_support", + "//chromeos/ash/services/quick_pair", + "//chromeos/ash/services/quick_pair:test_support", "//dbus:test_support", "//device/bluetooth", "//device/bluetooth:mocks",
diff --git a/ash/quick_pair/scanning/fast_pair/fast_pair_discoverable_scanner_impl.cc b/ash/quick_pair/scanning/fast_pair/fast_pair_discoverable_scanner_impl.cc index fb9fe52..65a65c3 100644 --- a/ash/quick_pair/scanning/fast_pair/fast_pair_discoverable_scanner_impl.cc +++ b/ash/quick_pair/scanning/fast_pair/fast_pair_discoverable_scanner_impl.cc
@@ -15,8 +15,6 @@ #include "ash/quick_pair/common/pair_failure.h" #include "ash/quick_pair/common/protocol.h" #include "ash/quick_pair/repository/fast_pair_repository.h" -#include "ash/services/quick_pair/quick_pair_process.h" -#include "ash/services/quick_pair/quick_pair_process_manager.h" #include "base/bind.h" #include "base/callback_helpers.h" #include "base/check.h" @@ -25,6 +23,8 @@ #include "base/strings/string_util.h" #include "chromeos/ash/components/network/network_handler.h" #include "chromeos/ash/components/network/network_state_handler.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process_manager.h" #include "device/bluetooth//bluetooth_adapter.h" #include "device/bluetooth/bluetooth_device.h" #include "third_party/abseil-cpp/absl/types/optional.h"
diff --git a/ash/quick_pair/scanning/fast_pair/fast_pair_discoverable_scanner_impl.h b/ash/quick_pair/scanning/fast_pair/fast_pair_discoverable_scanner_impl.h index 674188e..d9c858c 100644 --- a/ash/quick_pair/scanning/fast_pair/fast_pair_discoverable_scanner_impl.h +++ b/ash/quick_pair/scanning/fast_pair/fast_pair_discoverable_scanner_impl.h
@@ -9,13 +9,13 @@ #include "ash/quick_pair/scanning/fast_pair/fast_pair_discoverable_scanner.h" #include "ash/quick_pair/scanning/fast_pair/fast_pair_scanner.h" -#include "ash/services/quick_pair/quick_pair_process_manager.h" #include "base/callback_forward.h" #include "base/containers/flat_map.h" #include "base/memory/scoped_refptr.h" #include "base/memory/weak_ptr.h" #include "base/scoped_observation.h" #include "chromeos/ash/components/network/network_state_handler_observer.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process_manager.h" #include "third_party/abseil-cpp/absl/types/optional.h" namespace device {
diff --git a/ash/quick_pair/scanning/fast_pair/fast_pair_discoverable_scanner_impl_unittest.cc b/ash/quick_pair/scanning/fast_pair/fast_pair_discoverable_scanner_impl_unittest.cc index 9a7b24e..af213f6f 100644 --- a/ash/quick_pair/scanning/fast_pair/fast_pair_discoverable_scanner_impl_unittest.cc +++ b/ash/quick_pair/scanning/fast_pair/fast_pair_discoverable_scanner_impl_unittest.cc
@@ -13,11 +13,6 @@ #include "ash/quick_pair/repository/fake_fast_pair_repository.h" #include "ash/quick_pair/scanning/fast_pair/fake_fast_pair_scanner.h" #include "ash/quick_pair/scanning/fast_pair/fast_pair_discoverable_scanner.h" -#include "ash/services/quick_pair/fast_pair_data_parser.h" -#include "ash/services/quick_pair/mock_quick_pair_process_manager.h" -#include "ash/services/quick_pair/quick_pair_process.h" -#include "ash/services/quick_pair/quick_pair_process_manager.h" -#include "ash/services/quick_pair/quick_pair_process_manager_impl.h" #include "base/callback_helpers.h" #include "base/memory/ptr_util.h" #include "base/memory/scoped_refptr.h" @@ -29,6 +24,11 @@ #include "chromeos/ash/components/network/network_handler.h" #include "chromeos/ash/components/network/network_state_handler.h" #include "chromeos/ash/components/network/network_state_test_helper.h" +#include "chromeos/ash/services/quick_pair/fast_pair_data_parser.h" +#include "chromeos/ash/services/quick_pair/mock_quick_pair_process_manager.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process_manager.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process_manager_impl.h" #include "device/bluetooth/bluetooth_adapter.h" #include "device/bluetooth/bluetooth_device.h" #include "device/bluetooth/test/mock_bluetooth_adapter.h"
diff --git a/ash/quick_pair/scanning/fast_pair/fast_pair_not_discoverable_scanner_impl.cc b/ash/quick_pair/scanning/fast_pair/fast_pair_not_discoverable_scanner_impl.cc index 70fc78d..968f842e 100644 --- a/ash/quick_pair/scanning/fast_pair/fast_pair_not_discoverable_scanner_impl.cc +++ b/ash/quick_pair/scanning/fast_pair/fast_pair_not_discoverable_scanner_impl.cc
@@ -19,10 +19,6 @@ #include "ash/quick_pair/repository/fast_pair/device_metadata.h" #include "ash/quick_pair/repository/fast_pair/pairing_metadata.h" #include "ash/quick_pair/repository/fast_pair_repository.h" -#include "ash/services/quick_pair/public/cpp/account_key_filter.h" -#include "ash/services/quick_pair/public/cpp/not_discoverable_advertisement.h" -#include "ash/services/quick_pair/quick_pair_process.h" -#include "ash/services/quick_pair/quick_pair_process_manager.h" #include "base/bind.h" #include "base/callback.h" #include "base/callback_helpers.h" @@ -31,6 +27,10 @@ #include "base/memory/scoped_refptr.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" +#include "chromeos/ash/services/quick_pair/public/cpp/account_key_filter.h" +#include "chromeos/ash/services/quick_pair/public/cpp/not_discoverable_advertisement.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process_manager.h" #include "device/bluetooth//bluetooth_adapter.h" #include "device/bluetooth/bluetooth_device.h" #include "third_party/abseil-cpp/absl/types/optional.h"
diff --git a/ash/quick_pair/scanning/fast_pair/fast_pair_not_discoverable_scanner_impl.h b/ash/quick_pair/scanning/fast_pair/fast_pair_not_discoverable_scanner_impl.h index 51f5e47f..685c3d1e 100644 --- a/ash/quick_pair/scanning/fast_pair/fast_pair_not_discoverable_scanner_impl.h +++ b/ash/quick_pair/scanning/fast_pair/fast_pair_not_discoverable_scanner_impl.h
@@ -11,12 +11,12 @@ #include "ash/quick_pair/scanning/fast_pair/fast_pair_not_discoverable_scanner.h" #include "ash/quick_pair/scanning/fast_pair/fast_pair_scanner.h" -#include "ash/services/quick_pair/quick_pair_process_manager.h" #include "base/callback_forward.h" #include "base/containers/flat_map.h" #include "base/memory/scoped_refptr.h" #include "base/memory/weak_ptr.h" #include "base/scoped_observation.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process_manager.h" namespace device { class BluetoothAdapter;
diff --git a/ash/quick_pair/scanning/fast_pair/fast_pair_not_discoverable_scanner_impl_unittest.cc b/ash/quick_pair/scanning/fast_pair/fast_pair_not_discoverable_scanner_impl_unittest.cc index 9a86b84..9f554b11 100644 --- a/ash/quick_pair/scanning/fast_pair/fast_pair_not_discoverable_scanner_impl_unittest.cc +++ b/ash/quick_pair/scanning/fast_pair/fast_pair_not_discoverable_scanner_impl_unittest.cc
@@ -20,11 +20,6 @@ #include "ash/quick_pair/repository/fast_pair/pairing_metadata.h" #include "ash/quick_pair/scanning/fast_pair/fake_fast_pair_scanner.h" #include "ash/quick_pair/scanning/fast_pair/fast_pair_not_discoverable_scanner.h" -#include "ash/services/quick_pair/fast_pair_data_parser.h" -#include "ash/services/quick_pair/mock_quick_pair_process_manager.h" -#include "ash/services/quick_pair/quick_pair_process.h" -#include "ash/services/quick_pair/quick_pair_process_manager.h" -#include "ash/services/quick_pair/quick_pair_process_manager_impl.h" #include "base/bind.h" #include "base/callback_helpers.h" #include "base/memory/scoped_refptr.h" @@ -33,6 +28,11 @@ #include "base/test/bind.h" #include "base/test/mock_callback.h" #include "base/test/task_environment.h" +#include "chromeos/ash/services/quick_pair/fast_pair_data_parser.h" +#include "chromeos/ash/services/quick_pair/mock_quick_pair_process_manager.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process_manager.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process_manager_impl.h" #include "device/bluetooth/bluetooth_adapter.h" #include "device/bluetooth/bluetooth_device.h" #include "device/bluetooth/test/mock_bluetooth_adapter.h"
diff --git a/ash/quick_pair/scanning/scanner_broker_impl.cc b/ash/quick_pair/scanning/scanner_broker_impl.cc index f697866..272e493 100644 --- a/ash/quick_pair/scanning/scanner_broker_impl.cc +++ b/ash/quick_pair/scanning/scanner_broker_impl.cc
@@ -13,12 +13,12 @@ #include "ash/quick_pair/scanning/fast_pair/fast_pair_discoverable_scanner_impl.h" #include "ash/quick_pair/scanning/fast_pair/fast_pair_not_discoverable_scanner.h" #include "ash/quick_pair/scanning/fast_pair/fast_pair_not_discoverable_scanner_impl.h" -#include "ash/services/quick_pair/quick_pair_process_manager.h" #include "ash/session/session_controller_impl.h" #include "ash/shell.h" #include "base/bind.h" #include "base/callback.h" #include "base/check.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process_manager.h" #include "device/bluetooth/bluetooth_adapter_factory.h" namespace {
diff --git a/ash/quick_pair/scanning/scanner_broker_impl_unittest.cc b/ash/quick_pair/scanning/scanner_broker_impl_unittest.cc index a5f89d5..5f66aa8 100644 --- a/ash/quick_pair/scanning/scanner_broker_impl_unittest.cc +++ b/ash/quick_pair/scanning/scanner_broker_impl_unittest.cc
@@ -16,12 +16,12 @@ #include "ash/quick_pair/scanning/fast_pair/fast_pair_scanner.h" #include "ash/quick_pair/scanning/fast_pair/fast_pair_scanner_impl.h" #include "ash/quick_pair/scanning/scanner_broker.h" -#include "ash/services/quick_pair/mock_quick_pair_process_manager.h" -#include "ash/services/quick_pair/quick_pair_process.h" -#include "ash/services/quick_pair/quick_pair_process_manager.h" -#include "ash/services/quick_pair/quick_pair_process_manager_impl.h" #include "ash/test/ash_test_base.h" #include "chromeos/ash/components/network/network_state_test_helper.h" +#include "chromeos/ash/services/quick_pair/mock_quick_pair_process_manager.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process_manager.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process_manager_impl.h" #include "device/bluetooth/bluetooth_adapter.h" #include "device/bluetooth/bluetooth_adapter_factory.h" #include "device/bluetooth/bluetooth_device.h"
diff --git a/ash/quick_pair/ui/BUILD.gn b/ash/quick_pair/ui/BUILD.gn index 1334ad8..9a7e99b2 100644 --- a/ash/quick_pair/ui/BUILD.gn +++ b/ash/quick_pair/ui/BUILD.gn
@@ -78,11 +78,11 @@ "//ash/quick_pair/proto:fastpair_proto", "//ash/quick_pair/repository:repository", "//ash/quick_pair/repository:test_support", - "//ash/services/quick_pair", - "//ash/services/quick_pair:test_support", - "//ash/services/quick_pair/public/cpp", "//base", "//base/test:test_support", + "//chromeos/ash/services/quick_pair", + "//chromeos/ash/services/quick_pair:test_support", + "//chromeos/ash/services/quick_pair/public/cpp", "//components/signin/public/identity_manager", "//components/signin/public/identity_manager:test_support", "//testing/gtest",
diff --git a/ash/quick_pair/ui/fast_pair/fast_pair_notification_controller_unittest.cc b/ash/quick_pair/ui/fast_pair/fast_pair_notification_controller_unittest.cc index 06121312..f1cb2624 100644 --- a/ash/quick_pair/ui/fast_pair/fast_pair_notification_controller_unittest.cc +++ b/ash/quick_pair/ui/fast_pair/fast_pair_notification_controller_unittest.cc
@@ -4,14 +4,14 @@ #include "ash/quick_pair/ui/fast_pair/fast_pair_notification_controller.h" -#include "ash/services/quick_pair/fast_pair_data_parser.h" -#include "ash/services/quick_pair/mock_quick_pair_process_manager.h" -#include "ash/services/quick_pair/quick_pair_process.h" -#include "ash/services/quick_pair/quick_pair_process_manager.h" -#include "ash/services/quick_pair/quick_pair_process_manager_impl.h" #include "ash/test/ash_test_base.h" #include "base/memory/weak_ptr.h" #include "base/test/mock_callback.h" +#include "chromeos/ash/services/quick_pair/fast_pair_data_parser.h" +#include "chromeos/ash/services/quick_pair/mock_quick_pair_process_manager.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process_manager.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process_manager_impl.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/gfx/image/image_skia.h"
diff --git a/ash/quick_pair/ui/fast_pair/fast_pair_presenter_impl_unittest.cc b/ash/quick_pair/ui/fast_pair/fast_pair_presenter_impl_unittest.cc index 95aa4dc..a5904383 100644 --- a/ash/quick_pair/ui/fast_pair/fast_pair_presenter_impl_unittest.cc +++ b/ash/quick_pair/ui/fast_pair/fast_pair_presenter_impl_unittest.cc
@@ -12,11 +12,6 @@ #include "ash/quick_pair/repository/fake_fast_pair_repository.h" #include "ash/quick_pair/ui/actions.h" #include "ash/quick_pair/ui/fast_pair/fast_pair_presenter.h" -#include "ash/services/quick_pair/fast_pair_data_parser.h" -#include "ash/services/quick_pair/mock_quick_pair_process_manager.h" -#include "ash/services/quick_pair/quick_pair_process.h" -#include "ash/services/quick_pair/quick_pair_process_manager.h" -#include "ash/services/quick_pair/quick_pair_process_manager_impl.h" #include "ash/shell.h" #include "ash/test/ash_test_base.h" #include "base/base64.h" @@ -25,6 +20,11 @@ #include "base/memory/weak_ptr.h" #include "base/test/scoped_feature_list.h" #include "base/time/time.h" +#include "chromeos/ash/services/quick_pair/fast_pair_data_parser.h" +#include "chromeos/ash/services/quick_pair/mock_quick_pair_process_manager.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process_manager.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process_manager_impl.h" #include "components/signin/public/base/consent_level.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/signin/public/identity_manager/identity_test_environment.h"
diff --git a/ash/services/BUILD.gn b/ash/services/BUILD.gn index c9ecec19..b04a8cbe 100644 --- a/ash/services/BUILD.gn +++ b/ash/services/BUILD.gn
@@ -21,7 +21,6 @@ "//ash/services/ime:unit_tests", "//ash/services/multidevice_setup:unit_tests", "//ash/services/nearby/public/cpp:unit_tests", - "//ash/services/quick_pair:unit_tests", "//ash/services/secure_channel:unit_tests", ] }
diff --git a/ash/shelf/login_shelf_view_pixeltest.cc b/ash/shelf/login_shelf_view_pixeltest.cc index 7b91a0d7..83fc960 100644 --- a/ash/shelf/login_shelf_view_pixeltest.cc +++ b/ash/shelf/login_shelf_view_pixeltest.cc
@@ -75,22 +75,21 @@ PressAndReleaseKey(ui::VKEY_TAB); PressAndReleaseKey(ui::VKEY_TAB); - EXPECT_TRUE(GetPixelDiffer()->CompareUiComponentScreenshot( - "focus_on_calendar_view", - AshPixelDiffTestHelper::UiComponent::kShelfWidget)); + aura::Window* primary_shelf_window = GetPrimaryShelf()->GetWindow(); + EXPECT_TRUE(GetPixelDiffer()->CompareUiComponentsOnPrimaryScreen( + "focus_on_calendar_view", primary_shelf_window)); // Focus on the time view. PressAndReleaseKey(ui::VKEY_TAB); - EXPECT_TRUE(GetPixelDiffer()->CompareUiComponentScreenshot( - "focus_on_time_view", AshPixelDiffTestHelper::UiComponent::kShelfWidget)); + EXPECT_TRUE(GetPixelDiffer()->CompareUiComponentsOnPrimaryScreen( + "focus_on_time_view", primary_shelf_window)); PressAndReleaseKey(ui::VKEY_TAB, ui::EF_SHIFT_DOWN); PressAndReleaseKey(ui::VKEY_TAB, ui::EF_SHIFT_DOWN); // Move the focus back to the add person button. - EXPECT_TRUE(GetPixelDiffer()->CompareUiComponentScreenshot( - "refocus_on_login_shelf", - AshPixelDiffTestHelper::UiComponent::kShelfWidget)); + EXPECT_TRUE(GetPixelDiffer()->CompareUiComponentsOnPrimaryScreen( + "refocus_on_login_shelf", primary_shelf_window)); } class LoginShelfWithPolicyWallpaperPixelTestWithRTL
diff --git a/ash/shelf/scrollable_shelf_view_pixeltest.cc b/ash/shelf/scrollable_shelf_view_pixeltest.cc index a17b2a2..edfdd95 100644 --- a/ash/shelf/scrollable_shelf_view_pixeltest.cc +++ b/ash/shelf/scrollable_shelf_view_pixeltest.cc
@@ -37,9 +37,9 @@ // Verifies the scrollable shelf under overflow. TEST_P(ScrollableShelfViewPixelRTLTest, Basics) { - EXPECT_TRUE(GetPixelDiffer()->CompareUiComponentScreenshot( + EXPECT_TRUE(GetPixelDiffer()->CompareUiComponentsOnPrimaryScreen( GetParam() ? "overflow_rtl" : "overflow", - AshPixelDiffTestHelper::UiComponent::kShelfWidget)); + GetPrimaryShelf()->GetWindow())); } class ScrollableShelfViewWithGuestModePixelTest
diff --git a/ash/shelf/shelf_container_view.cc b/ash/shelf/shelf_container_view.cc index f2489ba..a080386c 100644 --- a/ash/shelf/shelf_container_view.cc +++ b/ash/shelf/shelf_container_view.cc
@@ -25,7 +25,7 @@ } gfx::Size ShelfContainerView::CalculateIdealSize(int button_size) const { - const int button_strip_size = ShelfView::GetSizeOfAppButtons( + const int button_strip_size = shelf_view_->GetSizeOfAppButtons( shelf_view_->number_of_visible_apps(), button_size); return shelf_view_->shelf()->IsHorizontalAlignment() ? gfx::Size(button_strip_size, button_size)
diff --git a/ash/shelf/shelf_view.cc b/ash/shelf/shelf_view.cc index db07c51..9051b656 100644 --- a/ash/shelf/shelf_view.cc +++ b/ash/shelf/shelf_view.cc
@@ -38,6 +38,7 @@ #include "ash/shell_delegate.h" #include "ash/strings/grit/ash_strings.h" #include "ash/style/ash_color_provider.h" +#include "ash/style/rounded_label.h" #include "ash/system/status_area_widget.h" #include "ash/utility/haptics_util.h" #include "ash/wm/desks/desks_util.h" @@ -51,6 +52,7 @@ #include "base/containers/adapters.h" #include "base/containers/contains.h" #include "base/cxx17_backports.h" +#include "base/feature_list.h" #include "base/metrics/histogram_functions.h" #include "base/metrics/histogram_macros.h" #include "base/metrics/user_metrics.h" @@ -361,6 +363,18 @@ announcement_view_ = new views::View(); AddChildView(announcement_view_); + + if (base::FeatureList::IsEnabled(features::kShelfParty)) { + const int button_size = GetButtonSize(); + all_pinned_items_are_partying_label_ = new RoundedLabel( + button_size / 4, button_size / 8, button_size / 2, button_size, + l10n_util::GetStringUTF16(IDS_ASH_SHELF_ALL_PINNED_ITEMS_ARE_PARTYING)); + all_pinned_items_are_partying_label_->SetSize( + all_pinned_items_are_partying_label_->GetPreferredSize( + {{/* Unbounded */}, button_size})); + all_pinned_items_are_partying_label_->SetVisible(false); + AddChildView(all_pinned_items_are_partying_label_); + } } ShelfView::~ShelfView() { @@ -375,13 +389,10 @@ int ShelfView::GetSizeOfAppButtons(int count, int button_size) { const int button_spacing = ShelfConfig::Get()->button_spacing(); - - if (count == 0) - return 0; - - const int app_size = count * button_size; - int total_padding = button_spacing * (count - 1); - return app_size + total_padding; + return button_size * count + + (ShouldShowAllPinnedItemsArePartyingLabel() + ? AllPinnedItemsArePartyingLabelSpace() + button_spacing * count + : button_spacing * std::max(0, count - 1)); } void ShelfView::Init(views::FocusSearch* focus_search) { @@ -939,6 +950,8 @@ // The padding is handled in ScrollableShelfView. + UpdateAllPinnedItemsArePartyingLabel(); + const int button_size = GetButtonSize(); for (size_t i = 0; i < view_model_->view_size(); ++i) { if (view_model_->view_at(i)->GetVisible()) { @@ -1395,25 +1408,33 @@ } void ShelfView::UpdateSeparatorBounds(bool animate) { + // The `- 1` is because we expect at least one item after the separator. if (!separator_index_.has_value() || - separator_index_ >= view_model_->view_size()) { + separator_index_ >= view_model_->view_size() - 1) { return; } + // The ` + 1` is because we compute the separator position as an offset + // leftward from the item just after the separator. This matters because for + // an unknown reason, the space between `all_pinned_items_are_partying_label_` + // and the first item actually appears smaller than the space between items. gfx::Rect icon_bounds_beside_separator = - view_model_->ideal_bounds(separator_index_.value()); + view_model_->ideal_bounds(separator_index_.value() + 1); // Calculate the position value on the secondary axis. int secondary_offset = (shelf_->hotseat_widget()->GetHotseatSize() - kSeparatorSize) / 2; - int separator_x = - shelf()->PrimaryAxisValue(icon_bounds_beside_separator.right() + - ShelfConfig::Get()->button_spacing() / 2, - secondary_offset); - int separator_y = shelf()->PrimaryAxisValue( - secondary_offset, icon_bounds_beside_separator.bottom() + - ShelfConfig::Get()->button_spacing() / 2); + // Because we will be subtracting half the button spacing, round it up to + // favor leftward or upward. + const int half_button_spacing_rounded_up = + (ShelfConfig::Get()->button_spacing() + 1) / 2; + const int separator_x = shelf()->PrimaryAxisValue( + icon_bounds_beside_separator.x() - half_button_spacing_rounded_up, + secondary_offset); + const int separator_y = shelf()->PrimaryAxisValue( + secondary_offset, + icon_bounds_beside_separator.y() - half_button_spacing_rounded_up); gfx::Rect separator_bounds( separator_x, separator_y, shelf()->PrimaryAxisValue(kSeparatorThickness, kSeparatorSize), @@ -2598,8 +2619,11 @@ if (scrollable_shelf_view->ShouldAdaptToRTL()) return edge_padding_insets.right(); - return shelf_->IsHorizontalAlignment() ? edge_padding_insets.left() - : edge_padding_insets.top(); + int result = shelf_->PrimaryAxisValue(edge_padding_insets.left(), + edge_padding_insets.top()); + if (ShouldShowAllPinnedItemsArePartyingLabel()) + result += AllPinnedItemsArePartyingLabelSpace(); + return result; } gfx::Rect ShelfView::GetChildViewTargetMirroredBounds( @@ -2638,6 +2662,63 @@ } } +void ShelfView::UpdateAllPinnedItemsArePartyingLabel() { + if (!base::FeatureList::IsEnabled(features::kShelfParty)) + return; + + const bool should_show_all_pinned_items_are_partying_label = + ShouldShowAllPinnedItemsArePartyingLabel(); + all_pinned_items_are_partying_label_->SetVisible( + should_show_all_pinned_items_are_partying_label); + if (!should_show_all_pinned_items_are_partying_label) + return; + + // `target` indicates where the label should appear, but may need adjustment + // for `transform`. + const int target = + app_icons_layout_offset_ - AllPinnedItemsArePartyingLabelSpace(); + gfx::Point position; + gfx::Transform transform; + switch (shelf_->alignment()) { + case ShelfAlignment::kBottom: + case ShelfAlignment::kBottomLocked: + position = gfx::Point( + target, + (height() - all_pinned_items_are_partying_label_->height()) / 2); + break; + case ShelfAlignment::kLeft: + position = gfx::Point( + (width() - all_pinned_items_are_partying_label_->height()) / 2, + target + all_pinned_items_are_partying_label_->width()); + transform.Rotate(-90); + break; + case ShelfAlignment::kRight: + position = gfx::Point( + all_pinned_items_are_partying_label_->height() + + (width() - all_pinned_items_are_partying_label_->height()) / 2, + target); + transform.Rotate(90); + break; + } + all_pinned_items_are_partying_label_->SetPosition(position); + all_pinned_items_are_partying_label_->SetTransform(transform); +} + +bool ShelfView::ShouldShowAllPinnedItemsArePartyingLabel() const { + const bool should_show = + base::FeatureList::IsEnabled(features::kShelfParty) && + !model_->items().empty() && IsItemPinned(model_->items().front()) && + (visible_views_indices_.empty() || + !IsItemPinned(model_->items()[visible_views_indices_.front()])); + DCHECK(!should_show || model_->in_shelf_party()); + return should_show; +} + +int ShelfView::AllPinnedItemsArePartyingLabelSpace() const { + return all_pinned_items_are_partying_label_->width() + + ShelfConfig::Get()->button_spacing(); +} + void ShelfView::RemoveGhostView() { if (current_ghost_view_) { current_ghost_view_index_ = absl::nullopt;
diff --git a/ash/shelf/shelf_view.h b/ash/shelf/shelf_view.h index 03cf5e22..3cdf669 100644 --- a/ash/shelf/shelf_view.h +++ b/ash/shelf/shelf_view.h
@@ -125,7 +125,7 @@ // Returns the size occupied by |count| app buttons. |button_size| indicates // the size of each app button. - static int GetSizeOfAppButtons(int count, int button_size); + int GetSizeOfAppButtons(int count, int button_size); // Initializes shelf view elements. void Init(views::FocusSearch* focus_search); @@ -556,6 +556,17 @@ // this function causes the items that were partying to reappear on the shelf. void HandleShelfParty(); + // Updates the visibility, position, and transform of + // `all_pinned_items_are_partying_label_`. + void UpdateAllPinnedItemsArePartyingLabel(); + + // Returns true if `all_pinned_items_are_partying_label_` should be visible. + bool ShouldShowAllPinnedItemsArePartyingLabel() const; + + // Returns the space occupied by `all_pinned_items_are_partying_label_`, + // including the gap between that label and the first item, in DIPs. + int AllPinnedItemsArePartyingLabelSpace() const; + // Removes and reset |current_ghost_view| and |last_ghost_view|. void RemoveGhostView(); @@ -686,6 +697,10 @@ // alignment or auto-hide state). views::View* announcement_view_ = nullptr; // Owned by ShelfView + // A view used to indicate that all pinned items are partying. + views::View* all_pinned_items_are_partying_label_ = + nullptr; // Owned by ShelfView + // For dragging: -1 if scrolling back, 1 if scrolling forward, 0 if neither. int drag_scroll_dir_ = 0;
diff --git a/ash/shelf/shelf_view_unittest.cc b/ash/shelf/shelf_view_unittest.cc index e40f605..007817a 100644 --- a/ash/shelf/shelf_view_unittest.cc +++ b/ash/shelf/shelf_view_unittest.cc
@@ -2334,7 +2334,8 @@ } // Verifies that partying items are hidden from the shelf. -TEST_P(LtrRtlShelfViewTest, PartyingItemsHiddenFromShelf) { +// TODO(crbug/1372295): This test consistently times out. +TEST_P(LtrRtlShelfViewTest, DISABLED_PartyingItemsHiddenFromShelf) { AddAppShortcut(); AddAppShortcut(); AddApp();
diff --git a/ash/style/style_viewer/system_ui_components_style_viewer_view.cc b/ash/style/style_viewer/system_ui_components_style_viewer_view.cc new file mode 100644 index 0000000..9ced318 --- /dev/null +++ b/ash/style/style_viewer/system_ui_components_style_viewer_view.cc
@@ -0,0 +1,210 @@ +// 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 "ash/style/style_viewer/system_ui_components_style_viewer_view.h" + +#include <memory> +#include <string> + +#include "ash/shell.h" +#include "ash/style/style_viewer/system_ui_components_grid_view.h" +#include "ash/wm/desks/desks_util.h" +#include "base/bind.h" +#include "base/containers/contains.h" +#include "ui/chromeos/styles/cros_tokens_color_mappings.h" +#include "ui/color/color_id.h" +#include "ui/color/color_provider.h" +#include "ui/gfx/geometry/size.h" +#include "ui/gfx/text_constants.h" +#include "ui/views/background.h" +#include "ui/views/controls/button/label_button.h" +#include "ui/views/controls/scroll_view.h" +#include "ui/views/controls/scrollbar/overlay_scroll_bar.h" +#include "ui/views/highlight_border.h" +#include "ui/views/layout/box_layout.h" +#include "ui/views/widget/widget.h" + +namespace ash { + +namespace { + +// The width and height of viewer contents. +constexpr int kContentWidth = 960; +constexpr int kContentHeight = 480; +// The width of components menu. +constexpr int kMenuWidth = 160; +// The height of component button. +constexpr int kDefaultButtonHeight = 32; +// The background color id of active component button. +constexpr ui::ColorId kActiveButtonBackgroundColorId = + cros_tokens::kCrosSysPrimary; +// The text color id of active component button. +constexpr ui::ColorId kActiveButtonTextColorId = cros_tokens::kCrosSysOnPrimary; +// The background color id of inactive component button. +constexpr ui::ColorId kInactiveButtonBackgroundColorId = + cros_tokens::kCrosSysSysOnBase; +// The text color id of inactive component button. +constexpr ui::ColorId kInactiveButtonTextColorId = + cros_tokens::kCrosSysOnSurface; + +} // namespace + +// The global singleton of the viewer widget. +static views::Widget* g_instance = nullptr; + +// ----------------------------------------------------------------------------- +// SystemUIComponentsStyleViewerView::ComponentButton: +class SystemUIComponentsStyleViewerView::ComponentButton + : public views::LabelButton { + public: + ComponentButton(views::LabelButton::PressedCallback pressed_callback, + const std::u16string& name) + : views::LabelButton(pressed_callback, name) { + SetHorizontalAlignment(gfx::HorizontalAlignment::ALIGN_CENTER); + SetBorder(std::make_unique<views::HighlightBorder>( + 0, views::HighlightBorder::Type::kHighlightBorder1, + /*use_light_color=*/false)); + label()->SetSubpixelRenderingEnabled(false); + label()->SetFontList(views::Label::GetDefaultFontList().Derive( + 1, gfx::Font::NORMAL, gfx::Font::Weight::MEDIUM)); + } + ComponentButton(const ComponentButton&) = delete; + ComponentButton& operator=(const ComponentButton&) = delete; + ~ComponentButton() override = default; + + void SetActive(bool active) { + background_color_id_ = active ? kActiveButtonBackgroundColorId + : kInactiveButtonBackgroundColorId; + text_color_id_ = + active ? kActiveButtonTextColorId : kInactiveButtonTextColorId; + OnThemeChanged(); + } + + // views::LabelButton: + void AddedToWidget() override { + SetBackground(views::CreateSolidBackground( + GetColorProvider()->GetColor(background_color_id_))); + } + + gfx::Size CalculatePreferredSize() const override { + return gfx::Size(kMenuWidth, kDefaultButtonHeight); + } + + int GetHeightForWidth(int w) const override { return kDefaultButtonHeight; } + + void OnThemeChanged() override { + views::LabelButton::OnThemeChanged(); + + if (!GetWidget()) + return; + + ui::ColorProvider* color_provider = GetColorProvider(); + SetEnabledTextColors(color_provider->GetColor(text_color_id_)); + if (auto* bg = background()) + bg->SetNativeControlColor(color_provider->GetColor(background_color_id_)); + } + + private: + ui::ColorId background_color_id_ = kInactiveButtonBackgroundColorId; + ui::ColorId text_color_id_ = kInactiveButtonTextColorId; +}; + +// ----------------------------------------------------------------------------- +// SystemUIComponentsStyleViewerView: +SystemUIComponentsStyleViewerView::SystemUIComponentsStyleViewerView() + : menu_scroll_view_( + AddChildView(views::ScrollView::CreateScrollViewWithBorder())), + component_instances_scroll_view_( + AddChildView(std::make_unique<views::ScrollView>())) { + SetLayoutManager(std::make_unique<views::BoxLayout>( + views::BoxLayout::Orientation::kHorizontal)); + SetBackground(views::CreateThemedSolidBackground(ui::kColorDialogBackground)); + + // Set menu scroll view. + menu_scroll_view_->SetPreferredSize(gfx::Size(kMenuWidth, kContentHeight)); + menu_contents_view_ = + menu_scroll_view_->SetContents(std::make_unique<views::View>()); + menu_contents_view_->SetLayoutManager(std::make_unique<views::BoxLayout>( + views::BoxLayout::Orientation::kVertical)); + + component_instances_scroll_view_->SetPreferredSize( + gfx::Size(kContentWidth - kMenuWidth, kContentHeight)); + components_grid_view_ = component_instances_scroll_view_->SetContents( + std::make_unique<views::View>()); +} + +SystemUIComponentsStyleViewerView::~SystemUIComponentsStyleViewerView() = + default; + +// static. +void SystemUIComponentsStyleViewerView::CreateAndShowWidget() { + // Only create widget when there is no running instance. + if (g_instance) + return; + + // Owned by widget. + SystemUIComponentsStyleViewerView* viewer_view = + new SystemUIComponentsStyleViewerView(); + viewer_view->SetOwnedByWidget(true); + + // TODO(zxdan): Add components in the viewer. + + views::Widget::InitParams params; + params.parent = + desks_util::GetActiveDeskContainerForRoot(Shell::GetPrimaryRootWindow()); + params.type = views::Widget::InitParams::TYPE_WINDOW; + params.delegate = viewer_view; + + // The widget is owned by the native widget. + g_instance = new views::Widget(std::move(params)); + g_instance->AddObserver(viewer_view); + g_instance->Show(); +} + +void SystemUIComponentsStyleViewerView::AddComponent( + const std::u16string& name, + SystemUIComponentsStyleViewerView::ComponentsGridViewFactory + grid_view_factory) { + // Add a new component button and components grid view factory. + auto* button = + menu_contents_view_->AddChildView(std::make_unique<ComponentButton>( + base::BindRepeating( + &SystemUIComponentsStyleViewerView::ShowComponentInstances, + base::Unretained(this), name), + name)); + buttons_.push_back(button); + components_grid_view_factories_[name] = grid_view_factory; +} + +void SystemUIComponentsStyleViewerView::ShowComponentInstances( + const std::u16string& name) { + DCHECK(base::Contains(components_grid_view_factories_, name)); + + // Set the button corresponding to the component indicated by the name active. + // Set other buttons inactive. + for (auto* button : buttons_) + button->SetActive(button->GetText() == name); + + // Toggle corresponding components grid view. + components_grid_view_ = component_instances_scroll_view_->SetContents( + components_grid_view_factories_[name].Run()); +} + +void SystemUIComponentsStyleViewerView::Layout() { + menu_contents_view_->SetSize( + gfx::Size(kMenuWidth, menu_contents_view_->GetPreferredSize().height())); + components_grid_view_->SizeToPreferredSize(); + views::View::Layout(); +} + +std::u16string SystemUIComponentsStyleViewerView::GetWindowTitle() const { + return u"System Components Style Viewer"; +} + +void SystemUIComponentsStyleViewerView::OnWidgetDestroyed( + views::Widget* widget) { + g_instance = nullptr; +} + +} // namespace ash
diff --git a/ash/style/style_viewer/system_ui_components_style_viewer_view.h b/ash/style/style_viewer/system_ui_components_style_viewer_view.h new file mode 100644 index 0000000..97b1af8 --- /dev/null +++ b/ash/style/style_viewer/system_ui_components_style_viewer_view.h
@@ -0,0 +1,89 @@ +// 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 ASH_STYLE_STYLE_VIEWER_SYSTEM_UI_COMPONENTS_STYLE_VIEWER_VIEW_H_ +#define ASH_STYLE_STYLE_VIEWER_SYSTEM_UI_COMPONENTS_STYLE_VIEWER_VIEW_H_ + +#include <string> + +#include "base/callback_forward.h" +#include "ui/views/widget/widget_delegate.h" +#include "ui/views/widget/widget_observer.h" + +namespace views { +class ScrollView; +} // namespace views + +namespace ash { + +class SystemUIComponentsGridView; + +// SystemUIComponentsStyleViewerView is the client view of the system components +// style viewer. It has two parts: (1) the menu scroll view contains a list of +// component buttons which can toggle the component instances, (2) the component +// instances scroll view lists the instances of current selected component. The +// layout is shown below: +// +----------------------+---------------------------------------+ +// | Menu Scroll View | Component Instances Scroll View | +// | +------------------+ | | +// | | Component Button | | | +// | +------------------+ | | +// | | Component Button | | | +// | +------------------+ | | +// | | | +// +----------------------+---------------------------------------+ +class SystemUIComponentsStyleViewerView : public views::WidgetDelegateView, + public views::WidgetObserver { + public: + // A view factory of `SystemUIComponentsGridView` that shows the UI component + // instances in a m x n grids. + using ComponentsGridViewFactory = + base::RepeatingCallback<std::unique_ptr<SystemUIComponentsGridView>( + void)>; + + SystemUIComponentsStyleViewerView(); + SystemUIComponentsStyleViewerView(const SystemUIComponentsStyleViewerView&) = + delete; + SystemUIComponentsStyleViewerView& operator=( + const SystemUIComponentsStyleViewerView&) = delete; + ~SystemUIComponentsStyleViewerView() override; + + // Creates a widget using the view as delegate and contents. + static void CreateAndShowWidget(); + + // Adds a new component with component name and grid view factory. + void AddComponent(const std::u16string& name, + ComponentsGridViewFactory grid_view_factory); + // Shows the instances of the UI component indicated by the given name. + void ShowComponentInstances(const std::u16string& name); + + // views::WidgetDelegateView: + void Layout() override; + std::u16string GetWindowTitle() const override; + + // views::WidgetObserver: + void OnWidgetDestroyed(views::Widget* widget) override; + + private: + // The button which is used to toggle the instances of corresponding + // component. + class ComponentButton; + + // The scroll views. + views::ScrollView* menu_scroll_view_; + views::ScrollView* component_instances_scroll_view_; + // The contents of the scroll views. + views::View* menu_contents_view_; + views::View* components_grid_view_; + // Buttons used to toggle the component instances. + std::vector<ComponentButton*> buttons_; + // Factories of `SystemUIComponentsGridView` for different + // UI components. + std::map<std::u16string, ComponentsGridViewFactory> + components_grid_view_factories_; +}; + +} // namespace ash + +#endif // ASH_STYLE_STYLE_VIEWER_SYSTEM_UI_COMPONENTS_STYLE_VIEWER_VIEW_H_
diff --git a/ash/system/privacy/privacy_indicators_controller.cc b/ash/system/privacy/privacy_indicators_controller.cc index 1e8c097..29e3878a 100644 --- a/ash/system/privacy/privacy_indicators_controller.cc +++ b/ash/system/privacy/privacy_indicators_controller.cc
@@ -143,7 +143,9 @@ message_center->AddNotification(std::move(notification)); } -void UpdatePrivacyIndicatorsView(bool is_camera_used, bool is_microphone_used) { +void UpdatePrivacyIndicatorsView(const std::string& app_id, + bool is_camera_used, + bool is_microphone_used) { DCHECK(ash::Shell::HasInstance()); for (auto* root_window_controller : ash::Shell::Get()->GetAllRootWindowControllers()) { @@ -152,7 +154,8 @@ root_window_controller->GetStatusAreaWidget() ->unified_system_tray() - ->UpdatePrivacyIndicatorsTrayItem(is_camera_used, is_microphone_used); + ->privacy_indicators_view() + ->Update(app_id, is_camera_used, is_microphone_used); } }
diff --git a/ash/system/privacy/privacy_indicators_controller.h b/ash/system/privacy/privacy_indicators_controller.h index b2d268f3..0f39c264 100644 --- a/ash/system/privacy/privacy_indicators_controller.h +++ b/ash/system/privacy/privacy_indicators_controller.h
@@ -66,7 +66,8 @@ scoped_refptr<PrivacyIndicatorsNotificationDelegate> delegate); // Update the `PrivacyIndicatorsTrayItemView` across all status area widgets. -void ASH_EXPORT UpdatePrivacyIndicatorsView(bool is_camera_used, +void ASH_EXPORT UpdatePrivacyIndicatorsView(const std::string& app_id, + bool is_camera_used, bool is_microphone_used); // Update `PrivacyIndicatorsTrayItemView` screen share status across all status
diff --git a/ash/system/privacy/privacy_indicators_tray_item_view.cc b/ash/system/privacy/privacy_indicators_tray_item_view.cc index c3825f1..ab09658 100644 --- a/ash/system/privacy/privacy_indicators_tray_item_view.cc +++ b/ash/system/privacy/privacy_indicators_tray_item_view.cc
@@ -14,6 +14,7 @@ #include "ash/strings/grit/ash_strings.h" #include "ash/style/ash_color_provider.h" #include "ash/system/tray/tray_item_view.h" +#include "base/containers/flat_set.h" #include "base/metrics/histogram_functions.h" #include "base/time/time.h" #include "ui/base/l10n/l10n_util.h" @@ -128,21 +129,19 @@ PrivacyIndicatorsTrayItemView::~PrivacyIndicatorsTrayItemView() = default; -void PrivacyIndicatorsTrayItemView::Update(bool camera_is_used, - bool microphone_is_used) { - if (camera_is_used_ == camera_is_used && - microphone_is_used_ == microphone_is_used) { - return; - } - camera_is_used_ = camera_is_used; - microphone_is_used_ = microphone_is_used; +void PrivacyIndicatorsTrayItemView::Update(const std::string& app_id, + bool is_camera_used, + bool is_microphone_used) { + UpdateAccessStatus(app_id, /*is_accessed=*/is_camera_used, use_camera_apps_); + UpdateAccessStatus(app_id, + /*is_accessed=*/is_microphone_used, use_microphone_apps_); - SetVisible(camera_is_used_ || microphone_is_used_ || is_screen_sharing_); + UpdateVisibility(); if (!GetVisible()) return; - camera_icon_->SetVisible(camera_is_used); - microphone_icon_->SetVisible(microphone_is_used); + camera_icon_->SetVisible(IsCameraUsed()); + microphone_icon_->SetVisible(IsMicrophoneUsed()); TooltipTextChanged(); } @@ -152,7 +151,7 @@ return; is_screen_sharing_ = is_screen_sharing; - SetVisible(camera_is_used_ || microphone_is_used_ || is_screen_sharing_); + UpdateVisibility(); screen_share_icon_->SetVisible(is_screen_sharing_); TooltipTextChanged(); } @@ -167,13 +166,13 @@ std::u16string PrivacyIndicatorsTrayItemView::GetTooltipText( const gfx::Point& point) const { auto cam_and_mic_status = std::u16string(); - if (camera_is_used_ && microphone_is_used_) { + if (IsCameraUsed() && IsMicrophoneUsed()) { cam_and_mic_status = l10n_util::GetStringUTF16( IDS_PRIVACY_NOTIFICATION_TITLE_CAMERA_AND_MIC); - } else if (camera_is_used_) { + } else if (IsCameraUsed()) { cam_and_mic_status = l10n_util::GetStringUTF16(IDS_PRIVACY_NOTIFICATION_TITLE_CAMERA); - } else if (microphone_is_used_) { + } else if (IsMicrophoneUsed()) { cam_and_mic_status = l10n_util::GetStringUTF16(IDS_PRIVACY_NOTIFICATION_TITLE_MIC); } @@ -327,6 +326,14 @@ UpdateBoundsInset(); } +bool PrivacyIndicatorsTrayItemView::IsCameraUsed() const { + return !use_camera_apps_.empty(); +} + +bool PrivacyIndicatorsTrayItemView::IsMicrophoneUsed() const { + return !use_microphone_apps_.empty(); +} + void PrivacyIndicatorsTrayItemView::UpdateIcons() { const SkColor icon_color = AshColorProvider::Get()->GetContentLayerColor( AshColorProvider::ContentLayerType::kIconColorPrimary); @@ -378,11 +385,29 @@ int PrivacyIndicatorsTrayItemView::GetLongerSideLengthInExpandedMode() const { // If all three icons are visible, the view should be longer. - return camera_is_used_ && microphone_is_used_ && is_screen_sharing_ + return IsCameraUsed() && IsMicrophoneUsed() && is_screen_sharing_ ? kPrivacyIndicatorsViewExpandedWithScreenShareSize : kPrivacyIndicatorsViewExpandedLongerSideSize; } +void PrivacyIndicatorsTrayItemView::UpdateAccessStatus( + const std::string& app_id, + bool is_accessed, + base::flat_set<std::string>& access_set) { + if (access_set.contains(app_id) == is_accessed) + return; + + if (is_accessed) + access_set.insert(app_id); + else + access_set.erase(app_id); +} + +void PrivacyIndicatorsTrayItemView::UpdateVisibility() { + // We only hide the view when all the sets are empty. + SetVisible(IsCameraUsed() || IsMicrophoneUsed() || is_screen_sharing_); +} + void PrivacyIndicatorsTrayItemView::EndAllAnimations() { shorter_side_shrink_animation_->End(); longer_side_shrink_animation_->End();
diff --git a/ash/system/privacy/privacy_indicators_tray_item_view.h b/ash/system/privacy/privacy_indicators_tray_item_view.h index 6c75c99e..5fa4a3ec 100644 --- a/ash/system/privacy/privacy_indicators_tray_item_view.h +++ b/ash/system/privacy/privacy_indicators_tray_item_view.h
@@ -7,6 +7,7 @@ #include "ash/ash_export.h" #include "ash/system/tray/tray_item_view.h" +#include "base/containers/flat_set.h" #include "base/timer/timer.h" #include "ui/compositor/throughput_tracker.h" @@ -56,7 +57,9 @@ ~PrivacyIndicatorsTrayItemView() override; // Update the view according to the state of camara/microphone access. - void Update(bool camera_is_used, bool microphone_is_used); + void Update(const std::string& app_id, + bool is_camera_used, + bool is_microphone_used); // Update the view according to the state of screen sharing. void UpdateScreenShareStatus(bool is_screen_sharing); @@ -82,6 +85,10 @@ void AnimationEnded(const gfx::Animation* animation) override; void AnimationCanceled(const gfx::Animation* animation) override; + // Specify whether camera/microphone is in used. + bool IsCameraUsed() const; + bool IsMicrophoneUsed() const; + // Update the icons for the children views. void UpdateIcons(); @@ -96,6 +103,15 @@ // Calculate the length of the longer size, based on `is_screen_sharing_`. int GetLongerSideLengthInExpandedMode() const; + // Update the access status of `app_id` for the given `access_set`. + void UpdateAccessStatus(const std::string& app_id, + bool is_accessed, + base::flat_set<std::string>& access_set); + + // Update the view's visibility based on camera/mic access and screen sharing + // state. + void UpdateVisibility(); + // End all 3 animations contained in this class. void EndAllAnimations(); @@ -106,8 +122,11 @@ views::ImageView* microphone_icon_ = nullptr; views::ImageView* screen_share_icon_ = nullptr; - bool camera_is_used_ = false; - bool microphone_is_used_ = false; + // Store the app_id(s) that are currently accessing camera/microphone. + base::flat_set<std::string> use_camera_apps_; + base::flat_set<std::string> use_microphone_apps_; + + // Keep track of the current screen sharing state. bool is_screen_sharing_ = false; // Keep track the current animation state during the multi-part animation.
diff --git a/ash/system/privacy/privacy_indicators_tray_item_view_unittest.cc b/ash/system/privacy/privacy_indicators_tray_item_view_unittest.cc index 280514cd..a764c13 100644 --- a/ash/system/privacy/privacy_indicators_tray_item_view_unittest.cc +++ b/ash/system/privacy/privacy_indicators_tray_item_view_unittest.cc
@@ -138,26 +138,30 @@ TEST_F(PrivacyIndicatorsTrayItemViewTest, IconsVisibility) { EXPECT_FALSE(privacy_indicators_view()->GetVisible()); - privacy_indicators_view()->Update(/*camera_is_used=*/true, - /*microphone_is_used=*/false); + privacy_indicators_view()->Update(/*app_id=*/"app_id", + /*is_camera_used=*/true, + /*is_microphone_used=*/false); EXPECT_TRUE(privacy_indicators_view()->GetVisible()); EXPECT_TRUE(camera_icon()->GetVisible()); EXPECT_FALSE(microphone_icon()->GetVisible()); - privacy_indicators_view()->Update(/*camera_is_used=*/false, - /*microphone_is_used=*/true); + privacy_indicators_view()->Update(/*app_id=*/"app_id", + /*is_camera_used=*/false, + /*is_microphone_used=*/true); EXPECT_TRUE(privacy_indicators_view()->GetVisible()); EXPECT_FALSE(camera_icon()->GetVisible()); EXPECT_TRUE(microphone_icon()->GetVisible()); - privacy_indicators_view()->Update(/*camera_is_used=*/true, - /*microphone_is_used=*/true); + privacy_indicators_view()->Update(/*app_id=*/"app_id", + /*is_camera_used=*/true, + /*is_microphone_used=*/true); EXPECT_TRUE(privacy_indicators_view()->GetVisible()); EXPECT_TRUE(camera_icon()->GetVisible()); EXPECT_TRUE(microphone_icon()->GetVisible()); - privacy_indicators_view()->Update(/*camera_is_used=*/false, - /*microphone_is_used=*/false); + privacy_indicators_view()->Update(/*app_id=*/"app_id", + /*is_camera_used=*/false, + /*is_microphone_used=*/false); EXPECT_FALSE(privacy_indicators_view()->GetVisible()); } @@ -176,8 +180,9 @@ EXPECT_FALSE(privacy_indicators_view()->GetVisible()); // Test screen share showing up with other icons. - privacy_indicators_view()->Update(/*camera_is_used=*/false, - /*microphone_is_used=*/true); + privacy_indicators_view()->Update(/*app_id=*/"app_id", + /*is_camera_used=*/false, + /*is_microphone_used=*/true); privacy_indicators_view()->UpdateScreenShareStatus( /*is_screen_sharing=*/true); EXPECT_TRUE(privacy_indicators_view()->GetVisible()); @@ -198,30 +203,34 @@ /*screen_share_status=*/std::u16string()), GetTooltipText()); - privacy_indicators_view()->Update(/*camera_is_used=*/true, - /*microphone_is_used=*/false); + privacy_indicators_view()->Update(/*app_id=*/"app_id", + /*is_camera_used=*/true, + /*is_microphone_used=*/false); EXPECT_EQ(GetExpectedTooltipText(/*cam_mic_status=*/l10n_util::GetStringUTF16( IDS_PRIVACY_NOTIFICATION_TITLE_CAMERA), /*screen_share_status=*/std::u16string()), GetTooltipText()); - privacy_indicators_view()->Update(/*camera_is_used=*/false, - /*microphone_is_used=*/true); + privacy_indicators_view()->Update(/*app_id=*/"app_id", + /*is_camera_used=*/false, + /*is_microphone_used=*/true); EXPECT_EQ(GetExpectedTooltipText(/*cam_mic_status=*/l10n_util::GetStringUTF16( IDS_PRIVACY_NOTIFICATION_TITLE_MIC), /*screen_share_status=*/std::u16string()), GetTooltipText()); - privacy_indicators_view()->Update(/*camera_is_used=*/true, - /*microphone_is_used=*/true); + privacy_indicators_view()->Update(/*app_id=*/"app_id", + /*is_camera_used=*/true, + /*is_microphone_used=*/true); EXPECT_EQ( GetExpectedTooltipText(/*cam_mic_status=*/l10n_util::GetStringUTF16( IDS_PRIVACY_NOTIFICATION_TITLE_CAMERA_AND_MIC), /*screen_share_status=*/std::u16string()), GetTooltipText()); - privacy_indicators_view()->Update(/*camera_is_used=*/false, - /*microphone_is_used=*/false); + privacy_indicators_view()->Update(/*app_id=*/"app_id", + /*is_camera_used=*/false, + /*is_microphone_used=*/false); EXPECT_EQ(GetExpectedTooltipText(/*cam_mic_status=*/std::u16string(), /*screen_share_status=*/std::u16string()), GetTooltipText()); @@ -398,8 +407,9 @@ AnimateToValue(expand_animation(), progress); // Update state in mid animation, shouldn't crash anything. - privacy_indicators_view()->Update(/*camera_is_used=*/true, - /*microphone_is_used=*/false); + privacy_indicators_view()->Update(/*app_id=*/"app_id", + /*is_camera_used=*/true, + /*is_microphone_used=*/false); expand_animation()->End(); @@ -415,11 +425,44 @@ AnimateToValue(shorter_side_shrink_animation(), progress); // The view should become invisible immediately after setting these states. - privacy_indicators_view()->Update(/*camera_is_used=*/false, - /*microphone_is_used=*/false); + privacy_indicators_view()->Update(/*app_id=*/"app_id", + /*is_camera_used=*/false, + /*is_microphone_used=*/false); privacy_indicators_view()->UpdateScreenShareStatus( /*is_screen_sharing=*/false); EXPECT_FALSE(privacy_indicators_view()->GetVisible()); } +TEST_F(PrivacyIndicatorsTrayItemViewTest, MultipleAppsAccess) { + EXPECT_FALSE(privacy_indicators_view()->GetVisible()); + + privacy_indicators_view()->Update(/*app_id=*/"app_id1", + /*is_camera_used=*/true, + /*is_microphone_used=*/false); + EXPECT_TRUE(privacy_indicators_view()->GetVisible()); + EXPECT_TRUE(camera_icon()->GetVisible()); + EXPECT_FALSE(microphone_icon()->GetVisible()); + + privacy_indicators_view()->Update(/*app_id=*/"app_id2", + /*is_camera_used=*/true, + /*is_microphone_used=*/true); + EXPECT_TRUE(privacy_indicators_view()->GetVisible()); + EXPECT_TRUE(camera_icon()->GetVisible()); + EXPECT_TRUE(microphone_icon()->GetVisible()); + + // Indicator should still show when removing 1 app. + privacy_indicators_view()->Update(/*app_id=*/"app_id2", + /*is_camera_used=*/false, + /*is_microphone_used=*/false); + EXPECT_TRUE(privacy_indicators_view()->GetVisible()); + EXPECT_TRUE(camera_icon()->GetVisible()); + EXPECT_FALSE(microphone_icon()->GetVisible()); + + // Indicator should hide when removing all apps. + privacy_indicators_view()->Update(/*app_id=*/"app_id1", + /*is_camera_used=*/false, + /*is_microphone_used=*/false); + EXPECT_FALSE(privacy_indicators_view()->GetVisible()); +} + } // namespace ash
diff --git a/ash/system/time/calendar_unittest_utils.cc b/ash/system/time/calendar_unittest_utils.cc index b19dcf8..14bfd6bc 100644 --- a/ash/system/time/calendar_unittest_utils.cc +++ b/ash/system/time/calendar_unittest_utils.cc
@@ -83,11 +83,14 @@ google_apis::calendar::CalendarEventListCallback callback, const base::Time& start_time, const base::Time& end_time) { - // Give it a little bit of time to mock the api calling. + // Give it a little bit of time to mock the api calling. This duration is a + // little longer than the settle down duration, so in the test after the + // animation settled down it can still be with `kFetching` status until + // somemethod like `WaitUntilFetched` is called. base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, base::BindOnce(std::move(callback), error_, std::move(events_)), - base::Seconds(1)); + kAnimationSettleDownDuration + base::Seconds(2)); return base::DoNothing(); }
diff --git a/ash/system/time/calendar_view.cc b/ash/system/time/calendar_view.cc index e9f74d5..72f6e930 100644 --- a/ash/system/time/calendar_view.cc +++ b/ash/system/time/calendar_view.cc
@@ -702,10 +702,10 @@ void CalendarView::MaybeUpdateLoadingBarVisibility() { for (auto& it : on_screen_month_) { - // If there's an on-screen month that hasn't finished fetching and it's not - // on the lock screen, the loading bar should be visible. - if (it.second != CalendarModel::kSuccess && - it.second != CalendarModel::kNa) { + // If there's an on-screen month that hasn't finished fetching or + // re-fetching, the loading bar should be visible. + if (it.second == CalendarModel::kFetching || + it.second == CalendarModel::kRefetching) { ShowProgress(-1, true); return; }
diff --git a/ash/system/time/calendar_view_unittest.cc b/ash/system/time/calendar_view_unittest.cc index 37291b6..03a5b00 100644 --- a/ash/system/time/calendar_view_unittest.cc +++ b/ash/system/time/calendar_view_unittest.cc
@@ -1701,9 +1701,6 @@ // has not finished fetching and becomes invisible once all months on screen // have finished fetching events. TEST_F(CalendarViewAnimationTest, LoadingBarVisibilityForOneMonthOnScreen) { - base::Time date; - ASSERT_TRUE(base::Time::FromString("04 May 2022 15:00 GMT", &date)); - // Sets the timezone to "America/Los_Angeles". ash::system::ScopedTimezoneSettings timezone_settings(u"America/Los_Angeles"); @@ -1711,23 +1708,13 @@ // screen. UpdateDisplay("800x200"); CreateCalendarView(); + // Advances the time to allow `on_screen_month_` to initialize. task_environment()->FastForwardBy( calendar_test_utils::kAnimationSettleDownDuration); - UpdateMonth(date); EXPECT_EQ(1U, on_screen_month().size()); - // Sets the fetching status of current month to be kFetching, and tests the - // loading bar is visible. - base::Time start_of_month = calendar_utils::GetStartOfMonthUTC(date); - base::Time current_date = - calendar_view()->calendar_view_controller()->currently_shown_date(); - base::Time start_of_current_month = calendar_utils::GetStartOfMonthUTC( - current_date + calendar_utils::GetTimeDifference(current_date)); - EXPECT_EQ(start_of_month, start_of_current_month); - - calendar_model()->FetchEvents(start_of_current_month); EXPECT_TRUE(calendar_view()->children()[kLoadingBarIndex]->GetVisible()); // Waits until the events are fetched, and tests the loading bar is invisible. @@ -1736,35 +1723,19 @@ } TEST_F(CalendarViewAnimationTest, LoadingBarVisibilityForTwoMonthsOnScreen) { - base::Time date; - ASSERT_TRUE(base::Time::FromString("04 May 2022 15:00 GMT", &date)); - // Sets the timezone to "America/Los_Angeles". ash::system::ScopedTimezoneSettings timezone_settings(u"America/Los_Angeles"); // Tests when the `CalendarView` has two months on screen. UpdateDisplay("800x600"); CreateCalendarView(); + // Advances the time to allow `on_screen_month_` to initialize. task_environment()->FastForwardBy( calendar_test_utils::kAnimationSettleDownDuration); - UpdateMonth(date); EXPECT_EQ(2U, on_screen_month().size()); - // Sets the fetching status of both months to be kFetching, and tests the - // loading bar is visible. - base::Time start_of_month = calendar_utils::GetStartOfMonthUTC(date); - base::Time current_date = - calendar_view()->calendar_view_controller()->currently_shown_date(); - base::Time start_of_current_month = calendar_utils::GetStartOfMonthUTC( - current_date + calendar_utils::GetTimeDifference(current_date)); - base::Time start_of_next_month = - calendar_utils::GetStartOfNextMonthUTC(start_of_current_month); - EXPECT_EQ(start_of_month, start_of_current_month); - - calendar_model()->FetchEvents(start_of_current_month); - calendar_model()->FetchEvents(start_of_next_month); EXPECT_TRUE(calendar_view()->children()[kLoadingBarIndex]->GetVisible()); // Waits until the events are fetched, and tests the loading bar is invisible. @@ -1776,45 +1747,27 @@ // bar is visible. SetTodayFromTime(base::Time::Now()); ResetToTodayWithAnimation(); - // Advances the time to allow `on_screen_month_` to update, but don't advance - // too much since we don't want the events to be fetched. - task_environment()->FastForwardBy(base::Milliseconds(800)); + + // Advances the time to allow `on_screen_month_` to update. + task_environment()->FastForwardBy( + calendar_test_utils::kAnimationSettleDownDuration); EXPECT_TRUE(calendar_view()->children()[kLoadingBarIndex]->GetVisible()); } TEST_F(CalendarViewAnimationTest, LoadingBarVisibilityForThreeMonthsOnScreen) { - base::Time date; - ASSERT_TRUE(base::Time::FromString("04 May 2022 15:00 GMT", &date)); - // Sets the timezone to "America/Los_Angeles". ash::system::ScopedTimezoneSettings timezone_settings(u"America/Los_Angeles"); // Tests when the `CalendarView` has three months on screen. UpdateDisplay("800x1000"); CreateCalendarView(); + // Advances the time to allow `on_screen_month_` to initialize. task_environment()->FastForwardBy( calendar_test_utils::kAnimationSettleDownDuration); - UpdateMonth(date); EXPECT_EQ(3U, on_screen_month().size()); - // Sets the fetching status of all months to be kFetching, and tests the - // loading bar is visible. - base::Time start_of_month = calendar_utils::GetStartOfMonthUTC(date); - base::Time current_date = - calendar_view()->calendar_view_controller()->currently_shown_date(); - base::Time start_of_current_month = calendar_utils::GetStartOfMonthUTC( - current_date + calendar_utils::GetTimeDifference(current_date)); - base::Time start_of_next_month = - calendar_utils::GetStartOfNextMonthUTC(start_of_current_month); - base::Time start_of_next_next_month = - calendar_utils::GetStartOfNextMonthUTC(start_of_next_month); - EXPECT_EQ(start_of_month, start_of_current_month); - - calendar_model()->FetchEvents(start_of_current_month); - calendar_model()->FetchEvents(start_of_next_month); - calendar_model()->FetchEvents(start_of_next_next_month); EXPECT_TRUE(calendar_view()->children()[kLoadingBarIndex]->GetVisible()); // Waits until the events are fetched, and tests the loading bar is invisible. @@ -1826,49 +1779,50 @@ // bar is visible. SetTodayFromTime(base::Time::Now()); ResetToTodayWithAnimation(); - // Advances the time to allow `on_screen_month_` to update, but don't advance - // too much since we don't want the events to be fetched. - task_environment()->FastForwardBy(base::Milliseconds(800)); + + // Advances the time to allow `on_screen_month_` to update. + task_environment()->FastForwardBy( + calendar_test_utils::kAnimationSettleDownDuration); EXPECT_TRUE(calendar_view()->children()[kLoadingBarIndex]->GetVisible()); } // Tests the loading bar visibility for different user sessions. TEST_F(CalendarViewAnimationTest, LoadingBarVisibilityForDifferentUserSessions) { - base::Time date; - // Create a monthview based on May, 9th 2022. - ASSERT_TRUE(base::Time::FromString("9 May 2022 10:00 GMT", &date)); - - // Tests when the screen is locked, the loading bar is invisible. - GetSessionControllerClient()->SetSessionState( - session_manager::SessionState::LOCKED); - - CreateCalendarView(); - // Advances the time to allow `on_screen_month_` to initialize. - task_environment()->FastForwardBy( - calendar_test_utils::kAnimationSettleDownDuration); - UpdateMonth(date); - EXPECT_FALSE(calendar_view()->children()[kLoadingBarIndex]->GetVisible()); - - // Tests when the user starts the login process, the loading bar is invisible. - GetSessionControllerClient()->SetSessionState( - session_manager::SessionState::LOGIN_PRIMARY); - - CreateCalendarView(); - task_environment()->FastForwardBy( - calendar_test_utils::kAnimationSettleDownDuration); - UpdateMonth(date); - EXPECT_FALSE(calendar_view()->children()[kLoadingBarIndex]->GetVisible()); + // Make sure that the `CalendarView` can have enough space to hold at least 1 + // month. + UpdateDisplay("800x1000"); // Tests when the user is logged in, the loading bar is visible. GetSessionControllerClient()->SetSessionState( session_manager::SessionState::ACTIVE); - CreateCalendarView(); task_environment()->FastForwardBy( calendar_test_utils::kAnimationSettleDownDuration); - UpdateMonth(date); + EXPECT_TRUE(calendar_view()->children()[kLoadingBarIndex]->GetVisible()); + + // Tests when the screen is locked, the loading bar is invisible. + calendar_model()->ClearAllCachedEvents(); + GetSessionControllerClient()->SetSessionState( + session_manager::SessionState::LOCKED); + CreateCalendarView(); + + // Advances the time to allow `on_screen_month_` to initialize. + task_environment()->FastForwardBy( + calendar_test_utils::kAnimationSettleDownDuration); + + EXPECT_FALSE(calendar_view()->children()[kLoadingBarIndex]->GetVisible()); + + // Tests when the user starts the login process, the loading bar is invisible. + calendar_model()->ClearAllCachedEvents(); + GetSessionControllerClient()->SetSessionState( + session_manager::SessionState::LOGIN_PRIMARY); + CreateCalendarView(); + task_environment()->FastForwardBy( + calendar_test_utils::kAnimationSettleDownDuration); + + EXPECT_FALSE(calendar_view()->children()[kLoadingBarIndex]->GetVisible()); } // Tests that the EventListView does not crash if shown during the initial open.
diff --git a/ash/system/unified/unified_system_tray.cc b/ash/system/unified/unified_system_tray.cc index c043714..7723a95 100644 --- a/ash/system/unified/unified_system_tray.cc +++ b/ash/system/unified/unified_system_tray.cc
@@ -335,14 +335,6 @@ vertical_clock_padding_->SetVisible(should_show_padding); } -void UnifiedSystemTray::UpdatePrivacyIndicatorsTrayItem( - bool camera_is_used, - bool microphone_is_used) { - if (!features::IsPrivacyIndicatorsEnabled()) - return; - privacy_indicators_view_->Update(camera_is_used, microphone_is_used); -} - void UnifiedSystemTray::OnViewVisibilityChanged(views::View* observed_view, views::View* starting_view) { MaybeUpdateVerticalClockPadding();
diff --git a/ash/system/unified/unified_system_tray.h b/ash/system/unified/unified_system_tray.h index e9b287cc..04aef94 100644 --- a/ash/system/unified/unified_system_tray.h +++ b/ash/system/unified/unified_system_tray.h
@@ -90,10 +90,6 @@ // icons in the tray, removes it if the clock is the only visible icon. void MaybeUpdateVerticalClockPadding(); - // Update `privacy_indicators_view_` according to camera/microphone access. - void UpdatePrivacyIndicatorsTrayItem(bool camera_is_used, - bool microphone_is_used); - // views::ViewObserver: void OnViewVisibilityChanged(views::View* observed_view, views::View* starting_view) override;
diff --git a/ash/test/ash_pixel_diff_test_helper.cc b/ash/test/ash_pixel_diff_test_helper.cc index 6265036..c03ef2f 100644 --- a/ash/test/ash_pixel_diff_test_helper.cc +++ b/ash/test/ash_pixel_diff_test_helper.cc
@@ -5,23 +5,10 @@ #include "ash/test/ash_pixel_diff_test_helper.h" #include "ash/root_window_controller.h" -#include "ash/shelf/shelf.h" #include "ash/shell.h" namespace ash { -namespace { - -Shelf* GetPrimaryShelf() { - return Shell::GetPrimaryRootWindowController()->shelf(); -} - -gfx::Rect GetShelfWidgetScreenBounds() { - return GetPrimaryShelf()->GetWindow()->GetBoundsInScreen(); -} - -} // namespace - AshPixelDiffTestHelper::AshPixelDiffTestHelper( const std::string& screenshot_prefix, const std::string& corpus) { @@ -33,31 +20,40 @@ bool AshPixelDiffTestHelper::ComparePrimaryFullScreen( const std::string& screenshot_name) { aura::Window* primary_root_window = Shell::Get()->GetPrimaryRootWindow(); - return ComparePrimaryScreenshotWithBoundsInScreen( - screenshot_name, primary_root_window->bounds()); -} - -bool AshPixelDiffTestHelper::CompareUiComponentScreenshot( - const std::string& screenshot_name, - UiComponent ui_component) { - return ComparePrimaryScreenshotWithBoundsInScreen( - screenshot_name, GetUiComponentBoundsInScreen(ui_component)); -} - -bool AshPixelDiffTestHelper::ComparePrimaryScreenshotWithBoundsInScreen( - const std::string& screenshot_name, - const gfx::Rect& screen_bounds) { - aura::Window* primary_root_window = Shell::Get()->GetPrimaryRootWindow(); return pixel_diff_.CompareNativeWindowScreenshot( - screenshot_name, primary_root_window, screen_bounds); + screenshot_name, primary_root_window, primary_root_window->bounds()); } -gfx::Rect AshPixelDiffTestHelper::GetUiComponentBoundsInScreen( - UiComponent ui_component) const { - switch (ui_component) { - case UiComponent::kShelfWidget: - return GetShelfWidgetScreenBounds(); +bool AshPixelDiffTestHelper::ComparePrimaryScreenshotInRects( + const std::string& screenshot_name, + const std::vector<gfx::Rect>& rects_in_screen) { + aura::Window* primary_root_window = Shell::Get()->GetPrimaryRootWindow(); + const aura::WindowTreeHost* host = primary_root_window->GetHost(); + + // Handle the case that conversion from screen coordinates to pixel + // coordinates is not needed. + if (fabs(host->device_scale_factor() - 1.f) < + std::numeric_limits<float>::epsilon()) { + return pixel_diff_.CompareNativeWindowScreenshotInRects( + screenshot_name, primary_root_window, primary_root_window->bounds(), + /*algorithm=*/nullptr, rects_in_screen); } + + // Convert rects from screen coordinates to pixel coordinates. + std::vector<gfx::Rect> rects_in_pixel; + for (const gfx::Rect& screen_bounds : rects_in_screen) { + gfx::Point top_left = screen_bounds.origin(); + gfx::Point bottom_right = screen_bounds.bottom_right(); + host->ConvertDIPToScreenInPixels(&top_left); + host->ConvertDIPToScreenInPixels(&bottom_right); + rects_in_pixel.emplace_back(top_left, + gfx::Size(bottom_right.x() - top_left.x(), + bottom_right.y() - top_left.y())); + } + + return pixel_diff_.CompareNativeWindowScreenshotInRects( + screenshot_name, primary_root_window, primary_root_window->bounds(), + /*algorithm=*/nullptr, rects_in_pixel); } } // namespace ash
diff --git a/ash/test/ash_pixel_diff_test_helper.h b/ash/test/ash_pixel_diff_test_helper.h index f395ac0..5b26c1f 100644 --- a/ash/test/ash_pixel_diff_test_helper.h +++ b/ash/test/ash_pixel_diff_test_helper.h
@@ -5,6 +5,8 @@ #ifndef ASH_TEST_ASH_PIXEL_DIFF_TEST_HELPER_H_ #define ASH_TEST_ASH_PIXEL_DIFF_TEST_HELPER_H_ +#include "ash/test/ash_pixel_diff_util.h" +#include "base/check_op.h" #include "ui/views/test/view_skia_gold_pixel_diff.h" namespace ash { @@ -13,12 +15,6 @@ // tests via the Skia Gold. class AshPixelDiffTestHelper { public: - // Lists the UI components supported by pixel tests. - enum class UiComponent { - // The shelf widget that shows the shelf background. - kShelfWidget, - }; - // `screenshot_prefix` is the prefix of the screenshot names; `corpus` // specifies the result group that will be used to store screenshots in Skia // Gold. Read the comment of `SKiaGoldPixelDiff::Init()` for more details. @@ -29,26 +25,47 @@ ~AshPixelDiffTestHelper(); // Takes a screenshot of the primary fullscreen then uploads it to the Skia - // Gold to perform pixel comparison. Returns the comparison result. + // Gold to perform pixel comparison. `screenshot_name` specifies the benchmark + // image. Returns the comparison result. // NOTE: use this function only when necessary. Otherwise, a tiny UI change // may break many pixel tests. bool ComparePrimaryFullScreen(const std::string& screenshot_name); - // Takes a screenshot of the area associated to `ui_component` then compares - // it with the benchmark image. Returns the comparison result. - bool CompareUiComponentScreenshot(const std::string& screenshot_name, - UiComponent ui_component); - - // Compares the screenshot of the area specified by `screen_bounds` with the - // benchmark image. Returns the comparison result. - bool ComparePrimaryScreenshotWithBoundsInScreen( - const std::string& screenshot_name, - const gfx::Rect& screen_bounds); + // Similar to `ComparePrimaryFullScreen()` but with the difference that only + // the pixels within the screen bounds of `ui_components` are compared. The + // function caller has the duty to choose suitable `ui_components` in their + // tests to avoid unnecessary pixel comparisons. Otherwise, pixel tests could + // be fragile to the changes in production code. + // `ui_components` is a variadic argument list, consisting of view pointers, + // widget pointers or window pointers. `ui_components` can have the pointers + // of different categories. + // Example usages: + // + // views::View* view_ptr = ...; + // views::Widget* widget_ptr = ...; + // aura::Window* window_ptr = ...; + // + // CompareUiComponentsOnPrimaryScreen("foo_name1", view_ptr); + // + // CompareUiComponentsOnPrimaryScreen("foo_name2", + // view_ptr, + // widget_ptr, + // window_ptr); + template <class... UiComponentTypes> + bool CompareUiComponentsOnPrimaryScreen(const std::string& screenshot_name, + UiComponentTypes... ui_components) { + DCHECK_GT(sizeof...(ui_components), 0u); + std::vector<gfx::Rect> rects_in_screen; + PopulateUiComponentScreenBounds(&rects_in_screen, ui_components...); + return ComparePrimaryScreenshotInRects(screenshot_name, rects_in_screen); + } private: - // Returns the screen bounds of the given UI component. - // NOTE: this function assumes that the UI component is on the primary screen. - gfx::Rect GetUiComponentBoundsInScreen(UiComponent ui_component) const; + // Compares a screenshot of the primary screen with the specified benchmark + // image. Only the pixels in `rects_in_screen` affect the comparison result. + bool ComparePrimaryScreenshotInRects( + const std::string& screenshot_name, + const std::vector<gfx::Rect>& rects_in_screen); // Used to take screenshots and upload images to the Skia Gold server to // perform pixel comparison.
diff --git a/ash/test/ash_pixel_diff_util.cc b/ash/test/ash_pixel_diff_util.cc new file mode 100644 index 0000000..d23096f --- /dev/null +++ b/ash/test/ash_pixel_diff_util.cc
@@ -0,0 +1,27 @@ +// 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 "ash/test/ash_pixel_diff_util.h" + +#include "ui/aura/window.h" +#include "ui/views/view.h" +#include "ui/views/widget/widget.h" + +namespace ash { + +void PopulateUiComponentScreenBounds(std::vector<gfx::Rect>* rects) {} + +gfx::Rect GetUiComponentScreenBounds(views::View* view) { + return view->GetBoundsInScreen(); +} + +gfx::Rect GetUiComponentScreenBounds(views::Widget* widget) { + return widget->GetWindowBoundsInScreen(); +} + +gfx::Rect GetUiComponentScreenBounds(aura::Window* window) { + return window->GetBoundsInScreen(); +} + +} // namespace ash
diff --git a/ash/test/ash_pixel_diff_util.h b/ash/test/ash_pixel_diff_util.h new file mode 100644 index 0000000..d809a95 --- /dev/null +++ b/ash/test/ash_pixel_diff_util.h
@@ -0,0 +1,43 @@ +// 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 ASH_TEST_ASH_PIXEL_DIFF_UTIL_H_ +#define ASH_TEST_ASH_PIXEL_DIFF_UTIL_H_ + +#include <vector> + +#include "ui/gfx/geometry/rect.h" + +namespace aura { +class Window; +} // namespace aura + +namespace views { +class View; +class Widget; +} // namespace views + +namespace ash { + +// Returns the screen bounds of a UI component (a view, a widget or a window). +gfx::Rect GetUiComponentScreenBounds(views::View* view); +gfx::Rect GetUiComponentScreenBounds(views::Widget* widget); +gfx::Rect GetUiComponentScreenBounds(aura::Window* window); + +// An empty function. Used by the overloaded variadic function. +void PopulateUiComponentScreenBounds(std::vector<gfx::Rect>* rects); + +// Populates `rects` with the screen bounds of UI components. Each UI component +// can be a view, a widget or a window. +template <typename U, typename... T> +void PopulateUiComponentScreenBounds(std::vector<gfx::Rect>* rects, + U ui_component, + T... ui_components) { + rects->push_back(GetUiComponentScreenBounds(ui_component)); + PopulateUiComponentScreenBounds(rects, ui_components...); +} + +} // namespace ash + +#endif // ASH_TEST_ASH_PIXEL_DIFF_UTIL_H_
diff --git a/ash/webui/files_internals/BUILD.gn b/ash/webui/files_internals/BUILD.gn new file mode 100644 index 0000000..0e8fb659 --- /dev/null +++ b/ash/webui/files_internals/BUILD.gn
@@ -0,0 +1,22 @@ +# 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("//build/config/chromeos/ui_mode.gni") + +assert(is_chromeos_ash, "Files Internals is ash-chrome only") + +static_library("files_internals") { + sources = [ + "files_internals.cc", + "files_internals.h", + "files_internals_ui_delegate.h", + "url_constants.cc", + "url_constants.h", + ] + + deps = [ + "//content/public/browser", + "//ui/webui", + ] +}
diff --git a/ash/webui/files_internals/OWNERS b/ash/webui/files_internals/OWNERS new file mode 100644 index 0000000..73220a8 --- /dev/null +++ b/ash/webui/files_internals/OWNERS
@@ -0,0 +1 @@ +file://ui/file_manager/OWNERS
diff --git a/ash/webui/files_internals/files_internals.cc b/ash/webui/files_internals/files_internals.cc new file mode 100644 index 0000000..79cdb0e --- /dev/null +++ b/ash/webui/files_internals/files_internals.cc
@@ -0,0 +1,53 @@ +// 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 "ash/webui/files_internals/files_internals.h" + +#include "ash/webui/files_internals/url_constants.h" +#include "base/memory/ref_counted_memory.h" +#include "content/public/browser/web_contents.h" + +namespace ash { + +FilesInternalsUI::FilesInternalsUI( + content::WebUI* web_ui, + std::unique_ptr<FilesInternalsUIDelegate> delegate) + : ui::MojoWebUIController(web_ui), delegate_(std::move(delegate)) { + content::WebUIDataSource* data_source = + content::WebUIDataSource::CreateAndAdd( + web_ui->GetWebContents()->GetBrowserContext(), + kChromeUIFilesInternalsHost); + + auto should_handle_request_callback = + base::BindRepeating([](const std::string&) -> bool { return true; }); + + auto handle_request_callback = base::BindRepeating( + &FilesInternalsUI::HandleRequest, weak_ptr_factory_.GetWeakPtr()); + + data_source->SetRequestFilter(std::move(should_handle_request_callback), + std::move(handle_request_callback)); +} + +FilesInternalsUI::~FilesInternalsUI() = default; + +WEB_UI_CONTROLLER_TYPE_IMPL(FilesInternalsUI) + +void FilesInternalsUI::HandleRequest( + const std::string& url, + content::WebUIDataSource::GotDataCallback callback) { + // The content type is derived from the string url, so redirect an empty url + // to "debug.json". + if (url.empty()) { + std::string s( + "<html><head><meta " + "http-equiv=refresh content=\"0; url='debug.json'\"/></head></html>"); + std::move(callback).Run(base::RefCountedString::TakeString(&s)); + return; + } + + std::string s = delegate_->GetDebugJSON().DebugString(); + std::move(callback).Run(base::RefCountedString::TakeString(&s)); +} + +} // namespace ash
diff --git a/ash/webui/files_internals/files_internals.h b/ash/webui/files_internals/files_internals.h new file mode 100644 index 0000000..4e88545 --- /dev/null +++ b/ash/webui/files_internals/files_internals.h
@@ -0,0 +1,37 @@ +// 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 ASH_WEBUI_FILES_INTERNALS_FILES_INTERNALS_H_ +#define ASH_WEBUI_FILES_INTERNALS_FILES_INTERNALS_H_ + +#include "ash/webui/files_internals/files_internals_ui_delegate.h" +#include "base/memory/weak_ptr.h" +#include "content/public/browser/web_ui_data_source.h" +#include "ui/webui/mojo_web_ui_controller.h" + +namespace ash { + +// WebUIController for chrome://files-internals/. +class FilesInternalsUI : public ui::MojoWebUIController { + public: + FilesInternalsUI(content::WebUI* web_ui, + std::unique_ptr<FilesInternalsUIDelegate> delegate); + FilesInternalsUI(const FilesInternalsUI&) = delete; + FilesInternalsUI& operator=(const FilesInternalsUI&) = delete; + ~FilesInternalsUI() override; + + private: + void HandleRequest(const std::string& url, + content::WebUIDataSource::GotDataCallback callback); + + WEB_UI_CONTROLLER_TYPE_DECL(); + + std::unique_ptr<FilesInternalsUIDelegate> delegate_; + + base::WeakPtrFactory<FilesInternalsUI> weak_ptr_factory_{this}; +}; + +} // namespace ash + +#endif // ASH_WEBUI_FILES_INTERNALS_FILES_INTERNALS_H_
diff --git a/ash/webui/files_internals/files_internals_ui_delegate.h b/ash/webui/files_internals/files_internals_ui_delegate.h new file mode 100644 index 0000000..fe0e596 --- /dev/null +++ b/ash/webui/files_internals/files_internals_ui_delegate.h
@@ -0,0 +1,22 @@ +// Copyright 2020 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef ASH_WEBUI_FILES_INTERNALS_FILES_INTERNALS_UI_DELEGATE_H_ +#define ASH_WEBUI_FILES_INTERNALS_FILES_INTERNALS_UI_DELEGATE_H_ + +#include "base/values.h" + +namespace ash { + +// Delegate to expose //chrome services to //ash/webui FilesInternalsUI. +class FilesInternalsUIDelegate { + public: + virtual ~FilesInternalsUIDelegate() = default; + + virtual base::Value GetDebugJSON() const = 0; +}; + +} // namespace ash + +#endif // ASH_WEBUI_FILES_INTERNALS_FILES_INTERNALS_UI_DELEGATE_H_
diff --git a/ash/webui/files_internals/url_constants.cc b/ash/webui/files_internals/url_constants.cc new file mode 100644 index 0000000..3eeaad6 --- /dev/null +++ b/ash/webui/files_internals/url_constants.cc
@@ -0,0 +1,10 @@ +// 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 "ash/webui/files_internals/url_constants.h" + +namespace ash { +const char kChromeUIFilesInternalsHost[] = "files-internals"; +const char kChromeUIFilesInternalsURL[] = "chrome://files-internals"; +} // namespace ash
diff --git a/ash/webui/files_internals/url_constants.h b/ash/webui/files_internals/url_constants.h new file mode 100644 index 0000000..2639b497 --- /dev/null +++ b/ash/webui/files_internals/url_constants.h
@@ -0,0 +1,13 @@ +// 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 ASH_WEBUI_FILES_INTERNALS_URL_CONSTANTS_H_ +#define ASH_WEBUI_FILES_INTERNALS_URL_CONSTANTS_H_ + +namespace ash { +extern const char kChromeUIFilesInternalsHost[]; +extern const char kChromeUIFilesInternalsURL[]; +} // namespace ash + +#endif // ASH_WEBUI_FILES_INTERNALS_URL_CONSTANTS_H_
diff --git a/ash/wm/desks/desks_controller.cc b/ash/wm/desks/desks_controller.cc index a3a32def..aff50b3 100644 --- a/ash/wm/desks/desks_controller.cc +++ b/ash/wm/desks/desks_controller.cc
@@ -44,6 +44,7 @@ #include "ash/wm/window_cycle/window_cycle_controller.h" #include "ash/wm/window_restore/window_restore_controller.h" #include "ash/wm/window_restore/window_restore_util.h" +#include "ash/wm/window_state.h" #include "ash/wm/window_util.h" #include "ash/wm/workspace/workspace_layout_manager.h" #include "ash/wm/workspace_controller.h" @@ -794,8 +795,10 @@ DCHECK_NE(active_desk_, target_desk); // An active window might be an always-on-top or pip which doesn't belong to - // the active desk, and hence cannot be removed. - if (!base::Contains(active_desk_->windows(), window)) + // the active desk, and cannot be removed. Except floated window, which is + // handled by `FloatController::OnMovingFloatedWindowToDesk`. + const bool is_floated = WindowState::Get(window)->IsFloated(); + if (!base::Contains(active_desk_->windows(), window) && !is_floated) return false; const bool visible_on_all_desks = @@ -840,8 +843,15 @@ } } - active_desk_->MoveWindowToDesk(window, target_desk, target_root, - /*unminimize=*/true); + // Floated window doesn't belong to the desk container, float controller + // handles its desk-window relationship. + if (is_floated) { + Shell::Get()->float_controller()->OnMovingFloatedWindowToDesk( + window, target_desk, target_root); + } else { + active_desk_->MoveWindowToDesk(window, target_desk, target_root, + /*unminimize=*/true); + } MaybeUpdateShelfItems(/*windows_on_inactive_desk=*/{window}, /*windows_on_active_desk=*/{});
diff --git a/ash/wm/float/float_controller.cc b/ash/wm/float/float_controller.cc index 0a06fc96..b6d6d4c5 100644 --- a/ash/wm/float/float_controller.cc +++ b/ash/wm/float/float_controller.cc
@@ -25,6 +25,7 @@ #include "ash/wm/splitview/split_view_constants.h" #include "ash/wm/tablet_mode/tablet_mode_window_state.h" #include "ash/wm/window_state.h" +#include "ash/wm/window_util.h" #include "ash/wm/wm_event.h" #include "ash/wm/work_area_insets.h" #include "ash/wm/workspace/workspace_event_handler.h" @@ -75,7 +76,7 @@ window_state, WindowState::BoundsChangeAnimationType::kAnimate); } -// Shows the given floated window. +// Hides the given floated window. void HideFloatedWindow(aura::Window* floated_window) { // Disable the window animation here, because during desk deactivation we // are taking a screenshot of the desk (used for desk switch animations.) @@ -86,7 +87,7 @@ floated_window->Hide(); } -// Hides the given floated window. +// Shows the given floated window. void ShowFloatedWindow(aura::Window* floated_window) { DCHECK(floated_window); ScopedAnimationDisabler disabler(floated_window); @@ -521,6 +522,31 @@ } } +void FloatController::OnMovingFloatedWindowToDesk(aura::Window* floated_window, + Desk* target_desk, + aura::Window* target_root) { + auto* target_desk_floated_window = FindFloatedWindowOfDesk(target_desk); + aura::Window* root = floated_window->GetRootWindow(); + if (target_desk_floated_window) { + // Unfloat the floated window at `target_desk`. + ResetFloatedWindow(target_desk_floated_window); + } + auto* float_info = MaybeGetFloatedWindowInfo(floated_window); + DCHECK(float_info); + float_info->set_desk(target_desk); + if (root != target_root) { + // If `floated_window_` is dragged to a desk on a different display, we + // also need to move it to the target display. + window_util::MoveWindowToDisplay(floated_window, + display::Screen::GetScreen() + ->GetDisplayNearestWindow(target_root) + .id()); + } + + // Hide `floated_window` since it's been moved to an inactive desk. + HideFloatedWindow(floated_window); +} + void FloatController::OnTabletModeStarting() { DCHECK(!floated_window_info_map_.empty()); // Temporary vector here to avoid mutating the map while iterating it. @@ -686,6 +712,8 @@ // active desk container from float container. WindowState::Get(window)->SetPreAddedToWorkspaceWindowBounds( window->bounds()); + // Floated window have been hidden on purpose on the inactive desk. + ShowFloatedWindow(window); // Re-parent window to the "parent" desk's desk container. floated_window_info->desk() ->GetDeskContainerForRoot(window->GetRootWindow())
diff --git a/ash/wm/float/float_controller.h b/ash/wm/float/float_controller.h index 177e5e7..59ce88f 100644 --- a/ash/wm/float/float_controller.h +++ b/ash/wm/float/float_controller.h
@@ -94,6 +94,18 @@ // `target_desk` has a floated window. void OnMovingAllWindowsOutToDesk(Desk* original_desk, Desk* target_desk); + // Called when moving the `floated_window` to `target_desk`. This function + // takes care of floated window since it doesn't belong to the desk container. + // Note: Unlike `OnMovingAllWindowsOutToDesk` above, if `target_desk` has a + // floated window, it will be unfloated, while `floated_window` remains + // floated. + // Note: When dragging `floated_window` to a different display, we need to map + // `floated_window` to the desk container with same ID on target display's + // root. + void OnMovingFloatedWindowToDesk(aura::Window* floated_window, + Desk* target_desk, + aura::Window* target_root); + // TabletModeObserver: void OnTabletModeStarting() override; void OnTabletModeEnding() override;
diff --git a/ash/wm/float/float_controller_unittest.cc b/ash/wm/float/float_controller_unittest.cc index b13a698..df91a2b1 100644 --- a/ash/wm/float/float_controller_unittest.cc +++ b/ash/wm/float/float_controller_unittest.cc
@@ -17,10 +17,14 @@ #include "ash/test/ash_test_base.h" #include "ash/wm/cursor_manager_chromeos.h" #include "ash/wm/desks/desk.h" +#include "ash/wm/desks/desk_mini_view.h" +#include "ash/wm/desks/desks_bar_view.h" #include "ash/wm/desks/desks_test_api.h" #include "ash/wm/desks/desks_test_util.h" #include "ash/wm/mru_window_tracker.h" #include "ash/wm/overview/overview_controller.h" +#include "ash/wm/overview/overview_grid.h" +#include "ash/wm/overview/overview_item.h" #include "ash/wm/overview/overview_test_util.h" #include "ash/wm/splitview/split_view_metrics_controller.h" #include "ash/wm/tablet_mode/tablet_mode_controller.h" @@ -412,6 +416,103 @@ EXPECT_TRUE(base::Contains(all_desks_mru_list, window_2.get())); } +// Test moving floating window between desks. +TEST_F(WindowFloatTest, MoveFloatWindowBetweenDesks) { + auto* desks_controller = DesksController::Get(); + // Float `window_1` at `desk_1`. + auto* desk_1 = desks_controller->desks()[0].get(); + std::unique_ptr<aura::Window> window_1(CreateFloatedWindow()); + // Verify `window_1` belongs to `desk_1`. + auto* float_controller = Shell::Get()->float_controller(); + ASSERT_EQ(float_controller->FindDeskOfFloatedWindow(window_1.get()), desk_1); + NewDesk(); + auto* desk_2 = desks_controller->desks()[1].get(); + // Move to `desk_2`. + ActivateDesk(desk_2); + // Float `window_2` at `desk_2`. + std::unique_ptr<aura::Window> window_2(CreateFloatedWindow()); + // Move back to `desk_1`. + ActivateDesk(desk_1); + auto* overview_controller = Shell::Get()->overview_controller(); + EnterOverview(); + auto* overview_session = overview_controller->overview_session(); + // The window should exist on the grid of the first display. + auto* overview_item = + overview_session->GetOverviewItemForWindow(window_1.get()); + auto* grid = + overview_session->GetGridWithRootWindow(Shell::GetPrimaryRootWindow()); + EXPECT_EQ(1u, grid->size()); + // Get position of `desk_2`'s desk mini view on the secondary display. + const auto* desks_bar_view = grid->desks_bar_view(); + auto* desk_2_mini_view = desks_bar_view->mini_views()[1]; + gfx::Point desk_2_mini_view_center = + desk_2_mini_view->GetBoundsInScreen().CenterPoint(); + + // On overview, drag and drop floated `window_1` to `desk_2`. + DragItemToPoint(overview_item, desk_2_mini_view_center, GetEventGenerator(), + /*by_touch_gestures=*/false, + /*drop=*/true); + + // Verify `window_1` belongs to `desk_2`. + ASSERT_EQ(float_controller->FindDeskOfFloatedWindow(window_1.get()), desk_2); + // Verify `window_2` is unfloated. + ASSERT_FALSE(WindowState::Get(window_2.get())->IsFloated()); +} + +// Test drag floating window between desks on different displays. +TEST_F(WindowFloatTest, MoveFloatWindowBetweenDesksOnDifferentDisplay) { + UpdateDisplay("1000x400,1000+0-1000x400"); + auto* desks_controller = DesksController::Get(); + // Float `window_1` at `desk_1`. + auto* desk_1 = desks_controller->desks()[0].get(); + std::unique_ptr<aura::Window> window_1(CreateFloatedWindow()); + // Verify `window_1` belongs to `desk_1`. + auto* float_controller = Shell::Get()->float_controller(); + ASSERT_EQ(float_controller->FindDeskOfFloatedWindow(window_1.get()), desk_1); + // Create `desk_2`. + NewDesk(); + auto* desk_2 = desks_controller->desks()[1].get(); + // Move to `desk_2`. + ActivateDesk(desk_2); + // Float `window_2` at `desk_2`. + std::unique_ptr<aura::Window> window_2(CreateFloatedWindow()); + // Move back to `desk_1`. + ActivateDesk(desk_1); + auto* overview_controller = Shell::Get()->overview_controller(); + EnterOverview(); + auto* overview_session = overview_controller->overview_session(); + // Get root for displays. + auto roots = Shell::GetAllRootWindows(); + ASSERT_EQ(2u, roots.size()); + aura::Window* primary_root = roots[0]; + aura::Window* secondary_root = roots[1]; + // The window should exist on the grid of the first display. + auto* overview_item = + overview_session->GetOverviewItemForWindow(window_1.get()); + auto* grid1 = overview_session->GetGridWithRootWindow(primary_root); + auto* grid2 = overview_session->GetGridWithRootWindow(secondary_root); + EXPECT_EQ(1u, grid1->size()); + EXPECT_EQ(grid1, overview_item->overview_grid()); + EXPECT_EQ(0u, grid2->size()); + + // Get position of `desk_2`'s desk mini view on the secondary display. + const auto* desks_bar_view = grid2->desks_bar_view(); + auto* desk_2_mini_view = desks_bar_view->mini_views()[1]; + gfx::Point desk_2_mini_view_center = + desk_2_mini_view->GetBoundsInScreen().CenterPoint(); + + // On overview, drag and drop floated `window_1` to `desk_2` on display 2. + DragItemToPoint(overview_item, desk_2_mini_view_center, GetEventGenerator(), + /*by_touch_gestures=*/false, + /*drop=*/true); + // Verify `window_2` is unfloated. + ASSERT_FALSE(WindowState::Get(window_2.get())->IsFloated()); + // Verify `window_1` belongs to `desk_2`. + ASSERT_EQ(float_controller->FindDeskOfFloatedWindow(window_1.get()), desk_2); + // Verify `window_1` belongs to display 2. + EXPECT_TRUE(secondary_root->Contains(window_1.get())); +} + class TabletWindowFloatTest : public WindowFloatTest { public: TabletWindowFloatTest() = default;
diff --git a/ash/wm/overview/overview_session_unittest.cc b/ash/wm/overview/overview_session_unittest.cc index a920de8..86ee605 100644 --- a/ash/wm/overview/overview_session_unittest.cc +++ b/ash/wm/overview/overview_session_unittest.cc
@@ -3115,11 +3115,11 @@ // Tests exiting the overview session using kFadeOutExit type. TEST_P(OverviewSessionTest, FadeOutExit) { EnterTabletMode(); - // Create a test window. - std::unique_ptr<views::Widget> test_widget(CreateTestWidget()); + std::unique_ptr<aura::Window> test_window(CreateAppWindow()); + ToggleOverview(); ASSERT_TRUE(InOverviewSession()); - EXPECT_FALSE(test_widget->IsMinimized()); + EXPECT_FALSE(WindowState::Get(test_window.get())->IsMinimized()); ui::ScopedAnimationDurationScaleMode test_duration_mode( ui::ScopedAnimationDurationScaleMode::NON_ZERO_DURATION); @@ -3129,7 +3129,7 @@ // that NON_ZERO_DURATION animation duration scale, it should be safe to // dereference the widget pointer immediately (synchronously) after the // session ends. - OverviewItem* item = GetOverviewItemForWindow(test_widget->GetNativeWindow()); + OverviewItem* item = GetOverviewItemForWindow(test_window.get()); views::Widget* grid_item_widget = item->item_widget(); gfx::Rect item_bounds = grid_item_widget->GetWindowBoundsInScreen(); @@ -3137,7 +3137,7 @@ ASSERT_FALSE(InOverviewSession()); // The test window should be minimized as overview fade out exit starts. - EXPECT_TRUE(test_widget->IsMinimized()); + EXPECT_TRUE(WindowState::Get(test_window.get())->IsMinimized()); // Verify that the item widget's transform is not animated as part of the // animation, and that item widget bounds are not changed after minimizing the
diff --git a/ash/wm/window_util.cc b/ash/wm/window_util.cc index e04879d..eb6e9c4 100644 --- a/ash/wm/window_util.cc +++ b/ash/wm/window_util.cc
@@ -269,12 +269,19 @@ // minimization. We minimize ARC windows first so they receive occlusion // updates before losing focus from being hidden. See crbug.com/910304. // TODO(oshima): Investigate better way to handle ARC apps immediately. - WindowState::Get(window)->Minimize(); + + // Suspect some callsites may use this on a window without a window state + // (`aura::client::WINDOW_TYPE_CONTROL`) or windows that cannot be + // minimized. See https://crbug.com/1200596. + auto* window_state = WindowState::Get(window); + if (window_state && window_state->CanMinimize()) + window_state->Minimize(); window->Hide(); } + if (windows.size()) { - // Disable the animations using |disable|. However, doing so will skip + // Disabling the animations using `ScopedAnimationDisabler` will skip // detaching the resources associated with the layer. So we have to trick // the compositor into releasing the resources. // crbug.com/924802.
diff --git a/base/BUILD.gn b/base/BUILD.gn index 4ce40ab..5922a2f 100644 --- a/base/BUILD.gn +++ b/base/BUILD.gn
@@ -201,7 +201,6 @@ "allocator/dispatcher/reentry_guard.cc", "allocator/dispatcher/reentry_guard.h", "allocator/dispatcher/subsystem.h", - "as_const.h", "at_exit.cc", "at_exit.h", "atomic_ref_count.h", @@ -3081,7 +3080,6 @@ "allocator/dispatcher/testing/dispatcher_test.h", "allocator/dispatcher/testing/observer_mock.h", "allocator/dispatcher/testing/tools.h", - "as_const_unittest.cc", "at_exit_unittest.cc", "atomicops_unittest.cc", "auto_reset_unittest.cc",
diff --git a/base/allocator/partition_alloc_support.cc b/base/allocator/partition_alloc_support.cc index 4660b87..54781e0 100644 --- a/base/allocator/partition_alloc_support.cc +++ b/base/allocator/partition_alloc_support.cc
@@ -486,23 +486,22 @@ // allowed. In particular, symbolizing and printing the StackTraces may // allocate memory. debug::StackTrace stack_trace_release; + debug::TaskTrace task_trace_release; absl::optional<debug::StackTrace> stack_trace_free = TakeStackTrace(id); if (stack_trace_free) { - LOG(ERROR) << StringPrintf( - "Detected dangling raw_ptr with id=0x%016" PRIxPTR - ":\n\n" - "The memory was freed at:\n%s\n" - "The dangling raw_ptr was released at:\n%s", - id, stack_trace_free->ToString().c_str(), - stack_trace_release.ToString().c_str()); + LOG(ERROR) << "Detected dangling raw_ptr with id=" + << StringPrintf("0x%016" PRIxPTR, id) << ":\n\n" + << "The memory was freed at:\n" + << *stack_trace_free << "\n" + << "The dangling raw_ptr was released at:\n" + << stack_trace_release << task_trace_release; } else { - LOG(ERROR) << StringPrintf( - "Detected dangling raw_ptr with id=0x%016" PRIxPTR - ":\n\n" - "It was not recorded where the memory was freed.\n\n" - "The dangling raw_ptr was released at:\n%s", - id, stack_trace_release.ToString().c_str()); + LOG(ERROR) << "Detected dangling raw_ptr with id=" + << StringPrintf("0x%016" PRIxPTR, id) << ":\n\n" + << "It was not recorded where the memory was freed.\n\n" + << "The dangling raw_ptr was released at:\n" + << stack_trace_release << task_trace_release; } IMMEDIATE_CRASH(); } @@ -555,17 +554,9 @@ void UnretainedDanglingRawPtrDetectedCrash(uintptr_t id) { debug::TaskTrace task_trace; debug::StackTrace stack_trace; - if (!task_trace.empty()) { - LOG(ERROR) << "Detected dangling raw_ptr in unretained with id=" - << StringPrintf("0x%016" PRIxPTR, id) << ":\n\n" - << task_trace << ":\n Stack trace:\n" - << stack_trace; - } else { - LOG(ERROR) << "Detected dangling raw_ptr in unretained with id=" - << StringPrintf("0x%016" PRIxPTR, id) << ":\n\n" - << "Stack trace:\n" - << stack_trace; - } + LOG(ERROR) << "Detected dangling raw_ptr in unretained with id=" + << StringPrintf("0x%016" PRIxPTR, id) << ":\n\n" + << task_trace << stack_trace; IMMEDIATE_CRASH(); }
diff --git a/base/allocator/partition_allocator/shim/allocator_interception_mac.mm b/base/allocator/partition_allocator/shim/allocator_interception_mac.mm index 0350821..e35dc29 100644 --- a/base/allocator/partition_allocator/shim/allocator_interception_mac.mm +++ b/base/allocator/partition_allocator/shim/allocator_interception_mac.mm
@@ -24,6 +24,7 @@ #import <objc/runtime.h> #include <stddef.h> +#include <algorithm> #include <new> #include "base/allocator/buildflags.h" @@ -602,6 +603,10 @@ zone->free_definite_size = functions->free_definite_size; } + // Cap the version to the max supported to ensure malloc doesn't try to call + // functions that weren't replaced. + zone->version = std::min(zone->version, 12U); + // Restore protection if it was active. if (reprotection_start) { kern_return_t result =
diff --git a/base/as_const.h b/base/as_const.h deleted file mode 100644 index 3c7071a..0000000 --- a/base/as_const.h +++ /dev/null
@@ -1,24 +0,0 @@ -// Copyright 2021 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_AS_CONST_H_ -#define BASE_AS_CONST_H_ - -#include <type_traits> - -namespace base { - -// C++14 implementation of C++17's std::as_const(): -// https://en.cppreference.com/w/cpp/utility/as_const -template <typename T> -constexpr std::add_const_t<T>& as_const(T& t) noexcept { - return t; -} - -template <typename T> -void as_const(const T&& t) = delete; - -} // namespace base - -#endif // BASE_AS_CONST_H_
diff --git a/base/as_const_unittest.cc b/base/as_const_unittest.cc deleted file mode 100644 index acbad6e..0000000 --- a/base/as_const_unittest.cc +++ /dev/null
@@ -1,28 +0,0 @@ -// Copyright 2021 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/as_const.h" - -#include <type_traits> - -#include "testing/gtest/include/gtest/gtest.h" - -namespace base { -namespace { - -TEST(AsConstTest, AsConst) { - int i = 123; - EXPECT_EQ(&i, &base::as_const(i)); - static_assert(std::is_same<const int&, decltype(base::as_const(i))>::value, - "Error: base::as_const() returns an unexpected type"); - - const int ci = 456; - static_assert(&ci == &base::as_const(ci), - "Error: base::as_const() returns an unexpected reference"); - static_assert(std::is_same<const int&, decltype(base::as_const(ci))>::value, - "Error: base::as_const() returns an unexpected type"); -} - -} // namespace -} // namespace base
diff --git a/base/containers/circular_deque.h b/base/containers/circular_deque.h index 4d1fa90..926f0bc6 100644 --- a/base/containers/circular_deque.h +++ b/base/containers/circular_deque.h
@@ -11,7 +11,6 @@ #include <type_traits> #include <utility> -#include "base/as_const.h" #include "base/check.h" #include "base/containers/vector_buffer.h" #include "base/dcheck_is_on.h" @@ -529,11 +528,11 @@ return buffer_[i - right_size]; } value_type& at(size_type i) { - return const_cast<value_type&>(base::as_const(*this).at(i)); + return const_cast<value_type&>(std::as_const(*this).at(i)); } value_type& operator[](size_type i) { - return const_cast<value_type&>(base::as_const(*this)[i]); + return const_cast<value_type&>(std::as_const(*this)[i]); } const value_type& operator[](size_type i) const { return at(i); }
diff --git a/base/containers/flat_map_unittest.cc b/base/containers/flat_map_unittest.cc index 52ff107c..f15b03e 100644 --- a/base/containers/flat_map_unittest.cc +++ b/base/containers/flat_map_unittest.cc
@@ -5,6 +5,7 @@ #include "base/containers/flat_map.h" #include <string> +#include <utility> #include <vector> #include "base/ranges/algorithm.h" @@ -215,7 +216,7 @@ EXPECT_EQ("b", m.at(2)); // Const reference works. - const std::string& const_ref = base::as_const(m).at(1); + const std::string& const_ref = std::as_const(m).at(1); EXPECT_EQ("a", const_ref); // Reference works, can operate on the string. @@ -229,7 +230,7 @@ // Heterogeneous look-up works. base::flat_map<std::string, int> m2 = {{"a", 1}, {"b", 2}}; EXPECT_EQ(1, m2.at(base::StringPiece("a"))); - EXPECT_EQ(2, base::as_const(m2).at(base::StringPiece("b"))); + EXPECT_EQ(2, std::as_const(m2).at(base::StringPiece("b"))); } // insert_or_assign(K&&, M&&)
diff --git a/base/containers/flat_tree.h b/base/containers/flat_tree.h index c778387..0c93c79 100644 --- a/base/containers/flat_tree.h +++ b/base/containers/flat_tree.h
@@ -12,7 +12,6 @@ #include <type_traits> #include <utility> -#include "base/as_const.h" #include "base/check.h" #include "base/compiler_specific.h" #include "base/functional/not_fn.h" @@ -951,7 +950,7 @@ template <typename K> auto flat_tree<Key, GetKeyFromValue, KeyCompare, Container>::find(const K& key) -> iterator { - return const_cast_it(base::as_const(*this).find(key)); + return const_cast_it(std::as_const(*this).find(key)); } template <class Key, class GetKeyFromValue, class KeyCompare, class Container> @@ -974,7 +973,7 @@ template <typename K> auto flat_tree<Key, GetKeyFromValue, KeyCompare, Container>::equal_range( const K& key) -> std::pair<iterator, iterator> { - auto res = base::as_const(*this).equal_range(key); + auto res = std::as_const(*this).equal_range(key); return {const_cast_it(res.first), const_cast_it(res.second)}; } @@ -995,7 +994,7 @@ template <typename K> auto flat_tree<Key, GetKeyFromValue, KeyCompare, Container>::lower_bound( const K& key) -> iterator { - return const_cast_it(base::as_const(*this).lower_bound(key)); + return const_cast_it(std::as_const(*this).lower_bound(key)); } template <class Key, class GetKeyFromValue, class KeyCompare, class Container> @@ -1016,7 +1015,7 @@ template <typename K> auto flat_tree<Key, GetKeyFromValue, KeyCompare, Container>::upper_bound( const K& key) -> iterator { - return const_cast_it(base::as_const(*this).upper_bound(key)); + return const_cast_it(std::as_const(*this).upper_bound(key)); } template <class Key, class GetKeyFromValue, class KeyCompare, class Container>
diff --git a/base/cpu.cc b/base/cpu.cc index 6bca5512..798ab7d8 100644 --- a/base/cpu.cc +++ b/base/cpu.cc
@@ -300,6 +300,8 @@ has_aesni_ = (cpu_info[2] & 0x02000000) != 0; has_fma3_ = (cpu_info[2] & 0x00001000) != 0; has_avx2_ = has_avx_ && (cpu_info7[1] & 0x00000020) != 0; + + has_pku_ = (cpu_info7[2] & 0x00000008) != 0; } // Get the brand string of the cpu.
diff --git a/base/cpu.h b/base/cpu.h index 2cb4c67..db0b93f 100644 --- a/base/cpu.h +++ b/base/cpu.h
@@ -103,6 +103,13 @@ #endif #if defined(ARCH_CPU_X86_FAMILY) + // Memory protection key support for user-mode pages + bool has_pku() const { return has_pku_; } +#else + constexpr bool has_pku() const { return false; } +#endif + +#if defined(ARCH_CPU_X86_FAMILY) IntelMicroArchitecture GetIntelMicroArchitecture() const; #endif const std::string& cpu_brand() const { return cpu_brand_; } @@ -193,6 +200,9 @@ bool has_mte_ = false; // Armv8.5-A MTE (Memory Taggging Extension) bool has_bti_ = false; // Armv8.5-A BTI (Branch Target Identification) #endif +#if defined(ARCH_CPU_X86_FAMILY) + bool has_pku_ = false; +#endif bool has_non_stop_time_stamp_counter_ = false; bool is_running_in_vm_ = false; std::string cpu_vendor_ = "unknown";
diff --git a/base/cpu_unittest.cc b/base/cpu_unittest.cc index 88cc992..402e386 100644 --- a/base/cpu_unittest.cc +++ b/base/cpu_unittest.cc
@@ -72,6 +72,14 @@ // Execute an AVX 2 instruction. __asm__ __volatile__("vpunpcklbw %%ymm0, %%ymm0, %%ymm0\n" : : : "xmm0"); } + + if (cpu.has_pku()) { + // rdpkru + uint32_t pkru; + __asm__ __volatile__(".byte 0x0f,0x01,0xee\n" + : "=a"(pkru) + : "c"(0), "d"(0)); + } // Visual C 32 bit and ClangCL 32/64 bit test. #elif defined(COMPILER_MSVC) && (defined(ARCH_CPU_32_BITS) || \ (defined(ARCH_CPU_64_BITS) && defined(__clang__)))
diff --git a/base/memory/weak_ptr.h b/base/memory/weak_ptr.h index a50e91f..c71c49e9 100644 --- a/base/memory/weak_ptr.h +++ b/base/memory/weak_ptr.h
@@ -241,19 +241,24 @@ // Allow conversion from U to T provided U "is a" T. Note that this // is separate from the (implicit) copy and move constructors. - template <typename U> - WeakPtr(const WeakPtr<U>& other) : WeakPtrBase(other) { + template <typename U, + typename = std::enable_if_t<std::is_convertible_v<U*, T*>>> + // NOLINTNEXTLINE(google-explicit-constructor) + /*implicit*/ WeakPtr(const WeakPtr<U>& other) : WeakPtrBase(other) { // Need to cast from U* to T* to do pointer adjustment in case of multiple - // inheritance. This also enforces the "U is a T" rule. - T* t = reinterpret_cast<U*>(other.ptr_); - ptr_ = reinterpret_cast<uintptr_t>(t); + // inheritance. + T* t_ptr = reinterpret_cast<U*>(ptr_); + ptr_ = reinterpret_cast<uintptr_t>(t_ptr); } - template <typename U> - WeakPtr(WeakPtr<U>&& other) noexcept : WeakPtrBase(std::move(other)) { + template <typename U, + typename = std::enable_if_t<std::is_convertible_v<U*, T*>>> + // NOLINTNEXTLINE(google-explicit-constructor) + /*implicit*/ WeakPtr(WeakPtr<U>&& other) noexcept + : WeakPtrBase(std::move(other)) { // Need to cast from U* to T* to do pointer adjustment in case of multiple - // inheritance. This also enforces the "U is a T" rule. - T* t = reinterpret_cast<U*>(other.ptr_); - ptr_ = reinterpret_cast<uintptr_t>(t); + // inheritance. + T* t_ptr = reinterpret_cast<U*>(ptr_); + ptr_ = reinterpret_cast<uintptr_t>(t_ptr); } T* get() const {
diff --git a/base/memory/weak_ptr_unittest.cc b/base/memory/weak_ptr_unittest.cc index ec4374c..e4f3baf0 100644 --- a/base/memory/weak_ptr_unittest.cc +++ b/base/memory/weak_ptr_unittest.cc
@@ -318,13 +318,22 @@ } TEST(WeakPtrTest, DerivedTargetMultipleInheritance) { - DerivedTargetMultipleInheritance d; - Target& b = d; - EXPECT_NE(static_cast<void*>(&d), static_cast<void*>(&b)); - const WeakPtr<Target> pb = AsWeakPtr(&b); - EXPECT_EQ(pb.get(), &b); - const WeakPtr<DerivedTargetMultipleInheritance> pd = AsWeakPtr(&d); - EXPECT_EQ(pd.get(), &d); + DerivedTargetMultipleInheritance derived_target; + Target& target = derived_target; + EXPECT_NE(static_cast<void*>(&derived_target), static_cast<void*>(&target)); + + WeakPtr<Target> target_weak_ptr = AsWeakPtr(&target); + EXPECT_EQ(target_weak_ptr.get(), &target); + + WeakPtr<DerivedTargetMultipleInheritance> derived_target_weak_ptr = + AsWeakPtr(&derived_target); + EXPECT_EQ(derived_target_weak_ptr.get(), &derived_target); + + target_weak_ptr = derived_target_weak_ptr; + EXPECT_EQ(target_weak_ptr.get(), &target); + + target_weak_ptr = std::move(derived_target_weak_ptr); + EXPECT_EQ(target_weak_ptr.get(), &target); } TEST(WeakPtrFactoryTest, BooleanTesting) { @@ -689,8 +698,13 @@ TEST(WeakPtrTest, ConstUpCast) { Target target; - // WeakPtrs can upcast to const T from a non-const T. + + // WeakPtrs can upcast from non-const T to const T. WeakPtr<const Target> const_weak_ptr = target.AsWeakPtr(); + + // WeakPtrs don't enable conversion from const T to nonconst T. + static_assert( + !std::is_constructible_v<WeakPtr<Target>, WeakPtr<const Target>>); } TEST(WeakPtrTest, GetMutableWeakPtr) {
diff --git a/base/memory/weak_ptr_unittest.nc b/base/memory/weak_ptr_unittest.nc index d75e919..2cdd7b7 100644 --- a/base/memory/weak_ptr_unittest.nc +++ b/base/memory/weak_ptr_unittest.nc
@@ -17,7 +17,7 @@ struct Unrelated {}; struct DerivedUnrelated : Unrelated {}; -#if defined(NCTEST_AUTO_DOWNCAST) // [r"cannot initialize a variable of type 'base::DerivedProducer \*' with an rvalue of type 'base::Producer \*'"] +#if defined(NCTEST_AUTO_DOWNCAST) // [r"no viable conversion from 'WeakPtr<Producer>' to 'WeakPtr<DerivedProducer>'"] void WontCompile() { Producer f; @@ -25,7 +25,7 @@ WeakPtr<DerivedProducer> derived_ptr = ptr; } -#elif defined(NCTEST_STATIC_DOWNCAST) // [r"cannot initialize a variable of type 'base::DerivedProducer \*' with an rvalue of type 'base::Producer \*'"] +#elif defined(NCTEST_STATIC_DOWNCAST) // [r"no matching conversion for static_cast from 'WeakPtr<Producer>' to 'WeakPtr<DerivedProducer>'"] void WontCompile() { Producer f; @@ -59,7 +59,7 @@ SupportsWeakPtr<Producer>::StaticAsWeakPtr<DerivedProducer>(&f); } -#elif defined(NCTEST_UNSAFE_HELPER_DOWNCAST) // [r"cannot initialize a variable of type 'base::DerivedProducer \*' with an rvalue of type 'base::Producer \*'"] +#elif defined(NCTEST_UNSAFE_HELPER_DOWNCAST) // [r"no viable conversion from 'WeakPtr<base::Producer>' to 'WeakPtr<DerivedProducer>'"] void WontCompile() { Producer f; @@ -73,14 +73,14 @@ WeakPtr<DerivedProducer> ptr = AsWeakPtr<DerivedProducer>(&f); } -#elif defined(NCTEST_UNSAFE_WRONG_INSANTIATED_HELPER_DOWNCAST) // [r"cannot initialize a variable of type 'base::DerivedProducer \*' with an rvalue of type 'base::Producer \*'"] +#elif defined(NCTEST_UNSAFE_WRONG_INSANTIATED_HELPER_DOWNCAST) // [r"no viable conversion from 'WeakPtr<base::Producer>' to 'WeakPtr<DerivedProducer>'"] void WontCompile() { Producer f; WeakPtr<DerivedProducer> ptr = AsWeakPtr<Producer>(&f); } -#elif defined(NCTEST_UNSAFE_HELPER_CAST) // [r"cannot initialize a variable of type 'base::OtherDerivedProducer \*' with an rvalue of type 'base::DerivedProducer \*'"] +#elif defined(NCTEST_UNSAFE_HELPER_CAST) // [r"no viable conversion from 'WeakPtr<base::DerivedProducer>' to 'WeakPtr<OtherDerivedProducer>'"] void WontCompile() { DerivedProducer f; @@ -94,14 +94,14 @@ WeakPtr<OtherDerivedProducer> ptr = AsWeakPtr<OtherDerivedProducer>(&f); } -#elif defined(NCTEST_UNSAFE_WRONG_INSTANTIATED_HELPER_SIDECAST) // [r"cannot initialize a variable of type 'base::OtherDerivedProducer \*' with an rvalue of type 'base::DerivedProducer \*'"] +#elif defined(NCTEST_UNSAFE_WRONG_INSTANTIATED_HELPER_SIDECAST) // [r"no viable conversion from 'WeakPtr<base::DerivedProducer>' to 'WeakPtr<OtherDerivedProducer>'"] void WontCompile() { DerivedProducer f; WeakPtr<OtherDerivedProducer> ptr = AsWeakPtr<DerivedProducer>(&f); } -#elif defined(NCTEST_UNRELATED_HELPER) // [r"cannot initialize a variable of type 'base::Unrelated \*' with an rvalue of type 'base::DerivedProducer \*'"] +#elif defined(NCTEST_UNRELATED_HELPER) // [r"no viable conversion from 'WeakPtr<base::DerivedProducer>' to 'WeakPtr<Unrelated>'"] void WontCompile() { DerivedProducer f;
diff --git a/base/values.cc b/base/values.cc index bf9633b..e5432bf 100644 --- a/base/values.cc +++ b/base/values.cc
@@ -10,7 +10,6 @@ #include <tuple> #include <utility> -#include "base/as_const.h" #include "base/bit_cast.h" #include "base/check.h" #include "base/check_op.h" @@ -614,7 +613,7 @@ } Value* Value::Dict::FindByDottedPath(StringPiece path) { - return const_cast<Value*>(as_const(*this).FindByDottedPath(path)); + return const_cast<Value*>(std::as_const(*this).FindByDottedPath(path)); } absl::optional<bool> Value::Dict::FindBoolByDottedPath(StringPiece path) const { @@ -1096,7 +1095,7 @@ } Value* Value::FindKeyOfType(StringPiece key, Type type) { - return const_cast<Value*>(as_const(*this).FindKeyOfType(key, type)); + return const_cast<Value*>(std::as_const(*this).FindKeyOfType(key, type)); } const Value* Value::FindKeyOfType(StringPiece key, Type type) const { @@ -1194,10 +1193,6 @@ return GetDict().FindByDottedPath(path); } -Value* Value::FindPathOfType(StringPiece path, Type type) { - return const_cast<Value*>(as_const(*this).FindPathOfType(path, type)); -} - const Value* Value::FindPathOfType(StringPiece path, Type type) const { const Value* cur = FindPath(path); if (!cur || cur->type() != type) @@ -1230,7 +1225,7 @@ } Value* Value::FindDictPath(StringPiece path) { - return FindPathOfType(path, Type::DICTIONARY); + return const_cast<Value*>(std::as_const(*this).FindDictPath(path)); } const Value* Value::FindListPath(StringPiece path) const { @@ -1238,7 +1233,7 @@ } Value* Value::FindListPath(StringPiece path) { - return FindPathOfType(path, Type::LIST); + return const_cast<Value*>(std::as_const(*this).FindListPath(path)); } Value* Value::SetPath(StringPiece path, Value&& value) { @@ -1283,11 +1278,11 @@ // DEPRECATED METHODS Value* Value::FindPath(std::initializer_list<StringPiece> path) { - return const_cast<Value*>(as_const(*this).FindPath(path)); + return const_cast<Value*>(std::as_const(*this).FindPath(path)); } Value* Value::FindPath(span<const StringPiece> path) { - return const_cast<Value*>(as_const(*this).FindPath(path)); + return const_cast<Value*>(std::as_const(*this).FindPath(path)); } const Value* Value::FindPath(std::initializer_list<StringPiece> path) const { @@ -1306,11 +1301,11 @@ Value* Value::FindPathOfType(std::initializer_list<StringPiece> path, Type type) { - return const_cast<Value*>(as_const(*this).FindPathOfType(path, type)); + return const_cast<Value*>(std::as_const(*this).FindPathOfType(path, type)); } Value* Value::FindPathOfType(span<const StringPiece> path, Type type) { - return const_cast<Value*>(as_const(*this).FindPathOfType(path, type)); + return const_cast<Value*>(std::as_const(*this).FindPathOfType(path, type)); } const Value* Value::FindPathOfType(std::initializer_list<StringPiece> path, @@ -1722,7 +1717,7 @@ } bool DictionaryValue::Get(StringPiece path, Value** out_value) { - return as_const(*this).Get(path, const_cast<const Value**>(out_value)); + return std::as_const(*this).Get(path, const_cast<const Value**>(out_value)); } bool DictionaryValue::GetInteger(StringPiece path, int* out_value) const { @@ -1763,7 +1758,7 @@ bool DictionaryValue::GetDictionary(StringPiece path, DictionaryValue** out_value) { - return as_const(*this).GetDictionary( + return std::as_const(*this).GetDictionary( path, const_cast<const DictionaryValue**>(out_value)); } @@ -1781,8 +1776,8 @@ } bool DictionaryValue::GetList(StringPiece path, ListValue** out_value) { - return as_const(*this).GetList(path, - const_cast<const ListValue**>(out_value)); + return std::as_const(*this).GetList(path, + const_cast<const ListValue**>(out_value)); } void DictionaryValue::Swap(DictionaryValue* other) {
diff --git a/base/values.h b/base/values.h index 9324d9cb..e9950da 100644 --- a/base/values.h +++ b/base/values.h
@@ -864,7 +864,6 @@ // // DEPRECATED: Use `Value::Dict::FindBoolByDottedPath()`, // `Value::Dict::FindIntByDottedPath()`, et cetera. - Value* FindPathOfType(StringPiece path, Type type); const Value* FindPathOfType(StringPiece path, Type type) const; // Convenience accessors used when the expected type of a value is known.
diff --git a/base/values_unittest.cc b/base/values_unittest.cc index 73388a2..bde2b69 100644 --- a/base/values_unittest.cc +++ b/base/values_unittest.cc
@@ -16,7 +16,6 @@ #include <utility> #include <vector> -#include "base/as_const.h" #include "base/bits.h" #include "base/containers/adapters.h" #include "base/containers/contains.h"
diff --git a/build/config/mac/mac_sdk.gni b/build/config/mac/mac_sdk.gni index 98bedab..d39350e 100644 --- a/build/config/mac/mac_sdk.gni +++ b/build/config/mac/mac_sdk.gni
@@ -40,6 +40,11 @@ # will fail. mac_sdk_official_version = "12.3" + # The SDK build version used when making official builds. This is a single + # exact version found at "System/Library/CoreServices/SystemVersion.plist" + # inside the SDK. + mac_sdk_official_build_version = "21E226" + # Production builds should use hermetic Xcode. If you want to do production # builds with system Xcode to test new SDKs, set this. # Don't set this on any bots. @@ -103,11 +108,13 @@ find_sdk_args = [ "--print_sdk_path", "--print_bin_path", + "--print_sdk_build", mac_sdk_min, ] find_sdk_lines = exec_script("//build/mac/find_sdk.py", find_sdk_args, "list lines") - mac_sdk_version = find_sdk_lines[2] + mac_sdk_version = find_sdk_lines[3] + mac_sdk_build_version = find_sdk_lines[2] if (mac_sdk_path == "") { mac_sdk_path = find_sdk_lines[0] mac_bin_path = find_sdk_lines[1] @@ -116,6 +123,7 @@ } } else { mac_sdk_version = mac_sdk_official_version + mac_sdk_build_version = mac_sdk_official_build_version _dev = _hermetic_xcode_path + "/Contents/Developer" _sdk = "MacOSX${mac_sdk_version}.sdk" mac_sdk_path = _dev + "/Platforms/MacOSX.platform/Developer/SDKs/$_sdk"
diff --git a/build/config/mac/rules.gni b/build/config/mac/rules.gni index fbd84cc..f613a04 100644 --- a/build/config/mac/rules.gni +++ b/build/config/mac/rules.gni
@@ -41,7 +41,7 @@ apple_info_plist(target_name) { format = "xml1" extra_substitutions = [ - "MAC_SDK_BUILD=$mac_sdk_version", + "MAC_SDK_BUILD=$mac_sdk_build_version", "MAC_SDK_NAME=$mac_sdk_name$mac_sdk_version", "MACOSX_DEPLOYMENT_TARGET=$mac_deployment_target", "CHROMIUM_MIN_SYSTEM_VERSION=$mac_min_system_version",
diff --git a/build/config/posix/BUILD.gn b/build/config/posix/BUILD.gn index b02a084..8312d7ec 100644 --- a/build/config/posix/BUILD.gn +++ b/build/config/posix/BUILD.gn
@@ -33,12 +33,12 @@ # when turning the sysroot on or off. (defines are passed via the command # line, and build system rebuilds things when their commandline # changes). Nothing should ever read this define. - sysroot_hash = + sysroot_key = exec_script("//build/linux/sysroot_scripts/install-sysroot.py", - [ "--print-hash=$current_cpu" ], + [ "--print-key=$current_cpu" ], "trim string", [ "//build/linux/sysroot_scripts/sysroots.json" ]) - defines += [ "CR_SYSROOT_HASH=$sysroot_hash" ] + defines += [ "CR_SYSROOT_KEY=$sysroot_key" ] } asmflags += sysroot_flags ldflags += sysroot_flags
diff --git a/build/fuchsia/linux_internal.sdk.sha1 b/build/fuchsia/linux_internal.sdk.sha1 index fb5867f..dc1fa37 100644 --- a/build/fuchsia/linux_internal.sdk.sha1 +++ b/build/fuchsia/linux_internal.sdk.sha1
@@ -1 +1 @@ -9.20221006.4.1 +9.20221006.5.1
diff --git a/build/linux/chrome.map b/build/linux/chrome.map index 3038318..c84a0ca 100644 --- a/build/linux/chrome.map +++ b/build/linux/chrome.map
@@ -83,13 +83,6 @@ localtime64_r; localtime_r; - # getaddrinfo() is exported by the sandbox to ensure the network service and - # other sandboxed processes don't try to run system DNS resolution - # in-process, which is not supported by the sandbox. This override - # uses dlsym(getaddrinfo) to make the real calls in unsandboxed - # processes. - getaddrinfo; - v8dbg_*; local:
diff --git a/build/linux/sysroot_scripts/build_and_upload.py b/build/linux/sysroot_scripts/build_and_upload.py index df0374aa..dd5bac92 100755 --- a/build/linux/sysroot_scripts/build_and_upload.py +++ b/build/linux/sysroot_scripts/build_and_upload.py
@@ -40,7 +40,7 @@ return subprocess.check_output(args, encoding='utf-8').strip() -def build_and_upload(script_path, distro, release, arch, lock): +def build_and_upload(script_path, distro, release, key, arch, lock): script_dir = os.path.dirname(os.path.realpath(__file__)) run_script([script_path, 'BuildSysroot' + arch]) @@ -56,6 +56,7 @@ 'Tarball': tarball, 'Sha1Sum': sha1sum, 'SysrootDir': sysroot_dir, + 'Key': key, } with lock: fname = os.path.join(script_dir, 'sysroots.json') @@ -76,11 +77,12 @@ script_path = os.path.join(script_dir, filename) distro = get_proc_output([script_path, 'PrintDistro']) release = get_proc_output([script_path, 'PrintRelease']) + key = get_proc_output([script_path, 'PrintKey']) architectures = get_proc_output([script_path, 'PrintArchitectures']) for arch in architectures.split('\n'): - proc = multiprocessing.Process( - target=build_and_upload, - args=(script_path, distro, release, arch, lock)) + proc = multiprocessing.Process(target=build_and_upload, + args=(script_path, distro, release, key, + arch, lock)) procs.append(("%s %s (%s)" % (distro, release, arch), proc)) proc.start() for _, proc in procs:
diff --git a/build/linux/sysroot_scripts/install-sysroot.py b/build/linux/sysroot_scripts/install-sysroot.py index 7c18388..d7e36862 100755 --- a/build/linux/sysroot_scripts/install-sysroot.py +++ b/build/linux/sysroot_scripts/install-sysroot.py
@@ -80,14 +80,15 @@ parser.add_option('--all', action='store_true', help='Install all sysroot images (useful when updating the' ' images)') - parser.add_option('--print-hash', + parser.add_option('--print-key', help='Print the hash of the sysroot for the given arch.') options, _ = parser.parse_args(args) - if options.print_hash: - arch = options.print_hash - print(GetSysrootDict(DEFAULT_TARGET_PLATFORM, - ARCH_TRANSLATIONS.get(arch, arch))['Sha1Sum']) + if options.print_key: + arch = options.print_key + print( + GetSysrootDict(DEFAULT_TARGET_PLATFORM, + ARCH_TRANSLATIONS.get(arch, arch))['Key']) return 0 if options.arch: InstallSysroot(DEFAULT_TARGET_PLATFORM,
diff --git a/build/linux/sysroot_scripts/libdbus-1-3-symbols b/build/linux/sysroot_scripts/libdbus-1-3-symbols deleted file mode 100644 index 28050aa5..0000000 --- a/build/linux/sysroot_scripts/libdbus-1-3-symbols +++ /dev/null
@@ -1,235 +0,0 @@ -libdbus-1.so.3 libdbus-1-3 #MINVER# - dbus_address_entries_free@Base 1.0.2 - dbus_address_entry_get_method@Base 1.0.2 - dbus_address_entry_get_value@Base 1.0.2 - dbus_address_escape_value@Base 1.0.2 - dbus_address_unescape_value@Base 1.0.2 - dbus_bus_add_match@Base 1.0.2 - dbus_bus_get@Base 1.0.2 - dbus_bus_get_id@Base 1.1.1 - dbus_bus_get_private@Base 1.0.2 - dbus_bus_get_unique_name@Base 1.0.2 - dbus_bus_get_unix_user@Base 1.0.2 - dbus_bus_name_has_owner@Base 1.0.2 - dbus_bus_register@Base 1.0.2 - dbus_bus_release_name@Base 1.0.2 - dbus_bus_remove_match@Base 1.0.2 - dbus_bus_request_name@Base 1.0.2 - dbus_bus_set_unique_name@Base 1.0.2 - dbus_bus_start_service_by_name@Base 1.0.2 - dbus_connection_add_filter@Base 1.0.2 - dbus_connection_allocate_data_slot@Base 1.0.2 - dbus_connection_borrow_message@Base 1.0.2 - dbus_connection_can_send_type@Base 1.3.1 - dbus_connection_close@Base 1.0.2 - dbus_connection_dispatch@Base 1.0.2 - dbus_connection_flush@Base 1.0.2 - dbus_connection_free_data_slot@Base 1.0.2 - dbus_connection_free_preallocated_send@Base 1.0.2 - dbus_connection_get_adt_audit_session_data@Base 1.2.4 - dbus_connection_get_data@Base 1.0.2 - dbus_connection_get_dispatch_status@Base 1.0.2 - dbus_connection_get_is_anonymous@Base 1.1.1 - dbus_connection_get_is_authenticated@Base 1.0.2 - dbus_connection_get_is_connected@Base 1.0.2 - dbus_connection_get_max_message_size@Base 1.0.2 - dbus_connection_get_max_message_unix_fds@Base 1.3.1 - dbus_connection_get_max_received_size@Base 1.0.2 - dbus_connection_get_max_received_unix_fds@Base 1.3.1 - dbus_connection_get_object_path_data@Base 1.0.2 - dbus_connection_get_outgoing_size@Base 1.0.2 - dbus_connection_get_outgoing_unix_fds@Base 1.3.1 - dbus_connection_get_server_id@Base 1.1.1 - dbus_connection_get_socket@Base 1.0.2 - dbus_connection_get_unix_fd@Base 1.0.2 - dbus_connection_get_unix_process_id@Base 1.0.2 - dbus_connection_get_unix_user@Base 1.0.2 - dbus_connection_get_windows_user@Base 1.1.1 - dbus_connection_has_messages_to_send@Base 1.0.2 - dbus_connection_list_registered@Base 1.0.2 - dbus_connection_open@Base 1.0.2 - dbus_connection_open_private@Base 1.0.2 - dbus_connection_pop_message@Base 1.0.2 - dbus_connection_preallocate_send@Base 1.0.2 - dbus_connection_read_write@Base 1.0.2 - dbus_connection_read_write_dispatch@Base 1.0.2 - dbus_connection_ref@Base 1.0.2 - dbus_connection_register_fallback@Base 1.0.2 - dbus_connection_register_object_path@Base 1.0.2 - dbus_connection_remove_filter@Base 1.0.2 - dbus_connection_return_message@Base 1.0.2 - dbus_connection_send@Base 1.0.2 - dbus_connection_send_preallocated@Base 1.0.2 - dbus_connection_send_with_reply@Base 1.0.2 - dbus_connection_send_with_reply_and_block@Base 1.0.2 - dbus_connection_set_allow_anonymous@Base 1.1.1 - dbus_connection_set_change_sigpipe@Base 1.0.2 - dbus_connection_set_data@Base 1.0.2 - dbus_connection_set_dispatch_status_function@Base 1.0.2 - dbus_connection_set_exit_on_disconnect@Base 1.0.2 - dbus_connection_set_max_message_size@Base 1.0.2 - dbus_connection_set_max_message_unix_fds@Base 1.3.1 - dbus_connection_set_max_received_size@Base 1.0.2 - dbus_connection_set_max_received_unix_fds@Base 1.3.1 - dbus_connection_set_route_peer_messages@Base 1.0.2 - dbus_connection_set_timeout_functions@Base 1.0.2 - dbus_connection_set_unix_user_function@Base 1.0.2 - dbus_connection_set_wakeup_main_function@Base 1.0.2 - dbus_connection_set_watch_functions@Base 1.0.2 - dbus_connection_set_windows_user_function@Base 1.1.1 - dbus_connection_steal_borrowed_message@Base 1.0.2 - dbus_connection_try_register_fallback@Base 1.1.4 - dbus_connection_try_register_object_path@Base 1.1.4 - dbus_connection_unref@Base 1.0.2 - dbus_connection_unregister_object_path@Base 1.0.2 - dbus_error_free@Base 1.0.2 - dbus_error_has_name@Base 1.0.2 - dbus_error_init@Base 1.0.2 - dbus_error_is_set@Base 1.0.2 - dbus_free@Base 1.0.2 - dbus_free_string_array@Base 1.0.2 - dbus_get_local_machine_id@Base 1.0.2 - dbus_get_version@Base 1.1.4 - dbus_internal_do_not_use_create_uuid@Base 1.0.2 - dbus_internal_do_not_use_get_uuid@Base 1.0.2 - dbus_malloc0@Base 1.0.2 - dbus_malloc@Base 1.0.2 - dbus_message_allocate_data_slot@Base 1.0.2 - dbus_message_append_args@Base 1.0.2 - dbus_message_append_args_valist@Base 1.0.2 - dbus_message_contains_unix_fds@Base 1.3.1 - dbus_message_copy@Base 1.0.2 - dbus_message_demarshal@Base 1.1.1 - dbus_message_demarshal_bytes_needed@Base 1.2.14 - dbus_message_free_data_slot@Base 1.0.2 - dbus_message_get_args@Base 1.0.2 - dbus_message_get_args_valist@Base 1.0.2 - dbus_message_get_auto_start@Base 1.0.2 - dbus_message_get_data@Base 1.0.2 - dbus_message_get_destination@Base 1.0.2 - dbus_message_get_error_name@Base 1.0.2 - dbus_message_get_interface@Base 1.0.2 - dbus_message_get_member@Base 1.0.2 - dbus_message_get_no_reply@Base 1.0.2 - dbus_message_get_path@Base 1.0.2 - dbus_message_get_path_decomposed@Base 1.0.2 - dbus_message_get_reply_serial@Base 1.0.2 - dbus_message_get_sender@Base 1.0.2 - dbus_message_get_serial@Base 1.0.2 - dbus_message_get_signature@Base 1.0.2 - dbus_message_get_type@Base 1.0.2 - dbus_message_has_destination@Base 1.0.2 - dbus_message_has_interface@Base 1.0.2 - dbus_message_has_member@Base 1.0.2 - dbus_message_has_path@Base 1.0.2 - dbus_message_has_sender@Base 1.0.2 - dbus_message_has_signature@Base 1.0.2 - dbus_message_is_error@Base 1.0.2 - dbus_message_is_method_call@Base 1.0.2 - dbus_message_is_signal@Base 1.0.2 - dbus_message_iter_abandon_container@Base 1.2.16 - dbus_message_iter_append_basic@Base 1.0.2 - dbus_message_iter_append_fixed_array@Base 1.0.2 - dbus_message_iter_close_container@Base 1.0.2 - dbus_message_iter_get_arg_type@Base 1.0.2 - dbus_message_iter_get_array_len@Base 1.0.2 - dbus_message_iter_get_basic@Base 1.0.2 - dbus_message_iter_get_element_type@Base 1.0.2 - dbus_message_iter_get_fixed_array@Base 1.0.2 - dbus_message_iter_get_signature@Base 1.0.2 - dbus_message_iter_has_next@Base 1.0.2 - dbus_message_iter_init@Base 1.0.2 - dbus_message_iter_init_append@Base 1.0.2 - dbus_message_iter_next@Base 1.0.2 - dbus_message_iter_open_container@Base 1.0.2 - dbus_message_iter_recurse@Base 1.0.2 - dbus_message_lock@Base 1.2.14 - dbus_message_marshal@Base 1.1.1 - dbus_message_new@Base 1.0.2 - dbus_message_new_error@Base 1.0.2 - dbus_message_new_error_printf@Base 1.0.2 - dbus_message_new_method_call@Base 1.0.2 - dbus_message_new_method_return@Base 1.0.2 - dbus_message_new_signal@Base 1.0.2 - dbus_message_ref@Base 1.0.2 - dbus_message_set_auto_start@Base 1.0.2 - dbus_message_set_data@Base 1.0.2 - dbus_message_set_destination@Base 1.0.2 - dbus_message_set_error_name@Base 1.0.2 - dbus_message_set_interface@Base 1.0.2 - dbus_message_set_member@Base 1.0.2 - dbus_message_set_no_reply@Base 1.0.2 - dbus_message_set_path@Base 1.0.2 - dbus_message_set_reply_serial@Base 1.0.2 - dbus_message_set_sender@Base 1.0.2 - dbus_message_set_serial@Base 1.2.14 - dbus_message_type_from_string@Base 1.0.2 - dbus_message_type_to_string@Base 1.0.2 - dbus_message_unref@Base 1.0.2 - dbus_move_error@Base 1.0.2 - dbus_parse_address@Base 1.0.2 - dbus_pending_call_allocate_data_slot@Base 1.0.2 - dbus_pending_call_block@Base 1.0.2 - dbus_pending_call_cancel@Base 1.0.2 - dbus_pending_call_free_data_slot@Base 1.0.2 - dbus_pending_call_get_completed@Base 1.0.2 - dbus_pending_call_get_data@Base 1.0.2 - dbus_pending_call_ref@Base 1.0.2 - dbus_pending_call_set_data@Base 1.0.2 - dbus_pending_call_set_notify@Base 1.0.2 - dbus_pending_call_steal_reply@Base 1.0.2 - dbus_pending_call_unref@Base 1.0.2 - dbus_realloc@Base 1.0.2 - dbus_server_allocate_data_slot@Base 1.0.2 - dbus_server_disconnect@Base 1.0.2 - dbus_server_free_data_slot@Base 1.0.2 - dbus_server_get_address@Base 1.0.2 - dbus_server_get_data@Base 1.0.2 - dbus_server_get_id@Base 1.1.1 - dbus_server_get_is_connected@Base 1.0.2 - dbus_server_listen@Base 1.0.2 - dbus_server_ref@Base 1.0.2 - dbus_server_set_auth_mechanisms@Base 1.0.2 - dbus_server_set_data@Base 1.0.2 - dbus_server_set_new_connection_function@Base 1.0.2 - dbus_server_set_timeout_functions@Base 1.0.2 - dbus_server_set_watch_functions@Base 1.0.2 - dbus_server_unref@Base 1.0.2 - dbus_set_error@Base 1.0.2 - dbus_set_error_const@Base 1.0.2 - dbus_set_error_from_message@Base 1.0.2 - dbus_setenv@Base 1.7.6 - dbus_shutdown@Base 1.0.2 - dbus_signature_iter_get_current_type@Base 1.0.2 - dbus_signature_iter_get_element_type@Base 1.0.2 - dbus_signature_iter_get_signature@Base 1.0.2 - dbus_signature_iter_init@Base 1.0.2 - dbus_signature_iter_next@Base 1.0.2 - dbus_signature_iter_recurse@Base 1.0.2 - dbus_signature_validate@Base 1.0.2 - dbus_signature_validate_single@Base 1.0.2 - dbus_threads_init@Base 1.0.2 - dbus_threads_init_default@Base 1.0.2 - dbus_timeout_get_data@Base 1.0.2 - dbus_timeout_get_enabled@Base 1.0.2 - dbus_timeout_get_interval@Base 1.0.2 - dbus_timeout_handle@Base 1.0.2 - dbus_timeout_set_data@Base 1.0.2 - dbus_type_is_basic@Base 1.0.2 - dbus_type_is_container@Base 1.0.2 - dbus_type_is_fixed@Base 1.0.2 - dbus_type_is_valid@Base 1.5.0 - dbus_validate_bus_name@Base 1.5.12 - dbus_validate_error_name@Base 1.5.12 - dbus_validate_interface@Base 1.5.12 - dbus_validate_member@Base 1.5.12 - dbus_validate_path@Base 1.5.12 - dbus_validate_utf8@Base 1.5.12 - dbus_watch_get_data@Base 1.0.2 - dbus_watch_get_enabled@Base 1.0.2 - dbus_watch_get_fd@Base 1.0.2 - dbus_watch_get_flags@Base 1.0.2 - dbus_watch_get_socket@Base 1.1.1 - dbus_watch_get_unix_fd@Base 1.1.1 - dbus_watch_handle@Base 1.0.2 - dbus_watch_set_data@Base 1.0.2
diff --git a/build/linux/sysroot_scripts/libxkbcommon0-symbols b/build/linux/sysroot_scripts/libxkbcommon0-symbols deleted file mode 100644 index 5750fc0..0000000 --- a/build/linux/sysroot_scripts/libxkbcommon0-symbols +++ /dev/null
@@ -1,93 +0,0 @@ -libxkbcommon.so.0 libxkbcommon0 #MINVER# - xkb_context_get_log_level@Base 0.4.1 - xkb_context_get_log_verbosity@Base 0.4.1 - xkb_context_get_user_data@Base 0.4.1 - xkb_context_include_path_append@Base 0.4.1 - xkb_context_include_path_append_default@Base 0.4.1 - xkb_context_include_path_clear@Base 0.4.1 - xkb_context_include_path_get@Base 0.4.1 - xkb_context_include_path_reset_defaults@Base 0.4.1 - xkb_context_new@Base 0.4.1 - xkb_context_num_include_paths@Base 0.4.1 - xkb_context_ref@Base 0.4.1 - xkb_context_set_log_fn@Base 0.4.1 - xkb_context_set_log_level@Base 0.4.1 - xkb_context_set_log_verbosity@Base 0.4.1 - xkb_context_set_user_data@Base 0.4.1 - xkb_context_unref@Base 0.4.1 - xkb_key_get_syms@Base 0.4.1 - xkb_key_mod_index_is_consumed@Base 0.4.1 - xkb_key_mod_mask_remove_consumed@Base 0.4.1 - xkb_key_num_groups@Base 0.4.1 - xkb_key_repeats@Base 0.4.1 - xkb_keymap_get_as_string@Base 0.4.1 - xkb_keymap_key_for_each@Base 0.4.1 - xkb_keymap_key_get_syms_by_level@Base 0.4.1 - xkb_keymap_key_repeats@Base 0.4.1 - xkb_keymap_layout_get_index@Base 0.4.1 - xkb_keymap_layout_get_name@Base 0.4.1 - xkb_keymap_led_get_index@Base 0.4.1 - xkb_keymap_led_get_name@Base 0.4.1 - xkb_keymap_max_keycode@Base 0.4.1 - xkb_keymap_min_keycode@Base 0.4.1 - xkb_keymap_mod_get_index@Base 0.4.1 - xkb_keymap_mod_get_name@Base 0.4.1 - xkb_keymap_new_from_buffer@Base 0.4.1 - xkb_keymap_new_from_file@Base 0.4.1 - xkb_keymap_new_from_names@Base 0.4.1 - xkb_keymap_new_from_string@Base 0.4.1 - xkb_keymap_num_layouts@Base 0.4.1 - xkb_keymap_num_layouts_for_key@Base 0.4.1 - xkb_keymap_num_leds@Base 0.4.1 - xkb_keymap_num_levels_for_key@Base 0.4.1 - xkb_keymap_num_mods@Base 0.4.1 - xkb_keymap_ref@Base 0.4.1 - xkb_keymap_unref@Base 0.4.1 - xkb_keysym_from_name@Base 0.4.1 - xkb_keysym_get_name@Base 0.4.1 - xkb_keysym_to_utf32@Base 0.4.1 - xkb_keysym_to_utf8@Base 0.4.1 - xkb_map_get_as_string@Base 0.4.1 - xkb_map_group_get_index@Base 0.4.1 - xkb_map_group_get_name@Base 0.4.1 - xkb_map_led_get_index@Base 0.4.1 - xkb_map_led_get_name@Base 0.4.1 - xkb_map_mod_get_index@Base 0.4.1 - xkb_map_mod_get_name@Base 0.4.1 - xkb_map_new_from_file@Base 0.4.1 - xkb_map_new_from_names@Base 0.4.1 - xkb_map_new_from_string@Base 0.4.1 - xkb_map_num_groups@Base 0.4.1 - xkb_map_num_leds@Base 0.4.1 - xkb_map_num_mods@Base 0.4.1 - xkb_map_ref@Base 0.4.1 - xkb_map_unref@Base 0.4.1 - xkb_state_get_keymap@Base 0.4.1 - xkb_state_get_map@Base 0.4.1 - xkb_state_group_index_is_active@Base 0.4.1 - xkb_state_group_name_is_active@Base 0.4.1 - xkb_state_key_get_consumed_mods@Base 0.4.1 - xkb_state_key_get_layout@Base 0.4.1 - xkb_state_key_get_level@Base 0.4.1 - xkb_state_key_get_one_sym@Base 0.4.1 - xkb_state_key_get_syms@Base 0.4.1 - xkb_state_key_get_utf32@Base 0.4.1 - xkb_state_key_get_utf8@Base 0.4.1 - xkb_state_layout_index_is_active@Base 0.4.1 - xkb_state_layout_name_is_active@Base 0.4.1 - xkb_state_led_index_is_active@Base 0.4.1 - xkb_state_led_name_is_active@Base 0.4.1 - xkb_state_mod_index_is_active@Base 0.4.1 - xkb_state_mod_index_is_consumed@Base 0.4.1 - xkb_state_mod_indices_are_active@Base 0.4.1 - xkb_state_mod_mask_remove_consumed@Base 0.4.1 - xkb_state_mod_name_is_active@Base 0.4.1 - xkb_state_mod_names_are_active@Base 0.4.1 - xkb_state_new@Base 0.4.1 - xkb_state_ref@Base 0.4.1 - xkb_state_serialize_group@Base 0.4.1 - xkb_state_serialize_layout@Base 0.4.1 - xkb_state_serialize_mods@Base 0.4.1 - xkb_state_unref@Base 0.4.1 - xkb_state_update_key@Base 0.4.1 - xkb_state_update_mask@Base 0.4.1
diff --git a/build/linux/sysroot_scripts/reversion_glibc.py b/build/linux/sysroot_scripts/reversion_glibc.py index 61d5a63..8651386 100755 --- a/build/linux/sysroot_scripts/reversion_glibc.py +++ b/build/linux/sysroot_scripts/reversion_glibc.py
@@ -10,8 +10,10 @@ import subprocess import sys -# This constant comes from https://crbug.com/580892 -MAX_ALLOWED_GLIBC_VERSION = [2, 17] +# This constant comes from the oldest glibc version in +# //chrome/installer/linux/debian/dist_package_versions.json and +# //chrome/installer/linux/rpm/dist_package_provides.json +MAX_ALLOWED_GLIBC_VERSION = [2, 26] VERSION_PATTERN = re.compile('GLIBC_([0-9\.]+)') SECTION_PATTERN = re.compile(r'^ *\[ *[0-9]+\] +(\S+) +\S+ + ([0-9a-f]+) .*$')
diff --git a/build/linux/sysroot_scripts/sysroot-creator-bullseye.sh b/build/linux/sysroot_scripts/sysroot-creator-bullseye.sh index 9ee2f98d..87584eb2 100755 --- a/build/linux/sysroot_scripts/sysroot-creator-bullseye.sh +++ b/build/linux/sysroot_scripts/sysroot-creator-bullseye.sh
@@ -8,6 +8,11 @@ DISTRO=debian DIST=bullseye +# This number is appended to the sysroot key to cause full rebuilds. It +# should be incremented when removing packages or patching existing packages. +# It should not be incremented when adding packages. +SYSROOT_RELEASE=0 + ARCHIVE_TIMESTAMP=20220331T153654Z ARCHIVE_URL="https://snapshot.debian.org/archive/debian/$ARCHIVE_TIMESTAMP/" APT_SOURCES_LIST=(
diff --git a/build/linux/sysroot_scripts/sysroot-creator.sh b/build/linux/sysroot_scripts/sysroot-creator.sh index 4220cd3..bf9b435 100644 --- a/build/linux/sysroot_scripts/sysroot-creator.sh +++ b/build/linux/sysroot_scripts/sysroot-creator.sh
@@ -330,52 +330,23 @@ # Remove an unnecessary dependency on qtchooser. rm "${INSTALL_ROOT}/usr/lib/${arch}-${os}/qt-default/qtchooser/default.conf" - # Unversion libdbus and libxkbcommon symbols. This is required because - # libdbus-1-3 and libxkbcommon0 switched from unversioned symbols to versioned - # ones, and we must still support distros using the unversioned library. This - # hack can be removed once support for Ubuntu Trusty and Debian Jessie are - # dropped. - ${strip} -R .gnu.version_d -R .gnu.version \ - "${INSTALL_ROOT}/lib/${arch}-${os}/libdbus-1.so.3" - cp "${SCRIPT_DIR}/libdbus-1-3-symbols" \ - "${INSTALL_ROOT}/debian/libdbus-1-3/DEBIAN/symbols" - - ${strip} -R .gnu.version_d -R .gnu.version \ - "${INSTALL_ROOT}/usr/lib/${arch}-${os}/libxkbcommon.so.0.0.0" - cp "${SCRIPT_DIR}/libxkbcommon0-symbols" \ - "${INSTALL_ROOT}/debian/libxkbcommon0/DEBIAN/symbols" - # libxcomposite1 is missing a symbols file. cp "${SCRIPT_DIR}/libxcomposite1-symbols" \ "${INSTALL_ROOT}/debian/libxcomposite1/DEBIAN/symbols" - # Shared objects depending on libdbus-1.so.3 have unsatisfied undefined - # versioned symbols. To avoid LLD --no-allow-shlib-undefined errors, rewrite - # DT_NEEDED entries from libdbus-1.so.3 to a different string. LLD will - # suppress --no-allow-shlib-undefined diagnostics for such shared objects. - set +e - for f in "${INSTALL_ROOT}/lib/${arch}-${os}"/*.so \ - "${INSTALL_ROOT}/usr/lib/${arch}-${os}"/*.so; do - echo "$f" | grep -q 'libdbus-1.so$' && continue - # In a dependent shared object, the only occurrence of "libdbus-1.so.3" is - # the string referenced by the DT_NEEDED entry. - offset=$(LANG=C grep -abo libdbus-1.so.3 "$f") - [ -n "$offset" ] || continue - echo -n 'libdbus-1.so.0' | dd of="$f" conv=notrunc bs=1 \ - seek="$(echo -n "$offset" | cut -d : -f 1)" status=none - done - set -e + # __GLIBC_MINOR__ is used as a feature test macro. Replace it with the + # earliest supported version of glibc (2.26, obtained from the oldest glibc + # version in //chrome/installer/linux/debian/dist_packag_versions.json and + # //chrome/installer/linux/rpm/dist_package_provides.json). + local usr_include="${INSTALL_ROOT}/usr/include" + local features_h="${usr_include}/features.h" + sed -i 's|\(#define\s\+__GLIBC_MINOR__\)|\1 26 //|' "${features_h}" # fcntl64() was introduced in glibc 2.28. Make sure to use fcntl() instead. local fcntl_h="${INSTALL_ROOT}/usr/include/fcntl.h" sed -i '{N; s/#ifndef __USE_FILE_OFFSET64\(\nextern int fcntl\)/#if 1\1/}' \ "${fcntl_h}" - # __GLIBC_MINOR__ is used as a feature test macro. Replace it with the - # earliest supported version of glibc (2.17, https://crbug.com/376567). - local usr_include="${INSTALL_ROOT}/usr/include" - local features_h="${usr_include}/features.h" - sed -i 's|\(#define\s\+__GLIBC_MINOR__\)|\1 17 //|' "${features_h}" # Do not use pthread_cond_clockwait as it was introduced in glibc 2.30. local cppconfig_h="${usr_include}/${arch}-${os}/c++/10/bits/c++config.h" sed -i 's|\(#define\s\+_GLIBCXX_USE_PTHREAD_COND_CLOCKWAIT\)|// \1|' \ @@ -956,13 +927,21 @@ } #@ -#@ DumpRelease +#@ PrintRelease #@ -#@ Prints disto release. eg: jessie +#@ Prints disto release. eg: bullseye PrintRelease() { echo ${DIST} } +#@ +#@ PrintKey +#@ +#@ Prints sysroot key identifier. +PrintKey() { + echo "${ARCHIVE_TIMESTAMP}-${SYSROOT_RELEASE}" +} + RunCommand() { SetEnvironmentVariables "$1" SanityCheck
diff --git a/build/linux/sysroot_scripts/sysroots.json b/build/linux/sysroot_scripts/sysroots.json index 0549eaa..d06a94d3 100644 --- a/build/linux/sysroot_scripts/sysroots.json +++ b/build/linux/sysroot_scripts/sysroots.json
@@ -1,36 +1,43 @@ { "bullseye_amd64": { - "Sha1Sum": "393193b824afacfcd2fb53cb47fc2023740f4995", + "Key": "20220331T153654Z-0", + "Sha1Sum": "5ebc72fdaf206572cdc6664b7e78a8eb38d7f526", "SysrootDir": "debian_bullseye_amd64-sysroot", "Tarball": "debian_bullseye_amd64_sysroot.tar.xz" }, "bullseye_arm": { - "Sha1Sum": "1b097e2e837d7a0b81ae42c8ff6e473dbd24256d", + "Key": "20220331T153654Z-0", + "Sha1Sum": "85f072ac9cb695ca34685a40e8b3fe37a2891951", "SysrootDir": "debian_bullseye_arm-sysroot", "Tarball": "debian_bullseye_arm_sysroot.tar.xz" }, "bullseye_arm64": { - "Sha1Sum": "3a98f836c7a3386dd757268cd07c427f9e6c7c86", + "Key": "20220331T153654Z-0", + "Sha1Sum": "e5afb40447cef513ff99c772449048b73d7a28ff", "SysrootDir": "debian_bullseye_arm64-sysroot", "Tarball": "debian_bullseye_arm64_sysroot.tar.xz" }, "bullseye_armel": { - "Sha1Sum": "1ff91eb5b00cfc857d4ea99d45f32fd5df303292", + "Key": "20220331T153654Z-0", + "Sha1Sum": "18ca043c9e4adc5bd8a352e35e2db671ac3ed089", "SysrootDir": "debian_bullseye_armel-sysroot", "Tarball": "debian_bullseye_armel_sysroot.tar.xz" }, "bullseye_i386": { - "Sha1Sum": "af39443b6101f4c417bb83113a306fc028d2b665", + "Key": "20220331T153654Z-0", + "Sha1Sum": "bb5c9d52f69a97fc934f2b269375dcba0c7db8dc", "SysrootDir": "debian_bullseye_i386-sysroot", "Tarball": "debian_bullseye_i386_sysroot.tar.xz" }, "bullseye_mips": { - "Sha1Sum": "9ca3ace5b108e3078dee4b2f5d395f685a909acc", + "Key": "20220331T153654Z-0", + "Sha1Sum": "354f0d8aafe7d034f50287b840b3dff967d9a2a1", "SysrootDir": "debian_bullseye_mips-sysroot", "Tarball": "debian_bullseye_mips_sysroot.tar.xz" }, "bullseye_mips64el": { - "Sha1Sum": "9a5e7d0868f363f526675487568ab35a7254bdd5", + "Key": "20220331T153654Z-0", + "Sha1Sum": "3b52b8b86138b2392daf915928f29281000e2461", "SysrootDir": "debian_bullseye_mips64el-sysroot", "Tarball": "debian_bullseye_mips64el_sysroot.tar.xz" }
diff --git a/build/mac/find_sdk.py b/build/mac/find_sdk.py index bb36874f..50c1e3c1 100755 --- a/build/mac/find_sdk.py +++ b/build/mac/find_sdk.py
@@ -24,6 +24,7 @@ from __future__ import print_function import os +import plistlib import re import subprocess import sys @@ -51,6 +52,9 @@ parser.add_option("--print_bin_path", action="store_true", dest="print_bin_path", default=False, help="Additionally print the path the toolchain bin dir.") + parser.add_option("--print_sdk_build", + action="store_true", dest="print_sdk_build", default=False, + help="Additionally print the build version of the SDK.") options, args = parser.parse_args() if len(args) != 1: parser.error('Please specify a minimum SDK version') @@ -80,20 +84,30 @@ if not sdks: raise Exception('No %s+ SDK found' % min_sdk_version) best_sdk = sorted(sdks, key=parse_version)[0] + sdk_name = 'MacOSX' + best_sdk + '.sdk' + sdk_path = os.path.join(sdk_dir, sdk_name) if options.print_sdk_path: - sdk_name = 'MacOSX' + best_sdk + '.sdk' - print(os.path.join(sdk_dir, sdk_name)) + print(sdk_path) if options.print_bin_path: bin_path = 'Toolchains/XcodeDefault.xctoolchain/usr/bin/' print(os.path.join(dev_dir, bin_path)) - return best_sdk + if options.print_sdk_build: + system_version_plist = os.path.join(sdk_path, + 'System/Library/CoreServices/SystemVersion.plist') + with open(system_version_plist, 'rb') as f: + system_version_info = plistlib.load(f) + if 'ProductBuildVersion' not in system_version_info: + raise Exception('Failed to determine ProductBuildVersion' + + 'for SDK at path %s' % system_version_plist) + print(system_version_info['ProductBuildVersion']) + + print(best_sdk) if __name__ == '__main__': if sys.platform != 'darwin': raise Exception("This script only runs on Mac") - print(main()) - sys.exit(0) + sys.exit(main())
diff --git a/cc/layers/surface_layer.cc b/cc/layers/surface_layer.cc index 8426b3c..f85d61c 100644 --- a/cc/layers/surface_layer.cc +++ b/cc/layers/surface_layer.cc
@@ -154,6 +154,13 @@ if (layer_tree_host() == host) { return; } + + // Any time we change trees, start out as "not visible". If drawing starts, + // then the impl layer can call it again with correct visibility. + auto callback = update_submission_state_callback_.Read(*this); + if (callback) + callback.Run(false, nullptr); + if (layer_tree_host() && surface_range_.Read(*this).IsValid()) layer_tree_host()->RemoveSurfaceRange(surface_range_.Read(*this));
diff --git a/cc/layers/surface_layer_impl.cc b/cc/layers/surface_layer_impl.cc index 15e29759..71584f2 100644 --- a/cc/layers/surface_layer_impl.cc +++ b/cc/layers/surface_layer_impl.cc
@@ -50,8 +50,13 @@ std::move(update_submission_state_callback)) {} SurfaceLayerImpl::~SurfaceLayerImpl() { - if (update_submission_state_callback_) - update_submission_state_callback_.Run(false, nullptr); + // Do not call `update_submission_state_callback_` here. There is only very + // loose synchronization between when a layer gets a new impl layer and when + // the old layer is destroyed. For example, when a layer is moved to a new + // tree, the old tree's impl layer might be destroyed after drawing has + // started in the new tree with a new impl layer. In that case, we'd be + // clobbering the visibility state. Instead, trust that SurfaceLayer has done + // the right thing already. } std::unique_ptr<LayerImpl> SurfaceLayerImpl::CreateLayerImpl(
diff --git a/chrome/VERSION b/chrome/VERSION index d99e62e2..0d73eb2 100644 --- a/chrome/VERSION +++ b/chrome/VERSION
@@ -1,4 +1,4 @@ MAJOR=108 MINOR=0 -BUILD=5345 +BUILD=5346 PATCH=0
diff --git a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabUiFeatureUtilities.java b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabUiFeatureUtilities.java index bc4bc4ff..7609223 100644 --- a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabUiFeatureUtilities.java +++ b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabUiFeatureUtilities.java
@@ -170,7 +170,8 @@ return DeviceFormFactor.isNonMultiDisplayContextOnTablet(context) && ChromeFeatureList.sGridTabSwitcherForTablets.isEnabled() && ChromeFeatureList.sTabStripImprovements.isEnabled() - && ChromeFeatureList.sTabGroupsForTablets.isEnabled(); + && ChromeFeatureList.sTabGroupsForTablets.isEnabled() + && !DeviceClassManager.enableAccessibilityLayout(context); } /**
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/app/appmenu/AppMenuPropertiesDelegateImpl.java b/chrome/android/java/src/org/chromium/chrome/browser/app/appmenu/AppMenuPropertiesDelegateImpl.java index 274f6db..7d5ba8f 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/app/appmenu/AppMenuPropertiesDelegateImpl.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/app/appmenu/AppMenuPropertiesDelegateImpl.java
@@ -619,15 +619,12 @@ } if (item.getItemId() == R.id.new_incognito_tab_menu_id && item.isVisible()) { - // Disable new incognito tab when a re-authentication might be pending. - boolean isIncognitoReauthPending = (mIncognitoReauthController != null) - && mIncognitoReauthController.isIncognitoReauthPending(); - // Disable new incognito tab when it is blocked (e.g. by a policy). // findItem(...).setEnabled(...)" is not enough here, because of the inflated // main_menu.xml contains multiple items with the same id in different groups // e.g.: menu_new_incognito_tab. - item.setEnabled(isIncognitoEnabled() && !isIncognitoReauthPending); + // Disable new incognito tab when a re-authentication might be showing. + item.setEnabled(isIncognitoEnabled() && !isIncognitoReauthShowing); } if (item.getItemId() == R.id.divider_line_id) {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/StripLayoutHelper.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/StripLayoutHelper.java index 6a50906..e71021d7 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/StripLayoutHelper.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/StripLayoutHelper.java
@@ -220,7 +220,6 @@ // Experiment flags private final boolean mTabStripImpEnabled; - private final boolean mTabGroupsEnabled; /** * Creates an instance of the {@link StripLayoutHelper}. @@ -293,7 +292,6 @@ mTabMenu.setWidth(menuWidth); mTabMenu.setModal(true); - mTabGroupsEnabled = TabUiFeatureUtilities.isTabGroupsAndroidEnabled(mContext); mShouldCascadeTabs = DeviceFormFactor.isNonMultiDisplayContextOnTablet(context) && !mTabStripImpEnabled; mStripStacker = mShouldCascadeTabs ? mCascadingStripStacker : mScrollingStripStacker; @@ -1755,7 +1753,7 @@ calculateOffsetToMakeTabVisible(mInteractingTab, true, true, true, true); mScroller.startScroll(Math.round(mScrollOffset), 0, (int) fastExpandDelta, 0, time, getExpandDuration()); - } else if (mTabGroupsEnabled) { + } else if (TabUiFeatureUtilities.isTabletTabGroupsEnabled(mContext)) { Tab tab = getTabById(mInteractingTab.getId()); computeAndUpdateTabGroupMargins(true, true); setTabGroupDimmed(mTabGroupModelFilter.getRootId(tab), false); @@ -1784,7 +1782,7 @@ setBackgroundTabsDimmed(false); // 4. Clear any tab group margins if they are enabled. - if (mTabGroupsEnabled) resetTabGroupMargins(); + if (TabUiFeatureUtilities.isTabletTabGroupsEnabled(mContext)) resetTabGroupMargins(); // 5. Request an update. mUpdateHost.requestUpdate(); @@ -1960,7 +1958,7 @@ } private void setTabGroupDimmed(int groupId, boolean dimmed) { - assert mTabGroupsEnabled; + assert TabUiFeatureUtilities.isTabletTabGroupsEnabled(mContext); for (int i = 0; i < mStripTabs.length; i++) { final StripLayoutTab tab = mStripTabs[i]; @@ -2111,7 +2109,7 @@ int destIndex = TabModel.INVALID_TAB_INDEX; boolean isAnimating = mRunningAnimator != null && mRunningAnimator.isRunning(); boolean towardEnd = (offset >= 0) ^ LocalizationUtils.isLayoutRtl(); - boolean isInGroup = mTabGroupsEnabled + boolean isInGroup = TabUiFeatureUtilities.isTabletTabGroupsEnabled(mContext) && mTabGroupModelFilter.hasOtherRelatedTabs(getTabById(mInteractingTab.getId())); boolean hasTrailingMargin = mInteractingTab.getTrailingMargin() == mTabMarginWidth; boolean hasStartingMargin = curIndex == 0 @@ -2164,7 +2162,9 @@ // 3.c. Re-compute tab group margins if necessary. float oldIdealX = mInteractingTab.getIdealX(); float oldOffset = mScrollOffset; - if (mTabGroupsEnabled) computeAndUpdateTabGroupMargins(false, false); + if (TabUiFeatureUtilities.isTabletTabGroupsEnabled(mContext)) { + computeAndUpdateTabGroupMargins(false, false); + } // 3.d. Since we just moved the tab we're dragging, adjust its offset so it stays in // the same apparent position.
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/segmentation_platform/ContextualPageActionController.java b/chrome/android/java/src/org/chromium/chrome/browser/segmentation_platform/ContextualPageActionController.java index dd3913a2..798c1b7 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/segmentation_platform/ContextualPageActionController.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/segmentation_platform/ContextualPageActionController.java
@@ -4,14 +4,9 @@ package org.chromium.chrome.browser.segmentation_platform; -import android.content.res.Configuration; -import android.content.res.Resources; - import org.chromium.base.Callback; import org.chromium.base.annotations.NativeMethods; import org.chromium.base.supplier.ObservableSupplier; -import org.chromium.chrome.browser.lifecycle.ActivityLifecycleDispatcher; -import org.chromium.chrome.browser.lifecycle.ConfigurationChangedObserver; import org.chromium.chrome.browser.profiles.Profile; import org.chromium.chrome.browser.tab.CurrentTabObserver; import org.chromium.chrome.browser.tab.EmptyTabObserver; @@ -28,13 +23,11 @@ * segmentation platform for on-demand model execution on page load triggers. Provides updated * button data to the toolbar when asked for it. */ -public class ContextualPageActionController implements ConfigurationChangedObserver { +public class ContextualPageActionController { private final ObservableSupplier<Profile> mProfileSupplier; private final ObservableSupplier<Tab> mTabSupplier; - private final ActivityLifecycleDispatcher mActivityLifecycleDispatcher; private final AdaptiveToolbarButtonController mAdaptiveToolbarButtonController; private CurrentTabObserver mCurrentTabObserver; - private int mScreenWidthDp; /** * Constructor. @@ -45,11 +38,9 @@ */ public ContextualPageActionController(ObservableSupplier<Profile> profileSupplier, ObservableSupplier<Tab> tabSupplier, - ActivityLifecycleDispatcher activityLifecycleDispatcher, Resources resources, AdaptiveToolbarButtonController adaptiveToolbarButtonController) { mProfileSupplier = profileSupplier; mTabSupplier = tabSupplier; - mActivityLifecycleDispatcher = activityLifecycleDispatcher; mAdaptiveToolbarButtonController = adaptiveToolbarButtonController; profileSupplier.addObserver(profile -> { if (profile.isOffTheRecord()) return; @@ -70,14 +61,11 @@ } }, this::activeTabChanged); }); - mScreenWidthDp = resources.getConfiguration().screenWidthDp; - mActivityLifecycleDispatcher.register(this); } /** Called on destroy. */ public void destroy() { if (mCurrentTabObserver != null) mCurrentTabObserver.destroy(); - mActivityLifecycleDispatcher.unregister(this); } private void activeTabChanged(Tab tab) { @@ -90,8 +78,7 @@ private void maybeShowContextualPageAction() { Tab tab = mTabSupplier.get(); - if (tab == null || tab.isIncognito() || tab.isDestroyed() - || !isScreenWideEnoughForButton()) { + if (tab == null || tab.isIncognito() || tab.isDestroyed()) { // On incognito tabs revert back to static action. mAdaptiveToolbarButtonController.showDynamicAction( AdaptiveToolbarButtonVariant.UNKNOWN); @@ -114,28 +101,6 @@ }); } - private boolean isScreenWideEnoughForButton() { - return mScreenWidthDp >= AdaptiveToolbarFeatures.getDeviceMinimumWidthForShowingButton(); - } - - @Override - public void onConfigurationChanged(Configuration newConfig) { - if (!mActivityLifecycleDispatcher.isNativeInitializationFinished() - || !AdaptiveToolbarFeatures.isContextualPageActionsEnabled()) { - return; - } - if (mScreenWidthDp == newConfig.screenWidthDp) return; - - boolean isOldScreenWideEnoughForButton = isScreenWideEnoughForButton(); - - mScreenWidthDp = newConfig.screenWidthDp; - - // If the new width changes the button's visibility then update it. - if (isOldScreenWideEnoughForButton != isScreenWideEnoughForButton()) { - maybeShowContextualPageAction(); - } - } - @NativeMethods interface Natives { void computeContextualPageAction(
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/segmentation_platform/ContextualPageActionControllerTest.java b/chrome/android/java/src/org/chromium/chrome/browser/segmentation_platform/ContextualPageActionControllerTest.java index 4e6a20c2..88b50ea 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/segmentation_platform/ContextualPageActionControllerTest.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/segmentation_platform/ContextualPageActionControllerTest.java
@@ -7,7 +7,6 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -20,7 +19,6 @@ import org.junit.Test; import org.junit.rules.TestRule; import org.junit.runner.RunWith; -import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; @@ -32,7 +30,6 @@ import org.chromium.base.supplier.ObservableSupplierImpl; import org.chromium.base.test.BaseRobolectricTestRunner; import org.chromium.base.test.util.Features; -import org.chromium.base.test.util.Features.DisableFeatures; import org.chromium.base.test.util.Features.EnableFeatures; import org.chromium.base.test.util.JniMocker; import org.chromium.chrome.browser.flags.ChromeFeatureList; @@ -91,9 +88,8 @@ private ContextualPageActionController createContextualPageActionController() { ContextualPageActionController contextualPageActionController = - new ContextualPageActionController(mProfileSupplier, mTabSupplier, - mMockActivityLifecycleDispatcher, mMockResources, - mMockAdaptiveToolbarController); + new ContextualPageActionController( + mProfileSupplier, mTabSupplier, mMockAdaptiveToolbarController); mProfileSupplier.set(mMockProfile); @@ -168,112 +164,4 @@ // Even if the UI is disabled segmentation should be called. verify(mMockControllerJni).computeContextualPageAction(any(), any(), any()); } - - @Test - public void testButtonOnLargeScreens() { - mMockConfiguration.screenWidthDp = 450; - setMockSegmentationResult( - SegmentId.OPTIMIZATION_TARGET_CONTEXTUAL_PAGE_ACTION_PRICE_TRACKING); - - ContextualPageActionController contextualPageActionController = - createContextualPageActionController(); - - mTabSupplier.set(mMockTab); - - verify(mMockAdaptiveToolbarController) - .showDynamicAction(AdaptiveToolbarButtonVariant.PRICE_TRACKING); - } - - @Test - public void testButtonNotShownOnSmallScreens() { - mMockConfiguration.screenWidthDp = 320; - - ContextualPageActionController contextualPageActionController = - createContextualPageActionController(); - - mTabSupplier.set(mMockTab); - - verify(mMockAdaptiveToolbarController) - .showDynamicAction(AdaptiveToolbarButtonVariant.UNKNOWN); - verify(mMockControllerJni, never()).computeContextualPageAction(any(), any(), any()); - } - - @Test - @DisableFeatures({ChromeFeatureList.CONTEXTUAL_PAGE_ACTION_PRICE_TRACKING}) - public void testConfigurationChangeIgnoredWhenFeatureIsDisabled() { - mMockConfiguration.screenWidthDp = 600; - setMockSegmentationResult( - SegmentId.OPTIMIZATION_TARGET_CONTEXTUAL_PAGE_ACTION_PRICE_TRACKING); - - ContextualPageActionController contextualPageActionController = - createContextualPageActionController(); - - // Set tab, no button should be shown because feature is disabled. - mTabSupplier.set(mMockTab); - - // Change configuration, no button should be shown still. - mMockConfiguration.screenWidthDp = 450; - contextualPageActionController.onConfigurationChanged(mMockConfiguration); - - // Button should not be updated. - verify(mMockAdaptiveToolbarController, never()).showDynamicAction(anyInt()); - // Segmentation should not be called. - verify(mMockControllerJni, never()).computeContextualPageAction(any(), any(), any()); - } - - @Test - public void testConfigurationChangeIgnoredWhenNativeNotReady() { - mMockConfiguration.screenWidthDp = 600; - setMockSegmentationResult( - SegmentId.OPTIMIZATION_TARGET_CONTEXTUAL_PAGE_ACTION_PRICE_TRACKING); - doReturn(false).when(mMockActivityLifecycleDispatcher).isNativeInitializationFinished(); - - ContextualPageActionController contextualPageActionController = - createContextualPageActionController(); - - mTabSupplier.set(mMockTab); - - // Change configuration, button shouldn't update, and segmentation shouldn't be called. - mMockConfiguration.screenWidthDp = 450; - contextualPageActionController.onConfigurationChanged(mMockConfiguration); - - // Button should only be updated once when setting the tab. - verify(mMockAdaptiveToolbarController) - .showDynamicAction(AdaptiveToolbarButtonVariant.PRICE_TRACKING); - // Segmentation should only be called once. - verify(mMockControllerJni).computeContextualPageAction(any(), any(), any()); - } - - @Test - public void testButtonShowsOnConfigurationChange() { - // Screen is not wide enough to show button. - mMockConfiguration.screenWidthDp = 320; - setMockSegmentationResult( - SegmentId.OPTIMIZATION_TARGET_CONTEXTUAL_PAGE_ACTION_PRICE_TRACKING); - - ContextualPageActionController contextualPageActionController = - createContextualPageActionController(); - - mTabSupplier.set(mMockTab); - - // Screen is now wide enough to show button. - mMockConfiguration.screenWidthDp = 600; - contextualPageActionController.onConfigurationChanged(mMockConfiguration); - - // Return to original screen width. - mMockConfiguration.screenWidthDp = 320; - contextualPageActionController.onConfigurationChanged(mMockConfiguration); - - InOrder inOrder = inOrder(mMockAdaptiveToolbarController); - - inOrder.verify(mMockAdaptiveToolbarController) - .showDynamicAction(AdaptiveToolbarButtonVariant.UNKNOWN); - inOrder.verify(mMockAdaptiveToolbarController) - .showDynamicAction(AdaptiveToolbarButtonVariant.PRICE_TRACKING); - inOrder.verify(mMockAdaptiveToolbarController) - .showDynamicAction(AdaptiveToolbarButtonVariant.UNKNOWN); - - // Segmentation should only be called once. - verify(mMockControllerJni).computeContextualPageAction(any(), any(), any()); - } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/share/ShareButtonController.java b/chrome/android/java/src/org/chromium/chrome/browser/share/ShareButtonController.java index 56525c1a..d51b1af 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/share/ShareButtonController.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/share/ShareButtonController.java
@@ -4,26 +4,17 @@ package org.chromium.chrome.browser.share; -import android.content.Context; -import android.content.res.Configuration; import android.graphics.drawable.Drawable; -import android.view.View.OnClickListener; +import android.view.View; -import org.chromium.base.FeatureList; -import org.chromium.base.ObserverList; import org.chromium.base.metrics.RecordUserAction; import org.chromium.base.supplier.ObservableSupplier; import org.chromium.base.supplier.Supplier; import org.chromium.chrome.R; import org.chromium.chrome.browser.ActivityTabProvider; -import org.chromium.chrome.browser.lifecycle.ActivityLifecycleDispatcher; -import org.chromium.chrome.browser.lifecycle.ConfigurationChangedObserver; import org.chromium.chrome.browser.share.ShareDelegate.ShareOrigin; import org.chromium.chrome.browser.tab.Tab; -import org.chromium.chrome.browser.toolbar.ButtonData; -import org.chromium.chrome.browser.toolbar.ButtonDataImpl; -import org.chromium.chrome.browser.toolbar.ButtonDataProvider; -import org.chromium.chrome.browser.toolbar.adaptive.AdaptiveToolbarFeatures; +import org.chromium.chrome.browser.toolbar.BaseButtonDataProvider; import org.chromium.chrome.browser.toolbar.adaptive.AdaptiveToolbarFeatures.AdaptiveToolbarButtonVariant; import org.chromium.chrome.browser.user_education.IPHCommandBuilder; import org.chromium.components.browser_ui.widget.highlight.ViewHighlighter.HighlightParams; @@ -33,187 +24,82 @@ import org.chromium.components.feature_engagement.Tracker; import org.chromium.components.ukm.UkmRecorder; import org.chromium.ui.modaldialog.ModalDialogManager; -import org.chromium.ui.modaldialog.ModalDialogManager.ModalDialogManagerObserver; -import org.chromium.ui.modelutil.PropertyModel; /** * Handles displaying share button on toolbar depending on several conditions (e.g.,device width, * whether NTP is shown). */ -public class ShareButtonController implements ButtonDataProvider, ConfigurationChangedObserver { - // Context is used for fetching resources and launching preferences page. - private final Context mContext; - +public class ShareButtonController extends BaseButtonDataProvider { private final ShareUtils mShareUtils; private final ObservableSupplier<ShareDelegate> mShareDelegateSupplier; private final Supplier<Tracker> mTrackerSupplier; - - private ActivityLifecycleDispatcher mActivityLifecycleDispatcher; - - // The activity tab provider. - private ActivityTabProvider mTabProvider; - - private ButtonDataImpl mButtonData; - private ObserverList<ButtonDataObserver> mObservers = new ObserverList<>(); - private OnClickListener mOnClickListener; - - private ModalDialogManager mModalDialogManager; - private ModalDialogManagerObserver mModalDialogManagerObserver; - - private int mScreenWidthDp; + private final Runnable mOnShareRunnable; /** * Creates ShareButtonController object. - * @param context The Context for retrieving resources, etc. * @param buttonDrawable Drawable for the new tab button. * @param tabProvider The {@link ActivityTabProvider} used for accessing the tab. * @param shareDelegateSupplier The supplier to get a handle on the share delegate. * @param trackerSupplier Supplier for the current profile tracker. * @param shareUtils The share utility functions used by this class. - * @param activityLifecycleDispatcher Dispatcher for activity lifecycle events, e.g. - * configuration changes. * @param modalDialogManager dispatcher for modal lifecycles events * @param onShareRunnable A {@link Runnable} to execute when a share event occurs. This object * does not actually handle sharing, but can provide supplemental * functionality when the share button is pressed. */ - public ShareButtonController(Context context, Drawable buttonDrawable, - ActivityTabProvider tabProvider, + public ShareButtonController(Drawable buttonDrawable, ActivityTabProvider tabProvider, ObservableSupplier<ShareDelegate> shareDelegateSupplier, Supplier<Tracker> trackerSupplier, ShareUtils shareUtils, - ActivityLifecycleDispatcher activityLifecycleDispatcher, ModalDialogManager modalDialogManager, Runnable onShareRunnable) { - mContext = context; + super(tabProvider, modalDialogManager, buttonDrawable, R.string.share, + /*supportsTinting=*/true, + /*iphCommandBuilder=*/null, AdaptiveToolbarButtonVariant.SHARE); - mActivityLifecycleDispatcher = activityLifecycleDispatcher; - mActivityLifecycleDispatcher.register(this); - mTabProvider = tabProvider; mShareUtils = shareUtils; - mShareDelegateSupplier = shareDelegateSupplier; mTrackerSupplier = trackerSupplier; - mOnClickListener = ((view) -> { - ShareDelegate shareDelegate = mShareDelegateSupplier.get(); - assert shareDelegate - != null : "Share delegate became null after share button was displayed"; - if (shareDelegate == null) return; - Tab tab = mTabProvider.get(); - assert tab != null : "Tab became null after share button was displayed"; - if (tab == null) return; - if (onShareRunnable != null) onShareRunnable.run(); - RecordUserAction.record("MobileTopToolbarShareButton"); - if (tab.getWebContents() != null) { - new UkmRecorder.Bridge().recordEventWithBooleanMetric( - tab.getWebContents(), "TopToolbar.Share", "HasOccurred"); - } - shareDelegate.share(tab, /*shareDirectly=*/false, ShareOrigin.TOP_TOOLBAR); - - if (mTrackerSupplier.hasValue()) { - mTrackerSupplier.get().notifyEvent( - EventConstants.ADAPTIVE_TOOLBAR_CUSTOMIZATION_SHARE_OPENED); - } - }); - - mModalDialogManagerObserver = new ModalDialogManagerObserver() { - @Override - public void onDialogAdded(PropertyModel model) { - mButtonData.setEnabled(false); - notifyObservers(mButtonData.canShow()); - } - - @Override - public void onLastDialogDismissed() { - mButtonData.setEnabled(true); - notifyObservers(mButtonData.canShow()); - } - }; - mModalDialogManager = modalDialogManager; - mModalDialogManager.addObserver(mModalDialogManagerObserver); - - mButtonData = new ButtonDataImpl(/*canShow=*/false, buttonDrawable, mOnClickListener, - R.string.share, /*supportsTinting=*/true, - /*iphCommandBuilder=*/null, /*isEnabled=*/true, AdaptiveToolbarButtonVariant.SHARE); - - mScreenWidthDp = mContext.getResources().getConfiguration().screenWidthDp; + mOnShareRunnable = onShareRunnable; } @Override - public void onConfigurationChanged(Configuration configuration) { - if (mScreenWidthDp == configuration.screenWidthDp) { - return; + public void onClick(View view) { + ShareDelegate shareDelegate = mShareDelegateSupplier.get(); + assert shareDelegate + != null : "Share delegate became null after share button was displayed"; + if (shareDelegate == null) return; + Tab tab = mActiveTabSupplier.get(); + assert tab != null : "Tab became null after share button was displayed"; + if (tab == null) return; + if (mOnShareRunnable != null) mOnShareRunnable.run(); + RecordUserAction.record("MobileTopToolbarShareButton"); + if (tab.getWebContents() != null) { + new UkmRecorder.Bridge().recordEventWithBooleanMetric( + tab.getWebContents(), "TopToolbar.Share", "HasOccurred"); } - mScreenWidthDp = configuration.screenWidthDp; - updateButtonVisibility(mTabProvider.get()); - notifyObservers(mButtonData.canShow()); - } + shareDelegate.share(tab, /*shareDirectly=*/false, ShareOrigin.TOP_TOOLBAR); - @Override - public void destroy() { - if (mActivityLifecycleDispatcher != null) { - mActivityLifecycleDispatcher.unregister(this); - mActivityLifecycleDispatcher = null; - } - if (mModalDialogManagerObserver != null && mModalDialogManager != null) { - mModalDialogManager.removeObserver(mModalDialogManagerObserver); - mModalDialogManagerObserver = null; - mModalDialogManager = null; + if (mTrackerSupplier.hasValue()) { + mTrackerSupplier.get().notifyEvent( + EventConstants.ADAPTIVE_TOOLBAR_CUSTOMIZATION_SHARE_OPENED); } } @Override - public void addObserver(ButtonDataObserver obs) { - mObservers.addObserver(obs); - } + protected boolean shouldShowButton(Tab tab) { + if (!super.shouldShowButton(tab) || mShareDelegateSupplier.get() == null) return false; - @Override - public void removeObserver(ButtonDataObserver obs) { - mObservers.removeObserver(obs); - } - - @Override - public ButtonData get(Tab tab) { - updateButtonVisibility(tab); - maybeSetIphCommandBuilder(tab); - return mButtonData; - } - - private void updateButtonVisibility(Tab tab) { - if (tab == null || tab.getWebContents() == null || mTabProvider == null - || mTabProvider.get() == null) { - mButtonData.setCanShow(false); - return; - } - - final boolean isDeviceWideEnough = - mScreenWidthDp >= AdaptiveToolbarFeatures.getDeviceMinimumWidthForShowingButton(); - if (mShareDelegateSupplier.get() == null || !isDeviceWideEnough) { - mButtonData.setCanShow(false); - return; - } - - mButtonData.setCanShow(mShareUtils.shouldEnableShare(tab)); - } - - private void notifyObservers(boolean hint) { - for (ButtonDataObserver observer : mObservers) { - observer.buttonDataChanged(hint); - } + return mShareUtils.shouldEnableShare(tab); } /** - * Since Features are not yet initialized when ButtonData is created, use the - * fist available opportunity to create and set IPHCommandBuilder. Once set it's - * never updated. + * Returns an IPH for this button. Only called once native is initialized and when {@code + * AdaptiveToolbarFeatures.isCustomizationEnabled()} is true. + * @param tab Current tab. */ - private void maybeSetIphCommandBuilder(Tab tab) { - if (mButtonData.getButtonSpec().getIPHCommandBuilder() != null || tab == null - || !FeatureList.isInitialized() - || !AdaptiveToolbarFeatures.isCustomizationEnabled()) { - return; - } - + @Override + protected IPHCommandBuilder getIphCommandBuilder(Tab tab) { HighlightParams params = new HighlightParams(HighlightShape.CIRCLE); params.setBoundsRespectPadding(true); IPHCommandBuilder iphCommandBuilder = new IPHCommandBuilder(tab.getContext().getResources(), @@ -221,6 +107,6 @@ /* stringId = */ R.string.adaptive_toolbar_button_share_iph, /* accessibilityStringId = */ R.string.adaptive_toolbar_button_share_iph) .setHighlightParams(params); - mButtonData.updateIPHCommandBuilder(iphCommandBuilder); + return iphCommandBuilder; } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ui/RootUiCoordinator.java b/chrome/android/java/src/org/chromium/chrome/browser/ui/RootUiCoordinator.java index 0337ca2..66221606 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ui/RootUiCoordinator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ui/RootUiCoordinator.java
@@ -1108,13 +1108,16 @@ mIdentityDiscController = new IdentityDiscController( mActivity, mActivityLifecycleDispatcher, mProfileSupplier); PriceTrackingButtonController priceTrackingButtonController = - new PriceTrackingButtonController( - mActivity, mActivityTabProvider, mTabBookmarkerSupplier); - ShareButtonController shareButtonController = new ShareButtonController(mActivity, + new PriceTrackingButtonController(mActivityTabProvider, + mModalDialogManagerSupplier.get(), + AppCompatResources.getDrawable( + mActivity, R.drawable.price_tracking_disabled), + mTabBookmarkerSupplier); + ShareButtonController shareButtonController = new ShareButtonController( AppCompatResources.getDrawable( mActivity, R.drawable.ic_toolbar_share_offset_24dp), mActivityTabProvider, mShareDelegateSupplier, trackerSupplier, new ShareUtils(), - mActivityLifecycleDispatcher, mModalDialogManagerSupplier.get(), + mModalDialogManagerSupplier.get(), () -> mToolbarManager.setUrlBarFocus(false, OmniboxFocusReason.UNFOCUS)); VoiceToolbarButtonController.VoiceSearchDelegate voiceSearchDelegate = new VoiceToolbarButtonController.VoiceSearchDelegate() { @@ -1136,15 +1139,15 @@ } }; VoiceToolbarButtonController voiceToolbarButtonController = - new VoiceToolbarButtonController(mActivity, + new VoiceToolbarButtonController( AppCompatResources.getDrawable(mActivity, R.drawable.btn_mic), - mActivityTabProvider, trackerSupplier, mActivityLifecycleDispatcher, + mActivityTabProvider, trackerSupplier, mModalDialogManagerSupplier.get(), voiceSearchDelegate); OptionalNewTabButtonController newTabButtonController = new OptionalNewTabButtonController(mActivity, AppCompatResources.getDrawable(mActivity, R.drawable.new_tab_icon), mActivityLifecycleDispatcher, mTabCreatorManagerSupplier, - mTabModelSelectorSupplier, trackerSupplier); + mActivityTabProvider, trackerSupplier); AdaptiveToolbarButtonController adaptiveToolbarButtonController = new AdaptiveToolbarButtonController(mActivity, new SettingsLauncherImpl(), mActivityLifecycleDispatcher, new AdaptiveButtonActionMenuCoordinator(), @@ -1157,9 +1160,8 @@ AdaptiveToolbarButtonVariant.VOICE, voiceToolbarButtonController); adaptiveToolbarButtonController.addButtonVariant( AdaptiveToolbarButtonVariant.PRICE_TRACKING, priceTrackingButtonController); - mContextualPageActionController = new ContextualPageActionController(mProfileSupplier, - mActivityTabProvider, mActivityLifecycleDispatcher, mActivity.getResources(), - adaptiveToolbarButtonController); + mContextualPageActionController = new ContextualPageActionController( + mProfileSupplier, mActivityTabProvider, adaptiveToolbarButtonController); mButtonDataProviders = Arrays.asList(mIdentityDiscController, adaptiveToolbarButtonController);
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/toolbar/adaptive/OptionalNewTabButtonControllerPhoneTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/toolbar/adaptive/OptionalNewTabButtonControllerPhoneTest.java index d6cafe2..336ad76 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/toolbar/adaptive/OptionalNewTabButtonControllerPhoneTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/toolbar/adaptive/OptionalNewTabButtonControllerPhoneTest.java
@@ -6,6 +6,7 @@ import static androidx.test.espresso.Espresso.onView; import static androidx.test.espresso.action.ViewActions.click; +import static androidx.test.espresso.assertion.ViewAssertions.matches; import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed; import static androidx.test.espresso.matcher.ViewMatchers.isEnabled; import static androidx.test.espresso.matcher.ViewMatchers.isRoot; @@ -129,9 +130,16 @@ sActivityTestRule.getActivity(), Configuration.ORIENTATION_LANDSCAPE); sActivityTestRule.loadUrl(mTestPageUrl, /*secondsToWait=*/10); - onViewWaiting(allOf(withId(R.id.optional_toolbar_button), isDisplayed(), isEnabled(), - withContentDescription(mButtonDescription))) - .perform(click()); + // Check view exists and is set up correctly. + onViewWaiting(withId(R.id.optional_toolbar_button)) + .check(matches(allOf( + isDisplayed(), isEnabled(), withContentDescription(mButtonDescription)))); + // Clicking with espresso is flaky, perform click directly. + TestThreadUtils.runOnUiThreadBlocking(() -> { + sActivityTestRule.getActivity() + .findViewById(R.id.optional_toolbar_button) + .performClick(); + }); // Expected tabs: // 1: mTestPageUrl
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/app/appmenu/AppMenuPropertiesDelegateUnitTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/app/appmenu/AppMenuPropertiesDelegateUnitTest.java index a53eb0ec..47db25e 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/app/appmenu/AppMenuPropertiesDelegateUnitTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/app/appmenu/AppMenuPropertiesDelegateUnitTest.java
@@ -14,6 +14,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; import android.content.Context; @@ -914,11 +915,12 @@ .withShowAddToHomeScreen() .withAutoDarkEnabled()); - doReturn(true).when(mIncognitoReauthControllerMock).isIncognitoReauthPending(); + doReturn(true).when(mIncognitoReauthControllerMock).isReauthPageShowing(); + doReturn(mIncognitoTabModel).when(mTabModelSelector).getCurrentModel(); Menu menu = createTestMenu(); mAppMenuPropertiesDelegate.prepareMenu(menu, null); - verify(mIncognitoReauthControllerMock, times(1)).isIncognitoReauthPending(); + verify(mIncognitoReauthControllerMock, times(1)).isReauthPageShowing(); MenuItem item = menu.findItem(R.id.new_incognito_tab_menu_id); assertFalse(item.isEnabled()); @@ -926,17 +928,17 @@ @Test @SmallTest - public void testNewIncognitoTabOption_WithReauthIsNotInProgress() { + public void testNewIncognitoTabOption_FromRegularMode_WithReauthNotInProgress() { setUpMocksForPageMenu(); setMenuOptions(new MenuOptions() .withShowTranslate() .withShowAddToHomeScreen() .withAutoDarkEnabled()); - doReturn(false).when(mIncognitoReauthControllerMock).isIncognitoReauthPending(); + doReturn(mTabModel).when(mTabModelSelector).getCurrentModel(); Menu menu = createTestMenu(); mAppMenuPropertiesDelegate.prepareMenu(menu, null); - verify(mIncognitoReauthControllerMock, times(1)).isIncognitoReauthPending(); + verifyZeroInteractions(mIncognitoReauthControllerMock); MenuItem item = menu.findItem(R.id.new_incognito_tab_menu_id); assertTrue(item.isEnabled());
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/share/ShareButtonControllerUnitTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/share/ShareButtonControllerUnitTest.java index 15e6f8a..5ffa6ee 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/share/ShareButtonControllerUnitTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/share/ShareButtonControllerUnitTest.java
@@ -8,7 +8,6 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -106,17 +105,15 @@ doReturn(mConfiguration).when(mResources).getConfiguration(); doReturn(mock(WebContents.class)).when(mTab).getWebContents(); + doReturn("https").when(mMockGurl).getScheme(); doReturn(mMockGurl).when(mTab).getUrl(); doReturn(mShareDelegate).when(mShareDelegateSupplier).get(); AdaptiveToolbarFeatures.clearParsedParamsForTesting(); - mShareButtonController = - new ShareButtonController(mContext, mDrawable, mTabProvider, mShareDelegateSupplier, - () - -> mTracker, - mShareUtils, mActivityLifecycleDispatcher, mModalDialogManager, () -> {}); + mShareButtonController = new ShareButtonController(mDrawable, mTabProvider, + mShareDelegateSupplier, () -> mTracker, mShareUtils, mModalDialogManager, () -> {}); TrackerFactory.setTrackerForTests(mTracker); } @@ -152,29 +149,6 @@ @Test @EnableFeatures({ChromeFeatureList.ADAPTIVE_BUTTON_IN_TOP_TOOLBAR_CUSTOMIZATION_V2}) - public void testDoNotShowWhenTooNarrow() { - mConfiguration.screenWidthDp = AdaptiveToolbarFeatures.DEFAULT_MIN_WIDTH_DP - 1; - mShareButtonController.onConfigurationChanged(mConfiguration); - - ButtonData buttonData = mShareButtonController.get(mTab); - - assertFalse(buttonData.canShow()); - } - - @Test - @EnableFeatures({ChromeFeatureList.ADAPTIVE_BUTTON_IN_TOP_TOOLBAR_CUSTOMIZATION_V2}) - public void testDoShowWhenWideEnough() { - doReturn("https").when(mMockGurl).getScheme(); - mConfiguration.screenWidthDp = AdaptiveToolbarFeatures.DEFAULT_MIN_WIDTH_DP; - mShareButtonController.onConfigurationChanged(mConfiguration); - - ButtonData buttonData = mShareButtonController.get(mTab); - - assertTrue(buttonData.canShow()); - } - - @Test - @EnableFeatures({ChromeFeatureList.ADAPTIVE_BUTTON_IN_TOP_TOOLBAR_CUSTOMIZATION_V2}) public void testDoNotShowOnDataUrl() { doReturn("data").when(mMockGurl).getScheme(); doReturn(mMockGurl).when(mTab).getUrl();
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/toolbar/adaptive/OptionalNewTabButtonControllerActivityTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/toolbar/adaptive/OptionalNewTabButtonControllerActivityTest.java index 9ee324b..e383008 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/toolbar/adaptive/OptionalNewTabButtonControllerActivityTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/toolbar/adaptive/OptionalNewTabButtonControllerActivityTest.java
@@ -9,7 +9,6 @@ import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; import android.content.res.Configuration; import android.content.res.Resources; @@ -42,7 +41,6 @@ import org.chromium.chrome.browser.tabmodel.TabCreatorManager; import org.chromium.chrome.browser.tabmodel.TabModelSelector; import org.chromium.chrome.browser.toolbar.ButtonDataProvider; -import org.chromium.chrome.browser.toolbar.ButtonDataProvider.ButtonDataObserver; import org.chromium.chrome.browser.toolbar.adaptive.AdaptiveToolbarFeatures.AdaptiveToolbarButtonVariant; import org.chromium.chrome.browser.toolbar.top.OptionalBrowsingModeButtonController; import org.chromium.chrome.browser.toolbar.top.TopToolbarCoordinator; @@ -176,86 +174,28 @@ @Test @MediumTest - @Config(qualifiers = "w390dp-h820dp") - public void testRotateLandscape() { - mActivityScenario.onActivity(activity -> { - ButtonDataObserver observer = Mockito.mock(ButtonDataObserver.class); - mAdaptiveButtonController.addObserver(observer); - - assertTrue(mAdaptiveButtonController.get(mTab).canShow()); - - applyQualifiers(activity, "+land"); - - verify(observer).buttonDataChanged(/*canShowHint=*/true); - assertTrue(mAdaptiveButtonController.get(mTab).canShow()); - }); - } - - @Test - @MediumTest - @Config(qualifiers = "w359dp-h820dp") - public void testRotateLandscape_narrow() { - mActivityScenario.onActivity(activity -> { - ButtonDataObserver observer = Mockito.mock(ButtonDataObserver.class); - mAdaptiveButtonController.addObserver(observer); - - // The button needs width of at least 360dp to be visible. - // See OptionalNewTabButtonController#MIN_WIDTH_DP - assertFalse(mAdaptiveButtonController.get(mTab).canShow()); - - applyQualifiers(activity, "+land"); - - verify(observer).buttonDataChanged(/*canShowHint=*/true); - assertTrue(mAdaptiveButtonController.get(mTab).canShow()); - }); - } - - @Test - @MediumTest @Config(qualifiers = "w390dp-h820dp-land") - public void testRotatePortrait() { + public void testAlwaysShownOnPhone() { mActivityScenario.onActivity(activity -> { - ButtonDataObserver observer = Mockito.mock(ButtonDataObserver.class); - mAdaptiveButtonController.addObserver(observer); - assertTrue(mAdaptiveButtonController.get(mTab).canShow()); applyQualifiers(activity, "+port"); - verify(observer).buttonDataChanged(/*canShowHint=*/true); assertTrue(mAdaptiveButtonController.get(mTab).canShow()); }); } @Test @MediumTest - @Config(qualifiers = "w359dp-h820dp-land") - public void testRotatePortrait_narrow() { - mActivityScenario.onActivity(activity -> { - ButtonDataObserver observer = Mockito.mock(ButtonDataObserver.class); - mAdaptiveButtonController.addObserver(observer); - - assertTrue(mAdaptiveButtonController.get(mTab).canShow()); - - applyQualifiers(activity, "+port"); - - // The button needs width of at least 360dp to be visible. - // See OptionalNewTabButtonController#MIN_WIDTH_DP - verify(observer).buttonDataChanged(/*canShowHint=*/false); - assertFalse(mAdaptiveButtonController.get(mTab).canShow()); - }); - } - - @Test - @MediumTest @Config(qualifiers = "w600dp-h820dp") - public void testRotateTablet() { + public void testNeverShownOnTablet() { mActivityScenario.onActivity(activity -> { assertFalse(mAdaptiveButtonController.get(mTab).canShow()); // Rotating a tablet should not change canShow. applyQualifiers(activity, "+land"); + assertFalse(mAdaptiveButtonController.get(mTab).canShow()); }); }
diff --git a/chrome/app/chromeos_strings.grdp b/chrome/app/chromeos_strings.grdp index dfc6566..056ec41 100644 --- a/chrome/app/chromeos_strings.grdp +++ b/chrome/app/chromeos_strings.grdp
@@ -4085,15 +4085,9 @@ I have read and agree to the <ph name="BEGIN_LINK1"><a id="googleEulaLinkArcDisabled"></ph>Google Terms of Service<ph name="END_LINK1"></a></ph> and <ph name="BEGIN_LINK2"><a id="crosEulaLinkArcDisabled"></ph>Chrome and ChromeOS Additional Terms of Service<ph name="END_LINK2"></a></ph>. </message> <message name="IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_TITLE" desc="Title for the message in the consolidated consent screen to opt-in for metrics for accounts."> - Send usage and diagnostic data. + Send diagnostic and usage data. </message> <message name="IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_OWNER" desc="Message in the consolidated consent screen to opt-in for metrics when the user is the device owner."> - Help improve Chrome and ChromeOS features and performance by automatically sending crash reports as well as diagnostic and usage data to Google. Some aggregate data will also help Android apps and Google partners. If the Web & App Activity setting is turned on for your Google Account, your Android data may be saved to your Google Account. - </message> - <message name="IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_CHILD_OWNER" desc="Message in the consolidated consent screen to opt-in for metrics for a child device owner account."> - Help improve Chrome and ChromeOS features and performance by automatically sending crash reports as well as diagnostic and usage data to Google. Some aggregate data will also help Android apps and Google partners. If the Web & App Activity setting is turned on for your child's Google Account, your child's Android data may be saved to your child's Google Account. - </message> - <message name="IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_ARC_DISABLED_OWNER" desc="Message in the consolidated consent screen to opt-in for metrics when ARC is disabled for device owner."> Help improve Chrome and ChromeOS features and performance by automatically sending crash reports as well as diagnostic and usage data to Google. </message> <message name="IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_LINK" desc="Learn more about usage opt in"> @@ -4107,18 +4101,15 @@ <message name="IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_CHILD_OWNER" desc="Text shown in a pop-up dialog in the consolidated consent screen when the user clicks on the learn more for metrics opt-in for a child device owner account."> <ph name="BEGIN_PARAGRAPH1"><p></ph>Allowing ChromeOS devices to send automatic reports helps us prioritize what to fix and improve in ChromeOS. These reports can include things like when ChromeOS crashes, which features were used, how much memory was typically used, and Android app diagnostic and usage data. Some aggregate data will also help Google apps and partners, such as Android developers.<ph name="END_PARAGRAPH1"></p></ph> <ph name="BEGIN_PARAGRAPH2"><p></ph>You can start or stop allowing these reports any time in your child's ChromeOS device settings. If you're a domain administrator, you can change this setting in the admin console.<ph name="END_PARAGRAPH2"></p></ph> - <ph name="BEGIN_PARAGRAPH3"><p></ph>Turning off this feature doesn't affect this device's ability to send the information needed for essential services such as system updates and security.<ph name="END_PARAGRAPH3"></p></ph> <ph name="BEGIN_PARAGRAPH4"><p></ph>If the Web & App Activity setting is turned on for your child's Google Account, your child's data may be saved to their Google Account. Learn more about these settings and how to adjust them at families.google.com.<ph name="END_PARAGRAPH4"></p></ph> </message> <message name="IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_ARC_DISABLED_OWNER" desc="Text shown in a pop-up dialog in the consolidated consent screen when the device owner clicks on the learn more for metrics opt-in when ARC is disabled."> <ph name="BEGIN_PARAGRAPH1"><p></ph>Allowing your ChromeOS devices to send automatic reports helps us prioritize what to fix and improve in ChromeOS. These reports can include things like when ChromeOS crashes, which features you use and how much memory you typically use.<ph name="END_PARAGRAPH1"></p></ph> <ph name="BEGIN_PARAGRAPH2"><p></ph>You can start or stop allowing these reports any time in your Chrome device settings. If you’re a domain administrator, you can change this setting in the admin console.<ph name="END_PARAGRAPH2"></p></ph> - <ph name="BEGIN_PARAGRAPH3"><p></ph>Turning off this feature doesn't affect your device's ability to send the information needed for essential services such as system updates and security.<ph name="END_PARAGRAPH3"></p></ph> </message> <message name="IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_ARC_DISABLED_CHILD_OWNER" desc="Text shown in a pop-up dialog in the consolidated consent screen when the user clicks on the learn more for metrics opt-in when ARC is disabled in a child account."> <ph name="BEGIN_PARAGRAPH1"><p></ph>Allowing ChromeOS devices to send automatic reports helps us prioritize what to fix and improve in ChromeOS. These reports can include things like when ChromeOS crashes, which features were used, and how much memory was typically used.<ph name="END_PARAGRAPH1"></p></ph> <ph name="BEGIN_PARAGRAPH2"><p></ph>You can start or stop allowing these reports any time in your child's ChromeOS device settings. If you're a domain administrator, you can change this setting in the admin console.<ph name="END_PARAGRAPH2"></p></ph> - <ph name="BEGIN_PARAGRAPH3"><p></ph>Turning off this feature doesn't affect this device's ability to send the information needed for essential services such as system updates and security.<ph name="END_PARAGRAPH3"></p></ph> </message> <message name="IDS_CONSOLIDATED_CONSENT_BACKUP_OPT_IN_TITLE" desc="Title for the message in the consolidated consent screen to opt-in for back-up."> Back up Android apps to Google Drive. @@ -4226,7 +4217,7 @@ Google Chrome and ChromeOS Additional Terms </message> <message name="IDS_GUEST_TOS_USAGE_OPT_IN_TITLE" desc="Title for the message in the guest terms of service screen to opt-in for metrics during the guest session."> - Send usage and diagnostic data. + Send diagnostic and usage data. </message> <message name="IDS_GUEST_TOS_USAGE_OPT_IN" desc="Message in the guest terms of service screen to opt-in for metrics during the guest session."> Help improve Chrome and ChromeOS features and performance by automatically sending crash reports as well as diagnostic and usage data to Google. @@ -4237,7 +4228,6 @@ <message name="IDS_GUEST_TOS_USAGE_OPT_IN_LEARN_MORE" desc="Text shown in a pop-up dialog in the guest terms of service screen when the user clicks on the learn more for metrics opt-in."> <ph name="BEGIN_PARAGRAPH1"><p></ph>Allowing ChromeOS devices to send automatic reports helps us prioritize what to fix and improve in ChromeOS. These reports can include things like when ChromeOS crashes, which features were used, and how much memory was typically used.<ph name="END_PARAGRAPH1"></p></ph> <ph name="BEGIN_PARAGRAPH2"><p></ph>You can start or stop allowing these reports any time in your Chrome device settings. If you’re a domain administrator, you can change this setting in the admin console.<ph name="END_PARAGRAPH2"></p></ph> - <ph name="BEGIN_PARAGRAPH3"><p></ph>Turning off this feature doesn't affect your device's ability to send the information needed for essential services such as system updates and security.<ph name="END_PARAGRAPH3"></p></ph> </message> <!-- HW data collection screen -->
diff --git a/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_ARC_DISABLED_OWNER.png.sha1 b/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_ARC_DISABLED_OWNER.png.sha1 deleted file mode 100644 index 05ceeb9e..0000000 --- a/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_ARC_DISABLED_OWNER.png.sha1 +++ /dev/null
@@ -1 +0,0 @@ -f706de24ec66bc308c51855a429f50802c7efe25 \ No newline at end of file
diff --git a/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_CHILD_OWNER.png.sha1 b/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_CHILD_OWNER.png.sha1 deleted file mode 100644 index 613b243f..0000000 --- a/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_CHILD_OWNER.png.sha1 +++ /dev/null
@@ -1 +0,0 @@ -16abf29baa2c74893fb95ae09279fff82688e88f \ No newline at end of file
diff --git a/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_ARC_DISABLED_CHILD_OWNER.png.sha1 b/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_ARC_DISABLED_CHILD_OWNER.png.sha1 index 30aaa0e..14c78f4 100644 --- a/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_ARC_DISABLED_CHILD_OWNER.png.sha1 +++ b/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_ARC_DISABLED_CHILD_OWNER.png.sha1
@@ -1 +1 @@ -89beee08d2e95bda760c09134718b2d71b84c67b \ No newline at end of file +0114258fae1494f73bf58e8333d9a548db35c48d \ No newline at end of file
diff --git a/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_ARC_DISABLED_OWNER.png.sha1 b/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_ARC_DISABLED_OWNER.png.sha1 index 7b99ad4..4de572e 100644 --- a/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_ARC_DISABLED_OWNER.png.sha1 +++ b/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_ARC_DISABLED_OWNER.png.sha1
@@ -1 +1 @@ -5c461c450c910a514b1cfba79db97c1408c276ed \ No newline at end of file +93b129180c81e846686f1b8176ff47fa0590eb5f \ No newline at end of file
diff --git a/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_CHILD_OWNER.png.sha1 b/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_CHILD_OWNER.png.sha1 index 51d625b9..5e3e9cd 100644 --- a/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_CHILD_OWNER.png.sha1 +++ b/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_CHILD_OWNER.png.sha1
@@ -1 +1 @@ -aca682cabf3853132bfee89a29e06345372960b1 \ No newline at end of file +0f1b9cacab3e00fd8bdca5e98837aa7c52370c6c \ No newline at end of file
diff --git a/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_OWNER.png.sha1 b/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_OWNER.png.sha1 index b41225b..bb372ac6 100644 --- a/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_OWNER.png.sha1 +++ b/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_OWNER.png.sha1
@@ -1 +1 @@ -3a5e3d6ab5de38952508d88e82b1087d8f010b2d \ No newline at end of file +b54253df30ad0bda999b1638c05a567a4efcb6b2 \ No newline at end of file
diff --git a/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_TITLE.png.sha1 b/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_TITLE.png.sha1 index eabfac4c..bb372ac6 100644 --- a/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_TITLE.png.sha1 +++ b/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_TITLE.png.sha1
@@ -1 +1 @@ -360a6de3943e7dba1bf2b7cd428fa288bf16f581 \ No newline at end of file +b54253df30ad0bda999b1638c05a567a4efcb6b2 \ No newline at end of file
diff --git a/chrome/app/chromeos_strings_grdp/IDS_GUEST_TOS_USAGE_OPT_IN_LEARN_MORE.png.sha1 b/chrome/app/chromeos_strings_grdp/IDS_GUEST_TOS_USAGE_OPT_IN_LEARN_MORE.png.sha1 new file mode 100644 index 0000000..4d813fc --- /dev/null +++ b/chrome/app/chromeos_strings_grdp/IDS_GUEST_TOS_USAGE_OPT_IN_LEARN_MORE.png.sha1
@@ -0,0 +1 @@ +b3dfac0a87ff408bdca94f5ad62989744205d2f7 \ No newline at end of file
diff --git a/chrome/app/chromeos_strings_grdp/IDS_GUEST_TOS_USAGE_OPT_IN_TITLE.png.sha1 b/chrome/app/chromeos_strings_grdp/IDS_GUEST_TOS_USAGE_OPT_IN_TITLE.png.sha1 index 7ec0f2b..8eff653d 100644 --- a/chrome/app/chromeos_strings_grdp/IDS_GUEST_TOS_USAGE_OPT_IN_TITLE.png.sha1 +++ b/chrome/app/chromeos_strings_grdp/IDS_GUEST_TOS_USAGE_OPT_IN_TITLE.png.sha1
@@ -1 +1 @@ -ba340c5adc10ee2de718606756743208032f0c3a \ No newline at end of file +2500dbf73299d3d7384a7d522b20d06ecce80c22 \ No newline at end of file
diff --git a/chrome/app/chromium_strings.grd b/chrome/app/chromium_strings.grd index 267f4be..59c18c4 100644 --- a/chrome/app/chromium_strings.grd +++ b/chrome/app/chromium_strings.grd
@@ -1405,6 +1405,11 @@ Your account is managed by <ph name="MANAGER_NAME">$1<ex>example.com</ex></ph>. Your administrator can see and edit this Chromium browser profile and its data like bookmarks, history, and passwords. </message> </if> + <if expr="not chromeos_lacros"> + <message name="IDS_FRE_SIGN_IN_SUBTITLE" desc="The subtitle for the sign in page explaining to the users the benefits of signing in to Chrome"> + You can enjoy the most out of Chromium + </message> + </if> <!-- Profile switch IPH --> <message name="IDS_PROFILE_SWITCH_PROMO" desc="Text of the In-Product-Help bubble for profile switching.">
diff --git a/chrome/app/chromium_strings_grd/IDS_FRE_SIGN_IN_SUBTITLE.png.sha1 b/chrome/app/chromium_strings_grd/IDS_FRE_SIGN_IN_SUBTITLE.png.sha1 new file mode 100644 index 0000000..b9fb5e6 --- /dev/null +++ b/chrome/app/chromium_strings_grd/IDS_FRE_SIGN_IN_SUBTITLE.png.sha1
@@ -0,0 +1 @@ +a56d5beee7de160d4ed0ba0501e3200a04fce8de \ No newline at end of file
diff --git a/chrome/app/generated_resources.grd b/chrome/app/generated_resources.grd index 7bbd9b5..dbeb1dc 100644 --- a/chrome/app/generated_resources.grd +++ b/chrome/app/generated_resources.grd
@@ -4836,6 +4836,9 @@ <message name="IDS_EXTENSION_PROMPT_WARNING_CHROMEOS_TELEMETRY_SERIAL_NUMBER" desc="Permission string for serial number permission."> Read ChromeOS Flex device and component serial numbers. </message> + <message name="IDS_EXTENSION_PROMPT_WARNING_CHROMEOS_TELEMETRY_NETWORK_INFORMATION" desc="Permission string for accessing network information."> + Read ChromeOS Flex network information. + </message> </if> <if expr="not reven"> <message name="IDS_EXTENSION_PROMPT_WARNING_CHROMEOS_DIAGNOSTICS" desc="Permission string for chrome.os.diagnostcs API."> @@ -4847,6 +4850,9 @@ <message name="IDS_EXTENSION_PROMPT_WARNING_CHROMEOS_TELEMETRY_SERIAL_NUMBER" desc="Permission string for serial number permission."> Read ChromeOS device and component serial numbers. </message> + <message name="IDS_EXTENSION_PROMPT_WARNING_CHROMEOS_TELEMETRY_NETWORK_INFORMATION" desc="Permission string for accessing network information."> + Read ChromeOS network information. + </message> </if> </if> @@ -13747,28 +13753,34 @@ <message name="IDS_AUTOFILL_ASSISTANT_PASSWORD_CHANGE_STARTING_SCREEN_TITLE" desc="The title shown on the side panel after an Automated Password Change flow has been started. This message is shown until the first response from a script is received that resets the initial state."> Opening <ph name="URL">$1<ex>example.com</ex></ph>... </message> - <message name="IDS_AUTOFILL_ASSISTANT_PASSWORD_CHANGE_SUCCESSFULLY_CHANGED_PASSWORD_TITLE" desc="The title shown on the side panel after an Automated Password Change flow has been succeeded." translateable="false" > + <message name="IDS_AUTOFILL_ASSISTANT_PASSWORD_CHANGE_SUCCESSFULLY_CHANGED_PASSWORD_TITLE" desc="The title shown on the side panel after an Automated Password Change flow has been succeeded." > Successfully changed the compromised password </message> - <message name="IDS_AUTOFILL_ASSISTANT_PASSWORD_CHANGE_SUCCESSFULLY_CHANGED_PASSWORD_DESCRIPTION" desc="The description shown on the side panel after an Automated Password Change flow has been succeeded." translateable="false" > + <message name="IDS_AUTOFILL_ASSISTANT_PASSWORD_CHANGE_SUCCESSFULLY_RESET_PASSWORD_TITLE" desc="The title shown on the side panel after an Automated Password Change flow ended in a password reset request."> + Check your email to choose a new password + </message> + <message name="IDS_AUTOFILL_ASSISTANT_PASSWORD_CHANGE_SUCCESSFULLY_CHANGED_PASSWORD_DESCRIPTION" desc="The description shown on the side panel after an Automated Password Change flow has been succeeded."> Check your passwords anytime in <ph name="GOOGLE_PASSWORD_MANAGER">$1<ex>Google Password Manager</ex></ph>. </message> - <message name="IDS_AUTOFILL_ASSISTANT_PASSWORD_CHANGE_SUCCESSFULLY_CHANGED_PASSWORD_CLOSE_SIDE_PANEL" desc="The label of the button shown in the side panel after a sucessfull run. Once a user clicks on it, the side panel will close." translateable="false"> + <message name="IDS_AUTOFILL_ASSISTANT_PASSWORD_CHANGE_SUCCESSFULLY_CHANGED_PASSWORD_CLOSE_SIDE_PANEL" desc="The label of the button shown in the side panel after a sucessful run. Once a user clicks on it, the side panel will close."> Done </message> - <message name="IDS_AUTOFILL_ASSISTANT_PASSWORD_CHANGE_ERROR_SCREEN_TITLE" desc="The title shown in the side panel when an error with the script execution occurred." translateable="false"> + <message name="IDS_AUTOFILL_ASSISTANT_PASSWORD_CHANGE_SUCCESSFULLY_RESET_PASSWORD_CLOSE_SIDE_PANEL" desc="The label of the button shown in the side panel after a run that ended in a password reset request. Once a user clicks on it, the side panel will close."> + OK + </message> + <message name="IDS_AUTOFILL_ASSISTANT_PASSWORD_CHANGE_ERROR_SCREEN_TITLE" desc="The title shown in the side panel when an error with the script execution occurred."> Something went wrong. </message> - <message name="IDS_AUTOFILL_ASSISTANT_PASSWORD_CHANGE_ERROR_SCREEN_DESCRIPTION" desc="The description shown in the side panel when an error with the script execution occurred." translateable="false"> + <message name="IDS_AUTOFILL_ASSISTANT_PASSWORD_CHANGE_ERROR_SCREEN_DESCRIPTION" desc="The description shown in the side panel when an error with the script execution occurred."> Check the site and try changing your password. </message> - <message name="IDS_AUTOFILL_ASSISTANT_ASSISTANT_STOPPED_BUBBLE_TRY_AGAIN" desc="The reset link label shown in the assistant stopped bubble." translateable="false"> + <message name="IDS_AUTOFILL_ASSISTANT_ASSISTANT_STOPPED_BUBBLE_TRY_AGAIN" desc="The reset link label shown in the assistant stopped bubble."> Try again </message> - <message name="IDS_AUTOFILL_ASSISTANT_ASSISTANT_STOPPED_BUBBLE_DESCRIPTION" desc="The description shown in the assistant stopped bubble." translateable="false"> + <message name="IDS_AUTOFILL_ASSISTANT_ASSISTANT_STOPPED_BUBBLE_DESCRIPTION" desc="The description shown in the assistant stopped bubble."> Your password didn't change. To change it, try again and leave this tab and side panel open. <ph name="LINK_TEXT">$1<ex>Try again</ex></ph> </message> - <message name="IDS_AUTOFILL_ASSISTANT_ASSISTANT_STOPPED_BUBBLE_TITLE" desc="The title shown in the assistant stopped bubble." translateable="false"> + <message name="IDS_AUTOFILL_ASSISTANT_ASSISTANT_STOPPED_BUBBLE_TITLE" desc="The title shown in the assistant stopped bubble."> Google Assistant stopped </message> </if>
diff --git a/chrome/app/generated_resources_grd/IDS_AUTOFILL_ASSISTANT_ASSISTANT_STOPPED_BUBBLE_DESCRIPTION.png.sha1 b/chrome/app/generated_resources_grd/IDS_AUTOFILL_ASSISTANT_ASSISTANT_STOPPED_BUBBLE_DESCRIPTION.png.sha1 new file mode 100644 index 0000000..a8a407e --- /dev/null +++ b/chrome/app/generated_resources_grd/IDS_AUTOFILL_ASSISTANT_ASSISTANT_STOPPED_BUBBLE_DESCRIPTION.png.sha1
@@ -0,0 +1 @@ +ee5aa45b4ea4fa225424a89359b8442e1754060f \ No newline at end of file
diff --git a/chrome/app/generated_resources_grd/IDS_AUTOFILL_ASSISTANT_ASSISTANT_STOPPED_BUBBLE_TITLE.png.sha1 b/chrome/app/generated_resources_grd/IDS_AUTOFILL_ASSISTANT_ASSISTANT_STOPPED_BUBBLE_TITLE.png.sha1 new file mode 100644 index 0000000..d585c99 --- /dev/null +++ b/chrome/app/generated_resources_grd/IDS_AUTOFILL_ASSISTANT_ASSISTANT_STOPPED_BUBBLE_TITLE.png.sha1
@@ -0,0 +1 @@ +6fb7eb6590441402f768ebd5ff8e04f70b6a8939 \ No newline at end of file
diff --git a/chrome/app/generated_resources_grd/IDS_AUTOFILL_ASSISTANT_ASSISTANT_STOPPED_BUBBLE_TRY_AGAIN.png.sha1 b/chrome/app/generated_resources_grd/IDS_AUTOFILL_ASSISTANT_ASSISTANT_STOPPED_BUBBLE_TRY_AGAIN.png.sha1 new file mode 100644 index 0000000..f76ac1a --- /dev/null +++ b/chrome/app/generated_resources_grd/IDS_AUTOFILL_ASSISTANT_ASSISTANT_STOPPED_BUBBLE_TRY_AGAIN.png.sha1
@@ -0,0 +1 @@ +a31b5911cbcb977d8f3a483c4577e0c68f162f50 \ No newline at end of file
diff --git a/chrome/app/generated_resources_grd/IDS_AUTOFILL_ASSISTANT_PASSWORD_CHANGE_ERROR_SCREEN_DESCRIPTION.png.sha1 b/chrome/app/generated_resources_grd/IDS_AUTOFILL_ASSISTANT_PASSWORD_CHANGE_ERROR_SCREEN_DESCRIPTION.png.sha1 new file mode 100644 index 0000000..3f74900 --- /dev/null +++ b/chrome/app/generated_resources_grd/IDS_AUTOFILL_ASSISTANT_PASSWORD_CHANGE_ERROR_SCREEN_DESCRIPTION.png.sha1
@@ -0,0 +1 @@ +18b4e90be4464683f9bf5fc19c1930e3e29ee3cd \ No newline at end of file
diff --git a/chrome/app/generated_resources_grd/IDS_AUTOFILL_ASSISTANT_PASSWORD_CHANGE_ERROR_SCREEN_TITLE.png.sha1 b/chrome/app/generated_resources_grd/IDS_AUTOFILL_ASSISTANT_PASSWORD_CHANGE_ERROR_SCREEN_TITLE.png.sha1 new file mode 100644 index 0000000..0d6b5e24 --- /dev/null +++ b/chrome/app/generated_resources_grd/IDS_AUTOFILL_ASSISTANT_PASSWORD_CHANGE_ERROR_SCREEN_TITLE.png.sha1
@@ -0,0 +1 @@ +4f597d296b1ff028a3deaf4fa1c61382740ab62d \ No newline at end of file
diff --git a/chrome/app/generated_resources_grd/IDS_AUTOFILL_ASSISTANT_PASSWORD_CHANGE_SUCCESSFULLY_CHANGED_PASSWORD_CLOSE_SIDE_PANEL.png.sha1 b/chrome/app/generated_resources_grd/IDS_AUTOFILL_ASSISTANT_PASSWORD_CHANGE_SUCCESSFULLY_CHANGED_PASSWORD_CLOSE_SIDE_PANEL.png.sha1 new file mode 100644 index 0000000..0af3b16 --- /dev/null +++ b/chrome/app/generated_resources_grd/IDS_AUTOFILL_ASSISTANT_PASSWORD_CHANGE_SUCCESSFULLY_CHANGED_PASSWORD_CLOSE_SIDE_PANEL.png.sha1
@@ -0,0 +1 @@ +59ce90bbbbf0bd0ce6fbd0245b759540ccf2ddf4 \ No newline at end of file
diff --git a/chrome/app/generated_resources_grd/IDS_AUTOFILL_ASSISTANT_PASSWORD_CHANGE_SUCCESSFULLY_CHANGED_PASSWORD_DESCRIPTION.png.sha1 b/chrome/app/generated_resources_grd/IDS_AUTOFILL_ASSISTANT_PASSWORD_CHANGE_SUCCESSFULLY_CHANGED_PASSWORD_DESCRIPTION.png.sha1 new file mode 100644 index 0000000..d1e37d6 --- /dev/null +++ b/chrome/app/generated_resources_grd/IDS_AUTOFILL_ASSISTANT_PASSWORD_CHANGE_SUCCESSFULLY_CHANGED_PASSWORD_DESCRIPTION.png.sha1
@@ -0,0 +1 @@ +044df585108d1a7c32d5f4a9cb34b781b017d9c3 \ No newline at end of file
diff --git a/chrome/app/generated_resources_grd/IDS_AUTOFILL_ASSISTANT_PASSWORD_CHANGE_SUCCESSFULLY_CHANGED_PASSWORD_TITLE.png.sha1 b/chrome/app/generated_resources_grd/IDS_AUTOFILL_ASSISTANT_PASSWORD_CHANGE_SUCCESSFULLY_CHANGED_PASSWORD_TITLE.png.sha1 new file mode 100644 index 0000000..caed95fbc --- /dev/null +++ b/chrome/app/generated_resources_grd/IDS_AUTOFILL_ASSISTANT_PASSWORD_CHANGE_SUCCESSFULLY_CHANGED_PASSWORD_TITLE.png.sha1
@@ -0,0 +1 @@ +a2d0ab5cc4dd0150ec260e67636c0b5fb040531f \ No newline at end of file
diff --git a/chrome/app/generated_resources_grd/IDS_AUTOFILL_ASSISTANT_PASSWORD_CHANGE_SUCCESSFULLY_RESET_PASSWORD_CLOSE_SIDE_PANEL.png.sha1 b/chrome/app/generated_resources_grd/IDS_AUTOFILL_ASSISTANT_PASSWORD_CHANGE_SUCCESSFULLY_RESET_PASSWORD_CLOSE_SIDE_PANEL.png.sha1 new file mode 100644 index 0000000..996e9892 --- /dev/null +++ b/chrome/app/generated_resources_grd/IDS_AUTOFILL_ASSISTANT_PASSWORD_CHANGE_SUCCESSFULLY_RESET_PASSWORD_CLOSE_SIDE_PANEL.png.sha1
@@ -0,0 +1 @@ +8b5711fe41c8013f22bc6c74e185c5b263b4a268 \ No newline at end of file
diff --git a/chrome/app/generated_resources_grd/IDS_AUTOFILL_ASSISTANT_PASSWORD_CHANGE_SUCCESSFULLY_RESET_PASSWORD_TITLE.png.sha1 b/chrome/app/generated_resources_grd/IDS_AUTOFILL_ASSISTANT_PASSWORD_CHANGE_SUCCESSFULLY_RESET_PASSWORD_TITLE.png.sha1 new file mode 100644 index 0000000..e8140f6 --- /dev/null +++ b/chrome/app/generated_resources_grd/IDS_AUTOFILL_ASSISTANT_PASSWORD_CHANGE_SUCCESSFULLY_RESET_PASSWORD_TITLE.png.sha1
@@ -0,0 +1 @@ +771614e6ab697cac5f7c6c3c305f1425e2e99c8a \ No newline at end of file
diff --git a/chrome/app/generated_resources_grd/IDS_EXTENSION_PROMPT_WARNING_CHROMEOS_TELEMETRY_NETWORK_INFORMATION.png.sha1 b/chrome/app/generated_resources_grd/IDS_EXTENSION_PROMPT_WARNING_CHROMEOS_TELEMETRY_NETWORK_INFORMATION.png.sha1 new file mode 100644 index 0000000..d501ce8 --- /dev/null +++ b/chrome/app/generated_resources_grd/IDS_EXTENSION_PROMPT_WARNING_CHROMEOS_TELEMETRY_NETWORK_INFORMATION.png.sha1
@@ -0,0 +1 @@ +f76631fda140108255b3c03f325c0126f05a0b33 \ No newline at end of file
diff --git a/chrome/app/google_chrome_strings.grd b/chrome/app/google_chrome_strings.grd index 2cb988e4..78565107 100644 --- a/chrome/app/google_chrome_strings.grd +++ b/chrome/app/google_chrome_strings.grd
@@ -1500,6 +1500,11 @@ Your account is managed by <ph name="MANAGER_NAME">$1<ex>example.com</ex></ph>. Your administrator can see and edit this Chrome browser profile and its data like bookmarks, history, and passwords. </message> </if> + <if expr="not chromeos_lacros"> + <message name="IDS_FRE_SIGN_IN_SUBTITLE" desc="The subtitle for the sign in page explaining to the users the benefits of signing in to Chrome"> + You can enjoy the most out of Chrome + </message> + </if> <!-- Profile switch IPH --> <message name="IDS_PROFILE_SWITCH_PROMO" desc="Text of the In-Product-Help bubble for profile switching.">
diff --git a/chrome/app/google_chrome_strings_grd/IDS_FRE_SIGN_IN_SUBTITLE.png.sha1 b/chrome/app/google_chrome_strings_grd/IDS_FRE_SIGN_IN_SUBTITLE.png.sha1 new file mode 100644 index 0000000..b9fb5e6 --- /dev/null +++ b/chrome/app/google_chrome_strings_grd/IDS_FRE_SIGN_IN_SUBTITLE.png.sha1
@@ -0,0 +1 @@ +a56d5beee7de160d4ed0ba0501e3200a04fce8de \ No newline at end of file
diff --git a/chrome/app/profiles_strings.grdp b/chrome/app/profiles_strings.grdp index 89909dcd..c1a8f64e 100644 --- a/chrome/app/profiles_strings.grdp +++ b/chrome/app/profiles_strings.grdp
@@ -729,5 +729,36 @@ </message> </if> + <!-- First Run Experience strings --> + <if expr="not chromeos_lacros"> + <message name="IDS_FRE_SIGN_IN_TITLE" desc="The title for the sign in page explaining to the users the benefits of signing in to Chrome"> + Sign in for more benefits + </message> + <message name="IDS_FRE_DEVICES_CARD_TITLE" desc="The title of the benefits card explaining to the the users that they can continue their work on any of their signed in devices"> + Across devices + </message> + <message name="IDS_FRE_DEVICES_CARD_DESCRIPTION" desc="The description of the benefits card explaining to the users that they can continue their work on any of their signed in devices"> + Pick up where you left off on any device + </message> + <message name="IDS_FRE_SECURITY_CARD_TITLE" desc="The title of the benefits card explaining to the users that signing in to Chrome offers strong security features"> + Stronger security + </message> + <message name="IDS_FRE_SECURITY_CARD_DESCRIPTION" desc="The description of the benefits card explaining to the users that signing in to Chrome will grant them more security thus protecting their passwords and more"> + Extra protection to your passwords and more + </message> + <message name="IDS_FRE_BACKUP_CARD_TITLE" desc="The title of the benefits card explaining to the users that they can back up their stuff and use them across all signed in devices"> + Back up your stuff + </message> + <message name="IDS_FRE_BACKUP_CARD_DESCRIPTION" desc="The description of the benefits card giving users examples of data they can back up when they sign in"> + Store your bookmarks and more with sync + </message> + <message name="IDS_FRE_DECLINE_SIGN_IN_BUTTON_TITLE" desc="The title of the button giving the users the choice not to sign in to Chrome"> + Don't sign in + </message> + <message name="IDS_FRE_ACCEPT_SIGN_IN_BUTTON_TITLE" desc="The title of the button giving the users the choice to sign in to Chrome"> + Sign in + </message> + </if> + </if> </grit-part>
diff --git a/chrome/app/profiles_strings_grdp/IDS_FRE_ACCEPT_SIGN_IN_BUTTON_TITLE.png.sha1 b/chrome/app/profiles_strings_grdp/IDS_FRE_ACCEPT_SIGN_IN_BUTTON_TITLE.png.sha1 new file mode 100644 index 0000000..b63cfb6 --- /dev/null +++ b/chrome/app/profiles_strings_grdp/IDS_FRE_ACCEPT_SIGN_IN_BUTTON_TITLE.png.sha1
@@ -0,0 +1 @@ +03efb664202df737392addd7c362302e4bbc8468 \ No newline at end of file
diff --git a/chrome/app/profiles_strings_grdp/IDS_FRE_BACKUP_CARD_DESCRIPTION.png.sha1 b/chrome/app/profiles_strings_grdp/IDS_FRE_BACKUP_CARD_DESCRIPTION.png.sha1 new file mode 100644 index 0000000..90324f7 --- /dev/null +++ b/chrome/app/profiles_strings_grdp/IDS_FRE_BACKUP_CARD_DESCRIPTION.png.sha1
@@ -0,0 +1 @@ +4ea5d4a48276227bfb18051a535b2c751615ea53 \ No newline at end of file
diff --git a/chrome/app/profiles_strings_grdp/IDS_FRE_BACKUP_CARD_TITLE.png.sha1 b/chrome/app/profiles_strings_grdp/IDS_FRE_BACKUP_CARD_TITLE.png.sha1 new file mode 100644 index 0000000..dc7e310 --- /dev/null +++ b/chrome/app/profiles_strings_grdp/IDS_FRE_BACKUP_CARD_TITLE.png.sha1
@@ -0,0 +1 @@ +c137c065616f42903f80ec39eadd721fbedd3ef0 \ No newline at end of file
diff --git a/chrome/app/profiles_strings_grdp/IDS_FRE_DECLINE_SIGN_IN_BUTTON_TITLE.png.sha1 b/chrome/app/profiles_strings_grdp/IDS_FRE_DECLINE_SIGN_IN_BUTTON_TITLE.png.sha1 new file mode 100644 index 0000000..45853be --- /dev/null +++ b/chrome/app/profiles_strings_grdp/IDS_FRE_DECLINE_SIGN_IN_BUTTON_TITLE.png.sha1
@@ -0,0 +1 @@ +fa75cda7ac60a9b8f6d764d7518e9f72f1fa6346 \ No newline at end of file
diff --git a/chrome/app/profiles_strings_grdp/IDS_FRE_DEVICES_CARD_DESCRIPTION.png.sha1 b/chrome/app/profiles_strings_grdp/IDS_FRE_DEVICES_CARD_DESCRIPTION.png.sha1 new file mode 100644 index 0000000..ed3bbd1 --- /dev/null +++ b/chrome/app/profiles_strings_grdp/IDS_FRE_DEVICES_CARD_DESCRIPTION.png.sha1
@@ -0,0 +1 @@ +083fd8be43abd6a89b52c12f2d0df87a666165f6 \ No newline at end of file
diff --git a/chrome/app/profiles_strings_grdp/IDS_FRE_DEVICES_CARD_TITLE.png.sha1 b/chrome/app/profiles_strings_grdp/IDS_FRE_DEVICES_CARD_TITLE.png.sha1 new file mode 100644 index 0000000..1f7eaf1 --- /dev/null +++ b/chrome/app/profiles_strings_grdp/IDS_FRE_DEVICES_CARD_TITLE.png.sha1
@@ -0,0 +1 @@ +6fdefae9f5809e5f2baa86348d7c1cdc7f94bb9e \ No newline at end of file
diff --git a/chrome/app/profiles_strings_grdp/IDS_FRE_SECURITY_CARD_DESCRIPTION.png.sha1 b/chrome/app/profiles_strings_grdp/IDS_FRE_SECURITY_CARD_DESCRIPTION.png.sha1 new file mode 100644 index 0000000..ffd420808 --- /dev/null +++ b/chrome/app/profiles_strings_grdp/IDS_FRE_SECURITY_CARD_DESCRIPTION.png.sha1
@@ -0,0 +1 @@ +5ace06e4a4663e54c771afcdfee7dfe169d35f59 \ No newline at end of file
diff --git a/chrome/app/profiles_strings_grdp/IDS_FRE_SECURITY_CARD_TITLE.png.sha1 b/chrome/app/profiles_strings_grdp/IDS_FRE_SECURITY_CARD_TITLE.png.sha1 new file mode 100644 index 0000000..4f57300f --- /dev/null +++ b/chrome/app/profiles_strings_grdp/IDS_FRE_SECURITY_CARD_TITLE.png.sha1
@@ -0,0 +1 @@ +af226e4a25dc2dae6f37f6ddeb9c5e0e927bad7d \ No newline at end of file
diff --git a/chrome/app/profiles_strings_grdp/IDS_FRE_SIGN_IN_TITLE.png.sha1 b/chrome/app/profiles_strings_grdp/IDS_FRE_SIGN_IN_TITLE.png.sha1 new file mode 100644 index 0000000..d2860d3 --- /dev/null +++ b/chrome/app/profiles_strings_grdp/IDS_FRE_SIGN_IN_TITLE.png.sha1
@@ -0,0 +1 @@ +445677dcebac9cf1c2196756b72c4f9163d35d75 \ No newline at end of file
diff --git a/chrome/browser/BUILD.gn b/chrome/browser/BUILD.gn index 96bcf45..80ab073 100644 --- a/chrome/browser/BUILD.gn +++ b/chrome/browser/BUILD.gn
@@ -5155,7 +5155,6 @@ "//ash/components/arc/enterprise", "//ash/components/arc/mojom", "//ash/components/arc/mojom", - "//ash/components/tpm", "//ash/constants", "//ash/public/cpp", "//ash/public/cpp/external_arc", @@ -5186,6 +5185,7 @@ "//ash/webui/face_ml_app_ui/mojom:trusted", "//ash/webui/file_manager:file_manager_ui", "//ash/webui/file_manager/mojom", + "//ash/webui/files_internals", "//ash/webui/firmware_update_ui", "//ash/webui/firmware_update_ui/mojom", "//ash/webui/guest_os_installer", @@ -5287,6 +5287,7 @@ "//chromeos/ash/components/settings", "//chromeos/ash/components/sync_wifi", "//chromeos/ash/components/timezone", + "//chromeos/ash/components/tpm", "//chromeos/ash/services/assistant/public/cpp", "//chromeos/ash/services/auth_factor_config", "//chromeos/ash/services/bluetooth_config",
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index 0b2e78a..52db3a1d 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -5499,10 +5499,10 @@ flag_descriptions::kOmniboxLocalHistoryZeroSuggestBeyondNTPDescription, kOsAll, FEATURE_VALUE_TYPE(omnibox::kLocalHistoryZeroSuggestBeyondNTP)}, - {"omnibox-on-clobber-focus-type-on-android", - flag_descriptions::kOmniboxOnClobberFocusTypeOnAndroidName, - flag_descriptions::kOmniboxOnClobberFocusTypeOnAndroidDescription, kOsAll, - FEATURE_VALUE_TYPE(omnibox::kOmniboxOnClobberFocusTypeOnAndroid)}, + {"omnibox-on-clobber-focus-type-on-content", + flag_descriptions::kOmniboxOnClobberFocusTypeOnContentName, + flag_descriptions::kOmniboxOnClobberFocusTypeOnContentDescription, kOsAll, + FEATURE_VALUE_TYPE(omnibox::kOmniboxOnClobberFocusTypeOnContent)}, {"omnibox-on-focus-suggestions-contextual-web", flag_descriptions::kOmniboxFocusTriggersContextualWebZeroSuggestName,
diff --git a/chrome/browser/android/omnibox/autocomplete_controller_android.cc b/chrome/browser/android/omnibox/autocomplete_controller_android.cc index a3dce2b8..49385a8 100644 --- a/chrome/browser/android/omnibox/autocomplete_controller_android.cc +++ b/chrome/browser/android/omnibox/autocomplete_controller_android.cc
@@ -224,7 +224,7 @@ OmniboxEventProto::PageClassification(j_page_classification); bool interaction_clobber_focus_type = base::FeatureList::IsEnabled( - omnibox::kOmniboxOnClobberFocusTypeOnAndroid) && + omnibox::kOmniboxOnClobberFocusTypeOnContent) && !BaseSearchProvider::IsNTPPage(page_class); if (interaction_clobber_focus_type) omnibox_text.clear();
diff --git a/chrome/browser/apps/app_preload_service/app_preload_server_connector.cc b/chrome/browser/apps/app_preload_service/app_preload_server_connector.cc index a05a523..d8a62a4 100644 --- a/chrome/browser/apps/app_preload_service/app_preload_server_connector.cc +++ b/chrome/browser/apps/app_preload_service/app_preload_server_connector.cc
@@ -47,10 +47,7 @@ base::Value::Dict request; request.Set("board", info.board); request.Set("model", info.model); - - // TODO(b/249427934): Temporary test data. - request.Set("language", "en-US"); - request.Set("sku_id", "temporary"); + request.Set("language", info.locale); base::Value::Dict versions; versions.Set("ash_chrome", info.version_info.ash_chrome);
diff --git a/chrome/browser/apps/app_preload_service/app_preload_server_connector_unittest.cc b/chrome/browser/apps/app_preload_service/app_preload_server_connector_unittest.cc index f1ba4ba..dba3848 100644 --- a/chrome/browser/apps/app_preload_service/app_preload_server_connector_unittest.cc +++ b/chrome/browser/apps/app_preload_service/app_preload_server_connector_unittest.cc
@@ -45,6 +45,7 @@ device_info.user_type = "unmanaged"; device_info.version_info.ash_chrome = "10.10.10"; device_info.version_info.platform = "12345.0.0"; + device_info.locale = "en-US"; std::string method; std::string method_override_header; @@ -70,7 +71,7 @@ EXPECT_EQ(body, "{\"board\":\"brya\",\"chrome_os_version\":{\"ash_chrome\":\"10.10." "10\",\"platform\":\"12345.0.0\"},\"language\":\"en-US\",\"model\":" - "\"taniks\",\"sku_id\":\"temporary\"}"); + "\"taniks\"}"); } } // namespace apps
diff --git a/chrome/browser/apps/app_preload_service/device_info_manager.cc b/chrome/browser/apps/app_preload_service/device_info_manager.cc index 25bfe3f0..a036452 100644 --- a/chrome/browser/apps/app_preload_service/device_info_manager.cc +++ b/chrome/browser/apps/app_preload_service/device_info_manager.cc
@@ -8,7 +8,10 @@ #include "base/task/task_traits.h" #include "base/task/thread_pool.h" #include "chrome/browser/apps/user_type_filter.h" +#include "chrome/browser/profiles/profile.h" #include "chromeos/version/version_loader.h" +#include "components/language/core/browser/pref_names.h" +#include "components/prefs/pref_service.h" #include "components/version_info/version_info.h" namespace apps { @@ -45,6 +48,11 @@ device_info.version_info.ash_chrome = version_info::GetVersionNumber(); device_info.user_type = apps::DetermineUserType(profile_); + // Locale + PrefService* prefs = profile_->GetPrefs(); + DCHECK(prefs); + device_info.locale = prefs->GetString(language::prefs::kApplicationLocale); + base::ThreadPool::PostTaskAndReplyWithResult( FROM_HERE, {base::MayBlock()}, base::BindOnce(&chromeos::version_loader::GetVersion, @@ -78,6 +86,7 @@ os << "- Board: " << device_info.board << std::endl; os << "- Model: " << device_info.model << std::endl; os << "- User Type: " << device_info.user_type << std::endl; + os << "- Locale: " << device_info.locale << std::endl; os << device_info.version_info; return os; }
diff --git a/chrome/browser/apps/app_preload_service/device_info_manager.h b/chrome/browser/apps/app_preload_service/device_info_manager.h index 5de00e9..5f40916 100644 --- a/chrome/browser/apps/app_preload_service/device_info_manager.h +++ b/chrome/browser/apps/app_preload_service/device_info_manager.h
@@ -43,6 +43,9 @@ // The version info of the device. VersionInfo version_info; + + // The locale chosen by the user. + std::string locale; }; // This class is a helper interface to get info about the device the code is
diff --git a/chrome/browser/apps/app_preload_service/device_info_manager_unittest.cc b/chrome/browser/apps/app_preload_service/device_info_manager_unittest.cc index ddad775..8406282 100644 --- a/chrome/browser/apps/app_preload_service/device_info_manager_unittest.cc +++ b/chrome/browser/apps/app_preload_service/device_info_manager_unittest.cc
@@ -9,10 +9,18 @@ #include "base/callback.h" #include "base/run_loop.h" #include "chrome/test/base/testing_profile.h" +#include "components/language/core/browser/pref_names.h" +#include "components/prefs/pref_service.h" #include "content/public/test/browser_task_environment.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" +namespace { + +static constexpr char kTestLocale[] = "test_locale"; + +} // namespace + namespace apps { class DeviceInfoManagerTest : public testing::Test { @@ -25,12 +33,15 @@ ASSERT_FALSE(device_info.user_type.empty()); ASSERT_FALSE(device_info.version_info.ash_chrome.empty()); ASSERT_FALSE(device_info.version_info.platform.empty()); + ASSERT_EQ(device_info.locale, kTestLocale); std::move(on_complete).Run(); } protected: DeviceInfoManagerTest() { device_info_manager_ = std::make_unique<DeviceInfoManager>(&profile_); + PrefService* prefs = profile_.GetPrefs(); + prefs->SetString(language::prefs::kApplicationLocale, kTestLocale); } private:
diff --git a/chrome/browser/apps/guest_view/web_view_browsertest.cc b/chrome/browser/apps/guest_view/web_view_browsertest.cc index 3778325..791aad2 100644 --- a/chrome/browser/apps/guest_view/web_view_browsertest.cc +++ b/chrome/browser/apps/guest_view/web_view_browsertest.cc
@@ -5080,8 +5080,6 @@ GetGuestViewManager()->WaitForSingleGuestViewCreated(); ASSERT_TRUE(attached_guest_view); - auto* attached_guest_rfh = - GetGuestViewManager()->GetLastGuestRenderFrameHostCreated(); auto* find_helper = find_in_page::FindTabHelper::FromWebContents(embedder_web_contents); @@ -5095,6 +5093,7 @@ ASSERT_TRUE(guest_view); ASSERT_FALSE(guest_view->attached()); + auto* attached_guest_rfh = attached_guest_view->GetGuestMainFrame(); auto* unattached_guest_rfh = guest_view->GetGuestMainFrame(); EXPECT_NE(unattached_guest_rfh, attached_guest_rfh); find_helper->StartFinding(u"doesn't matter", true, true, false);
diff --git a/chrome/browser/ash/BUILD.gn b/chrome/browser/ash/BUILD.gn index 7dba67c1..9ecbb170 100644 --- a/chrome/browser/ash/BUILD.gn +++ b/chrome/browser/ash/BUILD.gn
@@ -2918,6 +2918,8 @@ "web_applications/face_ml_system_web_app_info.h", "web_applications/file_manager_web_app_info.cc", "web_applications/file_manager_web_app_info.h", + "web_applications/files_internals_ui_delegate.cc", + "web_applications/files_internals_ui_delegate.h", "web_applications/firmware_update_system_web_app_info.cc", "web_applications/firmware_update_system_web_app_info.h", "web_applications/help_app/help_app_discover_tab_notification.cc", @@ -3059,7 +3061,6 @@ "//ash/services/multidevice_setup/public/cpp:auth_token_validator", "//ash/services/nearby/public/cpp", "//ash/services/nearby/public/mojom", - "//ash/services/quick_pair/public/mojom:mojom_headers", "//ash/services/secure_channel/public/cpp/client", "//ash/services/secure_channel/public/mojom", "//ash/style", @@ -3067,6 +3068,7 @@ "//ash/webui/connectivity_diagnostics", "//ash/webui/eche_app_ui", "//ash/webui/file_manager:file_manager_ui", + "//ash/webui/files_internals", "//ash/webui/guest_os_installer/mojom", "//ash/webui/help_app_ui", "//ash/webui/media_app_ui", @@ -3182,6 +3184,7 @@ "//chromeos/ash/components/trash_service/public/cpp", "//chromeos/ash/services/cros_healthd/public/cpp", "//chromeos/ash/services/cros_healthd/public/mojom", + "//chromeos/ash/services/quick_pair/public/mojom:mojom_headers", "//chromeos/ash/services/rollback_network_config/public/mojom", "//chromeos/components/onc", "//chromeos/components/remote_apps/mojom", @@ -3374,8 +3377,6 @@ "//ash/components/arc/mojom:protected_buffer_manager", "//ash/components/fwupd", "//ash/components/peripheral_notification", - "//ash/components/tpm", - "//ash/components/tpm:buildflags", "//ash/keyboard/ui", "//ash/public/cpp/resources:ash_public_unscaled_resources", "//ash/quick_pair/feature_status_tracker", @@ -3387,7 +3388,6 @@ "//ash/services/multidevice_setup/public/cpp:oobe_completion_tracker", "//ash/services/multidevice_setup/public/cpp:prefs", "//ash/services/multidevice_setup/public/mojom", - "//ash/services/quick_pair/public/mojom", "//ash/services/secure_channel", "//ash/services/secure_channel/public/cpp/shared", "//ash/strings", @@ -3515,9 +3515,12 @@ "//chromeos/ash/components/multidevice/logging", "//chromeos/ash/components/power", "//chromeos/ash/components/sync_wifi", + "//chromeos/ash/components/tpm", + "//chromeos/ash/components/tpm:buildflags", "//chromeos/ash/services/assistant/public/cpp", "//chromeos/ash/services/bluetooth_config:in_process_bluetooth_config", "//chromeos/ash/services/cros_healthd/private/cpp", + "//chromeos/ash/services/quick_pair/public/mojom", "//chromeos/components/cdm_factory_daemon:cdm_factory_daemon_browser", "//chromeos/components/cdm_factory_daemon/mojom", "//chromeos/components/certificate_provider",
diff --git a/chrome/browser/ash/app_restore/app_restore_arc_task_handler.cc b/chrome/browser/ash/app_restore/app_restore_arc_task_handler.cc index 15f4794..5e4c38b 100644 --- a/chrome/browser/ash/app_restore/app_restore_arc_task_handler.cc +++ b/chrome/browser/ash/app_restore/app_restore_arc_task_handler.cc
@@ -18,13 +18,13 @@ namespace ash::app_restore { namespace { -constexpr int kFullRestoreId = -1; -constexpr int kArcWindowPredictorId = -2; - ::app_restore::AppRestoreArcInfo* GetAppRestoreArcInfo() { return ::app_restore::AppRestoreArcInfo::GetInstance(); } +constexpr LauncherTag kFullRestoreLaunchHandlerTag = { + LauncherType::kFullRestore, 0}; + } // namespace // static @@ -45,19 +45,9 @@ window_handler_ = std::make_unique<full_restore::ArcGhostWindowHandler>(); #endif - arc_app_launch_handlers_[kFullRestoreId] = - std::make_unique<ArcAppLaunchHandler>(); - full_restore_arc_app_launch_handler_observer_ = - arc_app_launch_handlers_[kFullRestoreId].get(); + // Create full restore arc app launch handler. + GetFullRestoreArcAppLaunchHandler(); - // TODO(sstan): Modify ArcAppLaunchHandler to prevent redundant launch. - if (::full_restore::features::IsArcWindowPredictorEnabled() || - base::FeatureList::IsEnabled(arc::kFixupWindowFeature)) { - arc_app_launch_handlers_[kArcWindowPredictorId] = - std::make_unique<ArcAppLaunchHandler>(); - window_predictor_arc_app_launch_handler_observer_ = - arc_app_launch_handlers_[kArcWindowPredictorId].get(); - } arc::ArcSessionManager* arc_session_manager = arc::ArcSessionManager::Get(); // arc::ArcSessionManager might not be set in tests. if (arc_session_manager) @@ -68,25 +58,15 @@ AppRestoreArcTaskHandler::GetDeskTemplateArcAppLaunchHandler( int32_t launch_id) { DCHECK_GT(launch_id, 0); - auto& handler = arc_app_launch_handlers_[launch_id]; - if (!handler) { - // We haven't seen this launch id before. Create a new entry. - handler = std::make_unique<ArcAppLaunchHandler>(); - handler->OnArcPlayStoreEnabledChanged(arc_play_store_enabled_); - if (app_connection_ready_) - handler->OnAppConnectionReady(); - if (shelf_ready_) - handler->OnShelfReady(); - } - - return handler.get(); + return CreateOrGetArcAppLaunchHandler( + {LauncherType::kDeskTemplate, launch_id}, /*call_init_callback=*/true); } void AppRestoreArcTaskHandler::ClearDeskTemplateArcAppLaunchHandler( int32_t launch_id) { DCHECK_GT(launch_id, 0); - arc_app_launch_handlers_.erase(launch_id); + arc_app_launch_handlers_.erase({LauncherType::kDeskTemplate, launch_id}); } AppRestoreArcTaskHandler::~AppRestoreArcTaskHandler() { @@ -98,13 +78,26 @@ bool AppRestoreArcTaskHandler::IsAppPendingRestore( const std::string& arc_app_id) const { - for (auto& handler : arc_app_launch_handlers_) { - if (handler.second->IsAppPendingRestore(arc_app_id)) + for (auto& [unused, launcher] : arc_app_launch_handlers_) { + if (launcher->IsAppPendingRestore(arc_app_id)) return true; } return false; } +ArcAppLaunchHandler* +AppRestoreArcTaskHandler::GetFullRestoreArcAppLaunchHandler() { + return CreateOrGetArcAppLaunchHandler(kFullRestoreLaunchHandlerTag, + /*call_init_callback=*/false); +} + +ArcAppLaunchHandler* +AppRestoreArcTaskHandler::GetWindowPredictorArcAppLaunchHandler( + int32_t launch_id) { + return CreateOrGetArcAppLaunchHandler( + {LauncherType::kWindowPredictor, launch_id}, /*call_init_callback=*/true); +} + void AppRestoreArcTaskHandler::OnAppStatesChanged( const std::string& id, const ArcAppListPrefs::AppInfo& app_info) { @@ -144,8 +137,8 @@ window_handler_->OnAppInstanceConnected(); #endif - for (auto& handler : arc_app_launch_handlers_) - handler.second->OnAppConnectionReady(); + for (auto& [unused, launcher] : arc_app_launch_handlers_) + launcher->OnAppConnectionReady(); GetAppRestoreArcInfo()->NotifyArcConnectionChanged( /*is_connection_ready=*/true); @@ -164,8 +157,8 @@ void AppRestoreArcTaskHandler::OnArcPlayStoreEnabledChanged(bool enabled) { arc_play_store_enabled_ = enabled; - for (auto& handler : arc_app_launch_handlers_) - handler.second->OnArcPlayStoreEnabledChanged(enabled); + for (auto& [unused, launcher] : arc_app_launch_handlers_) + launcher->OnArcPlayStoreEnabledChanged(enabled); GetAppRestoreArcInfo()->NotifyPlayStoreEnabledChanged(enabled); } @@ -173,24 +166,31 @@ void AppRestoreArcTaskHandler::OnShelfReady() { shelf_ready_ = true; - for (auto& handler : arc_app_launch_handlers_) - handler.second->OnShelfReady(); + for (auto& [unused, launcher] : arc_app_launch_handlers_) + launcher->OnShelfReady(); } void AppRestoreArcTaskHandler::Shutdown() { arc_app_launch_handlers_.clear(); - full_restore_arc_app_launch_handler_observer_ = nullptr; - window_predictor_arc_app_launch_handler_observer_ = nullptr; - window_handler_.reset(); } -void AppRestoreArcTaskHandler::CreateFullRestoreHandlerForTest() { - auto& full_restore_handler = arc_app_launch_handlers_[kFullRestoreId]; - if (!full_restore_handler) { - full_restore_handler = std::make_unique<ArcAppLaunchHandler>(); - full_restore_arc_app_launch_handler_observer_ = full_restore_handler.get(); +ArcAppLaunchHandler* AppRestoreArcTaskHandler::CreateOrGetArcAppLaunchHandler( + LauncherTag launcher_tag, + bool call_init_callback) { + if (!arc_app_launch_handlers_.count(launcher_tag)) { + auto handler = std::make_unique<ArcAppLaunchHandler>(); + if (call_init_callback) { + handler->OnArcPlayStoreEnabledChanged(arc_play_store_enabled_); + if (app_connection_ready_) + handler->OnAppConnectionReady(); + if (shelf_ready_) + handler->OnShelfReady(); + } + return arc_app_launch_handlers_.insert({launcher_tag, std::move(handler)}) + .first->second.get(); } + return arc_app_launch_handlers_[launcher_tag].get(); } } // namespace ash::app_restore
diff --git a/chrome/browser/ash/app_restore/app_restore_arc_task_handler.h b/chrome/browser/ash/app_restore/app_restore_arc_task_handler.h index f40375b..ae68677 100644 --- a/chrome/browser/ash/app_restore/app_restore_arc_task_handler.h +++ b/chrome/browser/ash/app_restore/app_restore_arc_task_handler.h
@@ -25,6 +25,18 @@ class ArcAppLaunchHandler; +namespace { + +enum class LauncherType { + kFullRestore, + kWindowPredictor, + kDeskTemplate, +}; + +using LauncherTag = std::pair<LauncherType, int32_t>; + +} // namespace + // The AppRestoreArcTaskHandler class observes ArcAppListPrefs, and calls // app restore clients to update the ARC app launch info when a task is created // or destroyed. AppRestoreArcTaskHandler is an independent KeyedService so that @@ -53,13 +65,13 @@ // which window info should be applied. bool IsAppPendingRestore(const std::string& arc_app_id) const; - ArcAppLaunchHandler* full_restore_arc_app_launch_handler() { - return full_restore_arc_app_launch_handler_observer_; - } - ArcAppLaunchHandler* window_predictor_arc_app_launch_handler() { - return window_predictor_arc_app_launch_handler_observer_; - } + // Get or create full restore arc app launch handler. + ArcAppLaunchHandler* GetFullRestoreArcAppLaunchHandler(); + // Get or create window predictor arc app launch handler by `launch_id`. + ArcAppLaunchHandler* GetWindowPredictorArcAppLaunchHandler(int32_t launch_id); + + // Get or create desk template arc app launch handler by `launch_id`. ArcAppLaunchHandler* GetDeskTemplateArcAppLaunchHandler(int32_t launch_id); void ClearDeskTemplateArcAppLaunchHandler(int32_t launch_id); @@ -93,8 +105,8 @@ private: friend class ash::full_restore::FullRestoreAppLaunchHandlerArcAppBrowserTest; - // Used for testing to install a handler for full restore. - void CreateFullRestoreHandlerForTest(); + ArcAppLaunchHandler* CreateOrGetArcAppLaunchHandler(LauncherTag launcher_tag, + bool call_init_callback); base::ScopedObservation<ArcAppListPrefs, ArcAppListPrefs::Observer> arc_prefs_observer_{this}; @@ -103,16 +115,10 @@ std::unique_ptr<full_restore::ArcGhostWindowHandler> window_handler_; #endif - // Maps launch ids to ArcAppLaunchHandlers. Positive ids are used for desk - // template launches. Negative ids are used for full restore and the window - // predictor. - std::map<int32_t, std::unique_ptr<ArcAppLaunchHandler>> + // Maps LauncherTag to ArcAppLaunchHandlers. + std::map<LauncherTag, std::unique_ptr<ArcAppLaunchHandler>> arc_app_launch_handlers_; - ArcAppLaunchHandler* full_restore_arc_app_launch_handler_observer_ = nullptr; - ArcAppLaunchHandler* window_predictor_arc_app_launch_handler_observer_ = - nullptr; - // These cache the readiness status of the subsystems needed to launch ARC // apps. They are used when new handlers are dynamically created so that the // handlers can learn the status of these systems.
diff --git a/chrome/browser/ash/app_restore/arc_app_launch_handler.h b/chrome/browser/ash/app_restore/arc_app_launch_handler.h index 6426d9b..ba57e2f 100644 --- a/chrome/browser/ash/app_restore/arc_app_launch_handler.h +++ b/chrome/browser/ash/app_restore/arc_app_launch_handler.h
@@ -122,7 +122,8 @@ ~ArcAppLaunchHandler() override; // Invoked when the restoration process can start. Reads the restore data, and - // add the ARC apps windows to `windows_` and `no_stack_windows_`. + // add the ARC apps windows to `windows_` and `no_stack_windows_`. For each + // AppLaunchHandler, it is only expected be called once. void RestoreArcApps(AppLaunchHandler* app_launch_handler); void OnAppConnectionReady();
diff --git a/chrome/browser/ash/app_restore/full_restore_app_launch_handler.cc b/chrome/browser/ash/app_restore/full_restore_app_launch_handler.cc index 089902f..7e67100 100644 --- a/chrome/browser/ash/app_restore/full_restore_app_launch_handler.cc +++ b/chrome/browser/ash/app_restore/full_restore_app_launch_handler.cc
@@ -245,8 +245,7 @@ VLOG(1) << "Restore apps in " << profile()->GetPath(); if (auto* arc_task_handler = app_restore::AppRestoreArcTaskHandler::GetForProfile(profile())) { - arc_task_handler->full_restore_arc_app_launch_handler()->RestoreArcApps( - this); + arc_task_handler->GetFullRestoreArcAppLaunchHandler()->RestoreArcApps(this); } MaybeRestoreLacros();
diff --git a/chrome/browser/ash/app_restore/full_restore_app_launch_handler_browsertest.cc b/chrome/browser/ash/app_restore/full_restore_app_launch_handler_browsertest.cc index 5fec380..4f69ec0 100644 --- a/chrome/browser/ash/app_restore/full_restore_app_launch_handler_browsertest.cc +++ b/chrome/browser/ash/app_restore/full_restore_app_launch_handler_browsertest.cc
@@ -1412,10 +1412,8 @@ app_restore::AppRestoreArcTaskHandler::GetForProfile(profile()); ASSERT_TRUE(arc_task_handler); - arc_task_handler->CreateFullRestoreHandlerForTest(); - arc_app_launch_handler_ = - arc_task_handler->full_restore_arc_app_launch_handler(); + arc_task_handler->GetFullRestoreArcAppLaunchHandler(); DCHECK(arc_app_launch_handler_); arc_app_launch_handler_->is_app_connection_ready_ = false; @@ -2348,7 +2346,7 @@ if (!arc_app_launch_handler_) { arc_app_launch_handler_ = app_restore::AppRestoreArcTaskHandler::GetForProfile(profile()) - ->full_restore_arc_app_launch_handler(); + ->GetFullRestoreArcAppLaunchHandler(); } arc_app_launch_handler_->OnAppConnectionReady(); }
diff --git a/chrome/browser/ash/arc/input_overlay/db/proto/app_data.proto b/chrome/browser/ash/arc/input_overlay/db/proto/app_data.proto index 9ee5c65..bdec3b7 100644 --- a/chrome/browser/ash/arc/input_overlay/db/proto/app_data.proto +++ b/chrome/browser/ash/arc/input_overlay/db/proto/app_data.proto
@@ -55,7 +55,7 @@ message ActionProto { // Action ID. Each action has a unique ID within the game/app. - required uint32 id = 1; + required int32 id = 1; // Input Element. Customized input binding for this action. optional InputElementProto input_element = 2; // Customized Positions for this action. Now it only saves one position. Use
diff --git a/chrome/browser/ash/arc/input_overlay/touch_injector_unittest.cc b/chrome/browser/ash/arc/input_overlay/touch_injector_unittest.cc index d9c1adcc..95b18438 100644 --- a/chrome/browser/ash/arc/input_overlay/touch_injector_unittest.cc +++ b/chrome/browser/ash/arc/input_overlay/touch_injector_unittest.cc
@@ -871,42 +871,42 @@ auto json_value = base::JSONReader::ReadAndReturnValueWithError(kValidJsonActionTapKey); injector_->ParseActions(*json_value); - EXPECT_EQ(2, (int)injector_->actions().size()); + EXPECT_EQ(2u, injector_->actions().size()); // Add->Save. injector_->AddNewAction(ActionType::MOVE); - EXPECT_EQ(1, (int)GetPendingAddActions().size()); + EXPECT_EQ(1u, GetPendingAddActions().size()); injector_->OnBindingSave(); - EXPECT_EQ(3, (int)injector_->actions().size()); - EXPECT_EQ(0, (int)GetPendingAddActions().size()); + EXPECT_EQ(3u, injector_->actions().size()); + EXPECT_EQ(0u, GetPendingAddActions().size()); EXPECT_EQ(kMaxDefaultActionID + 1, injector_->actions().back()->id()); EXPECT_EQ(kMaxDefaultActionID + 2, GetNextActionID()); // Add->Save->Restore->Save. Final result only has default actions. injector_->AddNewAction(ActionType::TAP); injector_->AddNewAction(ActionType::MOVE); - EXPECT_EQ(2, (int)GetPendingAddActions().size()); + EXPECT_EQ(2u, GetPendingAddActions().size()); injector_->OnBindingSave(); - EXPECT_EQ(0, (int)GetPendingAddActions().size()); - EXPECT_EQ(5, (int)injector_->actions().size()); + EXPECT_EQ(0u, GetPendingAddActions().size()); + EXPECT_EQ(5u, injector_->actions().size()); EXPECT_EQ(kMaxDefaultActionID + 2, (injector_->actions().rbegin() + 1)->get()->id()); EXPECT_EQ(kMaxDefaultActionID + 3, injector_->actions().back()->id()); EXPECT_EQ(kMaxDefaultActionID + 4, GetNextActionID()); injector_->OnBindingRestore(); - EXPECT_EQ(2, (int)injector_->actions().size()); - EXPECT_EQ(0, (int)GetPendingAddActions().size()); + EXPECT_EQ(2u, injector_->actions().size()); + EXPECT_EQ(0u, GetPendingAddActions().size()); EXPECT_EQ(kMaxDefaultActionID + 1, GetNextActionID()); injector_->OnBindingSave(); - EXPECT_EQ(2, (int)injector_->actions().size()); + EXPECT_EQ(2u, injector_->actions().size()); // Add->Cancel. Nothing is added. injector_->AddNewAction(ActionType::TAP); injector_->AddNewAction(ActionType::MOVE); - EXPECT_EQ(2, (int)GetPendingAddActions().size()); + EXPECT_EQ(2u, GetPendingAddActions().size()); injector_->OnBindingCancel(); - EXPECT_EQ(0, (int)GetPendingAddActions().size()); - EXPECT_EQ(2, (int)injector_->actions().size()); + EXPECT_EQ(0u, GetPendingAddActions().size()); + EXPECT_EQ(2u, injector_->actions().size()); EXPECT_EQ(kMaxDefaultActionID + 1, GetNextActionID()); // Add->Cancel->Add->Save. Second "add" is saved. @@ -915,15 +915,15 @@ EXPECT_EQ(kMaxDefaultActionID + 1, (GetPendingAddActions().rbegin() + 1)->get()->id()); EXPECT_EQ(kMaxDefaultActionID + 2, GetPendingAddActions().back()->id()); - EXPECT_EQ(2, (int)GetPendingAddActions().size()); + EXPECT_EQ(2u, GetPendingAddActions().size()); injector_->OnBindingCancel(); EXPECT_EQ(kMaxDefaultActionID + 1, GetNextActionID()); - EXPECT_EQ(2, (int)injector_->actions().size()); - EXPECT_EQ(0, (int)GetPendingAddActions().size()); + EXPECT_EQ(2u, injector_->actions().size()); + EXPECT_EQ(0u, GetPendingAddActions().size()); injector_->AddNewAction(ActionType::MOVE); - EXPECT_EQ(1, (int)GetPendingAddActions().size()); + EXPECT_EQ(1u, GetPendingAddActions().size()); injector_->OnBindingSave(); - EXPECT_EQ(3, (int)injector_->actions().size()); + EXPECT_EQ(3u, injector_->actions().size()); EXPECT_EQ(kMaxDefaultActionID + 1, injector_->actions().back()->id()); EXPECT_EQ(kMaxDefaultActionID + 2, GetNextActionID()); // Reset. @@ -934,20 +934,20 @@ injector_->AddNewAction(ActionType::MOVE); injector_->AddNewAction(ActionType::TAP); injector_->OnBindingSave(); - EXPECT_EQ(4, (int)injector_->actions().size()); - EXPECT_EQ(0, (int)GetPendingAddActions().size()); + EXPECT_EQ(4u, injector_->actions().size()); + EXPECT_EQ(0u, GetPendingAddActions().size()); EXPECT_EQ(kMaxDefaultActionID + 1, (injector_->actions().rbegin() + 1)->get()->id()); EXPECT_EQ(kMaxDefaultActionID + 2, injector_->actions().back()->id()); EXPECT_EQ(kMaxDefaultActionID + 3, GetNextActionID()); injector_->OnBindingRestore(); - EXPECT_EQ(2, (int)injector_->actions().size()); - EXPECT_EQ(2, (int)GetPendingDeleteActions().size()); + EXPECT_EQ(2u, injector_->actions().size()); + EXPECT_EQ(2u, GetPendingDeleteActions().size()); EXPECT_EQ(kMaxDefaultActionID + 1, GetNextActionID()); injector_->OnBindingCancel(); - EXPECT_EQ(4, (int)injector_->actions().size()); - EXPECT_EQ(0, (int)GetPendingAddActions().size()); - EXPECT_EQ(0, (int)GetPendingDeleteActions().size()); + EXPECT_EQ(4u, injector_->actions().size()); + EXPECT_EQ(0u, GetPendingAddActions().size()); + EXPECT_EQ(0u, GetPendingDeleteActions().size()); EXPECT_EQ(kMaxDefaultActionID + 1, (injector_->actions().rbegin() + 1)->get()->id()); EXPECT_EQ(kMaxDefaultActionID + 2, injector_->actions().back()->id());
diff --git a/chrome/browser/ash/arc/window_predictor/arc_predictor_app_launch_handler.cc b/chrome/browser/ash/arc/window_predictor/arc_predictor_app_launch_handler.cc index 8fcd2dc..48c9582 100644 --- a/chrome/browser/ash/arc/window_predictor/arc_predictor_app_launch_handler.cc +++ b/chrome/browser/ash/arc/window_predictor/arc_predictor_app_launch_handler.cc
@@ -5,14 +5,15 @@ #include "chrome/browser/ash/arc/window_predictor/arc_predictor_app_launch_handler.h" #include "chrome/browser/ash/arc/window_predictor/window_predictor_utils.h" +#include "chrome/browser/profiles/profile_manager.h" #include "components/app_restore/app_launch_info.h" #include "components/app_restore/window_info.h" #include "ui/display/screen.h" namespace arc { -ArcPredictorAppLaunchHandler::ArcPredictorAppLaunchHandler(Profile* profile) - : ash::AppLaunchHandler(profile) { +ArcPredictorAppLaunchHandler::ArcPredictorAppLaunchHandler() + : ash::AppLaunchHandler(ProfileManager::GetPrimaryUserProfile()) { set_restore_data(std::make_unique<app_restore::RestoreData>()); }
diff --git a/chrome/browser/ash/arc/window_predictor/arc_predictor_app_launch_handler.h b/chrome/browser/ash/arc/window_predictor/arc_predictor_app_launch_handler.h index a0e0f51..d52f998 100644 --- a/chrome/browser/ash/arc/window_predictor/arc_predictor_app_launch_handler.h +++ b/chrome/browser/ash/arc/window_predictor/arc_predictor_app_launch_handler.h
@@ -18,7 +18,7 @@ // policy to control the system resource usage. class ArcPredictorAppLaunchHandler : public ash::AppLaunchHandler { public: - explicit ArcPredictorAppLaunchHandler(Profile* profile); + ArcPredictorAppLaunchHandler(); ArcPredictorAppLaunchHandler(const ArcPredictorAppLaunchHandler&) = delete; ArcPredictorAppLaunchHandler& operator=(const ArcPredictorAppLaunchHandler&) = delete;
diff --git a/chrome/browser/ash/arc/window_predictor/window_predictor.cc b/chrome/browser/ash/arc/window_predictor/window_predictor.cc index b6a66942..73b25d12 100644 --- a/chrome/browser/ash/arc/window_predictor/window_predictor.cc +++ b/chrome/browser/ash/arc/window_predictor/window_predictor.cc
@@ -4,8 +4,11 @@ #include "chrome/browser/ash/arc/window_predictor/window_predictor.h" +#include "base/metrics/histogram_functions.h" #include "base/no_destructor.h" #include "chrome/browser/ash/app_restore/app_launch_handler.h" +#include "chrome/browser/ash/app_restore/app_restore_arc_task_handler.h" +#include "chrome/browser/ash/app_restore/arc_app_launch_handler.h" #include "chromeos/ui/base/window_state_type.h" #include "ui/display/screen.h" #include "ui/gfx/geometry/point.h" @@ -14,6 +17,19 @@ namespace { +constexpr char kWindowPredictorLaunchHistogram[] = "Arc.WindowPredictorLaunch"; + +// Reason for Window Predictor launch action enumeration; Used for UMA counter. +// These values are persisted to logs. Entries should not be renumbered and +// numeric values should never be reused. +enum class WindowPredictorLaunchType { + kSuccess = 0, + kFailedNoArcTaskHandler = 1, + kFailedAppPendingRestore = 2, + kFailedNoArcAppLaunchHandler = 3, + kMaxValue = kFailedNoArcAppLaunchHandler, +}; + // Pre-defined screen size for ARC. See ArcLaunchParamsModifier.java in ARC // codebase. @@ -60,12 +76,44 @@ WindowPredictor::~WindowPredictor() = default; -void WindowPredictor::MaybeCreateAppLaunchHandler(Profile* profile) { - DCHECK(profile); - if (app_launch_handler_ && app_launch_handler_->profile() == profile) - return; +bool WindowPredictor::LaunchArcAppWithGhostWindow( + Profile* profile, + const std::string& arc_app_id, + const ArcAppListPrefs::AppInfo& app_info, + int event_flags, + GhostWindowType window_type, + const arc::mojom::WindowInfoPtr& window_info) { + auto* arc_task_handler = + ash::app_restore::AppRestoreArcTaskHandler::GetForProfile(profile); + if (!arc_task_handler) { + base::UmaHistogramEnumeration( + kWindowPredictorLaunchHistogram, + WindowPredictorLaunchType::kFailedNoArcTaskHandler); + return false; + } - app_launch_handler_ = std::make_unique<ArcPredictorAppLaunchHandler>(profile); + // Do not launch ghost window and App if it exist in full restore pending + // launch queue. + if (arc_task_handler->IsAppPendingRestore(arc_app_id)) { + base::UmaHistogramEnumeration( + kWindowPredictorLaunchHistogram, + WindowPredictorLaunchType::kFailedAppPendingRestore); + return false; + } + + arc::mojom::WindowInfoPtr predict_window_info = + PredictAppWindowInfo(app_info, window_info.Clone()); + + auto data_handler = std::make_unique<ArcPredictorAppLaunchHandler>(); + data_handler->AddPendingApp(arc_app_id, event_flags, window_type, + std::move(predict_window_info)); + arc_task_handler->GetWindowPredictorArcAppLaunchHandler(handlers_.size()) + ->RestoreArcApps(data_handler.get()); + handlers_.push_back(std::move(data_handler)); + + base::UmaHistogramEnumeration(kWindowPredictorLaunchHistogram, + WindowPredictorLaunchType::kSuccess); + return true; } arc::mojom::WindowInfoPtr WindowPredictor::PredictAppWindowInfo(
diff --git a/chrome/browser/ash/arc/window_predictor/window_predictor.h b/chrome/browser/ash/arc/window_predictor/window_predictor.h index 61e9cd92..6292f32 100644 --- a/chrome/browser/ash/arc/window_predictor/window_predictor.h +++ b/chrome/browser/ash/arc/window_predictor/window_predictor.h
@@ -6,14 +6,13 @@ #define CHROME_BROWSER_ASH_ARC_WINDOW_PREDICTOR_WINDOW_PREDICTOR_H_ #include <memory> +#include <vector> #include "ash/components/arc/mojom/app.mojom.h" #include "base/no_destructor.h" #include "chrome/browser/ash/arc/window_predictor/arc_predictor_app_launch_handler.h" #include "chrome/browser/ui/app_list/arc/arc_app_list_prefs.h" -class Profile; - namespace arc { // Predict ARC app window initial launch window parameters and launch @@ -26,24 +25,27 @@ WindowPredictor(const WindowPredictor&) = delete; WindowPredictor& operator=(const WindowPredictor&) = delete; - // Create App Launch Handler. - void MaybeCreateAppLaunchHandler(Profile* profile); + // Create ARC app ghost window and add the corresponding to the launching + // list, it will be launched after ARC ready. + bool LaunchArcAppWithGhostWindow( + Profile* profile, + const std::string& app_id, + const ArcAppListPrefs::AppInfo& app_info, + int event_flags, + GhostWindowType window_type, + const arc::mojom::WindowInfoPtr& window_info); // Get predict app window info by app id and existed window info. arc::mojom::WindowInfoPtr PredictAppWindowInfo( const ArcAppListPrefs::AppInfo& app_info, arc::mojom::WindowInfoPtr window_info); - ArcPredictorAppLaunchHandler* app_launch_handler() { - return app_launch_handler_.get(); - } - private: friend class base::NoDestructor<WindowPredictor>; WindowPredictor(); ~WindowPredictor(); - std::unique_ptr<ArcPredictorAppLaunchHandler> app_launch_handler_; + std::vector<std::unique_ptr<ArcPredictorAppLaunchHandler>> handlers_; }; } // namespace arc
diff --git a/chrome/browser/ash/arc/window_predictor/window_predictor_utils.cc b/chrome/browser/ash/arc/window_predictor/window_predictor_utils.cc index 37563fd..12c2a73 100644 --- a/chrome/browser/ash/arc/window_predictor/window_predictor_utils.cc +++ b/chrome/browser/ash/arc/window_predictor/window_predictor_utils.cc
@@ -4,82 +4,11 @@ #include "chrome/browser/ash/arc/window_predictor/window_predictor_utils.h" -#include "base/metrics/histogram_functions.h" -#include "chrome/browser/ash/app_restore/app_restore_arc_task_handler.h" -#include "chrome/browser/ash/app_restore/arc_app_launch_handler.h" -#include "chrome/browser/ash/arc/window_predictor/window_predictor.h" +#include "chromeos/ui/base/window_state_type.h" +#include "components/app_restore/app_restore_data.h" namespace arc { -namespace { - -constexpr char kWindowPredictorLaunchHistogram[] = "Arc.WindowPredictorLaunch"; - -// Reason for Window Predictor launch action enumeration; Used for UMA counter. -// These values are persisted to logs. Entries should not be renumbered and -// numeric values should never be reused. -enum class WindowPredictorLaunchType { - kSuccess = 0, - kFailedNoArcTaskHandler = 1, - kFailedAppPendingRestore = 2, - kFailedNoArcAppLaunchHandler = 3, - kMaxValue = kFailedNoArcAppLaunchHandler, -}; - -} // namespace - -bool LaunchArcAppWithGhostWindow(Profile* profile, - const std::string& arc_app_id, - const ArcAppListPrefs::AppInfo& app_info, - int event_flags, - arc::UserInteractionType user_interaction_type, - GhostWindowType window_type, - const arc::mojom::WindowInfoPtr& window_info) { - WindowPredictor::GetInstance()->MaybeCreateAppLaunchHandler(profile); - - auto* arc_task_handler = - ash::app_restore::AppRestoreArcTaskHandler::GetForProfile(profile); - if (!arc_task_handler) { - base::UmaHistogramEnumeration( - kWindowPredictorLaunchHistogram, - WindowPredictorLaunchType::kFailedNoArcTaskHandler); - return false; - } - - // Do not launch ghost window and App if it exist in any pending launch - // queue. - if (arc_task_handler->IsAppPendingRestore(arc_app_id)) { - base::UmaHistogramEnumeration( - kWindowPredictorLaunchHistogram, - WindowPredictorLaunchType::kFailedAppPendingRestore); - return false; - } - - auto* arc_app_launch_handler = - arc_task_handler->window_predictor_arc_app_launch_handler(); - if (!arc_app_launch_handler) { - base::UmaHistogramEnumeration( - kWindowPredictorLaunchHistogram, - WindowPredictorLaunchType::kFailedNoArcAppLaunchHandler); - return false; - } - - arc::mojom::WindowInfoPtr predict_window_info = - WindowPredictor::GetInstance()->PredictAppWindowInfo(app_info, - window_info.Clone()); - auto* app_launch_handler = - WindowPredictor::GetInstance()->app_launch_handler(); - DCHECK(app_launch_handler); - - app_launch_handler->AddPendingApp(arc_app_id, event_flags, window_type, - std::move(predict_window_info)); - arc_app_launch_handler->RestoreArcApps(app_launch_handler); - - base::UmaHistogramEnumeration(kWindowPredictorLaunchHistogram, - WindowPredictorLaunchType::kSuccess); - return true; -} - bool CanLaunchGhostWindowByRestoreData( const app_restore::AppRestoreData& restore_data) { const bool not_need_bounds =
diff --git a/chrome/browser/ash/arc/window_predictor/window_predictor_utils.h b/chrome/browser/ash/arc/window_predictor/window_predictor_utils.h index 029e5093..626e143 100644 --- a/chrome/browser/ash/arc/window_predictor/window_predictor_utils.h +++ b/chrome/browser/ash/arc/window_predictor/window_predictor_utils.h
@@ -5,11 +5,7 @@ #ifndef CHROME_BROWSER_ASH_ARC_WINDOW_PREDICTOR_WINDOW_PREDICTOR_UTILS_H_ #define CHROME_BROWSER_ASH_ARC_WINDOW_PREDICTOR_WINDOW_PREDICTOR_UTILS_H_ -#include "ash/components/arc/metrics/arc_metrics_constants.h" #include "ash/components/arc/mojom/app.mojom.h" -#include "chrome/browser/ui/app_list/arc/arc_app_list_prefs.h" - -class Profile; namespace app_restore { struct AppRestoreData; @@ -31,16 +27,6 @@ kMaxValue = kFixup, }; -// Create ARC app ghost window and add the corresponding to the launching list, -// it will be launched after ARC ready. -bool LaunchArcAppWithGhostWindow(Profile* profile, - const std::string& app_id, - const ArcAppListPrefs::AppInfo& app_info, - int event_flags, - arc::UserInteractionType user_interaction_type, - GhostWindowType window_type, - const arc::mojom::WindowInfoPtr& window_info); - // Is the the window info provide enough data to create corresponding ARC ghost // window. bool CanLaunchGhostWindowByRestoreData(
diff --git a/chrome/browser/ash/camera_mic/vm_camera_mic_manager.cc b/chrome/browser/ash/camera_mic/vm_camera_mic_manager.cc index 4870d8d1..9597d4e 100644 --- a/chrome/browser/ash/camera_mic/vm_camera_mic_manager.cc +++ b/chrome/browser/ash/camera_mic/vm_camera_mic_manager.cc
@@ -215,10 +215,11 @@ if (ash::features::IsPrivacyIndicatorsEnabled()) { ash::UpdatePrivacyIndicatorsView( - /*is_camera_used=*/new_notification[static_cast<size_t>( - DeviceType::kCamera)], - /*is_microphone_used=*/new_notification[static_cast<size_t>( - DeviceType::kMic)]); + /*app_id=*/GetNotificationId(vm_type_, new_notification), + /*is_camera_used=*/ + new_notification[static_cast<size_t>(DeviceType::kCamera)], + /*is_microphone_used=*/ + new_notification[static_cast<size_t>(DeviceType::kMic)]); } notification_changed_callback_.Run();
diff --git a/chrome/browser/ash/chrome_browser_main_parts_ash.cc b/chrome/browser/ash/chrome_browser_main_parts_ash.cc index 789a622a..add33c6b 100644 --- a/chrome/browser/ash/chrome_browser_main_parts_ash.cc +++ b/chrome/browser/ash/chrome_browser_main_parts_ash.cc
@@ -15,7 +15,6 @@ #include "ash/components/arc/enterprise/arc_data_snapshotd_manager.h" #include "ash/components/fwupd/firmware_update_manager.h" #include "ash/components/peripheral_notification/peripheral_notification_manager.h" -#include "ash/components/tpm/tpm_token_loader.h" #include "ash/constants/ash_features.h" #include "ash/constants/ash_switches.h" #include "ash/keyboard/ui/resources/keyboard_resource_util.h" @@ -212,6 +211,7 @@ #include "chromeos/ash/components/network/system_token_cert_db_storage.h" #include "chromeos/ash/components/power/dark_resume_controller.h" #include "chromeos/ash/components/settings/cros_settings_names.h" +#include "chromeos/ash/components/tpm/tpm_token_loader.h" #include "chromeos/ash/services/cros_healthd/private/cpp/data_collector.h" #include "chromeos/ash/services/cros_healthd/public/cpp/service_connection.h" #include "chromeos/components/sensors/ash/sensor_hal_dispatcher.h"
diff --git a/chrome/browser/ash/crosapi/BUILD.gn b/chrome/browser/ash/crosapi/BUILD.gn index 8299b949..7f92b26 100644 --- a/chrome/browser/ash/crosapi/BUILD.gn +++ b/chrome/browser/ash/crosapi/BUILD.gn
@@ -244,7 +244,6 @@ "//ash/components/arc:arc_base_utils", "//ash/components/arc/mojom", "//ash/components/arc/session", - "//ash/components/tpm", "//ash/constants", "//ash/webui/camera_app_ui", "//ash/webui/connectivity_diagnostics", @@ -282,6 +281,7 @@ "//chromeos/ash/components/login/auth", "//chromeos/ash/components/network", "//chromeos/ash/components/settings", + "//chromeos/ash/components/tpm", "//chromeos/components/cdm_factory_daemon:cdm_factory_daemon_browser", "//chromeos/components/certificate_provider:certificate_provider", "//chromeos/components/quick_answers/public/cpp:prefs",
diff --git a/chrome/browser/ash/crosapi/browser_data_migrator_util.h b/chrome/browser/ash/crosapi/browser_data_migrator_util.h index f21b590..fed99c7 100644 --- a/chrome/browser/ash/crosapi/browser_data_migrator_util.h +++ b/chrome/browser/ash/crosapi/browser_data_migrator_util.h
@@ -173,6 +173,7 @@ "Service Worker", "Session Storage", "Sessions", + "SharedStorage", "Shortcuts", "Storage", "Sync App Settings", @@ -187,11 +188,11 @@ // thus should be copied to lacros while keeping the original files/dirs in ash // data dir. constexpr const char* const kNeedCopyForMoveDataPaths[]{ - "DNR Extension Rules", "Extension Cookies", "Policy", "shared_proto_db"}; + "DNR Extension Rules", "Extension Cookies", "shared_proto_db"}; // The same as `kNeedCopyDataPathsForMove` + "Preferences". constexpr const char* const kNeedCopyForCopyDataPaths[]{ - "DNR Extension Rules", "Extension Cookies", "Policy", "Preferences", + "DNR Extension Rules", "Extension Cookies", "Preferences", "shared_proto_db"}; // List of extension ids to be kept in Ash.
diff --git a/chrome/browser/ash/crosapi/browser_data_migrator_util_unittest.cc b/chrome/browser/ash/crosapi/browser_data_migrator_util_unittest.cc index 2e276f6..2c4e17ba 100644 --- a/chrome/browser/ash/crosapi/browser_data_migrator_util_unittest.cc +++ b/chrome/browser/ash/crosapi/browser_data_migrator_util_unittest.cc
@@ -30,7 +30,7 @@ namespace { constexpr char kDownloadsPath[] = "Downloads"; -constexpr char kPolicyDataPath[] = "Policy"; +constexpr char kSharedProtoDBPath[] = "shared_proto_db"; constexpr char kBookmarksPath[] = "Bookmarks"; constexpr char kCookiesPath[] = "Cookies"; constexpr char kCachePath[] = "Cache"; @@ -635,7 +635,7 @@ // |- Downloads/ /* remain in ash */ // |- file // |- file 2 - // |- Policy /* need to copy */ + // |- shared_proto_db /* need to copy */ // |- Cache /* deletable */ // |- Code Cache/ /* deletable */ // |- file @@ -658,7 +658,7 @@ kTextFileContent, kTextFileSize)); // Need to copy items. - ASSERT_TRUE(base::WriteFile(profile_data_dir_.Append(kPolicyDataPath), + ASSERT_TRUE(base::WriteFile(profile_data_dir_.Append(kSharedProtoDBPath), kTextFileContent, kTextFileSize)); // Deletable items. @@ -708,7 +708,7 @@ // Check for items that need copies in lacros. std::vector<TargetItem> expected_need_copy_items = { - {profile_data_dir_.Append(kPolicyDataPath), kTextFileSize, + {profile_data_dir_.Append(kSharedProtoDBPath), kTextFileSize, TargetItem::ItemType::kFile}}; TargetItems need_copy_items = GetTargetItems(profile_data_dir_, ItemType::kNeedCopyForMove); @@ -748,9 +748,9 @@ const std::string uma_name_downloads = std::string(browser_data_migrator_util::kUserDataStatsRecorderDataSize) + "Downloads"; - const std::string uma_name_policy = + const std::string uma_name_shared_proto_db = std::string(browser_data_migrator_util::kUserDataStatsRecorderDataSize) + - "Policy"; + "SharedProtoDb"; const std::string uma_name_cache = std::string(browser_data_migrator_util::kUserDataStatsRecorderDataSize) + "Cache"; @@ -764,7 +764,7 @@ kTextFileSize / 1024 / 1024, 1); histogram_tester.ExpectBucketCount(uma_name_downloads, kTextFileSize * 2 / 1024 / 1024, 1); - histogram_tester.ExpectBucketCount(uma_name_policy, + histogram_tester.ExpectBucketCount(uma_name_shared_proto_db, kTextFileSize / 1024 / 1024, 1); histogram_tester.ExpectBucketCount(uma_name_cache, kTextFileSize / 1024 / 1024, 1);
diff --git a/chrome/browser/ash/crosapi/browser_util.cc b/chrome/browser/ash/crosapi/browser_util.cc index 9a580a8..a631d0fe 100644 --- a/chrome/browser/ash/crosapi/browser_util.cc +++ b/chrome/browser/ash/crosapi/browser_util.cc
@@ -74,7 +74,6 @@ bool IsUserTypeAllowed(const User* user) { switch (user->GetType()) { case user_manager::USER_TYPE_REGULAR: - case user_manager::USER_TYPE_WEB_KIOSK_APP: case user_manager::USER_TYPE_PUBLIC_ACCOUNT: // Note: Lacros will not be enabled for Guest users unless LacrosSupport // flag is passed in --enable-features. See https://crbug.com/1294051#c25. @@ -82,6 +81,8 @@ return true; case user_manager::USER_TYPE_CHILD: return base::FeatureList::IsEnabled(kLacrosForSupervisedUsers); + case user_manager::USER_TYPE_WEB_KIOSK_APP: + return base::FeatureList::IsEnabled(features::kWebKioskEnableLacros); case user_manager::USER_TYPE_KIOSK_APP: return base::FeatureList::IsEnabled(features::kChromeKioskEnableLacros); case user_manager::USER_TYPE_ARC_KIOSK_APP: @@ -726,13 +727,11 @@ bool IsLacrosEnabledInWebKioskSession() { return user_manager::UserManager::Get()->IsLoggedInAsWebKioskApp() && - base::FeatureList::IsEnabled(features::kWebKioskEnableLacros) && IsLacrosEnabled(); } bool IsLacrosEnabledInChromeKioskSession() { return user_manager::UserManager::Get()->IsLoggedInAsKioskApp() && - base::FeatureList::IsEnabled(features::kChromeKioskEnableLacros) && IsLacrosEnabled(); }
diff --git a/chrome/browser/ash/crosapi/cert_database_ash.cc b/chrome/browser/ash/crosapi/cert_database_ash.cc index d0a8d83..7a47c13 100644 --- a/chrome/browser/ash/crosapi/cert_database_ash.cc +++ b/chrome/browser/ash/crosapi/cert_database_ash.cc
@@ -6,7 +6,6 @@ #include <algorithm> -#include "ash/components/tpm/tpm_token_info_getter.h" #include "base/bind.h" #include "base/ranges/algorithm.h" #include "base/system/sys_info.h" @@ -16,6 +15,7 @@ #include "chrome/browser/net/nss_service.h" #include "chrome/browser/net/nss_service_factory.h" #include "chrome/browser/profiles/profile_manager.h" +#include "chromeos/ash/components/tpm/tpm_token_info_getter.h" #include "chromeos/crosapi/mojom/cert_database.mojom.h" #include "chromeos/login/login_state/login_state.h" #include "components/account_id/account_id.h"
diff --git a/chrome/browser/ash/crosapi/move_migrator_unittest.cc b/chrome/browser/ash/crosapi/move_migrator_unittest.cc index 125f9fe..103bc4c 100644 --- a/chrome/browser/ash/crosapi/move_migrator_unittest.cc +++ b/chrome/browser/ash/crosapi/move_migrator_unittest.cc
@@ -41,7 +41,7 @@ constexpr char kCookiesFilePath[] = "Cookies"; // lacros constexpr char kDownloadsFilePath[] = "Downloads"; // remain in ash constexpr char kExtensionStateFilePath[] = "Extension State"; // split -constexpr char kPolicyFilePath[] = "Policy"; // need copy +constexpr char kSharedProtoDBPath[] = "shared_proto_db"; // need copy constexpr char kCacheFilePath[] = "Cache"; // deletable constexpr char kDataFilePath[] = "Data"; @@ -352,7 +352,7 @@ // |- IndexedDB/ // |- Local Storage/ // |- Login Data/ - // |- Policy/ + // |- shared_proto_db/ // |- Preferences // |- Storage/ // |- Sync Data/ @@ -378,10 +378,11 @@ base::WriteFile(path.Append(kCookiesFilePath), kDataContent, kDataSize), kDataSize); - ASSERT_TRUE(base::CreateDirectory(path.Append(kPolicyFilePath))); - ASSERT_EQ(base::WriteFile(path.Append(kPolicyFilePath).Append(kDataFilePath), - kDataContent, kDataSize), - kDataSize); + ASSERT_TRUE(base::CreateDirectory(path.Append(kSharedProtoDBPath))); + ASSERT_EQ( + base::WriteFile(path.Append(kSharedProtoDBPath).Append(kDataFilePath), + kDataContent, kDataSize), + kDataSize); ASSERT_TRUE(base::CreateDirectory( path.Append(browser_data_migrator_util::kSyncDataFilePath))); @@ -510,7 +511,7 @@ // Check chrome::kFirstRunSentinel, need copy item and lacros item exist in // lacros dir. EXPECT_TRUE(base::PathExists(tmp_user_dir.Append(chrome::kFirstRunSentinel))); - EXPECT_TRUE(base::PathExists(tmp_profile_dir.Append(kPolicyFilePath))); + EXPECT_TRUE(base::PathExists(tmp_profile_dir.Append(kSharedProtoDBPath))); } TEST(MoveMigratorTest, MoveLacrosItemsToNewDir) { @@ -741,7 +742,7 @@ // |- IndexedDB // |- Local Storage // |- Login Data - // |- Policy + // |- shared_proto_db // |- Preferences // |- Storage/ // |- Sync Data/LevelDB @@ -752,7 +753,7 @@ // |- Extensions // |- IndexedDB // |- Local Storage - // |- Policy + // |- shared_proto_db // |- Preferences // |- Storage/ // |- Sync Data/ @@ -776,8 +777,8 @@ EXPECT_TRUE(base::PathExists(new_profile_dir.Append(kCookiesFilePath))); EXPECT_TRUE( - base::PathExists(original_profile_dir_.Append(kPolicyFilePath))); - EXPECT_TRUE(base::PathExists(new_profile_dir.Append(kPolicyFilePath))); + base::PathExists(original_profile_dir_.Append(kSharedProtoDBPath))); + EXPECT_TRUE(base::PathExists(new_profile_dir.Append(kSharedProtoDBPath))); EXPECT_TRUE( base::PathExists(original_profile_dir_.Append(kDownloadsFilePath))); @@ -952,14 +953,14 @@ // Setup `original_profile_dir_` as below. // |- Cookies // |- Downloads - // |- Policy + // |- shared_proto_db // |- move_migrator/First Run // |- move_migrator/Default/ // |- Bookmarks // |- Extensions // |- IndexedDB // |- Local Storage - // |- Policy + // |- shared_proto_db // |- Preferences // |- Storage/ // |- Sync Data/ @@ -988,9 +989,10 @@ 0); ASSERT_TRUE(base::CreateDirectory(tmp_profile_dir)); ASSERT_TRUE(base::CreateDirectory(tmp_split_dir)); - ASSERT_TRUE(base::CopyDirectory(original_profile_dir_.Append(kPolicyFilePath), - tmp_profile_dir.Append(kPolicyFilePath), - /*recursive=*/true)); + ASSERT_TRUE( + base::CopyDirectory(original_profile_dir_.Append(kSharedProtoDBPath), + tmp_profile_dir.Append(kSharedProtoDBPath), + /*recursive=*/true)); ASSERT_TRUE(base::Move(original_profile_dir_.Append(kBookmarksFilePath), tmp_profile_dir.Append(kBookmarksFilePath))); @@ -1061,7 +1063,7 @@ // Setup `original_profile_dir_` as below. // |- Downloads - // |- Policy + // |- shared_proto_db // |- move_migrator/First Run // |- move_migrator/Default/ // |- Bookmarks @@ -1069,7 +1071,7 @@ // |- Extensions // |- IndexedDB // |- Local Storage - // |- Policy + // |- shared_proto_db // |- Preferences // |- Storage/ // |- Sync Data/ @@ -1098,9 +1100,10 @@ 0); ASSERT_TRUE(base::CreateDirectory(tmp_profile_dir)); ASSERT_TRUE(base::CreateDirectory(tmp_split_dir)); - ASSERT_TRUE(base::CopyDirectory(original_profile_dir_.Append(kPolicyFilePath), - tmp_profile_dir.Append(kPolicyFilePath), - /*recursive=*/true)); + ASSERT_TRUE( + base::CopyDirectory(original_profile_dir_.Append(kSharedProtoDBPath), + tmp_profile_dir.Append(kSharedProtoDBPath), + /*recursive=*/true)); ASSERT_TRUE(base::Move(original_profile_dir_.Append(kBookmarksFilePath), tmp_profile_dir.Append(kBookmarksFilePath))); ASSERT_TRUE(base::Move(original_profile_dir_.Append(kCookiesFilePath), @@ -1178,7 +1181,7 @@ // |- Downloads // |- Extensions // |- Local Storage - // |- Policy + // |- shared_proto_db // |- Preferences // |- Storage/ // |- Sync Data/LevelDB @@ -1188,7 +1191,7 @@ // |- Cookies // |- Extensions // |- Local Storage - // |- Policy + // |- shared_proto_db // |- Preferences // |- Storage/ // |- Sync Data/ @@ -1207,9 +1210,10 @@ base::WriteFile(tmp_user_dir.Append(chrome::kFirstRunSentinel), "", 0), 0); ASSERT_TRUE(base::CreateDirectory(tmp_profile_dir)); - ASSERT_TRUE(base::CopyDirectory(original_profile_dir_.Append(kPolicyFilePath), - tmp_profile_dir.Append(kPolicyFilePath), - /*recursive=*/true)); + ASSERT_TRUE( + base::CopyDirectory(original_profile_dir_.Append(kSharedProtoDBPath), + tmp_profile_dir.Append(kSharedProtoDBPath), + /*recursive=*/true)); ASSERT_TRUE(base::Move(original_profile_dir_.Append(kBookmarksFilePath), tmp_profile_dir.Append(kBookmarksFilePath))); ASSERT_TRUE(base::Move(original_profile_dir_.Append(kCookiesFilePath),
diff --git a/chrome/browser/ash/crosapi/test_controller_ash.cc b/chrome/browser/ash/crosapi/test_controller_ash.cc index 6645602..415fcf2 100644 --- a/chrome/browser/ash/crosapi/test_controller_ash.cc +++ b/chrome/browser/ash/crosapi/test_controller_ash.cc
@@ -22,6 +22,8 @@ #include "base/strings/utf_string_conversions.h" #include "base/version.h" #include "build/chromeos_buildflags.h" +#include "chrome/browser/apps/app_service/app_service_proxy.h" +#include "chrome/browser/apps/app_service/app_service_proxy_factory.h" #include "chrome/browser/ash/crosapi/browser_manager.h" #include "chrome/browser/ash/crosapi/input_method_test_interface_ash.h" #include "chrome/browser/ash/crosapi/vpn_service_ash.h" @@ -292,6 +294,14 @@ std::move(callback).Run(/*success=*/true); } +void TestControllerAsh::ReinitializeAppService( + ReinitializeAppServiceCallback callback) { + Profile* const profile = ProfileManager::GetPrimaryUserProfile(); + apps::AppServiceProxyFactory::GetForProfile(profile)->ReinitializeForTesting( + profile); + std::move(callback).Run(); +} + void TestControllerAsh::SelectItemInShelf(const std::string& item_id, SelectItemInShelfCallback callback) { ash::ShelfItemDelegate* delegate =
diff --git a/chrome/browser/ash/crosapi/test_controller_ash.h b/chrome/browser/ash/crosapi/test_controller_ash.h index 9c8f40d0..aac6afca 100644 --- a/chrome/browser/ash/crosapi/test_controller_ash.h +++ b/chrome/browser/ash/crosapi/test_controller_ash.h
@@ -61,6 +61,7 @@ void PinOrUnpinItemInShelf(const std::string& item_id, bool pin, PinOrUnpinItemInShelfCallback cb) override; + void ReinitializeAppService(ReinitializeAppServiceCallback callback) override; void SelectContextMenuForShelfItem( const std::string& item_id, uint32_t index,
diff --git a/chrome/browser/ash/crostini/crostini_manager.cc b/chrome/browser/ash/crostini/crostini_manager.cc index b218f1a..6d2a028 100644 --- a/chrome/browser/ash/crostini/crostini_manager.cc +++ b/chrome/browser/ash/crostini/crostini_manager.cc
@@ -2559,9 +2559,6 @@ guest_os::GuestOsSharePath::GetForProfile(profile_)->SharePath( vm_name, base::FilePath(file_manager::util::kSystemFontsPath), /*persist=*/false, base::DoNothing()); - // Share folders from Downloads, etc with VM. - guest_os::GuestOsSharePath::GetForProfile(profile_)->SharePersistedPaths( - vm_name, base::DoNothing()); // Run the original callback. std::move(callback).Run(/*success=*/true);
diff --git a/chrome/browser/ash/dbus/dlp_files_policy_service_provider.cc b/chrome/browser/ash/dbus/dlp_files_policy_service_provider.cc index 261eeed..f4d6c84 100644 --- a/chrome/browser/ash/dbus/dlp_files_policy_service_provider.cc +++ b/chrome/browser/ash/dbus/dlp_files_policy_service_provider.cc
@@ -33,6 +33,8 @@ return policy::DlpFilesController::FileAction::kUpload; case dlp::FileAction::OPEN: // TODO(crbug.com/1356109): Return open FileAction. + // TODO(crbug.com/1356109): Add copy FileAction. + // TODO(crbug.com/1356109): Add move FileAction. case dlp::FileAction::TRANSFER: return policy::DlpFilesController::FileAction::kTransfer; }
diff --git a/chrome/browser/ash/file_manager/file_tasks_unittest.cc b/chrome/browser/ash/file_manager/file_tasks_unittest.cc index 08a371c..9693a94 100644 --- a/chrome/browser/ash/file_manager/file_tasks_unittest.cc +++ b/chrome/browser/ash/file_manager/file_tasks_unittest.cc
@@ -634,6 +634,13 @@ : crostini_test_helper_(std::make_unique<crostini::CrostiniTestHelper>( test_profile_.get())), crostini_folder_(util::GetCrostiniMountDirectory(test_profile_.get())) { + // Disable kArcAndGuestOsFileTasksUseAppService to get Crostini file + // tasks from guest_os_file_tasks.cc. When the flag is enabled, we get + // Crostini file tasks from App Service and these test cases are covered in + // app_service_file_tasks_unittest.cc. + feature_list_.InitAndDisableFeature( + ash::features::kArcAndGuestOsFileTasksUseAppService); + ash::ConciergeClient::InitializeFake(/*fake_cicerone_client=*/nullptr); vm_tools::apps::App text_app = @@ -675,6 +682,7 @@ ->UpdateMimeTypes(mime_types_list); } ~FileManagerFileTasksCrostiniTest() override { + feature_list_.Reset(); crostini_test_helper_.reset(); test_profile_.reset(); ash::ConciergeClient::Shutdown(); @@ -699,6 +707,7 @@ return GURL("filesystem:chrome-extension://id/external/" + virtual_path); } + base::test::ScopedFeatureList feature_list_; std::unique_ptr<crostini::CrostiniTestHelper> crostini_test_helper_; base::FilePath crostini_folder_; std::string text_app_id_;
diff --git a/chrome/browser/ash/fusebox/fusebox_moniker.cc b/chrome/browser/ash/fusebox/fusebox_moniker.cc index 1605104..98b0fc3 100644 --- a/chrome/browser/ash/fusebox/fusebox_moniker.cc +++ b/chrome/browser/ash/fusebox/fusebox_moniker.cc
@@ -4,6 +4,7 @@ #include "chrome/browser/ash/fusebox/fusebox_moniker.h" +#include "base/strings/strcat.h" #include "content/public/browser/browser_thread.h" #include "third_party/cros_system_api/dbus/service_constants.h" @@ -83,4 +84,15 @@ return std::make_pair(storage::FileSystemURL(), false); } +base::Value MonikerMap::GetDebugJSON() { + base::Value::Dict dict; + for (const auto& i : map_) { + dict.Set(i.first.ToString(), + base::Value(base::StrCat( + {i.second.first.ToGURL().spec(), + i.second.second ? " (read-only)" : " (read-write)"}))); + } + return base::Value(std::move(dict)); +} + } // namespace fusebox
diff --git a/chrome/browser/ash/fusebox/fusebox_moniker.h b/chrome/browser/ash/fusebox/fusebox_moniker.h index 5c02f3e..f6bce4fe 100644 --- a/chrome/browser/ash/fusebox/fusebox_moniker.h +++ b/chrome/browser/ash/fusebox/fusebox_moniker.h
@@ -9,6 +9,7 @@ #include <utility> #include "base/token.h" +#include "base/values.h" #include "storage/browser/file_system/file_system_url.h" namespace fusebox { @@ -111,6 +112,9 @@ // CreateMoniker. FSURLAndReadOnlyState Resolve(const Moniker& moniker); + // Returns human-readable debugging information as a JSON value. + base::Value GetDebugJSON(); + private: std::map<base::Token, FSURLAndReadOnlyState> map_; };
diff --git a/chrome/browser/ash/fusebox/fusebox_server.cc b/chrome/browser/ash/fusebox/fusebox_server.cc index 6a6bd9f6..235feb2 100644 --- a/chrome/browser/ash/fusebox/fusebox_server.cc +++ b/chrome/browser/ash/fusebox/fusebox_server.cc
@@ -380,6 +380,22 @@ ->CrackURLInFirstPartyContext(GURL(resolved.first)); } +base::Value Server::GetDebugJSON() { + base::Value::Dict subdirs; + subdirs.Set(kMonikerSubdir, base::Value("[special]")); + for (const auto& i : prefix_map_) { + subdirs.Set(i.first, + base::Value(base::StrCat( + {i.second.fs_url_prefix, + i.second.read_only ? " (read-only)" : " (read-write)"}))); + } + + base::Value::Dict dict; + dict.Set("monikers", moniker_map_.GetDebugJSON()); + dict.Set("subdirs", std::move(subdirs)); + return base::Value(std::move(dict)); +} + void Server::Close(std::string fs_url_as_string, CloseCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
diff --git a/chrome/browser/ash/fusebox/fusebox_server.h b/chrome/browser/ash/fusebox/fusebox_server.h index 7d52b2d..cc2a60e7 100644 --- a/chrome/browser/ash/fusebox/fusebox_server.h +++ b/chrome/browser/ash/fusebox/fusebox_server.h
@@ -10,6 +10,7 @@ #include "base/callback_forward.h" #include "base/files/file.h" #include "base/memory/weak_ptr.h" +#include "base/values.h" #include "chrome/browser/ash/fusebox/fusebox_moniker.h" #include "chrome/browser/ash/fusebox/fusebox_staging.pb.h" #include "chromeos/ash/components/dbus/fusebox/fusebox.pb.h" @@ -65,6 +66,9 @@ storage::FileSystemURL ResolveFilename(Profile* profile, const std::string& filename); + // Returns human-readable debugging information as a JSON value. + base::Value GetDebugJSON(); + // These methods map 1:1 to the D-Bus methods implemented by // fusebox_service_provider.cc. //
diff --git a/chrome/browser/ash/guest_os/guest_os_session_tracker.cc b/chrome/browser/ash/guest_os/guest_os_session_tracker.cc index 6d43dddc..8b3fc18 100644 --- a/chrome/browser/ash/guest_os/guest_os_session_tracker.cc +++ b/chrome/browser/ash/guest_os/guest_os_session_tracker.cc
@@ -132,6 +132,15 @@ return iter->second; } +absl::optional<vm_tools::concierge::VmInfo> GuestOsSessionTracker::GetVmInfo( + const std::string& vm_name) { + auto iter = vms_.find(vm_name); + if (iter == vms_.end()) { + return absl::nullopt; + } + return iter->second; +} + bool GuestOsSessionTracker::IsRunning(const GuestId& id) { return guests_.contains(id); } @@ -222,8 +231,9 @@ void GuestOsSessionTracker::OnLxdContainerStopping( const vm_tools::cicerone::LxdContainerStoppingSignal& signal) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - if (signal.owner_id() != owner_id_) + if (signal.owner_id() != owner_id_) { return; + } if (signal.status() == vm_tools::cicerone::LxdContainerStoppingSignal::STOPPED) { HandleContainerShutdown(signal.vm_name(), signal.container_name());
diff --git a/chrome/browser/ash/guest_os/guest_os_session_tracker.h b/chrome/browser/ash/guest_os/guest_os_session_tracker.h index 9607d4f..42f95c0 100644 --- a/chrome/browser/ash/guest_os/guest_os_session_tracker.h +++ b/chrome/browser/ash/guest_os/guest_os_session_tracker.h
@@ -54,10 +54,6 @@ // Runs `callback` when the OnContainerStarted signal arrives for the guest // with the given `id`. To cancel the callback (e.g. upon timeout) destroy the // returned subscription. - // TODO(b/231390254): If Chrome crashes while a container is running then - // we'll never get another OnContainerStarted message, which means - // RunOnceContainerStarted hangs forever. We need to list running containers - // and adopt them, the same as we do for VMs. base::CallbackListSubscription RunOnceContainerStarted( const GuestId& id, base::OnceCallback<void(GuestInfo)> callback); @@ -73,6 +69,11 @@ // guest is running or not and don't need the info, use `IsRunning` instead absl::optional<GuestInfo> GetInfo(const GuestId& id); + // Returns information about a running VM. Returns nullopt if the VM + // isn't recognised e.g. it's not running. + absl::optional<vm_tools::concierge::VmInfo> GetVmInfo( + const std::string& vm_name); + // Returns true if a guest is running, false otherwise. bool IsRunning(const GuestId& id);
diff --git a/chrome/browser/ash/guest_os/guest_os_session_tracker_unittest.cc b/chrome/browser/ash/guest_os/guest_os_session_tracker_unittest.cc index b9ce4c71..09be4683 100644 --- a/chrome/browser/ash/guest_os/guest_os_session_tracker_unittest.cc +++ b/chrome/browser/ash/guest_os/guest_os_session_tracker_unittest.cc
@@ -257,6 +257,22 @@ EXPECT_TRUE(called); } +TEST_F(GuestOsSessionTrackerTest, RunOnLxdStopping) { + FakeConciergeClient()->NotifyVmStarted(vm_started_signal_); + FakeCiceroneClient()->NotifyContainerStarted(container_started_signal_); + GuestId id{VmType::TERMINA, "vm_name", "penguin"}; + bool called = false; + auto _ = tracker_.RunOnShutdown( + id, base::BindLambdaForTesting([&called]() { called = true; })); + vm_tools::cicerone::LxdContainerStoppingSignal signal; + signal.set_vm_name(id.vm_name); + signal.set_container_name(id.container_name); + signal.set_owner_id(OwnerId()); + signal.set_status(vm_tools::cicerone::LxdContainerStoppingSignal::STOPPED); + FakeCiceroneClient()->NotifyLxdContainerStopping(signal); + EXPECT_TRUE(called); +} + TEST_F(GuestOsSessionTrackerTest, RunOnVmShutdown) { FakeConciergeClient()->NotifyVmStarted(vm_started_signal_); FakeCiceroneClient()->NotifyContainerStarted(container_started_signal_); @@ -268,4 +284,21 @@ EXPECT_TRUE(called); } +TEST_F(GuestOsSessionTrackerTest, GetVmInfo) { + ASSERT_EQ(absl::nullopt, tracker_.GetVmInfo(vm_started_signal_.name())); + + FakeConciergeClient()->NotifyVmStarted(vm_started_signal_); + ASSERT_NE(absl::nullopt, tracker_.GetVmInfo(vm_started_signal_.name())); + + FakeCiceroneClient()->NotifyContainerStarted(container_started_signal_); + ASSERT_NE(absl::nullopt, tracker_.GetVmInfo(vm_started_signal_.name())); + + FakeCiceroneClient()->NotifyContainerShutdownSignal( + container_shutdown_signal_); + ASSERT_NE(absl::nullopt, tracker_.GetVmInfo(vm_started_signal_.name())); + + FakeConciergeClient()->NotifyVmStopped(vm_shutdown_signal_); + ASSERT_EQ(absl::nullopt, tracker_.GetVmInfo(vm_started_signal_.name())); +} + } // namespace guest_os
diff --git a/chrome/browser/ash/guest_os/guest_os_share_path.cc b/chrome/browser/ash/guest_os/guest_os_share_path.cc index f7407e8..8d835e7 100644 --- a/chrome/browser/ash/guest_os/guest_os_share_path.cc +++ b/chrome/browser/ash/guest_os/guest_os_share_path.cc
@@ -6,18 +6,21 @@ #include "ash/components/arc/arc_features.h" #include "ash/components/arc/arc_util.h" -#include "base/bind.h" #include "base/containers/contains.h" #include "base/files/file_util.h" +#include "base/functional/callback_helpers.h" +#include "base/logging.h" #include "base/ranges/algorithm.h" #include "base/task/thread_pool.h" #include "chrome/browser/ash/arc/session/arc_session_manager.h" +#include "chrome/browser/ash/crostini/crostini_manager.h" #include "chrome/browser/ash/crostini/crostini_util.h" #include "chrome/browser/ash/drive/drive_integration_service.h" #include "chrome/browser/ash/file_manager/path_util.h" #include "chrome/browser/ash/file_manager/volume_manager.h" #include "chrome/browser/ash/guest_os/guest_id.h" #include "chrome/browser/ash/guest_os/guest_os_pref_names.h" +#include "chrome/browser/ash/guest_os/guest_os_session_tracker.h" #include "chrome/browser/ash/guest_os/guest_os_share_path_factory.h" #include "chrome/browser/ash/plugin_vm/plugin_vm_manager.h" #include "chrome/browser/ash/plugin_vm/plugin_vm_manager_factory.h" @@ -25,6 +28,7 @@ #include "chrome/browser/ash/smb_client/smb_service.h" #include "chrome/browser/ash/smb_client/smb_service_factory.h" #include "chrome/browser/ash/smb_client/smbfs_share.h" +#include "chromeos/ash/components/dbus/concierge/concierge_client.h" #include "chromeos/ash/components/dbus/concierge/concierge_service.pb.h" #include "chromeos/ash/components/dbus/seneschal/seneschal_client.h" #include "chromeos/ash/components/drivefs/mojom/drivefs.mojom.h" @@ -185,8 +189,7 @@ file_watcher_task_runner_(base::ThreadPool::CreateSequencedTaskRunner( {base::MayBlock(), base::TaskPriority::USER_VISIBLE})), seneschal_callback_(base::BindRepeating(LogErrorResult)) { - auto* crostini_manager = crostini::CrostiniManager::GetForProfile(profile_); - crostini_manager->AddVmShutdownObserver(this); + ash::ConciergeClient::Get()->AddVmObserver(this); if (auto* vmgr = file_manager::VolumeManager::Get(profile_)) { vmgr->AddObserver(this); @@ -206,8 +209,7 @@ void GuestOsSharePath::Shutdown() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - auto* crostini_manager = crostini::CrostiniManager::GetForProfile(profile_); - crostini_manager->RemoveVmShutdownObserver(this); + ash::ConciergeClient::Get()->RemoveVmObserver(this); for (auto& shared_path : shared_paths_) { if (shared_path.second.watcher) { @@ -392,9 +394,13 @@ // PluginVm before sharing, we can detect that the VM is not started // if handle == 0. if (vm_name == plugin_vm::kPluginVmName) { - request.set_handle( - plugin_vm::PluginVmManagerFactory::GetForProfile(profile_) - ->seneschal_server_handle()); + auto info = + GuestOsSessionTracker::GetForProfile(profile_)->GetVmInfo(vm_name); + if (info) { + request.set_handle(info->seneschal_server_handle()); + } else { + LOG(WARNING) << "Trying to share with pluginvm when it's not running"; + } } else if (vm_name == arc::kArcVmName) { const auto& vm_info = arc::ArcSessionManager::Get()->GetVmInfo(); if (!vm_info) { @@ -437,15 +443,13 @@ // Return success if VM is not currently running. if (vm_name == plugin_vm::kPluginVmName) { - if (plugin_vm::PluginVmManagerFactory::GetForProfile(profile_) - ->vm_state() != - vm_tools::plugin_dispatcher::VmState::VM_STATE_RUNNING) { + auto vm_info = + GuestOsSessionTracker::GetForProfile(profile_)->GetVmInfo(vm_name); + if (!vm_info) { std::move(callback).Run(true, "PluginVm not running"); return; } - request.set_handle( - plugin_vm::PluginVmManagerFactory::GetForProfile(profile_) - ->seneschal_server_handle()); + request.set_handle(vm_info->seneschal_server_handle()); } else if (vm_name == arc::kArcVmName) { const auto& vm_info = arc::ArcSessionManager::Get()->GetVmInfo(); if (!vm_info) { @@ -627,10 +631,29 @@ } } -void GuestOsSharePath::OnVmShutdown(const std::string& vm_name) { +void GuestOsSharePath::OnVmStarted( + const vm_tools::concierge::VmStartedSignal& signal) { + // SharePersistedPaths fetches the seneschal handle from other services which + // also observe OnVmStarted. So we `PostTask` instead of running + // synchronously to give them a chance to update first. + content::GetUIThreadTaskRunner({})->PostTask( + FROM_HERE, + base::BindOnce( + &GuestOsSharePath::SharePersistedPaths, + weak_ptr_factory_.GetWeakPtr(), signal.name(), + base::BindOnce([](bool success, const std::string& failure_reason) { + if (!success) { + LOG(ERROR) << "Error sharing persistent paths: " + << failure_reason; + } + }))); +} + +void GuestOsSharePath::OnVmStopped( + const vm_tools::concierge::VmStoppedSignal& signal) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); for (auto it = shared_paths_.begin(); it != shared_paths_.end();) { - if (RemoveSharedPathInfo(it->second, vm_name)) { + if (RemoveSharedPathInfo(it->second, signal.name())) { shared_paths_.erase(it++); } else { ++it;
diff --git a/chrome/browser/ash/guest_os/guest_os_share_path.h b/chrome/browser/ash/guest_os/guest_os_share_path.h index 122dfe7..67b4f57d 100644 --- a/chrome/browser/ash/guest_os/guest_os_share_path.h +++ b/chrome/browser/ash/guest_os/guest_os_share_path.h
@@ -10,7 +10,6 @@ #include <set> #include <vector> -#include "base/callback.h" #include "base/files/file_path.h" #include "base/files/file_path_watcher.h" #include "base/memory/weak_ptr.h" @@ -19,6 +18,7 @@ #include "chrome/browser/ash/crostini/crostini_manager.h" #include "chrome/browser/ash/file_manager/volume_manager_observer.h" #include "chrome/browser/profiles/profile.h" +#include "chromeos/ash/components/dbus/concierge/concierge_client.h" #include "chromeos/ash/components/dbus/seneschal/seneschal_service.pb.h" #include "chromeos/ash/components/drivefs/drivefs_host_observer.h" #include "components/keyed_service/core/keyed_service.h" @@ -41,7 +41,7 @@ // Handles sharing and unsharing paths from the Chrome OS host to guest VMs via // seneschal. class GuestOsSharePath : public KeyedService, - public ash::VmShutdownObserver, + public ash::ConciergeClient::VmObserver, public file_manager::VolumeManagerObserver, public drivefs::DriveFsHostObserver { public: @@ -121,8 +121,9 @@ // Returns true if |path| or a parent is shared with |vm_name|. bool IsPathShared(const std::string& vm_name, base::FilePath path) const; - // ash::VmShutdownObserver - void OnVmShutdown(const std::string& vm_name) override; + // ash::ConciergeClient::VmObserver + void OnVmStarted(const vm_tools::concierge::VmStartedSignal& signal) override; + void OnVmStopped(const vm_tools::concierge::VmStoppedSignal& signal) override; // file_manager::VolumeManagerObserver void OnVolumeMounted(ash::MountError error_code,
diff --git a/chrome/browser/ash/guest_os/guest_os_share_path_unittest.cc b/chrome/browser/ash/guest_os/guest_os_share_path_unittest.cc index 97c96b5..ae8472e0 100644 --- a/chrome/browser/ash/guest_os/guest_os_share_path_unittest.cc +++ b/chrome/browser/ash/guest_os/guest_os_share_path_unittest.cc
@@ -1107,7 +1107,7 @@ vm_tools::concierge::VmStoppedSignal signal; signal.set_name(crostini::kCrostiniDefaultVmName); signal.set_owner_id("test"); - crostini::CrostiniManager::GetForProfile(profile())->OnVmStopped(signal); + fake_concierge_client_->NotifyVmStopped(signal); EXPECT_FALSE(guest_os_share_path_->IsPathShared( crostini::kCrostiniDefaultVmName, shared_path_)); }
diff --git a/chrome/browser/ash/input_method/input_method_engine.cc b/chrome/browser/ash/input_method/input_method_engine.cc index 1bdbfc4..c7ecd827 100644 --- a/chrome/browser/ash/input_method/input_method_engine.cc +++ b/chrome/browser/ash/input_method/input_method_engine.cc
@@ -652,6 +652,8 @@ // engine_id) is enabled. candidate_window_property_ = {component_id, InputMethodEngine::CandidateWindowProperty()}; + + is_ready_for_testing_ = false; } bool InputMethodEngine::IsActive() const { @@ -762,9 +764,7 @@ } bool InputMethodEngine::IsReadyForTesting() { - // For extension-based IMEs, we cannot tell if they are ready or not, so just - // return false. - return false; + return is_ready_for_testing_; } void InputMethodEngine::OnSuggestionsChanged( @@ -1184,6 +1184,10 @@ // TODO(nona): Support item.children. } +void InputMethodEngine::NotifyInputMethodExtensionReadyForTesting() { + is_ready_for_testing_ = true; +} + InputMethodEngine::PendingKeyEvent::PendingKeyEvent( const std::string& component_id, ui::TextInputMethod::KeyEventDoneCallback callback)
diff --git a/chrome/browser/ash/input_method/input_method_engine.h b/chrome/browser/ash/input_method/input_method_engine.h index cbf5615..f3502d1 100644 --- a/chrome/browser/ash/input_method/input_method_engine.h +++ b/chrome/browser/ash/input_method/input_method_engine.h
@@ -314,6 +314,8 @@ gfx::Range GetAutocorrectRange(); + void NotifyInputMethodExtensionReadyForTesting(); + protected: virtual void OnInputMethodOptionsChanged(); @@ -406,6 +408,8 @@ base::Value::Dict input_method_settings_snapshot_; + bool is_ready_for_testing_ = false; + base::ScopedObservation<Profile, ProfileObserver> profile_observation_{this}; };
diff --git a/chrome/browser/ash/input_method/input_method_settings.cc b/chrome/browser/ash/input_method/input_method_settings.cc index f9e153fd..09c2fedb 100644 --- a/chrome/browser/ash/input_method/input_method_settings.cc +++ b/chrome/browser/ash/input_method/input_method_settings.cc
@@ -83,16 +83,6 @@ return engine_id == "zh-hant-t-i0-und"; } -std::string GetPrefKeyForEngineId(const std::string& engine_id) { - if (engine_id == "zh-t-i0-pinyin") { - return "pinyin"; - } - if (engine_id == "zh-hant-t-i0-und") { - return "zhuyin"; - } - return engine_id; -} - mojom::LatinSettingsPtr CreateLatinSettings( const base::Value::Dict& input_method_specific_pref, const PrefService& prefs, @@ -259,7 +249,7 @@ // The subdictionary may be null if the user hasn't changed any settings for // that input method. const base::Value::Dict* input_method_specific_pref_or_null = - all_input_method_pref.FindDict(GetPrefKeyForEngineId(engine_id)); + all_input_method_pref.FindDict(engine_id); // For convenience, pass an empty dictionary if there are no settings for this // input method yet.
diff --git a/chrome/browser/ash/input_method/input_method_settings_unittest.cc b/chrome/browser/ash/input_method/input_method_settings_unittest.cc index eb8bbbb..1647f7b 100644 --- a/chrome/browser/ash/input_method/input_method_settings_unittest.cc +++ b/chrome/browser/ash/input_method/input_method_settings_unittest.cc
@@ -163,15 +163,20 @@ TEST(CreateSettingsFromPrefsTest, CreatePinyinSettings) { base::DictionaryValue dict; - dict.SetBoolPath("pinyin.en:eng", true); - dict.SetBoolPath("pinyin.k:g", true); - dict.SetBoolPath("pinyin.in:ing", true); - dict.SetStringPath("pinyin.xkbLayout", "Colemak"); - dict.SetBoolPath("pinyin.pinyinEnableLowerPaging", false); - dict.SetBoolPath("pinyin.pinyinEnableUpperPaging", false); - dict.SetBoolPath("pinyin.pinyinDefaultChinese", false); - dict.SetBoolPath("pinyin.pinyinFullWidthCharacter", true); - dict.SetBoolPath("pinyin.pinyinChinesePunctuation", false); + dict.SetBoolPath(base::StrCat({kPinyinEngineId, ".en:eng"}), true); + dict.SetBoolPath(base::StrCat({kPinyinEngineId, ".k:g"}), true); + dict.SetBoolPath(base::StrCat({kPinyinEngineId, ".in:ing"}), true); + dict.SetStringPath(base::StrCat({kPinyinEngineId, ".xkbLayout"}), "Colemak"); + dict.SetBoolPath(base::StrCat({kPinyinEngineId, ".pinyinEnableLowerPaging"}), + false); + dict.SetBoolPath(base::StrCat({kPinyinEngineId, ".pinyinEnableUpperPaging"}), + false); + dict.SetBoolPath(base::StrCat({kPinyinEngineId, ".pinyinDefaultChinese"}), + false); + dict.SetBoolPath(base::StrCat({kPinyinEngineId, ".pinyinFullWidthCharacter"}), + true); + dict.SetBoolPath(base::StrCat({kPinyinEngineId, ".pinyinChinesePunctuation"}), + false); TestingPrefServiceSimple prefs; RegisterTestingPrefs(prefs, dict); @@ -218,9 +223,11 @@ TEST(CreateSettingsFromPrefsTest, CreateZhuyinSettings) { base::DictionaryValue dict; - dict.SetStringPath("zhuyin.zhuyinKeyboardLayout", "IBM"); - dict.SetStringPath("zhuyin.zhuyinSelectKeys", "asdfghjkl;"); - dict.SetStringPath("zhuyin.zhuyinPageSize", "8"); + dict.SetStringPath(base::StrCat({kZhuyinEngineId, ".zhuyinKeyboardLayout"}), + "IBM"); + dict.SetStringPath(base::StrCat({kZhuyinEngineId, ".zhuyinSelectKeys"}), + "asdfghjkl;"); + dict.SetStringPath(base::StrCat({kZhuyinEngineId, ".zhuyinPageSize"}), "8"); TestingPrefServiceSimple prefs; RegisterTestingPrefs(prefs, dict);
diff --git a/chrome/browser/ash/input_method/native_input_method_engine_observer.cc b/chrome/browser/ash/input_method/native_input_method_engine_observer.cc index 593b26b..3430b69 100644 --- a/chrome/browser/ash/input_method/native_input_method_engine_observer.cc +++ b/chrome/browser/ash/input_method/native_input_method_engine_observer.cc
@@ -501,33 +501,6 @@ } } -void MigratePinyinAndZhuyinSettings(PrefService* prefs, - const std::string& engine_id) { - // We are using legacy pref keys for pinyin and zhuyin. To get rid of them, we - // need to write existing settings under the correct pref keys as the first - // step. - // TODO(b/175085612): Remove this function once we have migrated from the - // legacy pref keys. - if (engine_id != "zh-t-i0-pinyin" && engine_id != "zh-hant-t-i0-und") - return; - - const base::Value::Dict& all_input_method_pref = - prefs->GetDict(::prefs::kLanguageInputMethodSpecificSettings); - - // Check if the settings are already migrated. - if (all_input_method_pref.FindDict(engine_id)) - return; - - const base::Value::Dict* existing_pref_or_null = - all_input_method_pref.FindDict(engine_id == "zh-t-i0-pinyin" ? "pinyin" - : "zhuyin"); - if (existing_pref_or_null) { - ScopedDictPrefUpdate update(prefs, - ::prefs::kLanguageInputMethodSpecificSettings); - update->SetByDottedPath(engine_id, existing_pref_or_null->Clone()); - } -} - void UpdateCandidatesWindowSync(ime::mojom::CandidatesWindowPtr window) { IMECandidateWindowHandlerInterface* candidate_window_handler = ui::IMEBridge::Get()->GetCandidateWindowHandler(); @@ -650,8 +623,6 @@ ime::mojom::InputMethodSettingsPtr settings = CreateSettingsFromPrefs(*prefs_, engine_id); - MigratePinyinAndZhuyinSettings(prefs_, engine_id); - connection_factory_->ConnectToInputMethod( engine_id, input_method_.BindNewEndpointAndPassReceiver(), std::move(input_method_host), std::move(settings),
diff --git a/chrome/browser/ash/input_method/native_input_method_engine_unittest.cc b/chrome/browser/ash/input_method/native_input_method_engine_unittest.cc index 5620b3b..5aac331 100644 --- a/chrome/browser/ash/input_method/native_input_method_engine_unittest.cc +++ b/chrome/browser/ash/input_method/native_input_method_engine_unittest.cc
@@ -137,9 +137,6 @@ void SetPinyinLayoutPrefs(Profile& profile, const std::string& layout) { base::Value input_method_setting(base::Value::Type::DICTIONARY); - // TODO(b/175085612): Remove pinyin.xkbLayout once we migrated from the - // legacy pref keys. - input_method_setting.SetStringPath("pinyin.xkbLayout", layout); input_method_setting.SetStringPath("zh-t-i0-pinyin.xkbLayout", layout); profile.GetPrefs()->Set(::prefs::kLanguageInputMethodSpecificSettings, input_method_setting);
diff --git a/chrome/browser/ash/login/easy_unlock/easy_unlock_service_signin.cc b/chrome/browser/ash/login/easy_unlock/easy_unlock_service_signin.cc index 267bcaa..635cf4ce 100644 --- a/chrome/browser/ash/login/easy_unlock/easy_unlock_service_signin.cc +++ b/chrome/browser/ash/login/easy_unlock/easy_unlock_service_signin.cc
@@ -8,7 +8,6 @@ #include <memory> -#include "ash/components/tpm/tpm_token_loader.h" #include "ash/constants/ash_features.h" #include "ash/public/cpp/smartlock_state.h" #include "base/base64url.h" @@ -37,6 +36,7 @@ #include "chromeos/ash/components/multidevice/software_feature_state.h" #include "chromeos/ash/components/proximity_auth/proximity_auth_local_state_pref_manager.h" #include "chromeos/ash/components/proximity_auth/smart_lock_metrics_recorder.h" +#include "chromeos/ash/components/tpm/tpm_token_loader.h" #include "chromeos/login/login_state/login_state.h" namespace ash {
diff --git a/chrome/browser/ash/login/lock/screen_locker.cc b/chrome/browser/ash/login/lock/screen_locker.cc index c88d2d3c..d8ad10a9 100644 --- a/chrome/browser/ash/login/lock/screen_locker.cc +++ b/chrome/browser/ash/login/lock/screen_locker.cc
@@ -481,8 +481,7 @@ ContinueAuthenticate(user_context); } -void ScreenLocker::OnPinAttemptDone(const UserContext& user_context, - bool success) { +void ScreenLocker::OnPinAttemptDone(UserContext user_context, bool success) { if (success) { // Mark strong auth if this is cryptohome based pin. if (quick_unlock::PinBackend::GetInstance()->ShouldUseCryptohome( @@ -495,12 +494,14 @@ } OnAuthSuccess(user_context); } else { + user_context.SetIsUsingPin(false); // PIN authentication has failed; try submitting as a normal password. ContinueAuthenticate(user_context); } } void ScreenLocker::ContinueAuthenticate(const UserContext& user_context) { + DCHECK(!user_context.IsUsingPin()); if (user_context.GetAccountId().GetAccountType() == AccountType::ACTIVE_DIRECTORY && user_context.GetKey()->GetKeyType() == Key::KEY_TYPE_PASSWORD_PLAIN) {
diff --git a/chrome/browser/ash/login/lock/screen_locker.h b/chrome/browser/ash/login/lock/screen_locker.h index 0bb7b91c..48732fd 100644 --- a/chrome/browser/ash/login/lock/screen_locker.h +++ b/chrome/browser/ash/login/lock/screen_locker.h
@@ -259,7 +259,7 @@ const AccountId& account_id, std::vector<ChallengeResponseKey> challenge_response_keys); - void OnPinAttemptDone(const UserContext& user_context, bool success); + void OnPinAttemptDone(UserContext user_context, bool success); // Called to select the appropriate Authenticator and perform unlock // operation.
diff --git a/chrome/browser/ash/login/session/user_session_manager.cc b/chrome/browser/ash/login/session/user_session_manager.cc index 74de5f7..423ed81 100644 --- a/chrome/browser/ash/login/session/user_session_manager.cc +++ b/chrome/browser/ash/login/session/user_session_manager.cc
@@ -15,7 +15,6 @@ #include <vector> #include "ash/components/arc/arc_prefs.h" -#include "ash/components/tpm/prepare_tpm.h" #include "ash/constants/ash_features.h" #include "ash/constants/ash_switches.h" #include "base/base_paths.h" @@ -133,6 +132,7 @@ #include "chromeos/ash/components/login/session/session_termination_manager.h" #include "chromeos/ash/components/network/portal_detector/network_portal_detector.h" #include "chromeos/ash/components/settings/cros_settings_names.h" +#include "chromeos/ash/components/tpm/prepare_tpm.h" #include "chromeos/dbus/tpm_manager/tpm_manager.pb.h" #include "chromeos/dbus/tpm_manager/tpm_manager_client.h" #include "chromeos/ui/vector_icons/vector_icons.h"
diff --git a/chrome/browser/ash/login/webview_login_browsertest.cc b/chrome/browser/ash/login/webview_login_browsertest.cc index c17434f..ce0e197 100644 --- a/chrome/browser/ash/login/webview_login_browsertest.cc +++ b/chrome/browser/ash/login/webview_login_browsertest.cc
@@ -6,7 +6,6 @@ #include <iterator> #include <string> -#include "ash/components/tpm/tpm_token_loader.h" #include "ash/constants/ash_features.h" #include "ash/constants/ash_switches.h" #include "ash/public/cpp/login_screen_test_api.h" @@ -75,6 +74,7 @@ #include "chrome/test/base/ui_test_utils.h" #include "chromeos/ash/components/dbus/session_manager/fake_session_manager_client.h" #include "chromeos/ash/components/login/auth/public/user_context.h" +#include "chromeos/ash/components/tpm/tpm_token_loader.h" #include "chromeos/dbus/tpm_manager/fake_tpm_manager_client.h" #include "chromeos/dbus/tpm_manager/tpm_manager_client.h" #include "components/account_id/account_id.h"
diff --git a/chrome/browser/ash/ownership/owner_settings_service_ash.cc b/chrome/browser/ash/ownership/owner_settings_service_ash.cc index 419a192..94e8bca8 100644 --- a/chrome/browser/ash/ownership/owner_settings_service_ash.cc +++ b/chrome/browser/ash/ownership/owner_settings_service_ash.cc
@@ -11,7 +11,6 @@ #include <string> #include <utility> -#include "ash/components/tpm/tpm_token_loader.h" #include "ash/constants/ash_switches.h" #include "base/bind.h" #include "base/callback.h" @@ -34,6 +33,7 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "chromeos/ash/components/install_attributes/install_attributes.h" +#include "chromeos/ash/components/tpm/tpm_token_loader.h" #include "components/ownership/owner_key_util.h" #include "components/prefs/pref_service.h" #include "components/user_manager/user.h"
diff --git a/chrome/browser/ash/plugin_vm/plugin_vm_manager_impl.cc b/chrome/browser/ash/plugin_vm/plugin_vm_manager_impl.cc index aadaf4b69..817e43d 100644 --- a/chrome/browser/ash/plugin_vm/plugin_vm_manager_impl.cc +++ b/chrome/browser/ash/plugin_vm/plugin_vm_manager_impl.cc
@@ -357,7 +357,6 @@ // When the VM_STATE_RUNNING signal is received: // 1) Call Concierge::GetVmInfo to get seneschal server handle. // 2) Ensure default shared path exists. - // 3) Share paths with PluginVm if (vm_state_ == vm_tools::plugin_dispatcher::VmState::VM_STATE_RUNNING) { // If the VM was just created via VMC (instead of the installer), this flag // will not yet be set. Setting it here allows us to avoid showing the @@ -611,12 +610,10 @@ } seneschal_server_handle_ = reply->vm_info().seneschal_server_handle(); - // Create and share default folder, and other persisted shares. + // Create and share default folder. EnsureDefaultSharedDirExists( profile_, base::BindOnce(&PluginVmManagerImpl::OnDefaultSharedDirExists, weak_ptr_factory_.GetWeakPtr())); - guest_os::GuestOsSharePath::GetForProfile(profile_)->SharePersistedPaths( - kPluginVmName, base::DoNothing()); } void PluginVmManagerImpl::OnDefaultSharedDirExists(const base::FilePath& dir,
diff --git a/chrome/browser/ash/policy/dlp/dlp_files_controller.cc b/chrome/browser/ash/policy/dlp/dlp_files_controller.cc index daa81245..053de804a 100644 --- a/chrome/browser/ash/policy/dlp/dlp_files_controller.cc +++ b/chrome/browser/ash/policy/dlp/dlp_files_controller.cc
@@ -238,6 +238,7 @@ } request.set_destination_url(destination.path().value()); + // TODO(crbug.com/1356109): Set move or copy action instead of transfer. request.set_file_action(::dlp::FileAction::TRANSFER); auto return_transfers_callback = base::BindOnce(&DlpFilesController::ReturnDisallowedTransfers,
diff --git a/chrome/browser/ash/policy/dlp/dlp_files_controller.h b/chrome/browser/ash/policy/dlp/dlp_files_controller.h index 26f96be9..e26e27a 100644 --- a/chrome/browser/ash/policy/dlp/dlp_files_controller.h +++ b/chrome/browser/ash/policy/dlp/dlp_files_controller.h
@@ -47,7 +47,9 @@ kDownload = 1, kTransfer = 2, kUpload = 3, - kMaxValue = kUpload + kCopy = 4, + kMove = 5, + kMaxValue = kMove }; // DlpFileMetadata keeps metadata about a file, such as whether it's managed
diff --git a/chrome/browser/ash/policy/dlp/dlp_files_controller_unittest.cc b/chrome/browser/ash/policy/dlp/dlp_files_controller_unittest.cc index 1f2091f..eb376ec4 100644 --- a/chrome/browser/ash/policy/dlp/dlp_files_controller_unittest.cc +++ b/chrome/browser/ash/policy/dlp/dlp_files_controller_unittest.cc
@@ -1276,6 +1276,24 @@ std::vector<ino_t>({kInode1, kInode2}), std::vector<std::string>({kExampleUrl1, kExampleUrl2}), + std::vector<std::string>({kFilePath1, kFilePath2})), + FilesTransferInfo(policy::DlpFilesController::FileAction::kCopy, + std::vector<ino_t>({kInode1}), + std::vector<std::string>({kExampleUrl1}), + std::vector<std::string>({kFilePath1})), + FilesTransferInfo(policy::DlpFilesController::FileAction::kCopy, + std::vector<ino_t>({kInode1, kInode2}), + std::vector<std::string>({kExampleUrl1, + kExampleUrl2}), + std::vector<std::string>({kFilePath1, kFilePath2})), + FilesTransferInfo(policy::DlpFilesController::FileAction::kMove, + std::vector<ino_t>({kInode1}), + std::vector<std::string>({kExampleUrl1}), + std::vector<std::string>({kFilePath1})), + FilesTransferInfo(policy::DlpFilesController::FileAction::kMove, + std::vector<ino_t>({kInode1, kInode2}), + std::vector<std::string>({kExampleUrl1, + kExampleUrl2}), std::vector<std::string>({kFilePath1, kFilePath2})))); TEST_P(DlpFilesWarningDialogContentTest,
diff --git a/chrome/browser/ash/quick_pair/quick_pair_browser_delegate_impl.cc b/chrome/browser/ash/quick_pair/quick_pair_browser_delegate_impl.cc index 4c9e53d..f102f7c3 100644 --- a/chrome/browser/ash/quick_pair/quick_pair_browser_delegate_impl.cc +++ b/chrome/browser/ash/quick_pair/quick_pair_browser_delegate_impl.cc
@@ -5,13 +5,13 @@ #include "chrome/browser/ash/quick_pair/quick_pair_browser_delegate_impl.h" #include "ash/quick_pair/common/logging.h" -#include "ash/services/quick_pair/public/mojom/quick_pair_service.mojom.h" #include "base/memory/scoped_refptr.h" #include "base/notreached.h" #include "chrome/browser/ash/profiles/profile_helper.h" #include "chrome/browser/image_fetcher/image_decoder_impl.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/signin/identity_manager_factory.h" +#include "chromeos/ash/services/quick_pair/public/mojom/quick_pair_service.mojom.h" #include "components/image_fetcher/core/image_fetcher.h" #include "components/image_fetcher/core/image_fetcher_impl.h" #include "components/user_manager/user.h"
diff --git a/chrome/browser/ash/quick_pair/quick_pair_browser_delegate_impl.h b/chrome/browser/ash/quick_pair/quick_pair_browser_delegate_impl.h index cc202cd..a21ae48 100644 --- a/chrome/browser/ash/quick_pair/quick_pair_browser_delegate_impl.h +++ b/chrome/browser/ash/quick_pair/quick_pair_browser_delegate_impl.h
@@ -6,7 +6,7 @@ #define CHROME_BROWSER_ASH_QUICK_PAIR_QUICK_PAIR_BROWSER_DELEGATE_IMPL_H_ #include "ash/quick_pair/common/quick_pair_browser_delegate.h" -#include "ash/services/quick_pair/public/mojom/quick_pair_service.mojom-forward.h" +#include "chromeos/ash/services/quick_pair/public/mojom/quick_pair_service.mojom-forward.h" #include "mojo/public/cpp/bindings/pending_receiver.h" class Profile;
diff --git a/chrome/browser/ash/system_token_cert_db_initializer.cc b/chrome/browser/ash/system_token_cert_db_initializer.cc index 7253dde..4ff867f 100644 --- a/chrome/browser/ash/system_token_cert_db_initializer.cc +++ b/chrome/browser/ash/system_token_cert_db_initializer.cc
@@ -9,8 +9,6 @@ #include <memory> #include <utility> -#include "ash/components/tpm/buildflags.h" -#include "ash/components/tpm/tpm_token_loader.h" #include "base/bind.h" #include "base/callback.h" #include "base/callback_helpers.h" @@ -28,6 +26,8 @@ #include "chromeos/ash/components/dbus/userdataauth/userdataauth_client.h" #include "chromeos/ash/components/network/network_cert_loader.h" #include "chromeos/ash/components/network/system_token_cert_db_storage.h" +#include "chromeos/ash/components/tpm/buildflags.h" +#include "chromeos/ash/components/tpm/tpm_token_loader.h" #include "chromeos/dbus/common/dbus_method_call_status.h" #include "chromeos/dbus/tpm_manager/tpm_manager.pb.h" #include "chromeos/dbus/tpm_manager/tpm_manager_client.h"
diff --git a/chrome/browser/ash/system_token_cert_db_initializer_unittest.cc b/chrome/browser/ash/system_token_cert_db_initializer_unittest.cc index 7aca3db..731b8a0 100644 --- a/chrome/browser/ash/system_token_cert_db_initializer_unittest.cc +++ b/chrome/browser/ash/system_token_cert_db_initializer_unittest.cc
@@ -6,7 +6,6 @@ #include <memory> -#include "ash/components/tpm/tpm_token_loader.h" #include "base/bind.h" #include "base/callback.h" #include "base/memory/weak_ptr.h" @@ -15,6 +14,7 @@ #include "chromeos/ash/components/dbus/userdataauth/userdataauth_client.h" #include "chromeos/ash/components/network/network_cert_loader.h" #include "chromeos/ash/components/network/system_token_cert_db_storage_test_util.h" +#include "chromeos/ash/components/tpm/tpm_token_loader.h" #include "chromeos/dbus/tpm_manager/tpm_manager_client.h" #include "content/public/test/browser_task_environment.h" #include "crypto/nss_util.h"
diff --git a/chrome/browser/ash/web_applications/files_internals_ui_delegate.cc b/chrome/browser/ash/web_applications/files_internals_ui_delegate.cc new file mode 100644 index 0000000..be13b74 --- /dev/null +++ b/chrome/browser/ash/web_applications/files_internals_ui_delegate.cc
@@ -0,0 +1,22 @@ +// 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/ash/web_applications/files_internals_ui_delegate.h" + +#include "base/values.h" +#include "chrome/browser/ash/fusebox/fusebox_server.h" + +ChromeFilesInternalsUIDelegate::ChromeFilesInternalsUIDelegate() = default; + +base::Value ChromeFilesInternalsUIDelegate::GetDebugJSON() const { + base::Value::Dict dict; + + if (fusebox::Server* fusebox_server = fusebox::Server::GetInstance()) { + dict.Set("fusebox", fusebox_server->GetDebugJSON()); + } else { + dict.Set("fusebox", base::Value()); + } + + return base::Value(std::move(dict)); +}
diff --git a/chrome/browser/ash/web_applications/files_internals_ui_delegate.h b/chrome/browser/ash/web_applications/files_internals_ui_delegate.h new file mode 100644 index 0000000..85f38889 --- /dev/null +++ b/chrome/browser/ash/web_applications/files_internals_ui_delegate.h
@@ -0,0 +1,23 @@ +// 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_ASH_WEB_APPLICATIONS_FILES_INTERNALS_UI_DELEGATE_H_ +#define CHROME_BROWSER_ASH_WEB_APPLICATIONS_FILES_INTERNALS_UI_DELEGATE_H_ + +#include "ash/webui/files_internals/files_internals_ui_delegate.h" + +// Chrome browser FilesInternalsUIDelegate implementation. +class ChromeFilesInternalsUIDelegate : public ash::FilesInternalsUIDelegate { + public: + ChromeFilesInternalsUIDelegate(); + + ChromeFilesInternalsUIDelegate(const ChromeFilesInternalsUIDelegate&) = + delete; + ChromeFilesInternalsUIDelegate& operator=( + const ChromeFilesInternalsUIDelegate&) = delete; + + base::Value GetDebugJSON() const override; +}; + +#endif // CHROME_BROWSER_ASH_WEB_APPLICATIONS_FILES_INTERNALS_UI_DELEGATE_H_
diff --git a/chrome/browser/autofill/content_autofill_driver_browsertest.cc b/chrome/browser/autofill/content_autofill_driver_browsertest.cc index d7d720a..108c444 100644 --- a/chrome/browser/autofill/content_autofill_driver_browsertest.cc +++ b/chrome/browser/autofill/content_autofill_driver_browsertest.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 <utility> + #include "base/bind.h" #include "base/memory/ref_counted.h" #include "base/test/scoped_feature_list.h" @@ -48,7 +50,7 @@ ~MockAutofillClient() override = default; PrefService* GetPrefs() override { - return const_cast<PrefService*>(base::as_const(*this).GetPrefs()); + return const_cast<PrefService*>(std::as_const(*this).GetPrefs()); } const PrefService* GetPrefs() const override { return &prefs_; }
diff --git a/chrome/browser/autofill_assistant/password_change/apc_external_action_delegate.cc b/chrome/browser/autofill_assistant/password_change/apc_external_action_delegate.cc index e6637fb..f3e53a23 100644 --- a/chrome/browser/autofill_assistant/password_change/apc_external_action_delegate.cc +++ b/chrome/browser/autofill_assistant/password_change/apc_external_action_delegate.cc
@@ -30,6 +30,7 @@ #include "ui/base/l10n/l10n_util.h" #include "url/gurl.h" +using autofill_assistant::password_change::FlowType; using autofill_assistant::password_change::GenericPasswordChangeSpecification; ApcExternalActionDelegate::ApcExternalActionDelegate( @@ -79,6 +80,9 @@ HandleUpdateSidePanel( generic_password_change_specification.update_side_panel()); break; + case GenericPasswordChangeSpecification::SpecificationCase::kSetFlowType: + HandleSetFlowType(generic_password_change_specification.set_flow_type()); + break; case GenericPasswordChangeSpecification::SpecificationCase:: SPECIFICATION_NOT_SET: DLOG(ERROR) << "unknown password change action"; @@ -268,9 +272,9 @@ } void ApcExternalActionDelegate::ShowCompletionScreen( - base::RepeatingClosure onShowCompletionScreenDoneButtonClicked) { + base::RepeatingClosure done_button_callback) { password_change_run_display_->ShowCompletionScreen( - std::move(onShowCompletionScreenDoneButtonClicked)); + model_.flow_type, std::move(done_button_callback)); } void ApcExternalActionDelegate::OpenPasswordManager() { @@ -349,6 +353,13 @@ EndAction(true); } +void ApcExternalActionDelegate::HandleSetFlowType( + const autofill_assistant::password_change::SetFlowTypeSpecification& + specification) { + model_.flow_type = specification.flow_type(); + EndAction(/*success=*/true); +} + void ApcExternalActionDelegate::OnBasePromptDomUpdateReceived( const autofill_assistant::external::ElementConditionsUpdate& update) { // To ensure predictable behavior, we always choose the condition with the
diff --git a/chrome/browser/autofill_assistant/password_change/apc_external_action_delegate.h b/chrome/browser/autofill_assistant/password_change/apc_external_action_delegate.h index 1d9663db..b551f58 100644 --- a/chrome/browser/autofill_assistant/password_change/apc_external_action_delegate.h +++ b/chrome/browser/autofill_assistant/password_change/apc_external_action_delegate.h
@@ -87,7 +87,7 @@ void OnGeneratedPasswordSelected(bool selected) override; void ShowStartingScreen(const GURL& url) override; void ShowCompletionScreen( - base::RepeatingClosure onShowCompletionScreenDoneButtonClicked) override; + base::RepeatingClosure done_button_callback) override; void OpenPasswordManager() override; void ShowErrorScreen() override; bool PasswordWasSuccessfullyChanged() override; @@ -120,6 +120,9 @@ void HandleUpdateSidePanel( const autofill_assistant::password_change::UpdateSidePanelSpecification& specification); + void HandleSetFlowType( + const autofill_assistant::password_change::SetFlowTypeSpecification& + specification); void OnBasePromptDomUpdateReceived( const autofill_assistant::external::ElementConditionsUpdate& update);
diff --git a/chrome/browser/autofill_assistant/password_change/apc_external_action_delegate_unittest.cc b/chrome/browser/autofill_assistant/password_change/apc_external_action_delegate_unittest.cc index cd104cb7..35d1ce5 100644 --- a/chrome/browser/autofill_assistant/password_change/apc_external_action_delegate_unittest.cc +++ b/chrome/browser/autofill_assistant/password_change/apc_external_action_delegate_unittest.cc
@@ -34,8 +34,9 @@ using ::testing::SaveArg; using DomUpdateCallback = autofill_assistant::ExternalActionDelegate::DomUpdateCallback; -using ProgressStep = autofill_assistant::password_change::ProgressStep; -using TopIcon = autofill_assistant::password_change::TopIcon; +using autofill_assistant::password_change::FlowType; +using autofill_assistant::password_change::ProgressStep; +using autofill_assistant::password_change::TopIcon; namespace { @@ -148,6 +149,18 @@ return action; } +autofill_assistant::external::Action CreateAction( + const autofill_assistant::password_change::SetFlowTypeSpecification& + proto) { + autofill_assistant::external::Action action; + autofill_assistant::password_change::GenericPasswordChangeSpecification spec; + *spec.mutable_set_flow_type() = proto; + *action.mutable_info()->mutable_generic_password_change_specification() = + spec; + + return action; +} + } // namespace class ApcExternalActionDelegateTest : public ChromeRenderViewHostTestHarness { @@ -257,7 +270,8 @@ TEST_F(ApcExternalActionDelegateTest, ShowCompletionScreen) { base::RepeatingClosure show_completion_screen_callback; EXPECT_CALL(*display(), - ShowCompletionScreen(show_completion_screen_callback)); + ShowCompletionScreen(FlowType::FLOW_TYPE_UNSPECIFIED, + show_completion_screen_callback)); action_delegate()->ShowCompletionScreen(show_completion_screen_callback); } @@ -651,6 +665,36 @@ EXPECT_TRUE(result.success()); } +TEST_F(ApcExternalActionDelegateTest, ReceiveSetFlowTypeAction) { + base::MockOnceCallback<void( + const autofill_assistant::external::Result& result)> + result_callback; + base::MockOnceCallback<void(DomUpdateCallback)> start_dom_checks_callback; + + autofill_assistant::password_change::SetFlowTypeSpecification spec; + spec.set_flow_type(FlowType::FLOW_TYPE_PASSWORD_RESET); + + autofill_assistant::external::Result result; + EXPECT_CALL(result_callback, Run).WillOnce(SaveArg<0>(&result)); + + // DOM checks will never be started. + EXPECT_CALL(start_dom_checks_callback, Run).Times(0); + + action_delegate()->OnActionRequested(CreateAction(spec), + /*is_interrupt=*/false, + start_dom_checks_callback.Get(), + result_callback.Get()); + + // Check that the correct value was written into the model and is used when + // the completion scren is supposed to be shown. + base::RepeatingClosure show_completion_screen_callback; + EXPECT_CALL(*display(), + ShowCompletionScreen(FlowType::FLOW_TYPE_PASSWORD_RESET, + show_completion_screen_callback)); + + action_delegate()->ShowCompletionScreen(show_completion_screen_callback); +} + TEST_F(ApcExternalActionDelegateTest, PauseProgressBarAnimation) { EXPECT_CALL(*display(), PauseProgressBarAnimation); action_delegate()->PauseProgressBarAnimation();
diff --git a/chrome/browser/banners/android/java/src/org/chromium/chrome/browser/banners/AppBannerManagerTest.java b/chrome/browser/banners/android/java/src/org/chromium/chrome/browser/banners/AppBannerManagerTest.java index 6fca794..0b72f48 100644 --- a/chrome/browser/banners/android/java/src/org/chromium/chrome/browser/banners/AppBannerManagerTest.java +++ b/chrome/browser/banners/android/java/src/org/chromium/chrome/browser/banners/AppBannerManagerTest.java
@@ -1063,7 +1063,7 @@ TestThreadUtils.runOnUiThreadBlocking( () -> { backgroundTab.loadUrl(new LoadUrlParams(url)); }); - waitForAppBannerPipelineStatus(backgroundTab, /* PENDING_PROMPT */ 9); + waitForAppBannerPipelineStatus(backgroundTab, /* PENDING_PROMPT */ 8); ThreadUtils.runOnUiThreadBlocking(() -> { Assert.assertEquals(BottomSheetController.SheetState.HIDDEN, @@ -1182,7 +1182,7 @@ TestThreadUtils.runOnUiThreadBlocking( () -> { backgroundTab.loadUrl(new LoadUrlParams(url)); }); - waitForAppBannerPipelineStatus(backgroundTab, /* PENDING_PROMPT */ 9); + waitForAppBannerPipelineStatus(backgroundTab, /* PENDING_PROMPT */ 8); assertNoHelpBubble(withText(R.string.iph_pwa_install_available_text)); }
diff --git a/chrome/browser/banners/app_banner_manager_browsertest.cc b/chrome/browser/banners/app_banner_manager_browsertest.cc index 047765c0..345abbc 100644 --- a/chrome/browser/banners/app_banner_manager_browsertest.cc +++ b/chrome/browser/banners/app_banner_manager_browsertest.cc
@@ -156,12 +156,6 @@ return params; } - InstallableParams ParamsToPerformWorkerCheck() override { - InstallableParams params = AppBannerManager::ParamsToPerformWorkerCheck(); - params.wait_for_worker = wait_for_worker_; - return params; - } - void OnBannerPromptReply( mojo::Remote<blink::mojom::AppBannerController> controller, blink::mojom::AppBannerPromptReply reply) override { @@ -194,9 +188,9 @@ bool IsWebAppConsideredInstalled() const override { return false; } + private: base::OnceClosure on_done_; - private: // If non-null, |on_banner_prompt_reply_| will be invoked from // OnBannerPromptReply. base::OnceClosure on_banner_prompt_reply_; @@ -263,7 +257,6 @@ // cases navigate the page, causing the state to go back to INACTIVE. EXPECT_TRUE(manager->state() == State::COMPLETE || manager->state() == State::PENDING_PROMPT || - manager->state() == State::PENDING_WORKER || manager->state() == State::INACTIVE); // If in incognito, ensure that nothing is recorded. @@ -730,13 +723,6 @@ AppBannerManagerBrowserTestWithChromeBFCache() = default; ~AppBannerManagerBrowserTestWithChromeBFCache() override = default; - struct FeatureOperatorOverload { - bool operator()(const base::Feature& feature1, - const base::Feature& feature2) const { - return std::strcmp(feature1.name, feature2.name) < 0; - } - }; - void SetUpOnMainThread() override { host_resolver()->AddRule("*", "127.0.0.1"); } @@ -771,8 +757,8 @@ std::vector<base::test::ScopedFeatureList::FeatureAndParams> enabled_features; - for (const auto& feature_param : enabled_features_with_params_) { - enabled_features.emplace_back(feature_param.first, feature_param.second); + for (const auto& [feature, params] : enabled_features_with_params_) { + enabled_features.emplace_back(*feature, params); } feature_list_.InitWithFeaturesAndParameters(enabled_features, @@ -814,9 +800,7 @@ private: std::vector<base::test::FeatureRef> disabled_features_; - std::map<base::Feature, - std::map<std::string, std::string>, - FeatureOperatorOverload> + std::map<base::test::FeatureRef, std::map<std::string, std::string>> enabled_features_with_params_; base::test::ScopedFeatureList feature_list_; }; @@ -1130,8 +1114,6 @@ embedded_test_server()->GetURL("/banners/manifest_test_page.html"), absl::nullopt); EXPECT_EQ(manager->state(), AppBannerManager::State::PENDING_PROMPT); - EXPECT_EQ(manager->GetInstallableWebAppCheckResultForTesting(), - AppBannerManager::InstallableWebAppCheckResult::kYes_Promotable); } IN_PROC_BROWSER_TEST_P(AppBannerServiceWorkerCriteriaTest, NoServiceWorker) { @@ -1140,20 +1122,25 @@ // Set not wait for service worker so it will not timeout. manager->SetWaitForServiceWorker(false); + absl::optional<InstallableStatusCode> expected_code; + switch (GetParam()) { + case ServiceWorkerCriteriaType::kDisabled: + expected_code = NO_MATCHING_SERVICE_WORKER; + break; + case ServiceWorkerCriteriaType::kSkipForInstalls: + expected_code = SERVICE_WORKER_NOT_REQUIRED; + break; + } + RunBannerTest(browser(), manager.get(), embedded_test_server()->GetURL( "/banners/manifest_no_service_worker.html"), - NO_MATCHING_SERVICE_WORKER); + expected_code); - EXPECT_EQ(manager->state(), AppBannerManager::State::COMPLETE); - - if (GetParam() == ServiceWorkerCriteriaType::kDisabled) { - EXPECT_EQ(manager->GetInstallableWebAppCheckResultForTesting(), - AppBannerManager::InstallableWebAppCheckResult::kNo); + if (expected_code) { + EXPECT_EQ(manager->state(), AppBannerManager::State::COMPLETE); } else { - EXPECT_EQ( - manager->GetInstallableWebAppCheckResultForTesting(), - AppBannerManager::InstallableWebAppCheckResult::kYes_ByUserRequest); + EXPECT_EQ(manager->state(), AppBannerManager::State::PENDING_PROMPT); } } @@ -1161,69 +1148,28 @@ std::unique_ptr<AppBannerManagerTest> manager( CreateAppBannerManager(browser())); + absl::optional<InstallableStatusCode> expected_code; + switch (GetParam()) { + case ServiceWorkerCriteriaType::kDisabled: + expected_code = NOT_OFFLINE_CAPABLE; + break; + case ServiceWorkerCriteriaType::kSkipForInstalls: + expected_code = SERVICE_WORKER_NOT_REQUIRED; + break; + } + RunBannerTest(browser(), manager.get(), embedded_test_server()->GetURL( "/banners/no_sw_fetch_handler_test_page.html"), - NOT_OFFLINE_CAPABLE); + expected_code); - EXPECT_EQ(manager->state(), AppBannerManager::State::COMPLETE); - - if (GetParam() == ServiceWorkerCriteriaType::kDisabled) { - EXPECT_EQ(manager->GetInstallableWebAppCheckResultForTesting(), - AppBannerManager::InstallableWebAppCheckResult::kNo); + if (expected_code) { + EXPECT_EQ(manager->state(), AppBannerManager::State::COMPLETE); } else { - EXPECT_EQ( - manager->GetInstallableWebAppCheckResultForTesting(), - AppBannerManager::InstallableWebAppCheckResult::kYes_ByUserRequest); + EXPECT_EQ(manager->state(), AppBannerManager::State::PENDING_PROMPT); } } -class PendingWorkerAppBannerManager : public AppBannerManagerTest { - public: - explicit PendingWorkerAppBannerManager(content::WebContents* web_contents) - : AppBannerManagerTest(web_contents) {} - - PendingWorkerAppBannerManager(const PendingWorkerAppBannerManager&) = delete; - PendingWorkerAppBannerManager& operator=( - const PendingWorkerAppBannerManager&) = delete; - - ~PendingWorkerAppBannerManager() override = default; - - protected: - void UpdateState(AppBannerManager::State state) override { - AppBannerManagerTest::UpdateState(state); - if (state == AppBannerManager::State::PENDING_WORKER) { - if (on_done_) - base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, - std::move(on_done_)); - } - } -}; - -IN_PROC_BROWSER_TEST_P(AppBannerServiceWorkerCriteriaTest, - PendingServiceWorker) { - content::WebContents* web_contents = - browser()->tab_strip_model()->GetActiveWebContents(); - std::unique_ptr<PendingWorkerAppBannerManager> manager = - std::make_unique<PendingWorkerAppBannerManager>(web_contents); - - RunBannerTest(browser(), manager.get(), - embedded_test_server()->GetURL( - "/banners/manifest_no_service_worker.html"), - absl::nullopt); - - EXPECT_EQ(manager->state(), AppBannerManager::State::PENDING_WORKER); - if (GetParam() == ServiceWorkerCriteriaType::kDisabled) { - EXPECT_EQ(manager->GetInstallableWebAppCheckResultForTesting(), - AppBannerManager::InstallableWebAppCheckResult::kUnknown); - } else { - EXPECT_EQ( - manager->GetInstallableWebAppCheckResultForTesting(), - AppBannerManager::InstallableWebAppCheckResult::kYes_ByUserRequest); - } - EXPECT_EQ(manager->GetAppName(), u"Manifest test app"); -} - INSTANTIATE_TEST_SUITE_P( All, AppBannerServiceWorkerCriteriaTest,
diff --git a/chrome/browser/banners/test_app_banner_manager_desktop.cc b/chrome/browser/banners/test_app_banner_manager_desktop.cc index 607c9b2..031a929 100644 --- a/chrome/browser/banners/test_app_banner_manager_desktop.cc +++ b/chrome/browser/banners/test_app_banner_manager_desktop.cc
@@ -59,13 +59,7 @@ installable_quit_closure_ = run_loop.QuitClosure(); run_loop.Run(); } - // Only wait for worker check if it has started after the installable check. - if (waiting_for_worker_) { - base::RunLoop run_loop; - promotable_quit_closure_ = run_loop.QuitClosure(); - run_loop.Run(); - } - return *installable_ && promotable_; + return *installable_; } void TestAppBannerManagerDesktop::PrepareDone(base::OnceClosure on_done) { @@ -98,22 +92,9 @@ SetInstallable(result.NoBlockingErrors()); } -void TestAppBannerManagerDesktop::PerformServiceWorkerCheck() { - waiting_for_worker_ = true; - AppBannerManagerDesktop::PerformServiceWorkerCheck(); -} - -void TestAppBannerManagerDesktop::OnDidPerformWorkerCheck( - const InstallableData& result) { - AppBannerManagerDesktop::OnDidPerformWorkerCheck(result); - SetPromotable(result.NoBlockingErrors()); -} - void TestAppBannerManagerDesktop::ResetCurrentPageData() { AppBannerManagerDesktop::ResetCurrentPageData(); installable_.reset(); - promotable_ = false; - waiting_for_worker_ = false; if (tear_down_quit_closure_) std::move(tear_down_quit_closure_).Run(); } @@ -164,14 +145,6 @@ std::move(installable_quit_closure_).Run(); } -void TestAppBannerManagerDesktop::SetPromotable(bool promotable) { - DCHECK(waiting_for_worker_); - waiting_for_worker_ = false; - promotable_ = promotable; - if (promotable_quit_closure_) - std::move(promotable_quit_closure_).Run(); -} - void TestAppBannerManagerDesktop::OnFinished() { if (on_done_) { base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
diff --git a/chrome/browser/banners/test_app_banner_manager_desktop.h b/chrome/browser/banners/test_app_banner_manager_desktop.h index b109aba..90f3c37 100644 --- a/chrome/browser/banners/test_app_banner_manager_desktop.h +++ b/chrome/browser/banners/test_app_banner_manager_desktop.h
@@ -38,7 +38,7 @@ // Blocks until the existing installability check has been cleared. void WaitForInstallableCheckTearDown(); - // Returns whether both the installable and promotable check passed. + // Returns whether the installable check passed. bool WaitForInstallableCheck(); // Configures a callback to be invoked when the app banner flow finishes. @@ -54,8 +54,6 @@ void OnDidGetManifest(const InstallableData& result) override; void OnDidPerformInstallableWebAppCheck( const InstallableData& result) override; - void PerformServiceWorkerCheck() override; - void OnDidPerformWorkerCheck(const InstallableData& result) override; void ResetCurrentPageData() override; // AppBannerManagerDesktop: @@ -73,15 +71,11 @@ private: void SetInstallable(bool installable); - void SetPromotable(bool promotable); void OnFinished(); absl::optional<bool> installable_; - bool waiting_for_worker_; - bool promotable_; base::OnceClosure tear_down_quit_closure_; base::OnceClosure installable_quit_closure_; - base::OnceClosure promotable_quit_closure_; base::OnceClosure on_done_; base::OnceClosure on_install_; };
diff --git a/chrome/browser/chrome_back_forward_cache_browsertest.cc b/chrome/browser/chrome_back_forward_cache_browsertest.cc index 5100867..0ab7c86 100644 --- a/chrome/browser/chrome_back_forward_cache_browsertest.cc +++ b/chrome/browser/chrome_back_forward_cache_browsertest.cc
@@ -45,23 +45,6 @@ #include "third_party/blink/public/mojom/webshare/webshare.mojom.h" #include "ui/base/l10n/l10n_util.h" -namespace { - -// hash for std::unordered_map. -struct FeatureHash { - size_t operator()(base::Feature feature) const { - return base::FastHash(feature.name); - } -}; - -// compare operator for std::unordered_map. -struct FeatureEqualOperator { - bool operator()(base::Feature feature1, base::Feature feature2) const { - return std::strcmp(feature1.name, feature2.name) == 0; - } -}; -} // namespace - class ChromeBackForwardCacheBrowserTest : public InProcessBrowserTest { public: ChromeBackForwardCacheBrowserTest() = default; @@ -126,8 +109,8 @@ std::vector<base::test::ScopedFeatureList::FeatureAndParams> enabled_features; - for (const auto& feature_param : features_with_params_) { - enabled_features.emplace_back(feature_param.first, feature_param.second); + for (const auto& [feature, params] : features_with_params_) { + enabled_features.emplace_back(*feature, params); } scoped_feature_list_.InitWithFeaturesAndParameters(enabled_features, @@ -135,13 +118,13 @@ vmodule_switches_.InitWithSwitches("back_forward_cache_impl=1"); } - void EnableFeatureAndSetParams(base::Feature feature, - std::string param_name, - std::string param_value) { + void EnableFeatureAndSetParams(const base::Feature& feature, + const std::string& param_name, + const std::string& param_value) { features_with_params_[feature][param_name] = param_value; } - void DisableFeature(base::Feature feature) { + void DisableFeature(const base::Feature& feature) { disabled_features_.push_back(feature); } @@ -150,10 +133,7 @@ private: base::test::ScopedFeatureList scoped_feature_list_; logging::ScopedVmoduleSwitches vmodule_switches_; - std::unordered_map<base::Feature, - std::map<std::string, std::string>, - FeatureHash, - FeatureEqualOperator> + std::map<base::test::FeatureRef, std::map<std::string, std::string>> features_with_params_; std::vector<base::test::FeatureRef> disabled_features_; };
diff --git a/chrome/browser/chrome_browser_interface_binders.cc b/chrome/browser/chrome_browser_interface_binders.cc index dfc3e13..6f469fa 100644 --- a/chrome/browser/chrome_browser_interface_binders.cc +++ b/chrome/browser/chrome_browser_interface_binders.cc
@@ -1049,12 +1049,11 @@ chromeos::settings::OSSettingsUI>(map); RegisterWebUIControllerInterfaceBinder< - chromeos::settings::mojom::UserActionRecorder, + ash::settings::mojom::UserActionRecorder, chromeos::settings::OSSettingsUI>(map); - RegisterWebUIControllerInterfaceBinder< - chromeos::settings::mojom::SearchHandler, - chromeos::settings::OSSettingsUI>(map); + RegisterWebUIControllerInterfaceBinder<ash::settings::mojom::SearchHandler, + chromeos::settings::OSSettingsUI>(map); RegisterWebUIControllerInterfaceBinder< ash::personalization_app::mojom::SearchHandler,
diff --git a/chrome/browser/chrome_browser_main.cc b/chrome/browser/chrome_browser_main.cc index adc0ffd..e6e8872 100644 --- a/chrome/browser/chrome_browser_main.cc +++ b/chrome/browser/chrome_browser_main.cc
@@ -504,7 +504,8 @@ // ChromeBrowserMainParts::ProfileInitManager ---------------------------------- // Runs `CallPostProfileInit()` on all existing and future profiles, the -// initial profile is processed first. +// initial profile is processed first. The initial profile is nullptr when the +// profile picker is shown. class ChromeBrowserMainParts::ProfileInitManager : public ProfileManagerObserver { public: @@ -530,7 +531,9 @@ ChromeBrowserMainParts* browser_main, Profile* initial_profile) : browser_main_(browser_main) { - browser_main_->CallPostProfileInit(initial_profile); + // `initial_profile` is null when the profile picker is shown. + if (initial_profile) + browser_main_->CallPostProfileInit(initial_profile); if (base::FeatureList::IsEnabled(features::kObserverBasedPostProfileInit)) { // Run `CallPostProfileInit()` on the other existing and future profiles. @@ -1586,7 +1589,6 @@ StartupProfileInfo profile_info = CreateInitialProfile( /*cur_dir=*/base::FilePath(), *base::CommandLine::ForCurrentProcess()); - Profile* profile = profile_info.profile; if (profile_info.mode == StartupProfileMode::kError) return content::RESULT_CODE_NORMAL_EXIT; @@ -1639,6 +1641,8 @@ } #endif // !BUILDFLAG(GOOGLE_CHROME_FOR_TESTING_BRANDING) + // `profile` may be nullptr if the profile picker is shown. + Profile* profile = profile_info.profile; // Call `PostProfileInit()`and set it up for profiles created later. profile_init_manager_ = std::make_unique<ProfileInitManager>(this, profile); @@ -1647,7 +1651,11 @@ // and preferences have been registered since some of the import code depends // on preferences. if (first_run::IsChromeFirstRun()) { - first_run::AutoImport(profile, master_prefs_->import_bookmarks_path); + // `profile` may be nullptr even on first run, for example when the + // "BrowserSignin" policy is set to "Force". If so, skip the auto import. + if (profile) { + first_run::AutoImport(profile, master_prefs_->import_bookmarks_path); + } // Note: This can pop-up the first run consent dialog on Linux & Mac. first_run::DoPostImportTasks(master_prefs_->make_chrome_default_for_user); @@ -1739,11 +1747,12 @@ variations_service->PerformPreMainMessageLoopStartup(); #if BUILDFLAG(IS_ANDROID) + // The profile picker is never shown on Android. DCHECK_EQ(profile_info.mode, StartupProfileMode::kBrowserWindow); + DCHECK(profile); // Just initialize the policy prefs service here. Variations seed fetching // will be initialized when the app enters foreground mode. variations_service->set_policy_pref_service(profile->GetPrefs()); - #else // We are in regular browser boot sequence. Open initial tabs and enter the // main message loop.
diff --git a/chrome/browser/chrome_multiprofile_startup_browsertest.cc b/chrome/browser/chrome_multiprofile_startup_browsertest.cc index 09ec9bf..49112a6 100644 --- a/chrome/browser/chrome_multiprofile_startup_browsertest.cc +++ b/chrome/browser/chrome_multiprofile_startup_browsertest.cc
@@ -103,11 +103,8 @@ {HasBaseName(kOtherProfileDirPath), false}}}, {.should_enable_profile_observer = true, .should_show_profile_picker = true, - // TODO(https://crbug.com/1150326): The first call with guest profile - // should be skipped. .expected_post_profile_init_call_args = { - {Property(&Profile::IsGuestSession, true), true}, - {HasBaseName(chrome::kInitialProfile), false}, + {HasBaseName(chrome::kInitialProfile), true}, {HasBaseName(kOtherProfileDirPath), false}}}}; // Creates a new profile to be picked up on the actual test.
diff --git a/chrome/browser/chromeos/BUILD.gn b/chrome/browser/chromeos/BUILD.gn index 94bf8c3..3a556731 100644 --- a/chrome/browser/chromeos/BUILD.gn +++ b/chrome/browser/chromeos/BUILD.gn
@@ -82,8 +82,6 @@ "//ash/components/phonehub", "//ash/components/phonehub/proto", "//ash/components/tether", - "//ash/components/tpm", - "//ash/components/tpm:buildflags", "//ash/constants", "//ash/keyboard/ui", "//ash/public/cpp", @@ -107,7 +105,6 @@ "//ash/services/multidevice_setup/public/cpp:prefs", "//ash/services/nearby/public/cpp", "//ash/services/nearby/public/mojom", - "//ash/services/quick_pair/public/mojom", "//ash/services/secure_channel", "//ash/services/secure_channel/public/cpp/client", "//ash/services/secure_channel/public/mojom", @@ -325,12 +322,15 @@ "//chromeos/ash/components/string_matching", "//chromeos/ash/components/sync_wifi", "//chromeos/ash/components/timezone", + "//chromeos/ash/components/tpm", + "//chromeos/ash/components/tpm:buildflags", "//chromeos/ash/services/assistant:lib", "//chromeos/ash/services/assistant/public/cpp", "//chromeos/ash/services/bluetooth_config:in_process_bluetooth_config", "//chromeos/ash/services/cros_healthd/private/cpp", "//chromeos/ash/services/cros_healthd/public/cpp", "//chromeos/ash/services/cros_healthd/public/mojom", + "//chromeos/ash/services/quick_pair/public/mojom", "//chromeos/ash/services/rollback_network_config/public/mojom", "//chromeos/components/cdm_factory_daemon:cdm_factory_daemon_browser", "//chromeos/components/certificate_provider:certificate_provider", @@ -2035,7 +2035,6 @@ "//ash/components/arc:notification_test_support", "//ash/components/phonehub:test_support", "//ash/components/tether:test_support", - "//ash/components/tpm", "//ash/constants", "//ash/public/cpp", "//ash/public/cpp:test_support", @@ -2110,6 +2109,7 @@ "//chromeos/ash/components/scanning", "//chromeos/ash/components/settings", "//chromeos/ash/components/sync_wifi:test_support", + "//chromeos/ash/components/tpm", "//chromeos/components/sensors:test_support", "//chromeos/dbus/dlp", "//chromeos/dbus/missive",
diff --git a/chrome/browser/chromeos/app_mode/app_session_browser_window_handler.cc b/chrome/browser/chromeos/app_mode/app_session_browser_window_handler.cc index a811888364..5615c0f 100644 --- a/chrome/browser/chromeos/app_mode/app_session_browser_window_handler.cc +++ b/chrome/browser/chromeos/app_mode/app_session_browser_window_handler.cc
@@ -50,16 +50,19 @@ HandleNewSettingsWindow(browser, url_string); on_browser_window_added_callback_.Run(false); } else { - base::UmaHistogramEnumeration(kKioskNewBrowserWindowHistogram, - KioskBrowserWindowType::kOther); - if (IsNewBrowserWindowAllowed(browser)) { + base::UmaHistogramEnumeration( + kKioskNewBrowserWindowHistogram, + KioskBrowserWindowType::kOpenedRegularBrowser); LOG(WARNING) << "Open additional fullscreen browser window in kiosk session" << ", url=" << url_string; chrome::ToggleFullscreenMode(browser); on_browser_window_added_callback_.Run(false); } else { + base::UmaHistogramEnumeration( + kKioskNewBrowserWindowHistogram, + KioskBrowserWindowType::kClosedRegularBrowser); LOG(WARNING) << "Force close browser opened in kiosk session" << ", url=" << url_string; browser->window()->Close();
diff --git a/chrome/browser/chromeos/app_mode/app_session_browser_window_handler.h b/chrome/browser/chromeos/app_mode/app_session_browser_window_handler.h index f75793a..ee050c50 100644 --- a/chrome/browser/chromeos/app_mode/app_session_browser_window_handler.h +++ b/chrome/browser/chromeos/app_mode/app_session_browser_window_handler.h
@@ -22,8 +22,9 @@ // Keep in sync with respective enum in tools/metrics/histograms/enums.xml enum class KioskBrowserWindowType { kSettingsPage = 0, - kOther = 1, - kMaxValue = kOther, + kClosedRegularBrowser = 1, + kOpenedRegularBrowser = 2, + kMaxValue = kOpenedRegularBrowser, }; // This class monitors for the addition and removal of new browser windows
diff --git a/chrome/browser/chromeos/app_mode/app_session_unittest.cc b/chrome/browser/chromeos/app_mode/app_session_unittest.cc index 89b9db5..358ea65 100644 --- a/chrome/browser/chromeos/app_mode/app_session_unittest.cc +++ b/chrome/browser/chromeos/app_mode/app_session_unittest.cc
@@ -277,10 +277,6 @@ // The main browser window still exists, the kiosk session should not // shutdown. EXPECT_FALSE(IsSessionShuttingDown()); - histogram()->ExpectBucketCount(kKioskNewBrowserWindowHistogram, - KioskBrowserWindowType::kOther, 1); - histogram()->ExpectBucketCount(kKioskNewBrowserWindowHistogram, - KioskBrowserWindowType::kSettingsPage, 0); // Opening a new browser should not be counted as a new session. histogram()->ExpectTotalCount(kKioskSessionCountPerDayHistogram, 1); @@ -316,7 +312,8 @@ // Closing the browser should not shutdown the ChromeApp kiosk session. EXPECT_FALSE(IsSessionShuttingDown()); histogram()->ExpectBucketCount(kKioskNewBrowserWindowHistogram, - KioskBrowserWindowType::kOther, 1); + KioskBrowserWindowType::kClosedRegularBrowser, + 1); histogram()->ExpectTotalCount(kKioskNewBrowserWindowHistogram, 1); const base::Value::Dict& dict = local_state()->GetDict(prefs::kKioskMetrics); @@ -490,6 +487,32 @@ CreateBrowserForWebApp(kTestWebAppName2)->window())); } +TEST_F(AppSessionTest, NewOpenedRegularBrowserMetrics) { + GetPrefs()->SetBoolean(prefs::kNewWindowsInKioskAllowed, true); + StartWebKioskSession(kTestWebAppName1); + + ShouldBrowserBeClosedByAppSessionBrowserHander( + CreateBrowserForWebApp(kTestWebAppName1)->window()); + + histogram()->ExpectBucketCount(kKioskNewBrowserWindowHistogram, + KioskBrowserWindowType::kOpenedRegularBrowser, + 1); + histogram()->ExpectTotalCount(kKioskNewBrowserWindowHistogram, 1); +} + +TEST_F(AppSessionTest, NewClosedRegularBrowserMetrics) { + GetPrefs()->SetBoolean(prefs::kNewWindowsInKioskAllowed, false); + StartWebKioskSession(kTestWebAppName1); + + ShouldBrowserBeClosedByAppSessionBrowserHander( + CreateBrowserForWebApp(kTestWebAppName1)->window()); + + histogram()->ExpectBucketCount(kKioskNewBrowserWindowHistogram, + KioskBrowserWindowType::kClosedRegularBrowser, + 1); + histogram()->ExpectTotalCount(kKioskNewBrowserWindowHistogram, 1); +} + TEST_F(AppSessionTest, DoNotExitWebKioskSessionWhenSecondBrowserIsOpened) { GetPrefs()->SetBoolean(prefs::kNewWindowsInKioskAllowed, true); StartWebKioskSession();
diff --git a/chrome/browser/chromeos/extensions/file_manager/event_router.cc b/chrome/browser/chromeos/extensions/file_manager/event_router.cc index 34b3ede..0512238 100644 --- a/chrome/browser/chromeos/extensions/file_manager/event_router.cc +++ b/chrome/browser/chromeos/extensions/file_manager/event_router.cc
@@ -542,6 +542,8 @@ return file_manager_private::MOUNT_COMPLETED_STATUS_ERROR_IN_PROGRESS; case ash::MountError::kCancelled: return file_manager_private::MOUNT_COMPLETED_STATUS_ERROR_CANCELLED; + case ash::MountError::kBusy: + return file_manager_private::MOUNT_COMPLETED_STATUS_ERROR_BUSY; } NOTREACHED();
diff --git a/chrome/browser/chromeos/extensions/file_manager/event_router_unittest.cc b/chrome/browser/chromeos/extensions/file_manager/event_router_unittest.cc index 110f445..224425a 100644 --- a/chrome/browser/chromeos/extensions/file_manager/event_router_unittest.cc +++ b/chrome/browser/chromeos/extensions/file_manager/event_router_unittest.cc
@@ -177,7 +177,7 @@ const base::Value* outputs = arg[0].FindKeyOfType("outputs", base::Value::Type::LIST); EXPECT_TRUE(outputs) << "The outputs field is not available on the event"; - EXPECT_GT(static_cast<int>((*outputs).GetList().size()), index) + EXPECT_GT((*outputs).GetList().size(), index) << "The supplied index on outputs is not available, size: " << (*outputs).GetList().size() << ", index: " << index; const std::string* actual_value = @@ -217,10 +217,10 @@ observer, OnBroadcastEvent(Field( &extensions::Event::event_args, - AllOf(ExpectEventArgString(0, "fileFullPath", "/bar.txt"), - ExpectEventArgString(0, "fileSystemName", "Downloads"), + AllOf(ExpectEventArgString(0u, "fileFullPath", "/bar.txt"), + ExpectEventArgString(0u, "fileSystemName", "Downloads"), ExpectEventArgString( - 0, "fileSystemRoot", + 0u, "fileSystemRoot", "filesystem:chrome-extension://abc/external/Downloads/"))))) .WillOnce(RunClosure(run_loop.QuitClosure()));
diff --git a/chrome/browser/chromeos/extensions/input_method_api.cc b/chrome/browser/chromeos/extensions/input_method_api.cc index dd9683f..978fc7d3 100644 --- a/chrome/browser/chromeos/extensions/input_method_api.cc +++ b/chrome/browser/chromeos/extensions/input_method_api.cc
@@ -643,6 +643,18 @@ return RespondNow(NoArguments()); } +ExtensionFunction::ResponseAction +InputMethodPrivateNotifyInputMethodReadyForTestingFunction::Run() { + std::string error; + ash::input_method::InputMethodEngine* engine = GetEngineIfActive( + Profile::FromBrowserContext(browser_context()), extension_id(), &error); + if (!engine) + return RespondNow(Error(InformativeError(error, static_function_name()))); + + engine->NotifyInputMethodExtensionReadyForTesting(); // IN-TEST + return RespondNow(NoArguments()); +} + InputMethodAPI::InputMethodAPI(content::BrowserContext* context) : context_(context) { EventRouter::Get(context_)->RegisterObserver(this, OnChanged::kEventName);
diff --git a/chrome/browser/chromeos/extensions/input_method_api.h b/chrome/browser/chromeos/extensions/input_method_api.h index 1b46637a..f13aa6b 100644 --- a/chrome/browser/chromeos/extensions/input_method_api.h +++ b/chrome/browser/chromeos/extensions/input_method_api.h
@@ -474,6 +474,30 @@ INPUTMETHODPRIVATE_ONAUTOCORRECT) }; +class InputMethodPrivateNotifyInputMethodReadyForTestingFunction + : public ExtensionFunction { + public: + InputMethodPrivateNotifyInputMethodReadyForTestingFunction() = default; + + InputMethodPrivateNotifyInputMethodReadyForTestingFunction( + const InputMethodPrivateNotifyInputMethodReadyForTestingFunction&) = + delete; + InputMethodPrivateNotifyInputMethodReadyForTestingFunction& operator=( + const InputMethodPrivateNotifyInputMethodReadyForTestingFunction&) = + delete; + + protected: + ~InputMethodPrivateNotifyInputMethodReadyForTestingFunction() override = + default; + + ResponseAction Run() override; + + private: + DECLARE_EXTENSION_FUNCTION( + "inputMethodPrivate.notifyInputMethodReadyForTesting", + INPUTMETHODPRIVATE_NOTIFYINPUTMETHODREADYFORTESTING) +}; + class InputMethodAPI : public BrowserContextKeyedAPI, public extensions::EventRouter::Observer { public:
diff --git a/chrome/browser/chromeos/extensions/telemetry/api/base_telemetry_extension_browser_test.cc b/chrome/browser/chromeos/extensions/telemetry/api/base_telemetry_extension_browser_test.cc index bad1841a..cc01db341 100644 --- a/chrome/browser/chromeos/extensions/telemetry/api/base_telemetry_extension_browser_test.cc +++ b/chrome/browser/chromeos/extensions/telemetry/api/base_telemetry_extension_browser_test.cc
@@ -63,7 +63,8 @@ "permissions": [ "os.diagnostics", "os.telemetry", - "os.telemetry.serial_number" + "os.telemetry.serial_number", + "os.telemetry.network_info" ], "externally_connectable": { "matches": [
diff --git a/chrome/browser/chromeos/extensions/telemetry/chromeos_permission_messages_unittest.cc b/chrome/browser/chromeos/extensions/telemetry/chromeos_permission_messages_unittest.cc index 0d6c912..c82d5742 100644 --- a/chrome/browser/chromeos/extensions/telemetry/chromeos_permission_messages_unittest.cc +++ b/chrome/browser/chromeos/extensions/telemetry/chromeos_permission_messages_unittest.cc
@@ -39,6 +39,8 @@ u"Read ChromeOS device information and device data."; const std::u16string kTelemetrySerialNumberPermissionMessage = u"Read ChromeOS device and component serial numbers."; +const std::u16string kTelemetryNetworkInformationPermissionMessage = + u"Read ChromeOS network information."; } // namespace @@ -176,4 +178,26 @@ EXPECT_EQ(kTelemetrySerialNumberPermissionMessage, active_permissions()[0]); } +TEST_F(ChromeOSPermissionMessageUnittest, OsTelemetryNetworkInformation) { + CreateAndInstallExtensionWithPermissions( + extensions::ListBuilder().Build(), + extensions::ListBuilder().Append("os.telemetry.network_info").Build()); + + ASSERT_EQ(1U, optional_permissions().size()); + EXPECT_EQ(kTelemetryNetworkInformationPermissionMessage, + optional_permissions()[0]); + ASSERT_EQ(1U, GetInactiveOptionalPermissionMessages().size()); + EXPECT_EQ(kTelemetryNetworkInformationPermissionMessage, + GetInactiveOptionalPermissionMessages()[0]); + ASSERT_EQ(0U, required_permissions().size()); + ASSERT_EQ(0U, active_permissions().size()); + + GrantOptionalPermissions(); + + ASSERT_EQ(0U, GetInactiveOptionalPermissionMessages().size()); + ASSERT_EQ(1U, active_permissions().size()); + EXPECT_EQ(kTelemetryNetworkInformationPermissionMessage, + active_permissions()[0]); +} + } // namespace chromeos
diff --git a/chrome/browser/chromeos/policy/dlp/dlp_warn_dialog.cc b/chrome/browser/chromeos/policy/dlp/dlp_warn_dialog.cc index 781b292f..768036eb 100644 --- a/chrome/browser/chromeos/policy/dlp/dlp_warn_dialog.cc +++ b/chrome/browser/chromeos/policy/dlp/dlp_warn_dialog.cc
@@ -84,7 +84,7 @@ constexpr int kConfidentialContentListMaxHeight = 240; // Returns the destination name for |dst_component| -const std::u16string GetDestinationForFiles( +const std::u16string GetDestinationComponentForFiles( DlpRulesManager::Component dst_component) { switch (dst_component) { case DlpRulesManager::Component::kArc: @@ -116,6 +116,12 @@ case DlpFilesController::FileAction::kUpload: return l10n_util::GetStringUTF16( IDS_POLICY_DLP_FILES_UPLOAD_WARN_CONTINUE_BUTTON); + case DlpFilesController::FileAction::kCopy: + return l10n_util::GetStringUTF16( + IDS_POLICY_DLP_FILES_COPY_WARN_CONTINUE_BUTTON); + case DlpFilesController::FileAction::kMove: + return l10n_util::GetStringUTF16( + IDS_POLICY_DLP_FILES_MOVE_WARN_CONTINUE_BUTTON); case DlpFilesController::FileAction::kTransfer: case DlpFilesController::FileAction::kUnknown: // TODO(crbug.com/1361900) // Set proper text when file @@ -137,6 +143,12 @@ case DlpFilesController::FileAction::kUpload: return l10n_util::GetPluralStringFUTF16( IDS_POLICY_DLP_FILES_UPLOAD_WARN_TITLE, files_number); + case DlpFilesController::FileAction::kCopy: + return l10n_util::GetPluralStringFUTF16( + IDS_POLICY_DLP_FILES_COPY_WARN_TITLE, files_number); + case DlpFilesController::FileAction::kMove: + return l10n_util::GetPluralStringFUTF16( + IDS_POLICY_DLP_FILES_MOVE_WARN_TITLE, files_number); case DlpFilesController::FileAction::kTransfer: case DlpFilesController::FileAction::kUnknown: // TODO(crbug.com/1361900) // Set proper text when file @@ -157,7 +169,8 @@ l10n_util::GetPluralStringFUTF16( // Download action is only allowed for one file. IDS_POLICY_DLP_FILES_DOWNLOAD_WARN_MESSAGE, 1), - GetDestinationForFiles(options.destination_component.value()), + GetDestinationComponentForFiles( + options.destination_component.value()), /*offset=*/nullptr); case DlpFilesController::FileAction::kUpload: DCHECK(!options.destination_pattern->empty()); @@ -167,14 +180,32 @@ options.confidential_files.size()), base::UTF8ToUTF16(options.destination_pattern.value()), /*offset=*/nullptr); + case DlpFilesController::FileAction::kCopy: + DCHECK(!options.destination_pattern->empty()); + return base::ReplaceStringPlaceholders( + l10n_util::GetPluralStringFUTF16( + IDS_POLICY_DLP_FILES_COPY_WARN_MESSAGE, + options.confidential_files.size()), + GetDestinationComponentForFiles( + options.destination_component.value()), + /*offset=*/nullptr); + case DlpFilesController::FileAction::kMove: + DCHECK(!options.destination_pattern->empty()); + return base::ReplaceStringPlaceholders( + l10n_util::GetPluralStringFUTF16( + IDS_POLICY_DLP_FILES_MOVE_WARN_MESSAGE, + options.confidential_files.size()), + GetDestinationComponentForFiles( + options.destination_component.value()), + /*offset=*/nullptr); case DlpFilesController::FileAction::kTransfer: case DlpFilesController::FileAction::kUnknown: // TODO(crbug.com/1361900) // Set proper text when file // action is unknown std::u16string destination; if (options.destination_component.has_value()) { - destination = - GetDestinationForFiles(options.destination_component.value()); + destination = GetDestinationComponentForFiles( + options.destination_component.value()); } else { DCHECK(!options.destination_pattern->empty()); destination = base::UTF8ToUTF16(options.destination_pattern.value());
diff --git a/chrome/browser/commerce/price_tracking/android/java/src/org/chromium/chrome/browser/price_tracking/PriceTrackingButtonController.java b/chrome/browser/commerce/price_tracking/android/java/src/org/chromium/chrome/browser/price_tracking/PriceTrackingButtonController.java index 2d78ba6..61db5736 100644 --- a/chrome/browser/commerce/price_tracking/android/java/src/org/chromium/chrome/browser/price_tracking/PriceTrackingButtonController.java +++ b/chrome/browser/commerce/price_tracking/android/java/src/org/chromium/chrome/browser/price_tracking/PriceTrackingButtonController.java
@@ -4,68 +4,48 @@ package org.chromium.chrome.browser.price_tracking; -import android.app.Activity; import android.content.res.Resources; +import android.graphics.drawable.Drawable; +import android.view.View; import androidx.annotation.Nullable; -import androidx.appcompat.content.res.AppCompatResources; import org.chromium.base.FeatureList; -import org.chromium.base.ObserverList; import org.chromium.base.supplier.ObservableSupplier; import org.chromium.base.supplier.Supplier; import org.chromium.chrome.R; import org.chromium.chrome.browser.bookmarks.TabBookmarker; import org.chromium.chrome.browser.tab.Tab; +import org.chromium.chrome.browser.toolbar.BaseButtonDataProvider; import org.chromium.chrome.browser.toolbar.ButtonData; -import org.chromium.chrome.browser.toolbar.ButtonDataImpl; -import org.chromium.chrome.browser.toolbar.ButtonDataProvider; import org.chromium.chrome.browser.toolbar.adaptive.AdaptiveToolbarFeatures; import org.chromium.chrome.browser.toolbar.adaptive.AdaptiveToolbarFeatures.AdaptiveToolbarButtonVariant; import org.chromium.chrome.browser.user_education.IPHCommandBuilder; import org.chromium.components.feature_engagement.FeatureConstants; +import org.chromium.ui.modaldialog.ModalDialogManager; /** * Responsible for providing UI resources for showing price tracking action on optional toolbar * button. */ -public class PriceTrackingButtonController implements ButtonDataProvider { - private final Activity mActivity; +public class PriceTrackingButtonController extends BaseButtonDataProvider { private final Supplier<TabBookmarker> mTabBookmarkerSupplier; - private final ObserverList<ButtonDataObserver> mObservers = new ObserverList<>(); - private final ButtonDataImpl mButtonData; /** Constructor. */ - public PriceTrackingButtonController(Activity activity, ObservableSupplier<Tab> tabSupplier, + public PriceTrackingButtonController(ObservableSupplier<Tab> tabSupplier, + ModalDialogManager modalDialogManager, Drawable buttonDrawable, Supplier<TabBookmarker> tabBookmarkerSupplier) { - mActivity = activity; + super(tabSupplier, modalDialogManager, buttonDrawable, + R.string.enable_price_tracking_menu_item, + /*supportsTinting=*/true, /*iphCommandBuilder*/ null, + AdaptiveToolbarButtonVariant.PRICE_TRACKING); mTabBookmarkerSupplier = tabBookmarkerSupplier; - - // TODO(shaktisahu): Provide accurate icon and string. - mButtonData = new ButtonDataImpl(/*canShow=*/true, - AppCompatResources.getDrawable(mActivity, R.drawable.price_tracking_disabled), - view - -> onPriceTrackingClicked(tabSupplier.get()), - R.string.enable_price_tracking_menu_item, /*supportsTinting=*/true, - /*iphCommandBuilder*/ null, - /*isEnabled=*/true, AdaptiveToolbarButtonVariant.PRICE_TRACKING); - } - - @Override - public void addObserver(ButtonDataObserver obs) { - mObservers.addObserver(obs); - } - - @Override - public void removeObserver(ButtonDataObserver obs) { - mObservers.removeObserver(obs); } @Override public ButtonData get(@Nullable Tab tab) { - maybeSetIphCommandBuilder(tab); maybeSetActionChipResourceId(); - return mButtonData; + return super.get(tab); } private void maybeSetActionChipResourceId() { @@ -79,24 +59,20 @@ } @Override - public void destroy() { - mObservers.clear(); + public void onClick(View view) { + mTabBookmarkerSupplier.get().startOrModifyPriceTracking(mActiveTabSupplier.get()); } - private void onPriceTrackingClicked(Tab tab) { - mTabBookmarkerSupplier.get().startOrModifyPriceTracking(tab); - } - - private void maybeSetIphCommandBuilder(Tab tab) { - if (mButtonData.getButtonSpec().getIPHCommandBuilder() != null || tab == null - || !FeatureList.isInitialized() || AdaptiveToolbarFeatures.shouldShowActionChip()) { - return; + @Override + protected IPHCommandBuilder getIphCommandBuilder(Tab tab) { + if (AdaptiveToolbarFeatures.shouldShowActionChip()) { + return null; } IPHCommandBuilder iphCommandBuilder = new IPHCommandBuilder(tab.getContext().getResources(), FeatureConstants.CONTEXTUAL_PAGE_ACTIONS_PRICE_TRACKING, /* stringId = */ R.string.iph_price_tracking_menu_item, /* accessibilityStringId = */ R.string.iph_price_tracking_menu_item); - mButtonData.updateIPHCommandBuilder(iphCommandBuilder); + return iphCommandBuilder; } }
diff --git a/chrome/browser/download/download_ui_model.cc b/chrome/browser/download/download_ui_model.cc index ff33a2f2..ee27c17a 100644 --- a/chrome/browser/download/download_ui_model.cc +++ b/chrome/browser/download/download_ui_model.cc
@@ -4,6 +4,8 @@ #include "chrome/browser/download/download_ui_model.h" +#include <utility> + #include "base/feature_list.h" #include "base/i18n/rtl.h" #include "base/strings/utf_string_conversions.h" @@ -488,7 +490,7 @@ } DownloadItem* DownloadUIModel::GetDownloadItem() { - return const_cast<DownloadItem*>(base::as_const(*this).GetDownloadItem()); + return const_cast<DownloadItem*>(std::as_const(*this).GetDownloadItem()); } std::u16string DownloadUIModel::GetWebDriveName() const {
diff --git a/chrome/browser/enterprise/connectors/device_trust/signals/decorators/ash/ash_signals_decorator.cc b/chrome/browser/enterprise/connectors/device_trust/signals/decorators/ash/ash_signals_decorator.cc index ae94c19..ad3a75d 100644 --- a/chrome/browser/enterprise/connectors/device_trust/signals/decorators/ash/ash_signals_decorator.cc +++ b/chrome/browser/enterprise/connectors/device_trust/signals/decorators/ash/ash_signals_decorator.cc
@@ -136,17 +136,6 @@ signals.Set(device_signals::names::kMacAddresses, ToListValue({mac_address.value()})); } - absl::optional<net::IPAddress> ipv4_address = - result->get_network_details()->ipv4_address; - absl::optional<net::IPAddress> ipv6_address = - result->get_network_details()->ipv6_address; - if (ipv6_address.has_value()) { - signals.Set(device_signals::names::kIpAddress, - ipv6_address.value().ToString()); - } else if (ipv4_address.has_value()) { - signals.Set(device_signals::names::kIpAddress, - ipv4_address.value().ToString()); - } } LogSignalsCollectionLatency(kLatencyHistogramVariant, start_time);
diff --git a/chrome/browser/enterprise/connectors/device_trust/signals/decorators/ash/ash_signals_decorator_browsertest.cc b/chrome/browser/enterprise/connectors/device_trust/signals/decorators/ash/ash_signals_decorator_browsertest.cc index 90adeb21..0080912 100644 --- a/chrome/browser/enterprise/connectors/device_trust/signals/decorators/ash/ash_signals_decorator_browsertest.cc +++ b/chrome/browser/enterprise/connectors/device_trust/signals/decorators/ash/ash_signals_decorator_browsertest.cc
@@ -16,7 +16,6 @@ #include "chrome/browser/profiles/profile_manager.h" #include "chrome/test/base/testing_profile.h" #include "chromeos/ash/components/dbus/shill/shill_device_client.h" -#include "chromeos/ash/components/dbus/shill/shill_ipconfig_client.h" #include "chromeos/ash/components/dbus/shill/shill_profile_client.h" #include "chromeos/ash/components/dbus/shill/shill_service_client.h" #include "chromeos/ash/components/network/network_state_handler.h" @@ -43,12 +42,8 @@ constexpr char kFakeImei[] = "fake_imei"; constexpr char kFakeMeid[] = "fake_meid"; constexpr char kMacAddress[] = "00:00:00:00:00:00"; -constexpr char kIpv4Address[] = "192.168.0.42"; -constexpr char kIpv6Address[] = "fe80::1262:d0ff:fef5:e8a9"; constexpr char kWifiDevicePath[] = "/device/stub_wifi"; constexpr char kWifiServicePath[] = "/service/stub_wifi"; -constexpr char kWifiIPConfigV4Path[] = "/ipconfig/stub_wifi-ipv4"; -constexpr char kWifiIPConfigV6Path[] = "/ipconfig/stub_wifi-ipv6"; constexpr char kFakeSerialNumber[] = "fake_serial_number"; constexpr char kFakeDeviceHostName[] = "fake_device_host_name"; @@ -62,8 +57,6 @@ void SetupFakeNetwork() { ash::ShillDeviceClient::TestInterface* shill_device_client = ash::ShillDeviceClient::Get()->GetTestInterface(); - ash::ShillIPConfigClient::TestInterface* shill_ipconfig_client = - ash::ShillIPConfigClient::Get()->GetTestInterface(); ash::ShillServiceClient::TestInterface* shill_service_client = ash::ShillServiceClient::Get()->GetTestInterface(); ash::ShillProfileClient::TestInterface* shill_profile_client = @@ -76,7 +69,7 @@ "stub_wifi_device"); shill_device_client->SetDeviceProperty( kWifiDevicePath, shill::kAddressProperty, base::Value(kMacAddress), - /* notify_changed= */ false); + /*notify_changed=*/false); shill_device_client->SetDeviceProperty(kWifiDevicePath, shill::kMeidProperty, base::Value(kFakeMeid), @@ -85,32 +78,9 @@ base::Value(kFakeImei), /*notify_changed=*/false); - base::DictionaryValue ipconfig_v4_dictionary; - ipconfig_v4_dictionary.SetKey(shill::kAddressProperty, - base::Value(kIpv4Address)); - ipconfig_v4_dictionary.SetKey(shill::kMethodProperty, - base::Value(shill::kTypeIPv4)); - shill_ipconfig_client->AddIPConfig(kWifiIPConfigV4Path, - ipconfig_v4_dictionary); - - base::DictionaryValue ipconfig_v6_dictionary; - ipconfig_v6_dictionary.SetKey(shill::kAddressProperty, - base::Value(kIpv6Address)); - ipconfig_v6_dictionary.SetKey(shill::kMethodProperty, - base::Value(shill::kTypeIPv6)); - shill_ipconfig_client->AddIPConfig(kWifiIPConfigV6Path, - ipconfig_v6_dictionary); - - base::ListValue ip_configs; - ip_configs.Append(kWifiIPConfigV4Path); - ip_configs.Append(kWifiIPConfigV6Path); - shill_device_client->SetDeviceProperty(kWifiDevicePath, - shill::kIPConfigsProperty, ip_configs, - /*notify_changed=*/false); - shill_service_client->AddService(kWifiServicePath, "wifi_guid", "wifi_network_name", shill::kTypeWifi, - shill::kStateIdle, /* visible= */ true); + shill::kStateIdle, /*visible=*/true); shill_service_client->SetServiceProperty( kWifiServicePath, shill::kConnectableProperty, base::Value(true)); @@ -220,9 +190,6 @@ run_loop.Run(); - EXPECT_EQ(*signals.FindString(device_signals::names::kIpAddress), - kIpv6Address); - const auto* mac_addresses = signals.FindList(device_signals::names::kMacAddresses); ASSERT_TRUE(mac_addresses);
diff --git a/chrome/browser/extensions/BUILD.gn b/chrome/browser/extensions/BUILD.gn index 6d64a47d..6a58d64 100644 --- a/chrome/browser/extensions/BUILD.gn +++ b/chrome/browser/extensions/BUILD.gn
@@ -1139,7 +1139,6 @@ deps += [ "//ash", "//ash/components/arc", - "//ash/components/tpm", "//ash/constants", "//ash/keyboard/ui:resources_grit_grit", "//ash/public/cpp", @@ -1171,6 +1170,7 @@ "//chromeos/ash/components/network", "//chromeos/ash/components/proximity_auth", "//chromeos/ash/components/settings", + "//chromeos/ash/components/tpm", "//chromeos/ash/services/assistant/public/cpp", "//chromeos/ash/services/chromebox_for_meetings/public/cpp", "//chromeos/ash/services/chromebox_for_meetings/public/mojom",
diff --git a/chrome/browser/first_party_sets/BUILD.gn b/chrome/browser/first_party_sets/BUILD.gn index 6e4b92d5..ccba188 100644 --- a/chrome/browser/first_party_sets/BUILD.gn +++ b/chrome/browser/first_party_sets/BUILD.gn
@@ -54,4 +54,8 @@ "//testing/libfuzzer/proto:json_proto_converter", "//third_party/libprotobuf-mutator", ] + + if (is_chromeos) { + deps += [ "//chromeos/ash/components/dbus/cros_disks" ] + } }
diff --git a/chrome/browser/flag-metadata.json b/chrome/browser/flag-metadata.json index 8fc88f0..b78abd1e 100644 --- a/chrome/browser/flag-metadata.json +++ b/chrome/browser/flag-metadata.json
@@ -4240,6 +4240,11 @@ "expiry_milestone": 112 }, { + "name": "keyboard-shortcuts-menu", + "owners": [ "lpromero", "bling-flags@google.com" ], + "expiry_milestone": 112 + }, + { "name": "lacros-availability-ignore", "owners": [ "hidehiko", "erikchen", "lacros-team@google.com" ], // Once Lacros is launched, this flag can be removed. Until then, this @@ -5039,7 +5044,7 @@ "expiry_milestone": 107 }, { - "name": "omnibox-on-clobber-focus-type-on-android", + "name": "omnibox-on-clobber-focus-type-on-content", "owners": [ "rongtan", "ender", "chrome-omnibox-team@google.com" ], "expiry_milestone": 120 },
diff --git a/chrome/browser/flag_descriptions.cc b/chrome/browser/flag_descriptions.cc index d3188906..2203c5d 100644 --- a/chrome/browser/flag_descriptions.cc +++ b/chrome/browser/flag_descriptions.cc
@@ -2113,11 +2113,11 @@ "Offer most visited website tiles when the User is on the Search Results " "Page."; -const char kOmniboxOnClobberFocusTypeOnAndroidName[] = - "Omnibox On Clobber Focus Type On Android"; -const char kOmniboxOnClobberFocusTypeOnAndroidDescription[] = +const char kOmniboxOnClobberFocusTypeOnContentName[] = + "Omnibox On Clobber Focus Type On Content"; +const char kOmniboxOnClobberFocusTypeOnContentDescription[] = "Send ON_CLOBBER focus type for zero-prefix requests with an empty input " - "on Web/SRP on Android platform."; + "on Web/SRP."; const char kOmniboxShortBookmarkSuggestionsName[] = "Omnibox short bookmark suggestions";
diff --git a/chrome/browser/flag_descriptions.h b/chrome/browser/flag_descriptions.h index b1f06148..8249bc0 100644 --- a/chrome/browser/flag_descriptions.h +++ b/chrome/browser/flag_descriptions.h
@@ -1168,8 +1168,8 @@ extern const char kOmniboxMostVisitedTilesOnSrpName[]; extern const char kOmniboxMostVisitedTilesOnSrpDescription[]; -extern const char kOmniboxOnClobberFocusTypeOnAndroidName[]; -extern const char kOmniboxOnClobberFocusTypeOnAndroidDescription[]; +extern const char kOmniboxOnClobberFocusTypeOnContentName[]; +extern const char kOmniboxOnClobberFocusTypeOnContentDescription[]; extern const char kOmniboxShortBookmarkSuggestionsName[]; extern const char kOmniboxShortBookmarkSuggestionsDescription[];
diff --git a/chrome/browser/flags/android/chrome_feature_list.cc b/chrome/browser/flags/android/chrome_feature_list.cc index 2571621..f77391a 100644 --- a/chrome/browser/flags/android/chrome_feature_list.cc +++ b/chrome/browser/flags/android/chrome_feature_list.cc
@@ -372,7 +372,7 @@ &omnibox::kOmniboxRemoveSuggestionHeaderChevron, &omnibox::kOmniboxMostVisitedTilesFadingOnTablet, &omnibox::kOmniboxMostVisitedTilesOnSrp, - &omnibox::kOmniboxOnClobberFocusTypeOnAndroid, + &omnibox::kOmniboxOnClobberFocusTypeOnContent, &omnibox::kSuggestionAnswersColorReverse, &omnibox::kUpdatedConnectionSecurityIndicators, &optimization_guide::features::kPushNotifications, @@ -562,7 +562,7 @@ BASE_FEATURE(kCCTNewDownloadTab, "CCTNewDownloadTab", - base::FEATURE_DISABLED_BY_DEFAULT); + base::FEATURE_ENABLED_BY_DEFAULT); BASE_FEATURE(kCCTIncognito, "CCTIncognito", base::FEATURE_ENABLED_BY_DEFAULT);
diff --git a/chrome/browser/incognito/android/java/src/org/chromium/chrome/browser/incognito/reauth/IncognitoReauthControllerImpl.java b/chrome/browser/incognito/android/java/src/org/chromium/chrome/browser/incognito/reauth/IncognitoReauthControllerImpl.java index 466ed26..ef927d0 100644 --- a/chrome/browser/incognito/android/java/src/org/chromium/chrome/browser/incognito/reauth/IncognitoReauthControllerImpl.java +++ b/chrome/browser/incognito/android/java/src/org/chromium/chrome/browser/incognito/reauth/IncognitoReauthControllerImpl.java
@@ -108,6 +108,23 @@ } }; + private final LayoutStateProvider.LayoutStateObserver mLayoutStateObserver = + new LayoutStateProvider.LayoutStateObserver() { + @Override + public void onStartedShowing(int layoutType, boolean showToolbar) { + if (layoutType == LayoutType.BROWSING) { + showDialogIfRequired(); + } + } + + @Override + public void onFinishedHiding(int layoutType) { + if (layoutType == LayoutType.TAB_SWITCHER) { + hideDialogIfShowing(DialogDismissalCause.DIALOG_INTERACTION_DEFERRED); + } + } + }; + // The {@link TabModelSelectorProfileSupplier} passed to the constructor may not have a {@link // Profile} set if the Tab state is not initialized yet. We make use of the {@link Profile} when // accessing {@link UserPrefs} in showDialogIfRequired. A null {@link Profile} would result in a @@ -189,6 +206,7 @@ layoutStateProviderOneshotSupplier.onAvailable( mLayoutStateProviderCallbackController.makeCancelable(layoutStateProvider -> { mLayoutStateProvider = layoutStateProvider; + mLayoutStateProvider.addObserver(mLayoutStateObserver); showDialogIfRequired(); })); @@ -221,6 +239,10 @@ mLayoutStateProviderCallbackController.destroy(); mIncognitoReauthCoordinatorFactory.destroy(); mOnBackPressedInFullScreenReauthCallback.setEnabled(false); + + if (mLayoutStateProvider != null) { + mLayoutStateProvider.removeObserver(mLayoutStateObserver); + } hideDialogIfShowing(DialogDismissalCause.ACTIVITY_DESTROYED); }
diff --git a/chrome/browser/incognito/android/java/src/org/chromium/chrome/browser/incognito/reauth/IncognitoReauthControllerImplTest.java b/chrome/browser/incognito/android/java/src/org/chromium/chrome/browser/incognito/reauth/IncognitoReauthControllerImplTest.java index c9a2a38..b7768e4b 100644 --- a/chrome/browser/incognito/android/java/src/org/chromium/chrome/browser/incognito/reauth/IncognitoReauthControllerImplTest.java +++ b/chrome/browser/incognito/android/java/src/org/chromium/chrome/browser/incognito/reauth/IncognitoReauthControllerImplTest.java
@@ -90,6 +90,8 @@ ArgumentCaptor<TabModelSelectorObserver> mTabModelSelectorObserverCaptor; @Captor ArgumentCaptor<IncognitoTabModelObserver> mIncognitoTabModelObserverCaptor; + @Captor + ArgumentCaptor<LayoutStateProvider.LayoutStateObserver> mLayoutStateObserverArgumentCaptor; private IncognitoReauthControllerImpl mIncognitoReauthController; private OneshotSupplierImpl<LayoutStateProvider> mLayoutStateProviderOneshotSupplier; @@ -162,6 +164,9 @@ mActivityLifecycleDispatcherMock, mLayoutStateProviderOneshotSupplier, mProfileObservableSupplier, mIncognitoReauthCoordinatorFactoryMock); mProfileObservableSupplier.set(mProfileMock); + + verify(mLayoutStateProviderMock, times(1)) + .addObserver(mLayoutStateObserverArgumentCaptor.capture()); } @After @@ -359,4 +364,29 @@ .onIncognitoReauthSuccess(); verifyNoMoreInteractions(mIncognitoReauthCallbackMock); } + + @Test + @SmallTest + public void testLayoutStateChange_HidesOrShowsReauthScreen() { + doReturn(1).when(mIncognitoTabModelMock).getCount(); + switchToIncognitoTabModel(); + + // Chrome went to background. + mIncognitoReauthController.onStopWithNative(); + // Chrome coming to foregrounded. Re-auth would now be required since there are existing + // Incognito tabs. + doReturn(true).when(mTabModelSelectorMock).isIncognitoSelected(); + mIncognitoReauthController.onStartWithNative(); + assertTrue(mIncognitoReauthController.isReauthPageShowing()); + + // Trigger layout state change to indicate tab switcher is hidden. + mLayoutStateObserverArgumentCaptor.getValue().onFinishedHiding(LayoutType.TAB_SWITCHER); + assertFalse("Re-auth screen shouldn't be shown if we came out of tab switcher.", + mIncognitoReauthController.isReauthPageShowing()); + + // Trigger layout state change to indicate we are now showing a tab. + mLayoutStateObserverArgumentCaptor.getValue().onStartedShowing(LayoutType.BROWSING, false); + assertTrue("Re-auth screen should be shown if we are about to show a tab.", + mIncognitoReauthController.isReauthPageShowing()); + } }
diff --git a/chrome/browser/lookalikes/lookalike_url_navigation_throttle_browsertest.cc b/chrome/browser/lookalikes/lookalike_url_navigation_throttle_browsertest.cc index 5363b982..2beef83 100644 --- a/chrome/browser/lookalikes/lookalike_url_navigation_throttle_browsertest.cc +++ b/chrome/browser/lookalikes/lookalike_url_navigation_throttle_browsertest.cc
@@ -236,7 +236,7 @@ void SetUp() override { std::vector<base::test::ScopedFeatureList::FeatureAndParams> enabled_features; - std::vector<base::Feature> disabled_features; + std::vector<base::test::FeatureRef> disabled_features; enabled_features.emplace_back(features::kSignedHTTPExchange, base::FieldTrialParams());
diff --git a/chrome/browser/media/router/discovery/access_code/access_code_cast_sink_service_browsertest.cc b/chrome/browser/media/router/discovery/access_code/access_code_cast_sink_service_browsertest.cc index 12350908..bbbb902 100644 --- a/chrome/browser/media/router/discovery/access_code/access_code_cast_sink_service_browsertest.cc +++ b/chrome/browser/media/router/discovery/access_code/access_code_cast_sink_service_browsertest.cc
@@ -131,8 +131,8 @@ weak_ptr_factory_.GetWeakPtr())); } -// TODO(b/242928209): Saved device tests are flaky on linux-rel/Mac. -#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_MAC) +// TODO(b/242928209): Saved device tests are flaky on linux-rel/Mac/ChromeOS. +#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_CHROMEOS) #define MAYBE_PRE_SavedDevice DISABLED_PRE_SavedDevice #define MAYBE_SavedDevice DISABLED_SavedDevice #else
diff --git a/chrome/browser/net/nss_service_chromeos.cc b/chrome/browser/net/nss_service_chromeos.cc index cac6a12..7c4a323d 100644 --- a/chrome/browser/net/nss_service_chromeos.cc +++ b/chrome/browser/net/nss_service_chromeos.cc
@@ -7,7 +7,6 @@ #include <memory> #include <utility> -#include "ash/components/tpm/tpm_token_info_getter.h" #include "base/bind.h" #include "base/callback.h" #include "base/callback_helpers.h" @@ -27,6 +26,7 @@ #include "chromeos/ash/components/dbus/dbus_thread_manager.h" #include "chromeos/ash/components/dbus/userdataauth/cryptohome_pkcs11_client.h" #include "chromeos/ash/components/settings/cros_settings_names.h" +#include "chromeos/ash/components/tpm/tpm_token_info_getter.h" #include "components/user_manager/user.h" #include "components/user_manager/user_manager.h" #include "content/public/browser/browser_context.h"
diff --git a/chrome/browser/password_manager/chrome_password_manager_client.h b/chrome/browser/password_manager/chrome_password_manager_client.h index ca413b8..6467b9ff 100644 --- a/chrome/browser/password_manager/chrome_password_manager_client.h +++ b/chrome/browser/password_manager/chrome_password_manager_client.h
@@ -68,6 +68,9 @@ class Profile; namespace autofill { +class LogManager; +class RoutingLogManager; + namespace password_generation { struct PasswordGenerationUIData; } // namespace password_generation @@ -443,7 +446,7 @@ const password_manager::SyncCredentialsFilter credentials_filter_; #endif - std::unique_ptr<autofill::LogManager> log_manager_; + std::unique_ptr<autofill::RoutingLogManager> log_manager_; // Recorder of metrics that is associated with the last committed navigation // of the WebContents owning this ChromePasswordManagerClient. May be unset at
diff --git a/chrome/browser/password_manager/chrome_password_manager_client_unittest.cc b/chrome/browser/password_manager/chrome_password_manager_client_unittest.cc index 5f0311e5..4f4b8f37 100644 --- a/chrome/browser/password_manager/chrome_password_manager_client_unittest.cc +++ b/chrome/browser/password_manager/chrome_password_manager_client_unittest.cc
@@ -414,7 +414,18 @@ EXPECT_EQ(password_manager::SyncState::kSyncingNormalEncryption, client->GetPasswordSyncState()); + // Persistent auth error other than web signout (sync continues active). + sync_service_->SetPersistentAuthErrorOtherThanWebSignout(); + EXPECT_EQ(password_manager::SyncState::kSyncingNormalEncryption, + client->GetPasswordSyncState()); + + // Sync paused due to web signout. + sync_service_->SetPersistentAuthErrorWithWebSignout(); + EXPECT_EQ(password_manager::SyncState::kNotSyncing, + client->GetPasswordSyncState()); + // Again, using a custom passphrase. + sync_service_->ClearAuthError(); sync_service_->SetIsUsingExplicitPassphrase(true); EXPECT_EQ(password_manager::SyncState::kSyncingWithCustomPassphrase,
diff --git a/chrome/browser/payments/secure_payment_confirmation_creation_browsertest.cc b/chrome/browser/payments/secure_payment_confirmation_creation_browsertest.cc index 146a240..ef68529 100644 --- a/chrome/browser/payments/secure_payment_confirmation_creation_browsertest.cc +++ b/chrome/browser/payments/secure_payment_confirmation_creation_browsertest.cc
@@ -151,8 +151,14 @@ std::unique_ptr<autofill::EventWaiter<Event>> event_waiter_; }; +// TODO(crbug.com/1372198) Re-enable tests once fixed on Mac. +#if BUILDFLAG(IS_MAC) +#define MAYBE_SuccessfulEnrollment DISABLED_SuccessfulEnrollment +#else +#define MAYBE_SuccessfulEnrollment SuccessfulEnrollment +#endif IN_PROC_BROWSER_TEST_F(SecurePaymentConfirmationCreationTest, - SuccessfulEnrollment) { + MAYBE_SuccessfulEnrollment) { ReplaceFidoDiscoveryFactory(/*should_succeed=*/true); NavigateTo("a.com", "/secure_payment_confirmation.html"); @@ -169,7 +175,14 @@ ExpectJourneyLoggerEvent(/*spc_confirm_logged=*/false); } -IN_PROC_BROWSER_TEST_F(SecurePaymentConfirmationCreationTest, CredentialType) { +// TODO(crbug.com/1372198) Re-enable tests once fixed on Mac. +#if BUILDFLAG(IS_MAC) +#define MAYBE_CredentialType DISABLED_CredentialType +#else +#define MAYBE_CredentialType CredentialType +#endif +IN_PROC_BROWSER_TEST_F(SecurePaymentConfirmationCreationTest, + MAYBE_CredentialType) { ReplaceFidoDiscoveryFactory(/*should_succeed=*/true); NavigateTo("a.com", "/secure_payment_confirmation.html"); @@ -180,8 +193,14 @@ GetDefaultIconURL()))); } +// TODO(crbug.com/1372198) Re-enable tests once fixed on Mac. +#if BUILDFLAG(IS_MAC) +#define MAYBE_CreatePaymentCredential DISABLED_CreatePaymentCredential +#else +#define MAYBE_CreatePaymentCredential CreatePaymentCredential +#endif IN_PROC_BROWSER_TEST_F(SecurePaymentConfirmationCreationTest, - CreatePaymentCredential) { + MAYBE_CreatePaymentCredential) { ReplaceFidoDiscoveryFactory(/*should_succeed=*/true); NavigateTo("a.com", "/secure_payment_confirmation.html"); @@ -226,8 +245,14 @@ GetDefaultIconURL()))); } +// TODO(crbug.com/1372198) Re-enable tests once fixed on Mac. +#if BUILDFLAG(IS_MAC) +#define MAYBE_LookupPaymentCredential DISABLED_LookupPaymentCredential +#else +#define MAYBE_LookupPaymentCredential LookupPaymentCredential +#endif IN_PROC_BROWSER_TEST_F(SecurePaymentConfirmationCreationTest, - LookupPaymentCredential) { + MAYBE_LookupPaymentCredential) { ReplaceFidoDiscoveryFactory(/*should_succeed=*/true); NavigateTo("a.com", "/secure_payment_confirmation.html"); std::string credentialIdentifier = @@ -259,8 +284,14 @@ ExpectJourneyLoggerEvent(/*spc_confirm_logged=*/false); } +// TODO(crbug.com/1372198) Re-enable tests once fixed on Mac. +#if BUILDFLAG(IS_MAC) +#define MAYBE_PaymentExtension DISABLED_PaymentExtension +#else +#define MAYBE_PaymentExtension PaymentExtension +#endif IN_PROC_BROWSER_TEST_F(SecurePaymentConfirmationCreationTest, - PaymentExtension) { + MAYBE_PaymentExtension) { ReplaceFidoDiscoveryFactory(/*should_succeed=*/true); NavigateTo("a.com", "/secure_payment_confirmation.html"); @@ -313,8 +344,16 @@ .ExtractString()); } +// TODO(crbug.com/1372198) Re-enable tests once fixed on Mac. +#if BUILDFLAG(IS_MAC) +#define MAYBE_ConfirmPaymentInCrossOriginIframe \ + DISABLED_ConfirmPaymentInCrossOriginIframe +#else +#define MAYBE_ConfirmPaymentInCrossOriginIframe \ + ConfirmPaymentInCrossOriginIframe +#endif IN_PROC_BROWSER_TEST_F(SecurePaymentConfirmationCreationTest, - ConfirmPaymentInCrossOriginIframe) { + MAYBE_ConfirmPaymentInCrossOriginIframe) { NavigateTo("a.com", "/secure_payment_confirmation.html"); ReplaceFidoDiscoveryFactory(/*should_succeed=*/true); std::string credentialIdentifier = @@ -386,8 +425,16 @@ ExpectJourneyLoggerEvent(/*spc_confirm_logged=*/true); } +// TODO(crbug.com/1372198) Re-enable tests once fixed on Mac. +#if BUILDFLAG(IS_MAC) +#define MAYBE_ConfirmPaymentInCrossOriginIframeWithPayeeName \ + DISABLED_ConfirmPaymentInCrossOriginIframeWithPayeeName +#else +#define MAYBE_ConfirmPaymentInCrossOriginIframeWithPayeeName \ + ConfirmPaymentInCrossOriginIframeWithPayeeName +#endif IN_PROC_BROWSER_TEST_F(SecurePaymentConfirmationCreationTest, - ConfirmPaymentInCrossOriginIframeWithPayeeName) { + MAYBE_ConfirmPaymentInCrossOriginIframeWithPayeeName) { NavigateTo("a.com", "/secure_payment_confirmation.html"); ReplaceFidoDiscoveryFactory(/*should_succeed=*/true); std::string credentialIdentifier = @@ -435,9 +482,17 @@ ExpectJourneyLoggerEvent(/*spc_confirm_logged=*/true); } +// TODO(crbug.com/1372198) Re-enable tests once fixed on Mac. +#if BUILDFLAG(IS_MAC) +#define MAYBE_ConfirmPaymentInCrossOriginIframeWithPayeeNameAndOrigin \ + DISABLED_ConfirmPaymentInCrossOriginIframeWithPayeeNameAndOrigin +#else +#define MAYBE_ConfirmPaymentInCrossOriginIframeWithPayeeNameAndOrigin \ + ConfirmPaymentInCrossOriginIframeWithPayeeNameAndOrigin +#endif IN_PROC_BROWSER_TEST_F( SecurePaymentConfirmationCreationTest, - ConfirmPaymentInCrossOriginIframeWithPayeeNameAndOrigin) { + MAYBE_ConfirmPaymentInCrossOriginIframeWithPayeeNameAndOrigin) { NavigateTo("a.com", "/secure_payment_confirmation.html"); ReplaceFidoDiscoveryFactory(/*should_succeed=*/true); std::string credentialIdentifier = @@ -486,8 +541,14 @@ ExpectJourneyLoggerEvent(/*spc_confirm_logged=*/true); } +// TODO(crbug.com/1372198) Re-enable tests once fixed on Mac. +#if BUILDFLAG(IS_MAC) +#define MAYBE_ChallengeIsReturned DISABLED_ChallengeIsReturned +#else +#define MAYBE_ChallengeIsReturned ChallengeIsReturned +#endif IN_PROC_BROWSER_TEST_F(SecurePaymentConfirmationCreationTest, - ChallengeIsReturned) { + MAYBE_ChallengeIsReturned) { NavigateTo("a.com", "/secure_payment_confirmation.html"); ReplaceFidoDiscoveryFactory(/*should_succeed=*/true); std::string credentialIdentifier = @@ -541,8 +602,14 @@ ExpectJourneyLoggerEvent(/*spc_confirm_logged=*/true); } +// TODO(crbug.com/1372198) Re-enable tests once fixed on Mac. +#if BUILDFLAG(IS_MAC) +#define MAYBE_UserVerificationFails DISABLED_UserVerificationFails +#else +#define MAYBE_UserVerificationFails UserVerificationFails +#endif IN_PROC_BROWSER_TEST_F(SecurePaymentConfirmationCreationTest, - UserVerificationFails) { + MAYBE_UserVerificationFails) { NavigateTo("a.com", "/secure_payment_confirmation.html"); ReplaceFidoDiscoveryFactory(/*should_succeed=*/true); std::string credentialIdentifier = @@ -573,8 +640,14 @@ ExpectJourneyLoggerEvent(/*spc_confirm_logged=*/true); } +// TODO(crbug.com/1372198) Re-enable tests once fixed on Mac. +#if BUILDFLAG(IS_MAC) +#define MAYBE_CreatePaymentCredentialTwice DISABLED_CreatePaymentCredentialTwice +#else +#define MAYBE_CreatePaymentCredentialTwice CreatePaymentCredentialTwice +#endif IN_PROC_BROWSER_TEST_F(SecurePaymentConfirmationCreationTest, - CreatePaymentCredentialTwice) { + MAYBE_CreatePaymentCredentialTwice) { ReplaceFidoDiscoveryFactory(/*should_succeed=*/true); NavigateTo("a.com", "/secure_payment_confirmation.html"); @@ -598,8 +671,16 @@ ExpectJourneyLoggerEvent(/*spc_confirm_logged=*/false); } +// TODO(crbug.com/1372198) Re-enable tests once fixed on Mac. +#if BUILDFLAG(IS_MAC) +#define MAYBE_WebContentsClosedDuringEnrollmentOSPrompt \ + DISABLED_WebContentsClosedDuringEnrollmentOSPrompt +#else +#define MAYBE_WebContentsClosedDuringEnrollmentOSPrompt \ + WebContentsClosedDuringEnrollmentOSPrompt +#endif IN_PROC_BROWSER_TEST_F(SecurePaymentConfirmationCreationTest, - WebContentsClosedDuringEnrollmentOSPrompt) { + MAYBE_WebContentsClosedDuringEnrollmentOSPrompt) { ReplaceFidoDiscoveryFactory(/*should_succeed=*/true, /*should_hang=*/true); NavigateTo("a.com", "/secure_payment_confirmation.html"); @@ -622,8 +703,14 @@ ExpectJourneyLoggerEvent(/*spc_confirm_logged=*/false); } +// TODO(crbug.com/1372198) Re-enable tests once fixed on Mac. +#if BUILDFLAG(IS_MAC) +#define MAYBE_UserVerificationSucceeds DISABLED_UserVerificationSucceeds +#else +#define MAYBE_UserVerificationSucceeds UserVerificationSucceeds +#endif IN_PROC_BROWSER_TEST_F(SecurePaymentConfirmationCreationTest, - UserVerificationSucceeds) { + MAYBE_UserVerificationSucceeds) { NavigateTo("a.com", "/secure_payment_confirmation.html"); ReplaceFidoDiscoveryFactory(/*should_succeed=*/true); @@ -662,8 +749,14 @@ } // Test allowing a failed icon download with iconMustBeShown option +// TODO(crbug.com/1372198) Re-enable tests once fixed on Mac. +#if BUILDFLAG(IS_MAC) +#define MAYBE_IconMustBeShownFalse DISABLED_IconMustBeShownFalse +#else +#define MAYBE_IconMustBeShownFalse IconMustBeShownFalse +#endif IN_PROC_BROWSER_TEST_F(SecurePaymentConfirmationCreationTest, - IconMustBeShownFalse) { + MAYBE_IconMustBeShownFalse) { ReplaceFidoDiscoveryFactory(/*should_succeed=*/true); test_controller()->SetHasAuthenticator(true); confirm_payment_ = true;
diff --git a/chrome/browser/preloading/prefetch/zero_suggest_prefetch/zero_suggest_prefetch_tab_helper.cc b/chrome/browser/preloading/prefetch/zero_suggest_prefetch/zero_suggest_prefetch_tab_helper.cc index 1b7ba89..cfd0ad48 100644 --- a/chrome/browser/preloading/prefetch/zero_suggest_prefetch/zero_suggest_prefetch_tab_helper.cc +++ b/chrome/browser/preloading/prefetch/zero_suggest_prefetch/zero_suggest_prefetch_tab_helper.cc
@@ -4,16 +4,12 @@ #include "chrome/browser/preloading/prefetch/zero_suggest_prefetch/zero_suggest_prefetch_tab_helper.h" -#include "chrome/browser/autocomplete/chrome_autocomplete_scheme_classifier.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/browser_window.h" -#include "chrome/browser/ui/location_bar/location_bar.h" #include "chrome/browser/ui/search/omnibox_utils.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" -#include "chrome/common/webui_url_constants.h" -#include "components/google/core/common/google_util.h" #include "components/omnibox/browser/autocomplete_controller.h" #include "components/omnibox/browser/autocomplete_input.h" #include "components/omnibox/browser/base_search_provider.h" @@ -23,74 +19,6 @@ #include "content/public/browser/navigation_handle.h" #include "content/public/browser/web_contents.h" -namespace { - -using OEP = metrics::OmniboxEventProto; - -// Returns whether or not the given URL represents a New Tab Page (NTP). -bool IsNTP(const GURL& url) { - return url == GURL(chrome::kChromeUINewTabPageURL); -} - -// Returns whether or not the given URL represents a prefetch-eligible Web page. -bool IsEligibleWebPage(const GURL& url) { - return BaseSearchProvider::CanSendPageURLInRequest(url); -} - -// Returns whether or not the given URL is eligible for ZPS prefetching. -bool IsURLEligibleForZPSPrefetching(const GURL& url) { - if (base::FeatureList::IsEnabled(omnibox::kZeroSuggestPrefetching) && - IsNTP(url)) { - return true; - } else if (base::FeatureList::IsEnabled( - omnibox::kZeroSuggestPrefetchingOnSRP) && - google_util::IsGoogleSearchUrl(url)) { - return true; - } else if (base::FeatureList::IsEnabled( - omnibox::kZeroSuggestPrefetchingOnWeb) && - IsEligibleWebPage(url)) { - return true; - } - return false; -} - -// Starts prefetching zero-prefix suggestions using the AutocompleteController -// instance owned by the omnibox with a dedicated page context. -void StartPrefetch(content::WebContents* web_contents, const GURL& page_url) { - auto* omnibox_view = search::GetOmniboxView(web_contents); - if (!omnibox_view) { - return; - } - - auto* profile = - Profile::FromBrowserContext(web_contents->GetBrowserContext()); - - OEP::PageClassification page_classification = OEP::INVALID_SPEC; - if (IsNTP(page_url)) { - page_classification = OEP::NTP_ZPS_PREFETCH; - } else if (google_util::IsGoogleSearchUrl(page_url)) { - page_classification = OEP::SRP_ZPS_PREFETCH; - } else if (IsEligibleWebPage(page_url)) { - page_classification = OEP::OTHER_ZPS_PREFETCH; - } - DCHECK(page_classification != OEP::INVALID_SPEC) - << "Prefetch page classification undefined for given URL."; - - AutocompleteInput autocomplete_input( - u"", page_classification, ChromeAutocompleteSchemeClassifier(profile)); - autocomplete_input.set_focus_type( - metrics::OmniboxFocusType::INTERACTION_FOCUS); - // Construct proper on-clobber input for ZPS prefetch requests on SRP/Web. - if (page_classification != OEP::NTP_ZPS_PREFETCH) { - autocomplete_input.set_focus_type( - metrics::OmniboxFocusType::INTERACTION_CLOBBER); - autocomplete_input.set_current_url(page_url); - } - omnibox_view->StartPrefetch(autocomplete_input); -} - -} // namespace - ZeroSuggestPrefetchTabHelper::ZeroSuggestPrefetchTabHelper( content::WebContents* web_contents) : content::WebContentsObserver(web_contents), @@ -100,10 +28,6 @@ ZeroSuggestPrefetchTabHelper::~ZeroSuggestPrefetchTabHelper() = default; void ZeroSuggestPrefetchTabHelper::PrimaryPageChanged(content::Page& page) { - const auto& last_committed_url = page.GetMainDocument().GetLastCommittedURL(); - if (!IsURLEligibleForZPSPrefetching(last_committed_url)) - return; - // Make sure to observe the TabStripModel, if not already, in order to get // notified when a New Tab Page is switched to. // Note that this is done here, i.e., after the New Tab Page is navigated to, @@ -118,23 +42,34 @@ browser->tab_strip_model()->AddObserver(this); } - StartPrefetch(web_contents(), last_committed_url); + StartPrefetch(); } void ZeroSuggestPrefetchTabHelper::OnTabStripModelChanged( TabStripModel* tab_strip_model, const TabStripModelChange& change, const TabStripSelectionChange& selection) { - const auto& last_committed_url = - web_contents()->GetPrimaryPage().GetMainDocument().GetLastCommittedURL(); if (!selection.active_tab_changed() || - web_contents() != selection.new_contents || - !IsURLEligibleForZPSPrefetching(last_committed_url)) { + web_contents() != selection.new_contents) { return; } // We get here when a New Tab Page is brought to foreground (aka switched to). - StartPrefetch(web_contents(), last_committed_url); + StartPrefetch(); +} + +void ZeroSuggestPrefetchTabHelper::StartPrefetch() { + auto* omnibox_view = search::GetOmniboxView(web_contents()); + if (!omnibox_view) { + return; + } + + auto* omnibox_edit_model = omnibox_view->model(); + if (!omnibox_edit_model) { + return; + } + + omnibox_edit_model->StartPrefetch(); } WEB_CONTENTS_USER_DATA_KEY_IMPL(ZeroSuggestPrefetchTabHelper);
diff --git a/chrome/browser/preloading/prefetch/zero_suggest_prefetch/zero_suggest_prefetch_tab_helper.h b/chrome/browser/preloading/prefetch/zero_suggest_prefetch/zero_suggest_prefetch_tab_helper.h index 2d50ca7..d0f1a94 100644 --- a/chrome/browser/preloading/prefetch/zero_suggest_prefetch/zero_suggest_prefetch_tab_helper.h +++ b/chrome/browser/preloading/prefetch/zero_suggest_prefetch/zero_suggest_prefetch_tab_helper.h
@@ -33,6 +33,11 @@ private: explicit ZeroSuggestPrefetchTabHelper(content::WebContents* web_contents); + // Starts an autocomplete prefetch request so that zero-prefix providers can + // optionally start a prefetch request to warm up the their underlying + // service(s) and/or optionally cache their otherwise async response. + void StartPrefetch(); + friend class content::WebContentsUserData<ZeroSuggestPrefetchTabHelper>; WEB_CONTENTS_USER_DATA_KEY_DECL(); };
diff --git a/chrome/browser/preloading/prefetch/zero_suggest_prefetch/zero_suggest_prefetch_tab_helper_browsertest.cc b/chrome/browser/preloading/prefetch/zero_suggest_prefetch/zero_suggest_prefetch_tab_helper_browsertest.cc index 2be4d06..8d8ccca 100644 --- a/chrome/browser/preloading/prefetch/zero_suggest_prefetch/zero_suggest_prefetch_tab_helper_browsertest.cc +++ b/chrome/browser/preloading/prefetch/zero_suggest_prefetch/zero_suggest_prefetch_tab_helper_browsertest.cc
@@ -23,6 +23,7 @@ #include "components/search_engines/template_url_service_client.h" #include "content/public/test/browser_test.h" #include "testing/gmock/include/gmock/gmock.h" +#include "third_party/metrics_proto/omnibox_event.pb.h" namespace { @@ -78,7 +79,8 @@ public: ZeroSuggestPrefetchTabHelperBrowserTestOnNTP() { feature_list_.InitWithFeatures( - /*enabled_features=*/{omnibox::kZeroSuggestPrefetching}, + /*enabled_features=*/{omnibox::kZeroSuggestPrefetching, + omnibox::kOmniboxOnClobberFocusTypeOnContent}, /*disabled_features=*/{omnibox::kZeroSuggestPrefetchingOnSRP, omnibox::kZeroSuggestPrefetchingOnWeb}); } @@ -89,7 +91,8 @@ public: ZeroSuggestPrefetchTabHelperBrowserTestOnSRP() { feature_list_.InitWithFeatures( - /*enabled_features=*/{omnibox::kZeroSuggestPrefetchingOnSRP}, + /*enabled_features=*/{omnibox::kZeroSuggestPrefetchingOnSRP, + omnibox::kOmniboxOnClobberFocusTypeOnContent}, /*disabled_features=*/{omnibox::kZeroSuggestPrefetching, omnibox::kZeroSuggestPrefetchingOnWeb}); } @@ -100,70 +103,81 @@ public: ZeroSuggestPrefetchTabHelperBrowserTestOnWeb() { feature_list_.InitWithFeatures( - /*enabled_features=*/{omnibox::kZeroSuggestPrefetchingOnWeb}, + /*enabled_features=*/{omnibox::kZeroSuggestPrefetchingOnWeb, + omnibox::kOmniboxOnClobberFocusTypeOnContent}, /*disabled_features=*/{omnibox::kZeroSuggestPrefetching, omnibox::kZeroSuggestPrefetchingOnSRP}); } }; -// Tests that navigating to or switching to the NTP starts a prefetch request. +// Tests that navigating to or switching to the NTP starts a prefetch request +// with the expected page classification. IN_PROC_BROWSER_TEST_F(ZeroSuggestPrefetchTabHelperBrowserTestOnNTP, StartPrefetch) { - { - // Opening a background NTP triggers prefetching. - EXPECT_CALL(*controller_, StartPrefetch).Times(1); - EXPECT_CALL(*controller_, Start).Times(0); + const std::string srp_url = "https://www.google.com/search?q=hello+world"; + const std::string web_url = "https://www.example.com"; + auto input_is_correct = [](const AutocompleteInput& input) { + return input.current_page_classification() == + metrics::OmniboxEventProto::NTP_ZPS_PREFETCH && + input.focus_type() == metrics::OmniboxFocusType::INTERACTION_FOCUS; + }; - EXPECT_TRUE(ui_test_utils::NavigateToURLWithDisposition( - browser(), GURL(chrome::kChromeUINewTabPageURL), - WindowOpenDisposition::NEW_BACKGROUND_TAB, - ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP)); - ASSERT_EQ(2, browser()->tab_strip_model()->GetTabCount()); - - testing::Mock::VerifyAndClearExpectations(controller_); - } - { - // Opening a foreground NTP triggers prefetching. - EXPECT_CALL(*controller_, StartPrefetch).Times(1); - EXPECT_CALL(*controller_, Start).Times(0); - - EXPECT_TRUE(ui_test_utils::NavigateToURLWithDisposition( - browser(), GURL(chrome::kChromeUINewTabPageURL), - WindowOpenDisposition::NEW_FOREGROUND_TAB, - ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP)); - ASSERT_EQ(3, browser()->tab_strip_model()->GetTabCount()); - - testing::Mock::VerifyAndClearExpectations(controller_); - } - { - // Navigating to a url in a new foreground tab does not trigger prefetching. - EXPECT_CALL(*controller_, StartPrefetch).Times(0); - EXPECT_CALL(*controller_, Start).Times(0); - - ui_test_utils::NavigateToURLWithDisposition( - browser(), GURL("https://foo.com"), - WindowOpenDisposition::NEW_FOREGROUND_TAB, - ui_test_utils::BROWSER_TEST_NONE); - ASSERT_EQ(4, browser()->tab_strip_model()->GetTabCount()); - - testing::Mock::VerifyAndClearExpectations(controller_); - } { // Navigating to the NTP in the current tab triggers prefetching. - EXPECT_CALL(*controller_, StartPrefetch).Times(1); + EXPECT_CALL(*controller_, StartPrefetch(testing::Truly(input_is_correct))) + .Times(1); EXPECT_CALL(*controller_, Start).Times(0); EXPECT_TRUE(ui_test_utils::NavigateToURLWithDisposition( browser(), GURL(chrome::kChromeUINewTabPageURL), WindowOpenDisposition::CURRENT_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP)); + ASSERT_EQ(1, browser()->tab_strip_model()->GetTabCount()); + + testing::Mock::VerifyAndClearExpectations(controller_); + } + { + // Opening a foreground NTP triggers prefetching. + EXPECT_CALL(*controller_, StartPrefetch(testing::Truly(input_is_correct))) + .Times(1); + EXPECT_CALL(*controller_, Start).Times(0); + + EXPECT_TRUE(ui_test_utils::NavigateToURLWithDisposition( + browser(), GURL(chrome::kChromeUINewTabPageURL), + WindowOpenDisposition::NEW_FOREGROUND_TAB, + ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP)); + ASSERT_EQ(2, browser()->tab_strip_model()->GetTabCount()); + + testing::Mock::VerifyAndClearExpectations(controller_); + } + { + // Opening a foreground SRP does not trigger prefetching. + EXPECT_CALL(*controller_, StartPrefetch).Times(0); + EXPECT_CALL(*controller_, Start).Times(0); + + EXPECT_TRUE(ui_test_utils::NavigateToURLWithDisposition( + browser(), GURL(srp_url), WindowOpenDisposition::NEW_FOREGROUND_TAB, + ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP)); + ASSERT_EQ(3, browser()->tab_strip_model()->GetTabCount()); + + testing::Mock::VerifyAndClearExpectations(controller_); + } + { + // Opening a foreground Web page does not trigger prefetching. + EXPECT_CALL(*controller_, StartPrefetch).Times(0); + EXPECT_CALL(*controller_, Start).Times(0); + + ui_test_utils::NavigateToURLWithDisposition( + browser(), GURL(web_url), WindowOpenDisposition::NEW_FOREGROUND_TAB, + ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP); ASSERT_EQ(4, browser()->tab_strip_model()->GetTabCount()); testing::Mock::VerifyAndClearExpectations(controller_); } { // Switching to an NTP triggers prefetching. - EXPECT_CALL(*controller_, StartPrefetch).Times(1); + EXPECT_CALL(*controller_, StartPrefetch(testing::Truly(input_is_correct))) + .Times(1); EXPECT_CALL(*controller_, Start).Times(0); browser()->tab_strip_model()->ActivateTabAt(1); @@ -172,13 +186,35 @@ } } -// Tests that navigating to or switching to the SRP starts a prefetch request. +// Tests that navigating to or switching to the SRP starts a prefetch request +// with the expected page classification. IN_PROC_BROWSER_TEST_F(ZeroSuggestPrefetchTabHelperBrowserTestOnSRP, StartPrefetch) { const std::string srp_url = "https://www.google.com/search?q=hello+world"; + const std::string web_url = "https://www.example.com"; + auto input_is_correct = [](const AutocompleteInput& input) { + return input.current_page_classification() == + metrics::OmniboxEventProto::SRP_ZPS_PREFETCH && + input.focus_type() == metrics::OmniboxFocusType::INTERACTION_CLOBBER; + }; + + { + // Navigating to the SRP in the current tab triggers prefetching. + EXPECT_CALL(*controller_, StartPrefetch(testing::Truly(input_is_correct))) + .Times(1); + EXPECT_CALL(*controller_, Start).Times(0); + + EXPECT_TRUE(ui_test_utils::NavigateToURLWithDisposition( + browser(), GURL(srp_url), WindowOpenDisposition::CURRENT_TAB, + ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP)); + ASSERT_EQ(1, browser()->tab_strip_model()->GetTabCount()); + + testing::Mock::VerifyAndClearExpectations(controller_); + } { // Opening a background SRP triggers prefetching. - EXPECT_CALL(*controller_, StartPrefetch).Times(1); + EXPECT_CALL(*controller_, StartPrefetch(testing::Truly(input_is_correct))) + .Times(1); EXPECT_CALL(*controller_, Start).Times(0); EXPECT_TRUE(ui_test_utils::NavigateToURLWithDisposition( @@ -190,7 +226,8 @@ } { // Opening a foreground SRP triggers prefetching. - EXPECT_CALL(*controller_, StartPrefetch).Times(1); + EXPECT_CALL(*controller_, StartPrefetch(testing::Truly(input_is_correct))) + .Times(1); EXPECT_CALL(*controller_, Start).Times(0); EXPECT_TRUE(ui_test_utils::NavigateToURLWithDisposition( @@ -201,27 +238,13 @@ testing::Mock::VerifyAndClearExpectations(controller_); } { - // Navigating to a Web url in a new foreground tab does not trigger - // prefetching. + // Opening a foreground Web page does not trigger prefetching. EXPECT_CALL(*controller_, StartPrefetch).Times(0); EXPECT_CALL(*controller_, Start).Times(0); ui_test_utils::NavigateToURLWithDisposition( - browser(), GURL("https://foo.com"), - WindowOpenDisposition::NEW_FOREGROUND_TAB, - ui_test_utils::BROWSER_TEST_NONE); - ASSERT_EQ(4, browser()->tab_strip_model()->GetTabCount()); - - testing::Mock::VerifyAndClearExpectations(controller_); - } - { - // Navigating to the SRP in the current tab triggers prefetching. - EXPECT_CALL(*controller_, StartPrefetch).Times(1); - EXPECT_CALL(*controller_, Start).Times(0); - - EXPECT_TRUE(ui_test_utils::NavigateToURLWithDisposition( - browser(), GURL(srp_url), WindowOpenDisposition::CURRENT_TAB, - ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP)); + browser(), GURL(web_url), WindowOpenDisposition::NEW_FOREGROUND_TAB, + ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP); ASSERT_EQ(4, browser()->tab_strip_model()->GetTabCount()); testing::Mock::VerifyAndClearExpectations(controller_); @@ -238,13 +261,34 @@ } // Tests that navigating to or switching to a Web URL (non-NTP/non-SRP) starts a -// prefetch request. +// prefetch request with the expected page classification. IN_PROC_BROWSER_TEST_F(ZeroSuggestPrefetchTabHelperBrowserTestOnWeb, StartPrefetch) { + const std::string srp_url = "https://www.google.com/search?q=hello+world"; const std::string web_url = "https://www.example.com"; + auto input_is_correct = [](const AutocompleteInput& input) { + return input.current_page_classification() == + metrics::OmniboxEventProto::OTHER_ZPS_PREFETCH && + input.focus_type() == metrics::OmniboxFocusType::INTERACTION_CLOBBER; + }; + + { + // Navigating to a Web page in the current tab triggers prefetching. + EXPECT_CALL(*controller_, StartPrefetch(testing::Truly(input_is_correct))) + .Times(1); + EXPECT_CALL(*controller_, Start).Times(0); + + EXPECT_TRUE(ui_test_utils::NavigateToURLWithDisposition( + browser(), GURL(web_url), WindowOpenDisposition::CURRENT_TAB, + ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP)); + ASSERT_EQ(1, browser()->tab_strip_model()->GetTabCount()); + + testing::Mock::VerifyAndClearExpectations(controller_); + } { // Opening a background Web page triggers prefetching. - EXPECT_CALL(*controller_, StartPrefetch).Times(1); + EXPECT_CALL(*controller_, StartPrefetch(testing::Truly(input_is_correct))) + .Times(1); EXPECT_CALL(*controller_, Start).Times(0); EXPECT_TRUE(ui_test_utils::NavigateToURLWithDisposition( @@ -256,7 +300,8 @@ } { // Opening a foreground Web page triggers prefetching. - EXPECT_CALL(*controller_, StartPrefetch).Times(1); + EXPECT_CALL(*controller_, StartPrefetch(testing::Truly(input_is_correct))) + .Times(1); EXPECT_CALL(*controller_, Start).Times(0); EXPECT_TRUE(ui_test_utils::NavigateToURLWithDisposition( @@ -267,26 +312,12 @@ testing::Mock::VerifyAndClearExpectations(controller_); } { - // Navigating to an ineligible url in a new foreground tab does not trigger - // prefetching. + // Opening a foreground SRP does not trigger prefetching. EXPECT_CALL(*controller_, StartPrefetch).Times(0); EXPECT_CALL(*controller_, Start).Times(0); - ui_test_utils::NavigateToURLWithDisposition( - browser(), GURL("file://www.example.com"), - WindowOpenDisposition::NEW_FOREGROUND_TAB, - ui_test_utils::BROWSER_TEST_NONE); - ASSERT_EQ(4, browser()->tab_strip_model()->GetTabCount()); - - testing::Mock::VerifyAndClearExpectations(controller_); - } - { - // Navigating to the Web in the current tab triggers prefetching. - EXPECT_CALL(*controller_, StartPrefetch).Times(1); - EXPECT_CALL(*controller_, Start).Times(0); - EXPECT_TRUE(ui_test_utils::NavigateToURLWithDisposition( - browser(), GURL(web_url), WindowOpenDisposition::CURRENT_TAB, + browser(), GURL(srp_url), WindowOpenDisposition::NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP)); ASSERT_EQ(4, browser()->tab_strip_model()->GetTabCount()); @@ -294,7 +325,8 @@ } { // Switching to a Web tab triggers prefetching. - EXPECT_CALL(*controller_, StartPrefetch).Times(1); + EXPECT_CALL(*controller_, StartPrefetch(testing::Truly(input_is_correct))) + .Times(1); EXPECT_CALL(*controller_, Start).Times(0); browser()->tab_strip_model()->ActivateTabAt(1);
diff --git a/chrome/browser/privacy_budget/identifiability_study_state_unittest.cc b/chrome/browser/privacy_budget/identifiability_study_state_unittest.cc index 5c944a1..5a62919 100644 --- a/chrome/browser/privacy_budget/identifiability_study_state_unittest.cc +++ b/chrome/browser/privacy_budget/identifiability_study_state_unittest.cc
@@ -471,13 +471,38 @@ TestingPrefServiceSimple pref_service; prefs::RegisterPrivacyBudgetPrefs(pref_service.registry()); - test_utils::InspectableIdentifiabilityStudyState settings(&pref_service); + test_utils::InspectableIdentifiabilityStudyState state(&pref_service); + + EXPECT_TRUE(state.group_settings().enabled()); + EXPECT_TRUE(state.group_settings().IsUsingRandomSampling()); // The specific surface doesn't matter. - EXPECT_TRUE(settings.ShouldReportEncounteredSurface(ukm::AssignNewSourceId(), - kRegularSurface1)); - EXPECT_FALSE(settings.ShouldReportEncounteredSurface(ukm::NoURLSourceId(), - kRegularSurface1)); + EXPECT_TRUE(state.ShouldReportEncounteredSurface(ukm::AssignNewSourceId(), + kRegularSurface1)); + EXPECT_FALSE(state.ShouldReportEncounteredSurface(ukm::NoURLSourceId(), + kRegularSurface1)); +} + +// Test the mode in which only the meta experiment (i.e. reporting encountered +// surfaces) is enabled. +TEST(IdentifiabilityStudyStateStandaloneTest, OnlyReportEncounteredSurface) { + test::ScopedPrivacyBudgetConfig::Parameters params( + test::ScopedPrivacyBudgetConfig::Presets::kEnableRandomSampling); + params.allowed_random_types = { + blink::IdentifiableSurface::Type::kReservedInternal}; + test::ScopedPrivacyBudgetConfig config(params); + + TestingPrefServiceSimple pref_service; + prefs::RegisterPrivacyBudgetPrefs(pref_service.registry()); + test_utils::InspectableIdentifiabilityStudyState state(&pref_service); + + EXPECT_TRUE(state.group_settings().enabled()); + EXPECT_TRUE(state.group_settings().IsUsingRandomSampling()); + + // The specific surface doesn't matter. + EXPECT_TRUE(state.ShouldReportEncounteredSurface(ukm::AssignNewSourceId(), + kRegularSurface1)); + EXPECT_FALSE(state.ShouldRecordSurface(kRegularSurface1)); } TEST(IdentifiabilityStudyStateStandaloneTest, ClearsPrefsIfStudyIsDisabled) { @@ -920,7 +945,7 @@ prefs::RegisterPrivacyBudgetPrefs(pref_service.registry()); test_utils::InspectableIdentifiabilityStudyState state(&pref_service); - EXPECT_TRUE(state.IsUsingAssignedBlockSampling()); + EXPECT_TRUE(state.group_settings().IsUsingAssignedBlockSampling()); // Any single selected group contributes kSurfacesInGroup surfaces. EXPECT_EQ(kSurfacesInGroup, state.active_surfaces().Size());
diff --git a/chrome/browser/privacy_budget/inspectable_identifiability_study_state.cc b/chrome/browser/privacy_budget/inspectable_identifiability_study_state.cc index 59d6e17..da2fcf21 100644 --- a/chrome/browser/privacy_budget/inspectable_identifiability_study_state.cc +++ b/chrome/browser/privacy_budget/inspectable_identifiability_study_state.cc
@@ -37,9 +37,4 @@ CheckInvariants(); } -bool InspectableIdentifiabilityStudyState::IsUsingAssignedBlockSampling() - const { - return settings_.IsUsingAssignedBlockSampling(); -} - } // namespace test_utils
diff --git a/chrome/browser/privacy_budget/inspectable_identifiability_study_state.h b/chrome/browser/privacy_budget/inspectable_identifiability_study_state.h index 2646a29c..4a35568 100644 --- a/chrome/browser/privacy_budget/inspectable_identifiability_study_state.h +++ b/chrome/browser/privacy_budget/inspectable_identifiability_study_state.h
@@ -6,6 +6,7 @@ #define CHROME_BROWSER_PRIVACY_BUDGET_INSPECTABLE_IDENTIFIABILITY_STUDY_STATE_H_ #include "base/containers/flat_set.h" +#include "chrome/browser/privacy_budget/identifiability_study_group_settings.h" #include "chrome/browser/privacy_budget/identifiability_study_state.h" #include "chrome/browser/privacy_budget/representative_surface_set.h" #include "chrome/browser/privacy_budget/surface_set_valuation.h" @@ -32,7 +33,9 @@ } int active_surface_budget() const { return active_surface_budget_; } int selected_block_offset() const { return selected_block_offset_; } - bool IsUsingAssignedBlockSampling() const; + const IdentifiabilityStudyGroupSettings& group_settings() const { + return settings_; + } void SelectAllOffsetsForTesting();
diff --git a/chrome/browser/referrer_policy_browsertest.cc b/chrome/browser/referrer_policy_browsertest.cc index 5ca0c0c4..81ffab1 100644 --- a/chrome/browser/referrer_policy_browsertest.cc +++ b/chrome/browser/referrer_policy_browsertest.cc
@@ -778,7 +778,7 @@ // // These tests assume a default policy of no-referrer-when-downgrade. struct ReferrerOverrideParams { - absl::optional<base::Feature> feature_to_enable; + absl::optional<base::test::FeatureRef> feature_to_enable; network::mojom::ReferrerPolicy baseline_policy; network::mojom::ReferrerPolicy expected_policy; @@ -848,8 +848,10 @@ public ::testing::WithParamInterface<ReferrerOverrideParams> { public: ReferrerOverrideTest() { - if (GetParam().feature_to_enable) - scoped_feature_list_.InitAndEnableFeature(*GetParam().feature_to_enable); + if (GetParam().feature_to_enable) { + scoped_feature_list_.InitAndEnableFeature( + *GetParam().feature_to_enable.value()); + } } protected: @@ -935,9 +937,10 @@ ::testing::ValuesIn(kReferrerOverrideParams), [](const ::testing::TestParamInfo<ReferrerOverrideParams>& info) -> std::string { - if (info.param.feature_to_enable) + if (info.param.feature_to_enable) { return base::StringPrintf("Param%s", - info.param.feature_to_enable->name); + info.param.feature_to_enable.value()->name); + } return "NoFeature"; });
diff --git a/chrome/browser/resources/chromeos/login/screens/common/consolidated_consent.html b/chrome/browser/resources/chromeos/login/screens/common/consolidated_consent.html index bd0ad52..579406a37 100644 --- a/chrome/browser/resources/chromeos/login/screens/common/consolidated_consent.html +++ b/chrome/browser/resources/chromeos/login/screens/common/consolidated_consent.html
@@ -190,7 +190,7 @@ <span id="usageTitle" class="oobe-optin-title"> [[i18nDynamic(locale, 'consolidatedConsentUsageOptInTitle')]] </span> - [[getUsageText_(locale, isChildAccount_, isArcEnabled_, isDemo_)]] + [[i18nDynamic(locale, 'consolidatedConsentUsageOptIn')]] <a id="usageLearnMore" on-click="onUsageLearnMoreClick_" class="oobe-local-link" is="action-link"> [[i18nDynamic(locale,
diff --git a/chrome/browser/resources/chromeos/login/screens/common/consolidated_consent.js b/chrome/browser/resources/chromeos/login/screens/common/consolidated_consent.js index 7e0697f..5d882bd7 100644 --- a/chrome/browser/resources/chromeos/login/screens/common/consolidated_consent.js +++ b/chrome/browser/resources/chromeos/login/screens/common/consolidated_consent.js
@@ -567,16 +567,6 @@ return this.i18n('consolidatedConsentHeader'); } - getUsageText_(locale, isChildAccount, isArcEnabled, isDemo) { - if (this.isArcOptInsHidden_(isArcEnabled, isDemo)) { - return this.i18n('consolidatedConsentUsageOptInArcDisabled'); - } - if (isChildAccount) { - return this.i18n('consolidatedConsentUsageOptInChild'); - } - return this.i18n('consolidatedConsentUsageOptIn'); - } - getUsageLearnMoreText_(locale, isChildAccount, isArcEnabled, isDemo) { if (this.isArcOptInsHidden_(isArcEnabled, isDemo)) { if (isChildAccount) {
diff --git a/chrome/browser/resources/intro/dice_app.html b/chrome/browser/resources/intro/dice_app.html index 5a98fb7d..613ad27 100644 --- a/chrome/browser/resources/intro/dice_app.html +++ b/chrome/browser/resources/intro/dice_app.html
@@ -124,33 +124,33 @@ <!-- TODO(crbug.com/1347507): Implement this as an element?--> <div id="signInPromo" slot="view"> - <!-- TODO(crbug.com/1347507): Don't hardcode strings--> <div id="central-view-container"> <div class="placeholder-color" id="chrome-logo-placeholder"></div> - <h1>Sign in for more benefits</h1> - <h3>You can enjoy the most out of Chrome</h3> + <h1>$i18n{pageTitle}</h1> + <h3>$i18n{pageSubtitle}</h3> <div id="cards"> <div class="card"> <div class="placeholder-color card-icon-placeholder"></div> - <h6>Across devices</h6> - <p id="card-description">Pick up what you left off on any device</p> + <h6>$i18n{devicesCardTitle}</h6> + <p id="card-description">$i18n{devicesCardDescription}</p> </div> <div class="card"> <div class="placeholder-color card-icon-placeholder"></div> - <h6>Stronger security</h6> - <p id="card-description">Extra protection to your passwords and more</p> + <h6>$i18n{securityCardTitle}</h6> + <p id="card-description">$i18n{securityCardDescription}</p> </div> <div class="card"> <div class="placeholder-color card-icon-placeholder"></div> - <h6>Back up your stuff</h6> - <p id="card-description">Store your bookmarks and more with sync</p> + <h6>$i18n{backupCardTitle}</h6> + <p id="card-description">$i18n{backupCardDescription}</p> </div> </div> </div> <div id="button-container"> - <cr-button on-click="onContinueWithoutAccountClick_">Don't sign in</cr-button> - <cr-button id="sign-in" on-click="onContinueWithAccountClick_">Sign in</cr-button> + <cr-button on-click="onContinueWithoutAccountClick_">$i18n{declineSignInButtonTitle}</cr-button> + <cr-button id="sign-in" on-click="onContinueWithAccountClick_">$i18n{acceptSignInButtonTitle} + </cr-button> </div> </div> </cr-view-manager>
diff --git a/chrome/browser/resources/settings/chromeos/BUILD.gn b/chrome/browser/resources/settings/chromeos/BUILD.gn index 710a8652..41a29ea3 100644 --- a/chrome/browser/resources/settings/chromeos/BUILD.gn +++ b/chrome/browser/resources/settings/chromeos/BUILD.gn
@@ -419,7 +419,6 @@ "os_apps_page/app_management_page/plugin_vm_page:web_components", "os_apps_page/app_notifications_page:web_components", "os_bluetooth_page:web_components", - "os_files_page:web_components", "os_people_page:web_components", "os_printing_page:web_components", "os_privacy_page:web_components", @@ -445,7 +444,6 @@ "os_apps_page/app_management_page/plugin_vm_page:closure_compile_module", "os_apps_page/app_notifications_page:closure_compile", "os_bluetooth_page:closure_compile_module", - "os_files_page:closure_compile_module", "os_languages_page:closure_compile_module", "os_people_page:closure_compile_module", "os_printing_page:closure_compile_module",
diff --git a/chrome/browser/resources/settings/chromeos/os_files_page/BUILD.gn b/chrome/browser/resources/settings/chromeos/os_files_page/BUILD.gn deleted file mode 100644 index 6fcd723..0000000 --- a/chrome/browser/resources/settings/chromeos/os_files_page/BUILD.gn +++ /dev/null
@@ -1,41 +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. - -import("//third_party/closure_compiler/compile_js.gni") -import("//tools/polymer/html_to_js.gni") -import("../os_settings.gni") - -js_type_check("closure_compile_module") { - closure_flags = os_settings_closure_flags - is_polymer3 = true - deps = [ - ":os_files_page", - ":smb_shares_page", - ] -} - -js_library("os_files_page") { - deps = [ - "..:deep_linking_behavior", - "..:os_route", - "..:route_observer_behavior", - "../..:router", - ] -} - -js_library("smb_shares_page") { - deps = [ - "..:os_route", - "..:route_observer_behavior", - "../..:router", - "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled", - ] -} - -html_to_js("web_components") { - js_files = [ - "os_files_page.js", - "smb_shares_page.js", - ] -}
diff --git a/chrome/browser/resources/settings/chromeos/os_files_page/os_files_page.js b/chrome/browser/resources/settings/chromeos/os_files_page/os_files_page.ts similarity index 71% rename from chrome/browser/resources/settings/chromeos/os_files_page/os_files_page.js rename to chrome/browser/resources/settings/chromeos/os_files_page/os_files_page.ts index 578b0763e..0643230 100644 --- a/chrome/browser/resources/settings/chromeos/os_files_page/os_files_page.js +++ b/chrome/browser/resources/settings/chromeos/os_files_page/os_files_page.ts
@@ -13,7 +13,7 @@ import '../../settings_shared.css.js'; import './smb_shares_page.js'; -import {html, mixinBehaviors, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; +import {mixinBehaviors, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {Setting} from '../../mojom-webui/setting.mojom-webui.js'; import {Route, Router} from '../../router.js'; @@ -21,23 +21,22 @@ import {routes} from '../os_route.js'; import {RouteObserverBehavior, RouteObserverBehaviorInterface} from '../route_observer_behavior.js'; -/** - * @constructor - * @extends {PolymerElement} - * @implements {DeepLinkingBehaviorInterface} - * @implements {RouteObserverBehaviorInterface} - */ -const OsSettingsFilesPageElementBase = mixinBehaviors( - [DeepLinkingBehavior, RouteObserverBehavior], PolymerElement); +import {getTemplate} from './os_files_page.html.js'; -/** @polymer */ +const OsSettingsFilesPageElementBase = + mixinBehaviors( + [DeepLinkingBehavior, RouteObserverBehavior], PolymerElement) as { + new (): DeepLinkingBehaviorInterface & RouteObserverBehaviorInterface & + PolymerElement, + }; + class OsSettingsFilesPageElement extends OsSettingsFilesPageElementBase { static get is() { return 'os-settings-files-page'; } static get template() { - return html`{__html_template__}`; + return getTemplate(); } static get properties() { @@ -50,7 +49,14 @@ notify: true, }, - /** @private {!Map<string, string>} */ + /** + * Used by DeepLinkingBehavior to focus this page's deep links. + */ + supportedSettingIds: { + type: Object, + value: () => new Set([Setting.kGoogleDriveConnection]), + }, + focusConfig_: { type: Object, value() { @@ -61,23 +67,14 @@ return map; }, }, - - /** - * Used by DeepLinkingBehavior to focus this page's deep links. - * @type {!Set<!Setting>} - */ - supportedSettingIds: { - type: Object, - value: () => new Set([Setting.kGoogleDriveConnection]), - }, }; } - /** - * @param {!Route} route - * @param {!Route=} oldRoute - */ - currentRouteChanged(route, oldRoute) { + prefs: Object; + override supportedSettingIds: Set<Setting>; + private focusConfig_: Map<string, string>; + + override currentRouteChanged(route: Route, _oldRoute?: Route) { // Does not apply to this page. if (route !== routes.FILES) { return; @@ -86,11 +83,16 @@ this.attemptDeepLink(); } - /** @private */ - onTapSmbShares_() { + private onTapSmbShares_() { Router.getInstance().navigateTo(routes.SMB_SHARES); } } +declare global { + interface HTMLElementTagNameMap { + 'os-settings-files-page': OsSettingsFilesPageElement; + } +} + customElements.define( OsSettingsFilesPageElement.is, OsSettingsFilesPageElement);
diff --git a/chrome/browser/resources/settings/chromeos/os_files_page/smb_shares_page.js b/chrome/browser/resources/settings/chromeos/os_files_page/smb_shares_page.ts similarity index 72% rename from chrome/browser/resources/settings/chromeos/os_files_page/smb_shares_page.js rename to chrome/browser/resources/settings/chromeos/os_files_page/smb_shares_page.ts index 0a459501..7b5a618 100644 --- a/chrome/browser/resources/settings/chromeos/os_files_page/smb_shares_page.js +++ b/chrome/browser/resources/settings/chromeos/os_files_page/smb_shares_page.ts
@@ -11,28 +11,26 @@ import '../../settings_shared.css.js'; import '../../settings_vars.css.js'; -import {html, mixinBehaviors, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; +import {mixinBehaviors, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {Route, Router} from '../../router.js'; import {routes} from '../os_route.js'; import {RouteObserverBehavior, RouteObserverBehaviorInterface} from '../route_observer_behavior.js'; -/** - * @constructor - * @extends {PolymerElement} - * @implements {RouteObserverBehaviorInterface} - */ -const SettingsSmbSharesPageElementBase = - mixinBehaviors([RouteObserverBehavior], PolymerElement); +import {getTemplate} from './smb_shares_page.html.js'; -/** @polymer */ +const SettingsSmbSharesPageElementBase = + mixinBehaviors([RouteObserverBehavior], PolymerElement) as { + new (): PolymerElement & RouteObserverBehaviorInterface, + }; + class SettingsSmbSharesPageElement extends SettingsSmbSharesPageElementBase { static get is() { return 'settings-smb-shares-page'; } static get template() { - return html`{__html_template__}`; + return getTemplate(); } static get properties() { @@ -45,34 +43,37 @@ notify: true, }, - /** @private */ showAddSmbDialog_: Boolean, }; } + prefs: object; + private showAddSmbDialog_: boolean; + /** * Overridden from RouteObserverBehavior. - * @param {!Route} route - * @param {!Route=} oldRoute - * @protected */ - currentRouteChanged(route, oldRoute) { + override currentRouteChanged(route: Route) { if (route === routes.SMB_SHARES) { this.showAddSmbDialog_ = Router.getInstance().getQueryParameters().get( 'showAddShare') === 'true'; } } - /** @private */ - onAddShareTap_() { + private onAddShareTap_() { this.showAddSmbDialog_ = true; } - /** @private */ - onAddSmbDialogClosed_() { + private onAddSmbDialogClosed_() { this.showAddSmbDialog_ = false; } } +declare global { + interface HTMLElementTagNameMap { + 'settings-smb-shares-page': SettingsSmbSharesPageElement; + } +} + customElements.define( SettingsSmbSharesPageElement.is, SettingsSmbSharesPageElement);
diff --git a/chrome/browser/resources/settings/chromeos/os_settings.gni b/chrome/browser/resources/settings/chromeos/os_settings.gni index 379f49c..e02c0f0 100644 --- a/chrome/browser/resources/settings/chromeos/os_settings.gni +++ b/chrome/browser/resources/settings/chromeos/os_settings.gni
@@ -22,6 +22,8 @@ "chromeos/os_about_page/edit_hostname_dialog.ts", "chromeos/os_about_page/os_about_page.ts", "chromeos/os_about_page/update_warning_dialog.ts", + "chromeos/os_files_page/os_files_page.ts", + "chromeos/os_files_page/smb_shares_page.ts", "chromeos/os_languages_page/add_input_methods_dialog.js", "chromeos/os_languages_page/add_items_dialog.js", "chromeos/os_languages_page/add_spellcheck_languages_dialog.js", @@ -324,8 +326,6 @@ "chromeos/os_bluetooth_page/os_saved_devices_list.js", "chromeos/os_bluetooth_page/os_saved_devices_list_item.js", "chromeos/os_bluetooth_page/settings_fast_pair_toggle.js", - "chromeos/os_files_page/os_files_page.js", - "chromeos/os_files_page/smb_shares_page.js", "chromeos/os_icons.js", "chromeos/os_people_page/account_manager.js", "chromeos/os_people_page/fingerprint_list.js",
diff --git a/chrome/browser/resources/side_panel/bookmarks/bookmarks_list.html b/chrome/browser/resources/side_panel/bookmarks/bookmarks_list.html index af5186a..b48a3932 100644 --- a/chrome/browser/resources/side_panel/bookmarks/bookmarks_list.html +++ b/chrome/browser/resources/side_panel/bookmarks/bookmarks_list.html
@@ -1,12 +1,44 @@ <style include="cr-icons cr-hidden-style"> + :host { + --price-tracking-discount-color: var(--google-green-800); + --price-tracking-original-color: var(--cr-secondary-text-color); + --price-tracking-chip-background: var(--google-green-50); + } + + @media (prefers-color-scheme: dark) { + :host { + --price-tracking-discount-color: white; + --price-tracking-original-color: var(--google-green-200); + --price-tracking-chip-background: var(--google-green-900); + } + } + + .chip-discounted { + --power-bookmark-chip-background: var(--price-tracking-chip-background); + } + .divider { border-top: 1px solid var(--cr-separator-color); margin: 0 22px; } + .icon-discounted { + background-color: var(--price-tracking-discount-color); + } + .icon-tracked { --power-bookmark-chip-icon-image: url(../images/bookmarks_icon_tracked.svg); } + + .price-discounted { + color: var(--price-tracking-discount-color); + font-weight: 500; + } + + .price-original { + color: var(--price-tracking-original-color); + text-decoration: line-through; + } </style> <div id="bookmarksContainer"> @@ -16,10 +48,20 @@ description="[[getBookmarkDescription_(item, descriptions_.*)]]" compact="[[compact_]]"> <div slot="extra-content-container"> - <power-bookmark-chip> - <div class="icon icon-tracked"></div> - <div>$200</div> - </power-bookmark-chip> + <template is="dom-if" if="[[showDiscountedPrice_(item)]]" restamp> + <power-bookmark-chip class="chip-discounted"> + <div class="icon icon-tracked icon-discounted"></div> + <div class="price-discounted">$200</div> + <div class="price-original">$500</div> + </power-bookmark-chip> + </template> + <template is="dom-if" if="[[!showDiscountedPrice_(item)]]" restamp> + <power-bookmark-chip> + <div class="icon icon-tracked"></div> + <div>$200</div> + </power-bookmark-chip> + </template> + </template> </div> </power-bookmark-row> </template>
diff --git a/chrome/browser/resources/side_panel/bookmarks/bookmarks_list.ts b/chrome/browser/resources/side_panel/bookmarks/bookmarks_list.ts index 2e42bf8..d26b459 100644 --- a/chrome/browser/resources/side_panel/bookmarks/bookmarks_list.ts +++ b/chrome/browser/resources/side_panel/bookmarks/bookmarks_list.ts
@@ -258,6 +258,14 @@ } /** + * Whether the given price-tracked bookmark should display as if discounted. + */ + private showDiscountedPrice_(): boolean { + // TODO: Incorporate actual price tracking data here + return true; + } + + /** * Finds the node within the nested array of folders and returns the path to * the node in the tree. */
diff --git a/chrome/browser/resources/side_panel/bookmarks/power_bookmark_chip.html b/chrome/browser/resources/side_panel/bookmarks/power_bookmark_chip.html index 7c4a8bf..58b00c1 100644 --- a/chrome/browser/resources/side_panel/bookmarks/power_bookmark_chip.html +++ b/chrome/browser/resources/side_panel/bookmarks/power_bookmark_chip.html
@@ -1,6 +1,14 @@ <style> :host { --power-bookmark-chip-background: var(--google-grey-100); + --power-bookmark-chip-icon-color: var(--cr-secondary-text-color); + } + + @media (prefers-color-scheme: dark) { + :host { + --power-bookmark-chip-background: var(--google-grey-800); + --power-bookmark-chip-icon-color: var(--google-grey-100); + } } :host ::slotted(.icon) { @@ -8,7 +16,7 @@ -webkit-mask-image: var(--power-bookmark-chip-icon-image); -webkit-mask-repeat: no-repeat; -webkit-mask-size: var(--power-bookmark-chip-icon-size); - background-color: var(--cr-secondary-text-color); + background-color: var(--power-bookmark-chip-icon-color); height: var(--power-bookmark-chip-icon-size); width: var(--power-bookmark-chip-icon-size); }
diff --git a/chrome/browser/resources/side_panel/bookmarks/power_bookmark_row.html b/chrome/browser/resources/side_panel/bookmarks/power_bookmark_row.html index 6e087fed..0788642 100644 --- a/chrome/browser/resources/side_panel/bookmarks/power_bookmark_row.html +++ b/chrome/browser/resources/side_panel/bookmarks/power_bookmark_row.html
@@ -87,7 +87,7 @@ } .text-container { - align-items: center; + align-items: flex-start; display: flex; flex-direction: column; gap: 2px;
diff --git a/chrome/browser/resources/signin/profile_picker/BUILD.gn b/chrome/browser/resources/signin/profile_picker/BUILD.gn index d62680a0..05cdf76 100644 --- a/chrome/browser/resources/signin/profile_picker/BUILD.gn +++ b/chrome/browser/resources/signin/profile_picker/BUILD.gn
@@ -36,7 +36,6 @@ non_web_component_files = [ "ensure_lazy_loaded.ts", - "icons.ts", "lazy_load.ts", "manage_profiles_browser_proxy.ts", "navigation_mixin.ts", @@ -44,6 +43,8 @@ "profile_picker.ts", ] + icons_html_files = [ "icons.html" ] + css_files = [ "profile_creation_flow/profile_creation_shared.css", "profile_picker_shared.css",
diff --git a/chrome/browser/resources/signin/profile_picker/icons.html b/chrome/browser/resources/signin/profile_picker/icons.html new file mode 100644 index 0000000..d3845e1 --- /dev/null +++ b/chrome/browser/resources/signin/profile_picker/icons.html
@@ -0,0 +1,22 @@ +<iron-iconset-svg name="profiles"> + <svg> + <defs> + <g id="add" viewBox="0 0 74 74"> + <circle cx="37" cy="37" r="37" stroke="none"/> + <path d="M36.9999 46.4349C36.1315 46.4349 35.4274 45.7309 35.4274 44.8624V38.5724H29.1374C28.269 38.5724 27.5649 37.8684 27.5649 36.9999C27.5649 36.1315 28.269 35.4274 29.1374 35.4274H35.4274V29.1374C35.4274 28.269 36.1315 27.5649 36.9999 27.5649C37.8684 27.5649 38.5724 28.269 38.5724 29.1374V35.4274H44.8624C45.7309 35.4274 46.4349 36.1315 46.4349 36.9999C46.4349 37.8684 45.7309 38.5724 44.8624 38.5724H38.5724V44.8624C38.5724 45.7309 37.8684 46.4349 36.9999 46.4349Z" fill="var(--iron-icon-stroke-color)"/> + </g> + + <g id="account-circle" viewBox="0 0 24 24" fill="var(--footer-text-color)" width="18px" height="18px"> + <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 3c1.66 0 3 1.34 3 3s-1.34 3-3 3-3-1.34-3-3 1.34-3 3-3zm0 14.2c-2.5 0-4.71-1.28-6-3.22.03-1.99 4-3.08 6-3.08 1.99 0 5.97 1.09 6 3.08-1.29 1.94-3.5 3.22-6 3.22z"/> + </g> + + <g id="customize-banner" viewBox="0 0 678 180" width="678" height="180" fill="none" xmlns="http://www.w3.org/2000/svg"> + <path d="M70.51 115.677c-2.425 3.218-7.276 3.053-9.621-.248-6.711-9.738-6.63-23.107.97-32.928 7.762-9.903 20.538-12.957 31.453-8.5 3.639 1.65 4.852 6.272 2.426 9.408l-25.227 32.268zM531.612 112.52c1.744-1.18 4.236-.252 4.818 1.77 1.744 6.069-.582 12.811-6.064 16.351-5.566 3.624-12.544 2.95-17.279-1.18-1.578-1.433-1.412-3.961.332-5.141l18.193-11.8zM140 128.499c0 2.519-1.98 4.498-4.5 4.498-2.52.09-4.5-1.979-4.5-4.498 0-2.52 1.98-4.499 4.5-4.499 2.43 0 4.5 1.979 4.5 4.499z" fill="var(--theme-shape-color)"/><path d="M160.541 53.57c.993-4.303 5.297-7.035 9.601-6.042l18.294 4.222c4.304.993 7.035 5.297 6.042 9.602-.993 4.304-5.297 7.036-9.602 6.042L166.5 63.173c-4.304-.91-6.953-5.298-5.959-9.602z" stroke="var(--theme-shape-color)" stroke-width="2" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/><path d="M526 69c6.075 0 11-4.925 11-11s-4.925-11-11-11-11 4.925-11 11 4.925 11 11 11zM608.042 81.007L630.448 83c.944.08 1.631.876 1.545 1.753l-2.146 20.805c-.086.877-.945 1.515-1.889 1.435L605.552 105c-.944-.079-1.631-.876-1.545-1.753l2.146-20.805c.086-.877.945-1.515 1.889-1.435z" stroke="var(--theme-shape-color)" stroke-width="2"/> + </g> + + <g id="lock" viewBox="0 0 48 48"> + <path d="M0 0h48v48H0z" fill="none"/><path d="M36 16h-2v-4c0-5.52-4.48-10-10-10S14 6.48 14 12v4h-2c-2.21 0-4 1.79-4 4v20c0 2.21 1.79 4 4 4h24c2.21 0 4-1.79 4-4V20c0-2.21-1.79-4-4-4zM24 34c-2.21 0-4-1.79-4-4s1.79-4 4-4 4 1.79 4 4-1.79 4-4 4zm6.2-18H17.8v-4c0-3.42 2.78-6.2 6.2-6.2 3.42 0 6.2 2.78 6.2 6.2v4z"/> + </g> + </defs> + </svg> +</iron-iconset-svg>
diff --git a/chrome/browser/resources/signin/profile_picker/icons.ts b/chrome/browser/resources/signin/profile_picker/icons.ts deleted file mode 100644 index 28f70cb7..0000000 --- a/chrome/browser/resources/signin/profile_picker/icons.ts +++ /dev/null
@@ -1,30 +0,0 @@ -// Copyright 2020 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'chrome://resources/polymer/v3_0/iron-iconset-svg/iron-iconset-svg.js'; - -const element = document.createElement('iron-iconset-svg'); -element.name = 'profiles'; -element.innerHTML = ` -<svg> - <defs> - <g id="add" viewBox="0 0 74 74"> - <circle cx="37" cy="37" r="37" stroke="none"/> - <path d="M36.9999 46.4349C36.1315 46.4349 35.4274 45.7309 35.4274 44.8624V38.5724H29.1374C28.269 38.5724 27.5649 37.8684 27.5649 36.9999C27.5649 36.1315 28.269 35.4274 29.1374 35.4274H35.4274V29.1374C35.4274 28.269 36.1315 27.5649 36.9999 27.5649C37.8684 27.5649 38.5724 28.269 38.5724 29.1374V35.4274H44.8624C45.7309 35.4274 46.4349 36.1315 46.4349 36.9999C46.4349 37.8684 45.7309 38.5724 44.8624 38.5724H38.5724V44.8624C38.5724 45.7309 37.8684 46.4349 36.9999 46.4349Z" fill="var(--iron-icon-stroke-color)"/> - </g> - - <g id="account-circle" viewBox="0 0 24 24" fill="var(--footer-text-color)" width="18px" height="18px"> - <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 3c1.66 0 3 1.34 3 3s-1.34 3-3 3-3-1.34-3-3 1.34-3 3-3zm0 14.2c-2.5 0-4.71-1.28-6-3.22.03-1.99 4-3.08 6-3.08 1.99 0 5.97 1.09 6 3.08-1.29 1.94-3.5 3.22-6 3.22z"/> - </g> - - <g id="customize-banner" viewBox="0 0 678 180" width="678" height="180" fill="none" xmlns="http://www.w3.org/2000/svg"> - <path d="M70.51 115.677c-2.425 3.218-7.276 3.053-9.621-.248-6.711-9.738-6.63-23.107.97-32.928 7.762-9.903 20.538-12.957 31.453-8.5 3.639 1.65 4.852 6.272 2.426 9.408l-25.227 32.268zM531.612 112.52c1.744-1.18 4.236-.252 4.818 1.77 1.744 6.069-.582 12.811-6.064 16.351-5.566 3.624-12.544 2.95-17.279-1.18-1.578-1.433-1.412-3.961.332-5.141l18.193-11.8zM140 128.499c0 2.519-1.98 4.498-4.5 4.498-2.52.09-4.5-1.979-4.5-4.498 0-2.52 1.98-4.499 4.5-4.499 2.43 0 4.5 1.979 4.5 4.499z" fill="var(--theme-shape-color)"/><path d="M160.541 53.57c.993-4.303 5.297-7.035 9.601-6.042l18.294 4.222c4.304.993 7.035 5.297 6.042 9.602-.993 4.304-5.297 7.036-9.602 6.042L166.5 63.173c-4.304-.91-6.953-5.298-5.959-9.602z" stroke="var(--theme-shape-color)" stroke-width="2" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/><path d="M526 69c6.075 0 11-4.925 11-11s-4.925-11-11-11-11 4.925-11 11 4.925 11 11 11zM608.042 81.007L630.448 83c.944.08 1.631.876 1.545 1.753l-2.146 20.805c-.086.877-.945 1.515-1.889 1.435L605.552 105c-.944-.079-1.631-.876-1.545-1.753l2.146-20.805c.086-.877.945-1.515 1.889-1.435z" stroke="var(--theme-shape-color)" stroke-width="2"/> - </g> - - <g id="lock" viewBox="0 0 48 48"> - <path d="M0 0h48v48H0z" fill="none"/><path d="M36 16h-2v-4c0-5.52-4.48-10-10-10S14 6.48 14 12v4h-2c-2.21 0-4 1.79-4 4v20c0 2.21 1.79 4 4 4h24c2.21 0 4-1.79 4-4V20c0-2.21-1.79-4-4-4zM24 34c-2.21 0-4-1.79-4-4s1.79-4 4-4 4 1.79 4 4-1.79 4-4 4zm6.2-18H17.8v-4c0-3.42 2.78-6.2 6.2-6.2 3.42 0 6.2 2.78 6.2 6.2v4z"/> - </g> - </defs> -</svg>`; -document.head.appendChild(element);
diff --git a/chrome/browser/resources/signin/profile_picker/profile_creation_flow/local_profile_customization.ts b/chrome/browser/resources/signin/profile_picker/profile_creation_flow/local_profile_customization.ts index 0c0bc45c..6dc25fbe 100644 --- a/chrome/browser/resources/signin/profile_picker/profile_creation_flow/local_profile_customization.ts +++ b/chrome/browser/resources/signin/profile_picker/profile_creation_flow/local_profile_customization.ts
@@ -12,7 +12,7 @@ import 'chrome://resources/cr_elements/cr_shared_style.css.js'; import 'chrome://resources/cr_components/customize_themes/customize_themes.js'; import './profile_creation_shared.css.js'; -import '../icons.js'; +import '../icons.html.js'; import '../profile_picker_shared.css.js'; import {Theme, ThemeInfo, ThemeType} from 'chrome://resources/cr_components/customize_themes/customize_themes.mojom-webui.js'; @@ -21,8 +21,8 @@ import {CrInputElement} from 'chrome://resources/cr_elements/cr_input/cr_input.js'; import {AvatarIcon} from 'chrome://resources/cr_elements/cr_profile_avatar_selector/cr_profile_avatar_selector.js'; import {I18nMixin} from 'chrome://resources/cr_elements/i18n_mixin.js'; -import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {WebUIListenerMixin} from 'chrome://resources/cr_elements/web_ui_listener_mixin.js'; +import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {AutogeneratedThemeColorInfo, ManageProfilesBrowserProxy, ManageProfilesBrowserProxyImpl, UserThemeChoice} from '../manage_profiles_browser_proxy.js';
diff --git a/chrome/browser/resources/signin/profile_picker/profile_picker_main_view.ts b/chrome/browser/resources/signin/profile_picker/profile_picker_main_view.ts index 1360f7f..32fe568 100644 --- a/chrome/browser/resources/signin/profile_picker/profile_picker_main_view.ts +++ b/chrome/browser/resources/signin/profile_picker/profile_picker_main_view.ts
@@ -8,7 +8,7 @@ import 'chrome://resources/cr_elements/cr_shared_style.css.js'; import 'chrome://resources/cr_elements/cr_checkbox/cr_checkbox.js'; import 'chrome://resources/polymer/v3_0/iron-icon/iron-icon.js'; -import './icons.js'; +import './icons.html.js'; import './profile_card.js'; import './profile_picker_shared.css.js'; import './strings.m.js';
diff --git a/chrome/browser/safe_browsing/incident_reporting/state_store_unittest.cc b/chrome/browser/safe_browsing/incident_reporting/state_store_unittest.cc index 8fe6aae..14a164a 100644 --- a/chrome/browser/safe_browsing/incident_reporting/state_store_unittest.cc +++ b/chrome/browser/safe_browsing/incident_reporting/state_store_unittest.cc
@@ -110,9 +110,9 @@ std::unique_ptr<base::Value> prefs(JSONFileValueDeserializer(GetPrefsPath()) .Deserialize(nullptr, nullptr)); ASSERT_NE(nullptr, prefs.get()); - base::DictionaryValue* dict = nullptr; - ASSERT_TRUE(prefs->GetAsDictionary(&dict)); - ASSERT_TRUE(dict->RemovePath(prefs::kSafeBrowsingIncidentsSent)); + base::Value::Dict* dict = prefs->GetIfDict(); + ASSERT_TRUE(dict); + ASSERT_TRUE(dict->RemoveByDottedPath(prefs::kSafeBrowsingIncidentsSent)); ASSERT_TRUE(JSONFileValueSerializer(GetPrefsPath()).Serialize(*dict)); }
diff --git a/chrome/browser/ssl/typed_navigation_upgrade_throttle_browsertest.cc b/chrome/browser/ssl/typed_navigation_upgrade_throttle_browsertest.cc index 7bd242eb..cab47af 100644 --- a/chrome/browser/ssl/typed_navigation_upgrade_throttle_browsertest.cc +++ b/chrome/browser/ssl/typed_navigation_upgrade_throttle_browsertest.cc
@@ -158,7 +158,7 @@ void SetUpFeature(base::TimeDelta fallback_delay) { std::vector<base::test::ScopedFeatureList::FeatureAndParams> enabled_features; - std::vector<base::Feature> disabled_features; + std::vector<base::test::FeatureRef> disabled_features; if (IsFeatureEnabled()) { base::FieldTrialParams params; params[omnibox::kDefaultTypedNavigationsToHttpsTimeoutParam] =
diff --git a/chrome/browser/supervised_user/BUILD.gn b/chrome/browser/supervised_user/BUILD.gn index 0329bff3..815a9c91 100644 --- a/chrome/browser/supervised_user/BUILD.gn +++ b/chrome/browser/supervised_user/BUILD.gn
@@ -80,6 +80,7 @@ "//components/browser_ui/bottomsheet/android:java", "//components/browser_ui/widget/android:java", "//components/signin/public/android:java", + "//components/url_formatter/android:url_formatter_java", "//third_party/androidx:androidx_annotation_annotation_java", "//third_party/androidx:androidx_appcompat_appcompat_java", "//ui/android:ui_no_recycler_view_java", @@ -122,18 +123,23 @@ android_library("javatests") { testonly = true - sources = [ "android/java/src/org/chromium/chrome/browser/supervised_user/test/WebsiteParentApprovalTest.java" ] + sources = [ + "android/java/src/org/chromium/chrome/browser/supervised_user/test/WebsiteParentApprovalTest.java", + "android/javatests/src/org/chromium/chrome/browser/supervised_user/website_approval/WebsiteApprovalSheetContentUnitTest.java", + ] deps = [ ":test_support_java", "//base:base_java_test_support", "//chrome/android:chrome_java", "//chrome/browser/flags:java", "//chrome/browser/profiles/android:java", + "//chrome/browser/supervised_user:website_parent_approval_java", "//chrome/test/android:chrome_java_integration_test_support", "//content/public/test/android:content_java_test_support", "//net/android:net_java_test_support", "//third_party/androidx:androidx_test_runner_java", "//third_party/junit:junit", + "//url:gurl_java", ] } }
diff --git a/chrome/browser/supervised_user/android/java/res/layout/website_approval_bottom_sheet.xml b/chrome/browser/supervised_user/android/java/res/layout/website_approval_bottom_sheet.xml index 014cc4c..344b55a 100644 --- a/chrome/browser/supervised_user/android/java/res/layout/website_approval_bottom_sheet.xml +++ b/chrome/browser/supervised_user/android/java/res/layout/website_approval_bottom_sheet.xml
@@ -98,7 +98,6 @@ android:layout_height="wrap_content" android:minHeight="20dp" android:ellipsize="end" - android:singleLine="true" android:textAppearance="@style/TextAppearance.TextLarge.Primary" /> <TextView android:id="@+id/full_url" @@ -106,7 +105,6 @@ android:layout_height="wrap_content" android:minHeight="20dp" android:ellipsize="end" - android:singleLine="true" android:textAppearance="@style/TextAppearance.TextMedium.Secondary" /> </LinearLayout> </LinearLayout>
diff --git a/chrome/browser/supervised_user/android/java/src/org/chromium/chrome/browser/supervised_user/website_approval/WebsiteApprovalSheetContent.java b/chrome/browser/supervised_user/android/java/src/org/chromium/chrome/browser/supervised_user/website_approval/WebsiteApprovalSheetContent.java index 4f3a82f..cf82902 100644 --- a/chrome/browser/supervised_user/android/java/src/org/chromium/chrome/browser/supervised_user/website_approval/WebsiteApprovalSheetContent.java +++ b/chrome/browser/supervised_user/android/java/src/org/chromium/chrome/browser/supervised_user/website_approval/WebsiteApprovalSheetContent.java
@@ -13,17 +13,25 @@ import android.widget.TextView; import androidx.annotation.Nullable; +import androidx.annotation.VisibleForTesting; import androidx.appcompat.widget.DialogTitle; import org.chromium.chrome.browser.supervised_user.R; import org.chromium.components.browser_ui.bottomsheet.BottomSheetContent; +import org.chromium.components.url_formatter.UrlFormatter; import org.chromium.ui.widget.ButtonCompat; +import org.chromium.url.GURL; /** * Bottom sheet content for the screen which allows a parent to approve or deny a website. */ class WebsiteApprovalSheetContent implements BottomSheetContent { private static final String TAG = "WebsiteApprovalSheetContent"; + private static final String ELLIPSIS = "..."; + static final int MAX_HOST_SIZE = 256; + static final int SUBSTRING_LIMIT = 256; + static final int MAX_FULL_URL_SIZE = MAX_HOST_SIZE + SUBSTRING_LIMIT; + private final Context mContext; private final View mContentView; @@ -114,15 +122,46 @@ titleView.setText(mContext.getString(R.string.parent_website_approval_title, childName)); } - public void setDomainText(String domain) { + public void setDomainText(GURL url) { TextView domainTextView = mContentView.findViewById(R.id.all_pages_of); - domainTextView.setText( - mContext.getString(R.string.parent_website_approval_all_of_domain, domain)); + // Omit scheme, credentials, path and trivial subdomains + String formattedDomain = + UrlFormatter.formatUrlForDisplayOmitSchemePathAndTrivialSubdomains(url); + domainTextView.setText(mContext.getString( + R.string.parent_website_approval_all_of_domain, formattedDomain)); } - public void setFullUrlText(String url) { + @VisibleForTesting + static String truncateLongUrl(GURL url) { + // Omit user-specific and trivial url parts. + String formattedUrl = + UrlFormatter.formatUrlForDisplayOmitSchemeOmitTrivialSubdomains(url.getSpec()); + + if (formattedUrl.length() <= MAX_FULL_URL_SIZE) { + return formattedUrl; + } else { + // Omit scheme, credentials, path and trivial subdomains + String formattedHost = + UrlFormatter.formatUrlForDisplayOmitSchemePathAndTrivialSubdomains(url); + // Keep the full host but only portions of the path up to a limit. + // The urls the we process never contain query or fragments. + StringBuilder truncatedUrlBuilder = new StringBuilder(); + truncatedUrlBuilder.append(formattedHost); + int truncatedPathLength = Math.min(url.getPath().length(), SUBSTRING_LIMIT); + if (truncatedPathLength + ELLIPSIS.length() < url.getPath().length()) { + truncatedUrlBuilder.append(url.getPath().substring(0, truncatedPathLength)); + truncatedUrlBuilder.append(ELLIPSIS); + + } else { + truncatedUrlBuilder.append(url.getPath()); + } + return truncatedUrlBuilder.toString(); + } + } + + public void setFullUrlText(GURL url) { TextView urlTextView = mContentView.findViewById(R.id.full_url); - urlTextView.setText(url); + urlTextView.setText(truncateLongUrl(url)); } public void setFaviconBitmap(Bitmap bitmap) {
diff --git a/chrome/browser/supervised_user/android/java/src/org/chromium/chrome/browser/supervised_user/website_approval/WebsiteApprovalViewBinder.java b/chrome/browser/supervised_user/android/java/src/org/chromium/chrome/browser/supervised_user/website_approval/WebsiteApprovalViewBinder.java index 1f3a419..e511e3a1 100644 --- a/chrome/browser/supervised_user/android/java/src/org/chromium/chrome/browser/supervised_user/website_approval/WebsiteApprovalViewBinder.java +++ b/chrome/browser/supervised_user/android/java/src/org/chromium/chrome/browser/supervised_user/website_approval/WebsiteApprovalViewBinder.java
@@ -23,8 +23,8 @@ if (propertyKey == WebsiteApprovalProperties.CHILD_NAME) { view.setTitle(model.get(WebsiteApprovalProperties.CHILD_NAME)); } else if (propertyKey == WebsiteApprovalProperties.URL) { - view.setDomainText(model.get(WebsiteApprovalProperties.URL).getHost()); - view.setFullUrlText(model.get(WebsiteApprovalProperties.URL).getSpec()); + view.setDomainText(model.get(WebsiteApprovalProperties.URL)); + view.setFullUrlText(model.get(WebsiteApprovalProperties.URL)); } else if (propertyKey == WebsiteApprovalProperties.ON_CLICK_APPROVE) { view.getApproveButton().setOnClickListener( model.get(WebsiteApprovalProperties.ON_CLICK_APPROVE));
diff --git a/chrome/browser/supervised_user/android/javatests/src/org/chromium/chrome/browser/supervised_user/website_approval/WebsiteApprovalSheetContentUnitTest.java b/chrome/browser/supervised_user/android/javatests/src/org/chromium/chrome/browser/supervised_user/website_approval/WebsiteApprovalSheetContentUnitTest.java new file mode 100644 index 0000000..6beac37 --- /dev/null +++ b/chrome/browser/supervised_user/android/javatests/src/org/chromium/chrome/browser/supervised_user/website_approval/WebsiteApprovalSheetContentUnitTest.java
@@ -0,0 +1,98 @@ +// 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. + +package org.chromium.chrome.browser.supervised_user.website_approval; + +import static org.junit.Assert.assertEquals; + +import androidx.test.filters.SmallTest; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; + +import org.chromium.base.test.BaseJUnit4ClassRunner; +import org.chromium.base.test.util.Batch; +import org.chromium.url.GURL; + +/** + * Unit tests for {@link WebsiteApprovalSheetContent}. + */ +@RunWith(BaseJUnit4ClassRunner.class) +@Batch(Batch.UNIT_TESTS) +public class WebsiteApprovalSheetContentUnitTest { + private static final String PREFIX = "https://www."; + + private static final String BASE_URL = "somehost.com"; + + private static final String PATH_WITHIN_LIMIT = "/path0/path1/path2/path3/path4/path5/path6/" + + "path7/path8/path9/path10/path11/path12/path13/path14/path15"; + + @Test + @SmallTest + public void testTruncateLongUrlNoTruncation() { + // Url within MAX_HOST_SIZE test case. + String expectedUri = BASE_URL + PATH_WITHIN_LIMIT; + GURL url = new GURL(PREFIX + expectedUri); + + Assert.assertTrue(url.getSpec().length() < WebsiteApprovalSheetContent.MAX_HOST_SIZE); + String formattedString = WebsiteApprovalSheetContent.truncateLongUrl(url); + + assertEquals(expectedUri, formattedString); + } + + @Test + @SmallTest + public void testTruncateLongUrlNoTruncationNoEllipsis() { + String urlWithPathWithElipsisLimit = BASE_URL; + int elipsisSize = 3; + String charPad = "a"; + while (urlWithPathWithElipsisLimit.length() + elipsisSize + < WebsiteApprovalSheetContent.MAX_FULL_URL_SIZE) { + if (urlWithPathWithElipsisLimit.length() + elipsisSize + PATH_WITHIN_LIMIT.length() + < WebsiteApprovalSheetContent.MAX_FULL_URL_SIZE) { + urlWithPathWithElipsisLimit = urlWithPathWithElipsisLimit + PATH_WITHIN_LIMIT; + } else { + urlWithPathWithElipsisLimit = urlWithPathWithElipsisLimit + charPad; + } + } + + GURL url = new GURL(PREFIX + urlWithPathWithElipsisLimit); + Assert.assertTrue(url.getSpec().length() > WebsiteApprovalSheetContent.MAX_FULL_URL_SIZE); + + String formattedString = WebsiteApprovalSheetContent.truncateLongUrl(url); + + assertEquals(urlWithPathWithElipsisLimit, formattedString); + } + + @SmallTest + @Test + public void testTruncateLongUrlWithPathTruncationWithEllipsis() { + // Truncate url with long path. + String pathAboveLimit = ""; + String subpath = ""; + while (pathAboveLimit.length() < WebsiteApprovalSheetContent.MAX_FULL_URL_SIZE) { + pathAboveLimit = pathAboveLimit + PATH_WITHIN_LIMIT; + + if (subpath.length() + PATH_WITHIN_LIMIT.length() + <= WebsiteApprovalSheetContent.SUBSTRING_LIMIT) { + subpath = subpath + PATH_WITHIN_LIMIT; + } else if (subpath.length() < WebsiteApprovalSheetContent.SUBSTRING_LIMIT) { + for (int i = 0; i < PATH_WITHIN_LIMIT.length() + && subpath.length() < WebsiteApprovalSheetContent.SUBSTRING_LIMIT; + i++) { + subpath = subpath + PATH_WITHIN_LIMIT.charAt(i); + } + } + } + String uri = BASE_URL + pathAboveLimit; + GURL url = new GURL(PREFIX + uri); + + Assert.assertTrue(url.getSpec().length() > WebsiteApprovalSheetContent.MAX_FULL_URL_SIZE); + String formattedString = WebsiteApprovalSheetContent.truncateLongUrl(url); + + String expected = BASE_URL + subpath + "..."; + assertEquals(expected, formattedString); + } +}
diff --git a/chrome/browser/supervised_user/kids_chrome_management/kids_chrome_management_client.cc b/chrome/browser/supervised_user/kids_chrome_management/kids_chrome_management_client.cc index 6b54493..10b8bd8 100644 --- a/chrome/browser/supervised_user/kids_chrome_management/kids_chrome_management_client.cc +++ b/chrome/browser/supervised_user/kids_chrome_management/kids_chrome_management_client.cc
@@ -70,13 +70,16 @@ // ClassifyUrlResponse proto object. std::unique_ptr<kids_chrome_management::ClassifyUrlResponse> GetClassifyURLResponseProto(const std::string& response) { - absl::optional<base::Value> optional_value = base::JSONReader::Read(response); - const base::DictionaryValue* dict = nullptr; + absl::optional<base::Value> maybe_value = base::JSONReader::Read(response); + const base::Value::Dict* dict = nullptr; + if (maybe_value.has_value()) { + dict = maybe_value->GetIfDict(); + } auto response_proto = std::make_unique<kids_chrome_management::ClassifyUrlResponse>(); - if (!optional_value || !optional_value.value().GetAsDictionary(&dict)) { + if (!dict) { DLOG(WARNING) << "GetClassifyURLResponseProto failed to parse response dictionary"; response_proto->set_display_classification( @@ -85,9 +88,9 @@ return response_proto; } - const base::Value* classification_value = - dict->FindKey("displayClassification"); - if (!classification_value) { + const std::string* maybe_classification_string = + dict->FindString("displayClassification"); + if (!maybe_classification_string) { DLOG(WARNING) << "GetClassifyURLResponseProto failed to parse displayClassification"; response_proto->set_display_classification( @@ -96,7 +99,7 @@ return response_proto; } - const std::string classification_string = classification_value->GetString(); + const std::string classification_string = *maybe_classification_string; if (classification_string == kClassifyUrlAllowed) { response_proto->set_display_classification( kids_chrome_management::ClassifyUrlResponse::ALLOWED);
diff --git a/chrome/browser/supervised_user/supervised_user_settings_service_unittest.cc b/chrome/browser/supervised_user/supervised_user_settings_service_unittest.cc index 8cf8f0c..9642e64 100644 --- a/chrome/browser/supervised_user/supervised_user_settings_service_unittest.cc +++ b/chrome/browser/supervised_user/supervised_user_settings_service_unittest.cc
@@ -239,9 +239,7 @@ ASSERT_TRUE(settings_); value = settings_->FindKey(kSettingsName); ASSERT_TRUE(value); - const base::DictionaryValue* dict_value = nullptr; - ASSERT_TRUE(value->GetAsDictionary(&dict_value)); - EXPECT_EQ(*dict_value, dict); + EXPECT_EQ(value->GetDict(), dict); } TEST_F(SupervisedUserSettingsServiceTest, NotifyForWebsiteApprovals) {
diff --git a/chrome/browser/sync/test/integration/password_manager_sync_test.cc b/chrome/browser/sync/test/integration/password_manager_sync_test.cc index b3bd8f6..fadc5cab 100644 --- a/chrome/browser/sync/test/integration/password_manager_sync_test.cc +++ b/chrome/browser/sync/test/integration/password_manager_sync_test.cc
@@ -32,6 +32,7 @@ #include "components/password_manager/core/browser/password_form.h" #include "components/password_manager/core/browser/password_manager_features_util.h" #include "components/password_manager/core/browser/password_manager_test_utils.h" +#include "components/password_manager/core/browser/password_manager_util.h" #include "components/password_manager/core/browser/password_store_interface.h" #include "components/password_manager/core/browser/password_sync_util.h" #include "components/password_manager/core/common/password_manager_features.h" @@ -907,10 +908,14 @@ password_manager::sync_util::IsPasswordSyncEnabled(GetSyncService(0))); EXPECT_TRUE( password_manager::sync_util::IsPasswordSyncActive(GetSyncService(0))); + EXPECT_NE(absl::nullopt, + password_manager::sync_util::GetSyncingAccount(GetSyncService(0))); EXPECT_EQ(password_manager::sync_util::GetSyncUsernameIfSyncingPasswords( GetSyncService(0), IdentityManagerFactory::GetForProfile(GetProfile(0))), kExpectedUsername); + EXPECT_EQ(password_manager_util::GetPasswordSyncState(GetSyncService(0)), + password_manager::SyncState::kSyncingNormalEncryption); // Enter a persistent auth error state (web signout). GetClient(0)->EnterSyncPausedStateForPrimaryAccount(); @@ -925,11 +930,15 @@ // all persistent auth errors. EXPECT_FALSE( password_manager::sync_util::IsPasswordSyncActive(GetSyncService(0))); + EXPECT_EQ(password_manager_util::GetPasswordSyncState(GetSyncService(0)), + password_manager::SyncState::kNotSyncing); - // In the current implementation, these predicates return true even if sync is - // paused. + // In the current implementation, the APIs below treat sync as enabled/active + // even while paused. EXPECT_TRUE( password_manager::sync_util::IsPasswordSyncEnabled(GetSyncService(0))); + EXPECT_NE(absl::nullopt, + password_manager::sync_util::GetSyncingAccount(GetSyncService(0))); EXPECT_EQ(password_manager::sync_util::GetSyncUsernameIfSyncingPasswords( GetSyncService(0), IdentityManagerFactory::GetForProfile(GetProfile(0))),
diff --git a/chrome/browser/sync/test/integration/sync_test.cc b/chrome/browser/sync/test/integration/sync_test.cc index 45af12a..f2d553e 100644 --- a/chrome/browser/sync/test/integration/sync_test.cc +++ b/chrome/browser/sync/test/integration/sync_test.cc
@@ -6,7 +6,6 @@ #include <utility> -#include "base/as_const.h" #include "base/bind.h" #include "base/callback_helpers.h" #include "base/command_line.h" @@ -521,7 +520,7 @@ SyncServiceImplHarness* SyncTest::GetClient(int index) { return const_cast<SyncServiceImplHarness*>( - base::as_const(*this).GetClient(index)); + std::as_const(*this).GetClient(index)); } const SyncServiceImplHarness* SyncTest::GetClient(int index) const {
diff --git a/chrome/browser/ui/BUILD.gn b/chrome/browser/ui/BUILD.gn index 4359e49b..6bf91cd 100644 --- a/chrome/browser/ui/BUILD.gn +++ b/chrome/browser/ui/BUILD.gn
@@ -5625,6 +5625,11 @@ "web_applications/app_browser_controller.h", "web_applications/diagnostics/app_type_initialized_event.cc", "web_applications/diagnostics/app_type_initialized_event.h", + "web_applications/diagnostics/callback_utils.h", + "web_applications/diagnostics/web_app_icon_diagnostic.cc", + "web_applications/diagnostics/web_app_icon_diagnostic.h", + "web_applications/diagnostics/web_app_icon_health_checks.cc", + "web_applications/diagnostics/web_app_icon_health_checks.h", "web_applications/draggable_region_host_impl.cc", "web_applications/draggable_region_host_impl.h", "web_applications/share_target_utils.cc",
diff --git a/chrome/browser/ui/android/strings/android_chrome_strings.grd b/chrome/browser/ui/android/strings/android_chrome_strings.grd index fd7da046..7a8f1c8 100644 --- a/chrome/browser/ui/android/strings/android_chrome_strings.grd +++ b/chrome/browser/ui/android/strings/android_chrome_strings.grd
@@ -4538,18 +4538,6 @@ <message name="IDS_IPH_IDENTITY_DISC_ACCESSIBILITY_TEXT" desc="The in-product-help accessibility text prompting the user that tapping identity disc will navigate to 'Sync and Google services' settings page."> To manage your Google account, tap the "Manage account" button </message> - <message name="IDS_IPH_MIC_TOOLBAR_GENERIC_MESSAGE_TEXT" desc="The in-product-help message encouraging to execute a voice search."> - Search with your voice - </message> - <message name="IDS_IPH_MIC_TOOLBAR_GENERIC_MESSAGE_ACCESSIBILITY_TEXT" desc="The in-product-help message encouraging to execute a voice search."> - Tap the mic to search with your voice - </message> - <message name="IDS_IPH_MIC_TOOLBAR_EXAMPLE_QUERY_TEXT" desc="The in-product-help message encouraging to execute a voice search by giving an example command to try."> - Try “What’s the weather today?” - </message> - <message name="IDS_IPH_MIC_TOOLBAR_EXAMPLE_QUERY_ACCESSIBILITY_TEXT" desc="The in-product-help message encouraging to execute a voice search by giving an example command to try."> - To check the weather, tap the mic and say “What’s the weather today?” - </message> <message name="IDS_IPH_NTP_WITHOUT_FEED_TEXT" desc="The in-product-help message to open the new tab page with personalized top sites."> See your top sites </message>
diff --git a/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_IPH_MIC_TOOLBAR_EXAMPLE_QUERY_ACCESSIBILITY_TEXT.png.sha1 b/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_IPH_MIC_TOOLBAR_EXAMPLE_QUERY_ACCESSIBILITY_TEXT.png.sha1 deleted file mode 100644 index 23649dc7..0000000 --- a/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_IPH_MIC_TOOLBAR_EXAMPLE_QUERY_ACCESSIBILITY_TEXT.png.sha1 +++ /dev/null
@@ -1 +0,0 @@ -c93d977b4ff4b4662ae468cf15c1d4f4891d9557 \ No newline at end of file
diff --git a/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_IPH_MIC_TOOLBAR_EXAMPLE_QUERY_TEXT.png.sha1 b/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_IPH_MIC_TOOLBAR_EXAMPLE_QUERY_TEXT.png.sha1 deleted file mode 100644 index 23649dc7..0000000 --- a/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_IPH_MIC_TOOLBAR_EXAMPLE_QUERY_TEXT.png.sha1 +++ /dev/null
@@ -1 +0,0 @@ -c93d977b4ff4b4662ae468cf15c1d4f4891d9557 \ No newline at end of file
diff --git a/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_IPH_MIC_TOOLBAR_GENERIC_MESSAGE_ACCESSIBILITY_TEXT.png.sha1 b/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_IPH_MIC_TOOLBAR_GENERIC_MESSAGE_ACCESSIBILITY_TEXT.png.sha1 deleted file mode 100644 index 9d2c9ed..0000000 --- a/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_IPH_MIC_TOOLBAR_GENERIC_MESSAGE_ACCESSIBILITY_TEXT.png.sha1 +++ /dev/null
@@ -1 +0,0 @@ -bc1746fb2c5127a0d73a63b2023d7dc1e74c56f9 \ No newline at end of file
diff --git a/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_IPH_MIC_TOOLBAR_GENERIC_MESSAGE_TEXT.png.sha1 b/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_IPH_MIC_TOOLBAR_GENERIC_MESSAGE_TEXT.png.sha1 deleted file mode 100644 index 9d2c9ed..0000000 --- a/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_IPH_MIC_TOOLBAR_GENERIC_MESSAGE_TEXT.png.sha1 +++ /dev/null
@@ -1 +0,0 @@ -bc1746fb2c5127a0d73a63b2023d7dc1e74c56f9 \ No newline at end of file
diff --git a/chrome/browser/ui/android/toolbar/BUILD.gn b/chrome/browser/ui/android/toolbar/BUILD.gn index 77b3318..8e85137 100644 --- a/chrome/browser/ui/android/toolbar/BUILD.gn +++ b/chrome/browser/ui/android/toolbar/BUILD.gn
@@ -8,6 +8,7 @@ android_library("java") { sources = [ + "java/src/org/chromium/chrome/browser/toolbar/BaseButtonDataProvider.java", "java/src/org/chromium/chrome/browser/toolbar/ButtonData.java", "java/src/org/chromium/chrome/browser/toolbar/ButtonDataImpl.java", "java/src/org/chromium/chrome/browser/toolbar/ButtonDataProvider.java",
diff --git a/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/BaseButtonDataProvider.java b/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/BaseButtonDataProvider.java new file mode 100644 index 0000000..2e6ed7a --- /dev/null +++ b/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/BaseButtonDataProvider.java
@@ -0,0 +1,167 @@ +// 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. + +package org.chromium.chrome.browser.toolbar; + +import android.graphics.drawable.Drawable; +import android.view.View; +import android.view.View.OnClickListener; + +import androidx.annotation.CallSuper; +import androidx.annotation.Nullable; +import androidx.annotation.StringRes; + +import org.chromium.base.FeatureList; +import org.chromium.base.ObserverList; +import org.chromium.base.supplier.Supplier; +import org.chromium.chrome.browser.tab.Tab; +import org.chromium.chrome.browser.toolbar.adaptive.AdaptiveToolbarFeatures; +import org.chromium.chrome.browser.toolbar.adaptive.AdaptiveToolbarFeatures.AdaptiveToolbarButtonVariant; +import org.chromium.chrome.browser.user_education.IPHCommandBuilder; +import org.chromium.ui.modaldialog.ModalDialogManager; +import org.chromium.ui.modaldialog.ModalDialogManager.ModalDialogManagerObserver; +import org.chromium.ui.modelutil.PropertyModel; + +/** + * Base class for button data providers used on the adaptive toolbar. + */ +public abstract class BaseButtonDataProvider implements ButtonDataProvider, OnClickListener { + protected final ButtonDataImpl mButtonData; + protected final Supplier<Tab> mActiveTabSupplier; + + private final ObserverList<ButtonDataObserver> mObservers = new ObserverList<>(); + private final ModalDialogManager mModalDialogManager; + private ModalDialogManagerObserver mModalDialogObserver; + + private boolean mShouldShowOnIncognitoTabs; + + /** + * Creates a new instance of {@code BaseButtonDataProvider}. + * @param activeTabSupplier Supplier for the current active tab. + * @param modalDialogManager Modal dialog manager, used to disable the button when a dialog is + * visible. Can be null to disable this behavior. + * @param buttonDrawable Drawable for the button icon. + * @param contentDescriptionResId Resource ID for the button's content description. + * @param supportsTinting Whether the button's icon should be tinted. + * @param iphCommandBuilder An IPH command builder instance to show when the button is + * displayed, can be null. + * @param adaptiveButtonVariant Enum value of {@link AdaptiveToolbarButtonVariant}, used for + * metrics. + */ + public BaseButtonDataProvider(Supplier<Tab> activeTabSupplier, + @Nullable ModalDialogManager modalDialogManager, Drawable buttonDrawable, + @StringRes int contentDescriptionResId, boolean supportsTinting, + @Nullable IPHCommandBuilder iphCommandBuilder, + @AdaptiveToolbarButtonVariant int adaptiveButtonVariant) { + mActiveTabSupplier = activeTabSupplier; + mModalDialogManager = modalDialogManager; + if (mModalDialogManager != null) { + mModalDialogObserver = new ModalDialogManagerObserver() { + @Override + public void onDialogAdded(PropertyModel model) { + mButtonData.setEnabled(false); + notifyObservers(mButtonData.canShow()); + } + + @Override + public void onLastDialogDismissed() { + mButtonData.setEnabled(true); + notifyObservers(mButtonData.canShow()); + } + }; + mModalDialogManager.addObserver(mModalDialogObserver); + } + + mButtonData = new ButtonDataImpl(/*canShow=*/false, buttonDrawable, + /* onClickListener= */ this, contentDescriptionResId, supportsTinting, + /* iphCommandBuilder= */ iphCommandBuilder, /*isEnabled=*/true, + adaptiveButtonVariant); + } + + /** + * Checks if the button should be shown for the current tab. Called every time {@code get()} is + * invoked. + * @param tab Current tab. + * @return whether the button should be shown for the current tab. + */ + @CallSuper + protected boolean shouldShowButton(Tab tab) { + if (tab == null) return false; + + if (tab.isIncognito() && !mShouldShowOnIncognitoTabs) return false; + + return true; + } + + protected void notifyObservers(boolean hint) { + for (ButtonDataObserver observer : mObservers) { + observer.buttonDataChanged(hint); + } + } + + /** + * Sets the button's {@link IPHCommandBuilder} if needed, called every time {@code get()} is + * invoked. + * @param tab Current tab. + */ + private void maybeSetIphCommandBuilder(Tab tab) { + if (mButtonData.getButtonSpec().getIPHCommandBuilder() != null || tab == null + || !FeatureList.isInitialized() + || !AdaptiveToolbarFeatures.isCustomizationEnabled()) { + return; + } + + mButtonData.updateIPHCommandBuilder(getIphCommandBuilder(tab)); + } + + /** + * Sets whether the button should be shown on incognito tabs, default is false. + */ + protected void setShouldShowOnIncognitoTabs(boolean shouldShowOnIncognitoTabs) { + mShouldShowOnIncognitoTabs = shouldShowOnIncognitoTabs; + } + + /** + * Gets an {@link IPHCommandBuilder} builder instance to use on this button. Only called when + * native is initialized and when there's no IPHCommandBuilder set. + * @param tab Current tab. + * @return An {@link org.chromium.chrome.browser.user_education.IPHCommand} instance to set on + * this button, or null if no IPH should be used. + */ + protected IPHCommandBuilder getIphCommandBuilder(Tab tab) { + return null; + } + + /** ButtonDataProvider implementation. */ + @Override + public void addObserver(ButtonDataObserver obs) { + mObservers.addObserver(obs); + } + + @Override + public void removeObserver(ButtonDataObserver obs) { + mObservers.removeObserver(obs); + } + + @Override + public ButtonData get(Tab tab) { + mButtonData.setCanShow(shouldShowButton(tab)); + maybeSetIphCommandBuilder(tab); + + return mButtonData; + } + + @Override + @CallSuper + public void destroy() { + mObservers.clear(); + if (mModalDialogManager != null) { + mModalDialogManager.removeObserver(mModalDialogObserver); + } + } + + /* OnClickListener implementation. */ + @Override + public abstract void onClick(View view); +}
diff --git a/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/VoiceToolbarButtonController.java b/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/VoiceToolbarButtonController.java index 071403ff..e6ef51bc 100644 --- a/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/VoiceToolbarButtonController.java +++ b/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/VoiceToolbarButtonController.java
@@ -4,20 +4,12 @@ package org.chromium.chrome.browser.toolbar; -import android.content.Context; -import android.content.res.Configuration; import android.graphics.drawable.Drawable; -import android.view.View.OnClickListener; - -import androidx.annotation.StringRes; +import android.view.View; import org.chromium.base.FeatureList; -import org.chromium.base.ObserverList; import org.chromium.base.metrics.RecordUserAction; import org.chromium.base.supplier.Supplier; -import org.chromium.chrome.browser.flags.ChromeFeatureList; -import org.chromium.chrome.browser.lifecycle.ActivityLifecycleDispatcher; -import org.chromium.chrome.browser.lifecycle.ConfigurationChangedObserver; import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.toolbar.adaptive.AdaptiveToolbarFeatures; import org.chromium.chrome.browser.toolbar.adaptive.AdaptiveToolbarFeatures.AdaptiveToolbarButtonVariant; @@ -29,8 +21,6 @@ import org.chromium.components.feature_engagement.FeatureConstants; import org.chromium.components.feature_engagement.Tracker; import org.chromium.ui.modaldialog.ModalDialogManager; -import org.chromium.ui.modaldialog.ModalDialogManager.ModalDialogManagerObserver; -import org.chromium.ui.modelutil.PropertyModel; /** * Handles displaying the voice search button on toolbar depending on several conditions (e.g. @@ -39,24 +29,11 @@ * TODO(crbug.com/1144976): Move this to ../voice/ along with VoiceRecognitionHandler and the * assistant support. */ -public class VoiceToolbarButtonController - implements ButtonDataProvider, ConfigurationChangedObserver { - private static final String IPH_PROMO_PARAM = "generic_message"; - - private final Supplier<Tab> mActiveTabSupplier; +public class VoiceToolbarButtonController extends BaseButtonDataProvider { private final Supplier<Tracker> mTrackerSupplier; - private final ActivityLifecycleDispatcher mActivityLifecycleDispatcher; - - private final ModalDialogManager mModalDialogManager; - private final ModalDialogManagerObserver mModalDialogManagerObserver; private final VoiceSearchDelegate mVoiceSearchDelegate; - private final ButtonDataImpl mButtonData; - private final ObserverList<ButtonDataObserver> mObservers = new ObserverList<>(); - - private int mScreenWidthDp; - /** * Delegate interface for interacting with voice search. */ @@ -74,169 +51,47 @@ /** * Creates a VoiceToolbarButtonController object. - * @param context The Context for retrieving resources, etc. * @param buttonDrawable Drawable for the voice button. * @param activeTabSupplier Provides the currently displayed {@link Tab}. * @param trackerSupplier Supplier for the current profile tracker. - * @param activityLifecycleDispatcher Dispatcher for activity lifecycle events, e.g. - * configuration changes. * @param modalDialogManager Dispatcher for modal lifecycle events * @param voiceSearchDelegate Provides interaction with voice search. */ - public VoiceToolbarButtonController(Context context, Drawable buttonDrawable, - Supplier<Tab> activeTabSupplier, Supplier<Tracker> trackerSupplier, - ActivityLifecycleDispatcher activityLifecycleDispatcher, - ModalDialogManager modalDialogManager, VoiceSearchDelegate voiceSearchDelegate) { - mActiveTabSupplier = activeTabSupplier; - mTrackerSupplier = trackerSupplier; - - // Register for onConfigurationChanged events, which notify on changes to screen width. - mActivityLifecycleDispatcher = activityLifecycleDispatcher; - mActivityLifecycleDispatcher.register(this); - - mModalDialogManagerObserver = new ModalDialogManagerObserver() { - @Override - public void onDialogAdded(PropertyModel model) { - mButtonData.setEnabled(false); - notifyObservers(mButtonData.canShow()); - } - - @Override - public void onLastDialogDismissed() { - mButtonData.setEnabled(true); - notifyObservers(mButtonData.canShow()); - } - }; - mModalDialogManager = modalDialogManager; - mModalDialogManager.addObserver(mModalDialogManagerObserver); - - mVoiceSearchDelegate = voiceSearchDelegate; - - OnClickListener onClickListener = (view) -> { - RecordUserAction.record("MobileTopToolbarVoiceButton"); - mVoiceSearchDelegate.startVoiceRecognition(); - - if (mTrackerSupplier.hasValue()) { - mTrackerSupplier.get().notifyEvent( - EventConstants.ADAPTIVE_TOOLBAR_CUSTOMIZATION_VOICE_SEARCH_OPENED); - } - }; - - mButtonData = new ButtonDataImpl(/*canShow=*/false, buttonDrawable, onClickListener, + public VoiceToolbarButtonController(Drawable buttonDrawable, Supplier<Tab> activeTabSupplier, + Supplier<Tracker> trackerSupplier, ModalDialogManager modalDialogManager, + VoiceSearchDelegate voiceSearchDelegate) { + super(activeTabSupplier, modalDialogManager, buttonDrawable, R.string.accessibility_toolbar_btn_mic, - /*supportsTinting=*/true, /*iphCommandBuilder=*/null, /*isEnabled=*/true, + /* supportsTinting= */ true, /* iphCommandBuilder= */ null, AdaptiveToolbarButtonVariant.VOICE); - - mScreenWidthDp = context.getResources().getConfiguration().screenWidthDp; + mTrackerSupplier = trackerSupplier; + mVoiceSearchDelegate = voiceSearchDelegate; } @Override - public void onConfigurationChanged(Configuration configuration) { - if (mScreenWidthDp == configuration.screenWidthDp) { - return; + public void onClick(View view) { + RecordUserAction.record("MobileTopToolbarVoiceButton"); + mVoiceSearchDelegate.startVoiceRecognition(); + + if (mTrackerSupplier.hasValue()) { + mTrackerSupplier.get().notifyEvent( + EventConstants.ADAPTIVE_TOOLBAR_CUSTOMIZATION_VOICE_SEARCH_OPENED); } - mScreenWidthDp = configuration.screenWidthDp; - mButtonData.setCanShow(shouldShowVoiceButton(mActiveTabSupplier.get())); - notifyObservers(mButtonData.canShow()); } /** Triggers checking and possibly updating the mic visibility */ public void updateMicButtonState() { - mButtonData.setCanShow(shouldShowVoiceButton(mActiveTabSupplier.get())); + mButtonData.setCanShow(shouldShowButton(mActiveTabSupplier.get())); notifyObservers(mButtonData.canShow()); } - @Override - public void destroy() { - mActivityLifecycleDispatcher.unregister(this); - mModalDialogManager.removeObserver(mModalDialogManagerObserver); - mObservers.clear(); - } - - @Override - public void addObserver(ButtonDataObserver obs) { - mObservers.addObserver(obs); - } - - @Override - public void removeObserver(ButtonDataObserver obs) { - mObservers.removeObserver(obs); - } - - @Override - public ButtonData get(Tab tab) { - mButtonData.setCanShow(shouldShowVoiceButton(tab)); - maybeSetIphCommandBuilder(tab); - return mButtonData; - } - /** - * Since Features are not yet initialized when ButtonData is created, use the - * fist available opportunity to create and set IPHCommandBuilder. Once set it's - * never updated. + * Returns an IPH for this button. Only called once native is initialized and when {@code + * AdaptiveToolbarFeatures.isCustomizationEnabled()} is true. + * @param tab Current tab. */ - private void maybeSetIphCommandBuilder(Tab tab) { - if (mButtonData.getButtonSpec().getIPHCommandBuilder() != null || tab == null - || !FeatureList.isInitialized()) { - return; - } - - IPHCommandBuilder iphCommandBuilder = null; - if (AdaptiveToolbarFeatures.isCustomizationEnabled()) { - iphCommandBuilder = createCustomizationIPHCommandBuilder(tab); - } else { - // No IPH features enabled. - return; - } - - mButtonData.updateIPHCommandBuilder(iphCommandBuilder); - } - - private boolean shouldShowVoiceButton(Tab tab) { - if (tab == null || tab.isIncognito() || !mVoiceSearchDelegate.isVoiceSearchEnabled()) { - return false; - } - - boolean isDeviceWideEnough = - mScreenWidthDp >= AdaptiveToolbarFeatures.getDeviceMinimumWidthForShowingButton(); - if (!isDeviceWideEnough) return false; - - return UrlUtilities.isHttpOrHttps(tab.getUrl()); - } - - /** Returns whether the feature flags allow showing the mic icon in the toolbar. */ - public static boolean isToolbarMicEnabled() { - if (!FeatureList.isInitialized()) return false; - return AdaptiveToolbarFeatures.isCustomizationEnabled(); - } - - private void notifyObservers(boolean hint) { - for (ButtonDataObserver observer : mObservers) { - observer.buttonDataChanged(hint); - } - } - - private IPHCommandBuilder createVoiceButtonIPHCommandBuilder(Tab tab) { - boolean useGenericMessage = ChromeFeatureList.getFieldTrialParamByFeatureAsBoolean( - ChromeFeatureList.TOOLBAR_MIC_IPH_ANDROID, IPH_PROMO_PARAM, true); - @StringRes - int text = useGenericMessage ? R.string.iph_mic_toolbar_generic_message_text - : R.string.iph_mic_toolbar_example_query_text; - @StringRes - int accessibilityText = - useGenericMessage ? R.string.iph_mic_toolbar_generic_message_accessibility_text - : R.string.iph_mic_toolbar_example_query_accessibility_text; - - HighlightParams params = new HighlightParams(HighlightShape.CIRCLE); - params.setBoundsRespectPadding(true); - IPHCommandBuilder iphCommandBuilder = new IPHCommandBuilder(tab.getContext().getResources(), - FeatureConstants.IPH_MIC_TOOLBAR_FEATURE, text, accessibilityText) - .setHighlightParams(params); - - return iphCommandBuilder; - } - - private IPHCommandBuilder createCustomizationIPHCommandBuilder(Tab tab) { + @Override + protected IPHCommandBuilder getIphCommandBuilder(Tab tab) { HighlightParams params = new HighlightParams(HighlightShape.CIRCLE); params.setBoundsRespectPadding(true); IPHCommandBuilder iphCommandBuilder = new IPHCommandBuilder(tab.getContext().getResources(), @@ -247,4 +102,18 @@ return iphCommandBuilder; } + + @Override + protected boolean shouldShowButton(Tab tab) { + if (!super.shouldShowButton(tab)) return false; + + return mVoiceSearchDelegate.isVoiceSearchEnabled() + && UrlUtilities.isHttpOrHttps(tab.getUrl()); + } + + /** Returns whether the feature flags allow showing the mic icon in the toolbar. */ + public static boolean isToolbarMicEnabled() { + if (!FeatureList.isInitialized()) return false; + return AdaptiveToolbarFeatures.isCustomizationEnabled(); + } }
diff --git a/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/VoiceToolbarButtonControllerUnitTest.java b/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/VoiceToolbarButtonControllerUnitTest.java index 6d11ea6..bb17b52 100644 --- a/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/VoiceToolbarButtonControllerUnitTest.java +++ b/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/VoiceToolbarButtonControllerUnitTest.java
@@ -5,7 +5,6 @@ package org.chromium.chrome.browser.toolbar; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; @@ -116,8 +115,8 @@ doReturn(mContext).when(mTab).getContext(); AdaptiveToolbarFeatures.clearParsedParamsForTesting(); // clang-format off - mVoiceToolbarButtonController = new VoiceToolbarButtonController(mContext, mDrawable, - () -> mTab, () -> mTracker, mActivityLifecycleDispatcher, mModalDialogManager, + mVoiceToolbarButtonController = new VoiceToolbarButtonController(mDrawable, + () -> mTab, () -> mTracker, mModalDialogManager, mVoiceSearchDelegate); // clang-format on @@ -125,24 +124,6 @@ } @Test - @EnableFeatures({ChromeFeatureList.ADAPTIVE_BUTTON_IN_TOP_TOOLBAR_CUSTOMIZATION_V2}) - public void onConfigurationChanged_screenWidthChanged() { - assertTrue(mVoiceToolbarButtonController.get(mTab).canShow()); - - // Screen width shrinks below the threshold (e.g. screen rotated). - mConfiguration.screenWidthDp = AdaptiveToolbarFeatures.DEFAULT_MIN_WIDTH_DP - 1; - mVoiceToolbarButtonController.onConfigurationChanged(mConfiguration); - - assertFalse(mVoiceToolbarButtonController.get(mTab).canShow()); - - // Make sure the opposite works as well. - mConfiguration.screenWidthDp = AdaptiveToolbarFeatures.DEFAULT_MIN_WIDTH_DP; - mVoiceToolbarButtonController.onConfigurationChanged(mConfiguration); - - assertTrue(mVoiceToolbarButtonController.get(mTab).canShow()); - } - - @Test @EnableFeatures({ChromeFeatureList.ADAPTIVE_BUTTON_IN_TOP_TOOLBAR_CUSTOMIZATION_V2, ChromeFeatureList.TOOLBAR_MIC_IPH_ANDROID}) public void
diff --git a/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/adaptive/AdaptiveToolbarButtonController.java b/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/adaptive/AdaptiveToolbarButtonController.java index 03ac1c7d..8aecc30c 100644 --- a/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/adaptive/AdaptiveToolbarButtonController.java +++ b/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/adaptive/AdaptiveToolbarButtonController.java
@@ -8,6 +8,7 @@ import static org.chromium.chrome.browser.preferences.ChromePreferenceKeys.ADAPTIVE_TOOLBAR_CUSTOMIZATION_SETTINGS; import android.content.Context; +import android.content.res.Configuration; import android.view.View; import androidx.annotation.Nullable; @@ -19,6 +20,7 @@ import org.chromium.base.metrics.RecordHistogram; import org.chromium.base.metrics.RecordUserAction; import org.chromium.chrome.browser.lifecycle.ActivityLifecycleDispatcher; +import org.chromium.chrome.browser.lifecycle.ConfigurationChangedObserver; import org.chromium.chrome.browser.lifecycle.NativeInitObserver; import org.chromium.chrome.browser.preferences.SharedPreferencesManager; import org.chromium.chrome.browser.tab.Tab; @@ -38,9 +40,9 @@ import java.util.Map; /** Meta {@link ButtonDataProvider} which chooses the optional button variant that will be shown. */ -public class AdaptiveToolbarButtonController implements ButtonDataProvider, ButtonDataObserver, - NativeInitObserver, - SharedPreferencesManager.Observer { +public class AdaptiveToolbarButtonController + implements ButtonDataProvider, ButtonDataObserver, NativeInitObserver, + SharedPreferencesManager.Observer, ConfigurationChangedObserver { private ObserverList<ButtonDataObserver> mObservers = new ObserverList<>(); @Nullable private ButtonDataProvider mSingleProvider; @@ -69,6 +71,7 @@ private View.OnLongClickListener mMenuHandler; private final Callback<Integer> mMenuClickListener; private final AdaptiveButtonActionMenuCoordinator mMenuCoordinator; + private int mScreenWidthDp; @AdaptiveToolbarButtonVariant private int mSessionButtonVariant = AdaptiveToolbarButtonVariant.UNKNOWN; @@ -101,6 +104,7 @@ mMenuCoordinator = menuCoordinator; mSharedPreferencesManager = sharedPreferencesManager; mSharedPreferencesManager.addObserver(this); + mScreenWidthDp = context.getResources().getConfiguration().screenWidthDp; } /** @@ -184,7 +188,7 @@ AdaptiveToolbarButtonVariant.NUM_ENTRIES); } - mButtonData.setCanShow(receivedButtonData.canShow()); + mButtonData.setCanShow(receivedButtonData.canShow() && isScreenWideEnoughForButton()); mButtonData.setEnabled(receivedButtonData.isEnabled()); final ButtonSpec receivedButtonSpec = receivedButtonData.getButtonSpec(); // ButtonSpec is immutable, so we keep the previous value when noting changes. @@ -258,6 +262,10 @@ } } + private boolean isScreenWideEnoughForButton() { + return mScreenWidthDp >= AdaptiveToolbarFeatures.getDeviceMinimumWidthForShowingButton(); + } + /** Returns the {@link ButtonDataProvider} used in a single-variant mode. */ @Nullable @VisibleForTesting @@ -289,4 +297,20 @@ setSingleProvider(actionToShow); notifyObservers(true); } + + @Override + public void onConfigurationChanged(Configuration newConfig) { + if (!mLifecycleDispatcher.isNativeInitializationFinished() + || mScreenWidthDp == newConfig.screenWidthDp) { + return; + } + + boolean wasOldScreenWideEnoughForButton = isScreenWideEnoughForButton(); + + mScreenWidthDp = newConfig.screenWidthDp; + + if (wasOldScreenWideEnoughForButton != isScreenWideEnoughForButton()) { + notifyObservers(mButtonData.canShow()); + } + } }
diff --git a/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/adaptive/AdaptiveToolbarButtonControllerTest.java b/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/adaptive/AdaptiveToolbarButtonControllerTest.java index 67a83fa..13ccdc01 100644 --- a/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/adaptive/AdaptiveToolbarButtonControllerTest.java +++ b/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/adaptive/AdaptiveToolbarButtonControllerTest.java
@@ -8,6 +8,7 @@ import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -15,6 +16,8 @@ import static org.chromium.chrome.browser.preferences.ChromePreferenceKeys.ADAPTIVE_TOOLBAR_CUSTOMIZATION_SETTINGS; import android.app.Activity; +import android.content.res.Configuration; +import android.content.res.Resources; import android.util.Pair; import android.view.View; import android.view.View.OnLongClickListener; @@ -78,6 +81,8 @@ private ActivityLifecycleDispatcher mActivityLifecycleDispatcher; @Mock private Tab mTab; + @Mock + private Configuration mConfiguration; private ButtonDataImpl mButtonData; @@ -92,6 +97,7 @@ /*contentDescriptionResId=*/0, /*supportsTinting=*/false, /*iphCommandBuilder=*/null, /*isEnabled=*/true, AdaptiveToolbarButtonVariant.UNKNOWN); + mConfiguration.screenWidthDp = 420; } @After @@ -300,10 +306,131 @@ adaptiveToolbarButtonController.destroy(); } + @Test + @SmallTest + @EnableFeatures({ChromeFeatureList.ADAPTIVE_BUTTON_IN_TOP_TOOLBAR_CUSTOMIZATION_V2}) + @DisableFeatures({ChromeFeatureList.ADAPTIVE_BUTTON_IN_TOP_TOOLBAR}) + public void testButtonOnLargeScreens() { + // Screen is wide enough to fit the button, it should appear. + mConfiguration.screenWidthDp = 450; + mButtonData.setCanShow(true); + mButtonData.setEnabled(true); + when(mVoiceToolbarButtonController.get(any())).thenReturn(mButtonData); + + AdaptiveToolbarPrefs.saveToolbarSettingsToggleState(true); + AdaptiveToolbarStatePredictor.setSegmentationResultsForTesting( + new Pair<>(true, AdaptiveToolbarButtonVariant.VOICE)); + + AdaptiveToolbarButtonController adaptiveToolbarButtonController = buildController(); + + ButtonDataObserver observer = mock(ButtonDataObserver.class); + adaptiveToolbarButtonController.addObserver(observer); + adaptiveToolbarButtonController.onFinishNativeInitialization(); + + verify(observer).buttonDataChanged(true); + Assert.assertEquals(mVoiceToolbarButtonController, + adaptiveToolbarButtonController.getSingleProviderForTesting()); + + Assert.assertTrue(adaptiveToolbarButtonController.get(mTab).canShow()); + } + + @Test + @SmallTest + @EnableFeatures({ChromeFeatureList.ADAPTIVE_BUTTON_IN_TOP_TOOLBAR_CUSTOMIZATION_V2}) + @DisableFeatures({ChromeFeatureList.ADAPTIVE_BUTTON_IN_TOP_TOOLBAR}) + public void testButtonNotShownOnSmallScreens() { + // Screen too narrow, button shouldn't appear. + mConfiguration.screenWidthDp = 320; + mButtonData.setCanShow(true); + mButtonData.setEnabled(true); + when(mVoiceToolbarButtonController.get(any())).thenReturn(mButtonData); + + AdaptiveToolbarPrefs.saveToolbarSettingsToggleState(true); + AdaptiveToolbarStatePredictor.setSegmentationResultsForTesting( + new Pair<>(true, AdaptiveToolbarButtonVariant.VOICE)); + + AdaptiveToolbarButtonController adaptiveToolbarButtonController = buildController(); + + ButtonDataObserver observer = mock(ButtonDataObserver.class); + adaptiveToolbarButtonController.addObserver(observer); + adaptiveToolbarButtonController.onFinishNativeInitialization(); + + verify(observer).buttonDataChanged(true); + Assert.assertEquals(mVoiceToolbarButtonController, + adaptiveToolbarButtonController.getSingleProviderForTesting()); + + Assert.assertFalse(adaptiveToolbarButtonController.get(mTab).canShow()); + } + + @Test + @SmallTest + @EnableFeatures({ChromeFeatureList.ADAPTIVE_BUTTON_IN_TOP_TOOLBAR_CUSTOMIZATION_V2}) + @DisableFeatures({ChromeFeatureList.ADAPTIVE_BUTTON_IN_TOP_TOOLBAR}) + public void testButtonVisibilityChangeOnConfigurationChange() { + // Screen too narrow, button shouldn't appear. + mConfiguration.screenWidthDp = 320; + mButtonData.setCanShow(true); + mButtonData.setEnabled(true); + when(mVoiceToolbarButtonController.get(any())).thenReturn(mButtonData); + doReturn(true).when(mActivityLifecycleDispatcher).isNativeInitializationFinished(); + + AdaptiveToolbarPrefs.saveToolbarSettingsToggleState(true); + AdaptiveToolbarStatePredictor.setSegmentationResultsForTesting( + new Pair<>(true, AdaptiveToolbarButtonVariant.VOICE)); + + AdaptiveToolbarButtonController adaptiveToolbarButtonController = buildController(); + + ButtonDataObserver observer = mock(ButtonDataObserver.class); + adaptiveToolbarButtonController.addObserver(observer); + adaptiveToolbarButtonController.onFinishNativeInitialization(); + + verify(observer).buttonDataChanged(true); + Assert.assertEquals(mVoiceToolbarButtonController, + adaptiveToolbarButtonController.getSingleProviderForTesting()); + + Assert.assertFalse(adaptiveToolbarButtonController.get(mTab).canShow()); + + // New screen configuration is wider, button should be visible. + mConfiguration.screenWidthDp = 450; + + adaptiveToolbarButtonController.onConfigurationChanged(mConfiguration); + + verify(observer).buttonDataChanged(false); + Assert.assertTrue(adaptiveToolbarButtonController.get(mTab).canShow()); + } + + @Test + @SmallTest + @EnableFeatures({ChromeFeatureList.ADAPTIVE_BUTTON_IN_TOP_TOOLBAR_CUSTOMIZATION_V2}) + @DisableFeatures({ChromeFeatureList.ADAPTIVE_BUTTON_IN_TOP_TOOLBAR}) + public void testConfigurationChangeIgnoredWhenNativeNotReady() { + AdaptiveToolbarPrefs.saveToolbarSettingsToggleState(true); + AdaptiveToolbarStatePredictor.setSegmentationResultsForTesting( + new Pair<>(true, AdaptiveToolbarButtonVariant.VOICE)); + // If native is not done initializing then ignore all configuration changes. + doReturn(false).when(mActivityLifecycleDispatcher).isNativeInitializationFinished(); + + AdaptiveToolbarButtonController adaptiveToolbarButtonController = buildController(); + + ButtonDataObserver observer = mock(ButtonDataObserver.class); + adaptiveToolbarButtonController.addObserver(observer); + + // Change configuration, button shouldn't update. + mConfiguration.screenWidthDp = 320; + adaptiveToolbarButtonController.onConfigurationChanged(mConfiguration); + + verify(observer, never()).buttonDataChanged(true); + } + private AdaptiveToolbarButtonController buildController() { + Activity mockActivity = mock(Activity.class); + Resources mockResources = mock(Resources.class); + doReturn(mockResources).when(mockActivity).getResources(); + doReturn(mConfiguration).when(mockResources).getConfiguration(); + AdaptiveToolbarButtonController adaptiveToolbarButtonController = - new AdaptiveToolbarButtonController(mock(Activity.class), - mock(SettingsLauncher.class), mActivityLifecycleDispatcher, + new AdaptiveToolbarButtonController(mockActivity, mock(SettingsLauncher.class), + mActivityLifecycleDispatcher, mock(AdaptiveButtonActionMenuCoordinator.class), mAndroidPermissionDelegate, SharedPreferencesManager.getInstance()); adaptiveToolbarButtonController.addButtonVariant(
diff --git a/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/adaptive/OptionalNewTabButtonController.java b/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/adaptive/OptionalNewTabButtonController.java index b3f898dc..7635168 100644 --- a/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/adaptive/OptionalNewTabButtonController.java +++ b/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/adaptive/OptionalNewTabButtonController.java
@@ -12,8 +12,6 @@ import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; -import org.chromium.base.FeatureList; -import org.chromium.base.ObserverList; import org.chromium.base.metrics.RecordUserAction; import org.chromium.base.supplier.Supplier; import org.chromium.chrome.browser.lifecycle.ActivityLifecycleDispatcher; @@ -21,9 +19,7 @@ import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.tabmodel.TabCreatorManager; import org.chromium.chrome.browser.tabmodel.TabModelSelector; -import org.chromium.chrome.browser.toolbar.ButtonData; -import org.chromium.chrome.browser.toolbar.ButtonDataImpl; -import org.chromium.chrome.browser.toolbar.ButtonDataProvider; +import org.chromium.chrome.browser.toolbar.BaseButtonDataProvider; import org.chromium.chrome.browser.toolbar.R; import org.chromium.chrome.browser.toolbar.adaptive.AdaptiveToolbarFeatures.AdaptiveToolbarButtonVariant; import org.chromium.chrome.browser.user_education.IPHCommandBuilder; @@ -40,7 +36,7 @@ * AdaptiveToolbarButtonController}. */ public class OptionalNewTabButtonController - implements ButtonDataProvider, ConfigurationChangedObserver { + extends BaseButtonDataProvider implements ConfigurationChangedObserver { /** * Set of methods used to interact with dependencies which may require native libraries to * function. Robolectric tests can use shadows to inject dependencies in tests. @@ -48,12 +44,12 @@ @VisibleForTesting /* package */ static class Delegate { private final Supplier<TabCreatorManager> mTabCreatorManagerSupplier; - private final Supplier<TabModelSelector> mTabModelSelectorSupplier; + private final Supplier<Tab> mActiveTabSupplier; public Delegate(Supplier<TabCreatorManager> tabCreatorManagerSupplier, - Supplier<TabModelSelector> tabModelSelectorSupplier) { + Supplier<Tab> activeTabSupplier) { mTabCreatorManagerSupplier = tabCreatorManagerSupplier; - mTabModelSelectorSupplier = tabModelSelectorSupplier; + mActiveTabSupplier = activeTabSupplier; } /** Returns a {@link TabCreatorManager} used for creating the new tab. */ @@ -72,21 +68,18 @@ * <p>TODO(crbug.com/1185948): Make IncognitoStateProvider available in RootUiCooridnator. */ @Nullable - TabModelSelector getTabModelSelector() { - return mTabModelSelectorSupplier.get(); + Supplier<Tab> getActiveTabSupplier() { + return mActiveTabSupplier; } } /** Context used for fetching resources and window size. */ private final Context mContext; private final Delegate mDelegate; - private final ActivityLifecycleDispatcher mActivityLifecycleDispatcher; - private final ButtonDataImpl mButtonData; - private final ObserverList<ButtonDataObserver> mObservers = new ObserverList<>(); private final Supplier<Tracker> mTrackerSupplier; private boolean mIsTablet; - private int mScreenWidthDp; + private final ActivityLifecycleDispatcher mActivityLifecycleDispatcher; /** * Creates {@code OptionalNewTabButtonController}. @@ -96,137 +89,73 @@ * @param activityLifecycleDispatcher Dispatcher for activity lifecycle events, e.g. * configuration changes. * @param tabCreatorManagerSupplier Used to open new tabs. - * @param tabModelSelectorSupplier Used to access the current incognito state. + * @param activeTabSupplier Used to access the current tab. * @param trackerSupplier Supplier for the current profile tracker. */ public OptionalNewTabButtonController(Context context, Drawable buttonDrawable, ActivityLifecycleDispatcher activityLifecycleDispatcher, - Supplier<TabCreatorManager> tabCreatorManagerSupplier, - Supplier<TabModelSelector> tabModelSelectorSupplier, + Supplier<TabCreatorManager> tabCreatorManagerSupplier, Supplier<Tab> activeTabSupplier, Supplier<Tracker> trackerSupplier) { + super(activeTabSupplier, /* modalDialogManager= */ null, buttonDrawable, + R.string.button_new_tab, + /*supportsTinting= */ true, /* iphCommandBuilder= */ null, + AdaptiveToolbarButtonVariant.NEW_TAB); + setShouldShowOnIncognitoTabs(true); + mContext = context; + mDelegate = new Delegate(tabCreatorManagerSupplier, activeTabSupplier); + mTrackerSupplier = trackerSupplier; mActivityLifecycleDispatcher = activityLifecycleDispatcher; mActivityLifecycleDispatcher.register(this); - mDelegate = new Delegate(tabCreatorManagerSupplier, tabModelSelectorSupplier); - mTrackerSupplier = trackerSupplier; - - View.OnClickListener onClickListener = view -> { - TabModelSelector tabModelSelector = mDelegate.getTabModelSelector(); - if (tabModelSelector == null) return; - - TabCreatorManager tabCreatorManager = mDelegate.getTabCreatorManager(); - if (tabCreatorManager == null) return; - - boolean isIncognito = tabModelSelector.isIncognitoSelected(); - RecordUserAction.record("MobileTopToolbarOptionalButtonNewTab"); - tabCreatorManager.getTabCreator(isIncognito).launchNTP(); - - if (mTrackerSupplier.hasValue()) { - mTrackerSupplier.get().notifyEvent( - EventConstants.ADAPTIVE_TOOLBAR_CUSTOMIZATION_NEW_TAB_OPENED); - } - }; - - mButtonData = new ButtonDataImpl(/*canShow=*/false, buttonDrawable, onClickListener, - R.string.button_new_tab, /*supportsTinting=*/true, - /*iphCommandBuilder=*/null, - /*isEnabled=*/true, AdaptiveToolbarButtonVariant.NEW_TAB); mIsTablet = DeviceFormFactor.isNonMultiDisplayContextOnTablet(mContext); - mScreenWidthDp = mContext.getResources().getConfiguration().screenWidthDp; } @Override - public void destroy() { - mActivityLifecycleDispatcher.unregister(this); - mObservers.clear(); + public void onClick(View view) { + Supplier<Tab> activeTabSupplier = mDelegate.getActiveTabSupplier(); + if (activeTabSupplier == null || activeTabSupplier.get() == null) return; + + TabCreatorManager tabCreatorManager = mDelegate.getTabCreatorManager(); + if (tabCreatorManager == null) return; + + boolean isIncognito = activeTabSupplier.get().isIncognito(); + RecordUserAction.record("MobileTopToolbarOptionalButtonNewTab"); + tabCreatorManager.getTabCreator(isIncognito).launchNTP(); + + if (mTrackerSupplier.hasValue()) { + mTrackerSupplier.get().notifyEvent( + EventConstants.ADAPTIVE_TOOLBAR_CUSTOMIZATION_NEW_TAB_OPENED); + } } @Override public void onConfigurationChanged(Configuration configuration) { boolean isTablet = DeviceFormFactor.isNonMultiDisplayContextOnTablet(mContext); - if (mScreenWidthDp == configuration.screenWidthDp && mIsTablet == isTablet) { + if (mIsTablet == isTablet) { return; } - mScreenWidthDp = configuration.screenWidthDp; mIsTablet = isTablet; - updateCanShow(getCurrentTab()); - notifyObservers(mButtonData.canShow()); + + mButtonData.setCanShow(shouldShowButton(mActiveTabSupplier.get())); } @Override - public void addObserver(ButtonDataObserver obs) { - mObservers.addObserver(obs); - } + protected boolean shouldShowButton(Tab tab) { + if (!super.shouldShowButton(tab) || mIsTablet) return false; - @Override - public void removeObserver(ButtonDataObserver obs) { - mObservers.removeObserver(obs); - } - - @Override - public ButtonData get(Tab tab) { - updateCanShow(tab); - maybeSetIphCommandBuilder(tab); - return mButtonData; - } - - /** - * Notifies each observer that the {@link ButtonData} provided by this {@link - * ButtonDataProvider} has changed. - * - * @see #get(Tab) - * @param canShowHint Hints whether the provided button can be shown. - */ - private void notifyObservers(boolean canShowHint) { - for (ButtonDataObserver observer : mObservers) { - observer.buttonDataChanged(canShowHint); - } - } - - @Nullable - private Tab getCurrentTab() { - TabModelSelector tabModelSelector = mDelegate.getTabModelSelector(); - if (tabModelSelector == null) return null; - return tabModelSelector.getCurrentTab(); - } - - private void updateCanShow(@Nullable Tab tab) { - mButtonData.setCanShow(calculateCanShow(tab)); - } - - private boolean calculateCanShow(@Nullable Tab tab) { - if (tab == null || tab.getWebContents() == null) { - return false; - } - // The screen is too narrow to fit the icon. - if (mScreenWidthDp < AdaptiveToolbarFeatures.getDeviceMinimumWidthForShowingButton()) { - return false; - } - // On tablets a new tab button is shown on the tab strip. - if (mIsTablet) { - return false; - } - // Don't show on the NTP. - if (UrlUtilities.isNTPUrl(tab.getUrl())) { - return false; - } + if (UrlUtilities.isNTPUrl(tab.getUrl())) return false; return true; } /** - * Since Features are not yet initialized when ButtonData is created, use the - * fist available opportunity to create and set IPHCommandBuilder. Once set it's - * never updated. + * Returns an IPH for this button. Only called once native is initialized and when {@code + * AdaptiveToolbarFeatures.isCustomizationEnabled()} is true. + * @param tab Current tab. */ - private void maybeSetIphCommandBuilder(Tab tab) { - if (mButtonData.getButtonSpec().getIPHCommandBuilder() != null || tab == null - || !FeatureList.isInitialized() - || !AdaptiveToolbarFeatures.isCustomizationEnabled()) { - return; - } - + @Override + protected IPHCommandBuilder getIphCommandBuilder(Tab tab) { HighlightParams params = new HighlightParams(HighlightShape.CIRCLE); params.setBoundsRespectPadding(true); IPHCommandBuilder iphCommandBuilder = new IPHCommandBuilder(tab.getContext().getResources(), @@ -234,6 +163,6 @@ /* stringId = */ R.string.adaptive_toolbar_button_new_tab_iph, /* accessibilityStringId = */ R.string.adaptive_toolbar_button_new_tab_iph) .setHighlightParams(params); - mButtonData.updateIPHCommandBuilder(iphCommandBuilder); + return iphCommandBuilder; } }
diff --git a/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/adaptive/OptionalNewTabButtonControllerUnitTest.java b/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/adaptive/OptionalNewTabButtonControllerUnitTest.java index 3ebdb44..62afb12 100644 --- a/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/adaptive/OptionalNewTabButtonControllerUnitTest.java +++ b/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/adaptive/OptionalNewTabButtonControllerUnitTest.java
@@ -29,6 +29,7 @@ import org.robolectric.RuntimeEnvironment; import org.robolectric.annotation.Config; +import org.chromium.base.supplier.Supplier; import org.chromium.base.test.BaseRobolectricTestRunner; import org.chromium.chrome.browser.feature_engagement.TrackerFactory; import org.chromium.chrome.browser.flags.ChromeFeatureList; @@ -36,13 +37,13 @@ import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.tabmodel.TabCreator; import org.chromium.chrome.browser.tabmodel.TabCreatorManager; -import org.chromium.chrome.browser.tabmodel.TabModelSelector; import org.chromium.chrome.browser.user_education.IPHCommandBuilder; import org.chromium.chrome.test.util.browser.Features; import org.chromium.chrome.test.util.browser.Features.EnableFeatures; import org.chromium.components.feature_engagement.EventConstants; import org.chromium.components.feature_engagement.FeatureConstants; import org.chromium.components.feature_engagement.Tracker; +import org.chromium.url.JUnitTestGURLs; /** Unit tests for {@link OptionalNewTabButtonController}. */ @RunWith(BaseRobolectricTestRunner.class) @@ -68,7 +69,7 @@ @Mock TabCreator mTabCreator; @Mock - private TabModelSelector mTabModelSelector; + private Supplier<Tab> mTabSupplier; @Mock private Tracker mTracker; @@ -80,8 +81,11 @@ MockitoAnnotations.initMocks(this); mContext = RuntimeEnvironment.application; + doReturn(JUnitTestGURLs.getGURL(JUnitTestGURLs.EXAMPLE_URL)).when(mTab).getUrl(); doReturn(mContext).when(mTab).getContext(); + doReturn(mTab).when(mTabSupplier).get(); + mConfiguration.screenWidthDp = AdaptiveToolbarFeatures.DEFAULT_MIN_WIDTH_DP + WIDTH_DELTA; doReturn(mConfiguration).when(mResources).getConfiguration(); @@ -91,7 +95,7 @@ mOptionalNewTabButtonController = new OptionalNewTabButtonController(mContext, mDrawable, mActivityLifecycleDispatcher, - () -> mTabCreatorManager, () -> mTabModelSelector, () -> mTracker); + () -> mTabCreatorManager, mTabSupplier, () -> mTracker); TrackerFactory.setTrackerForTests(mTracker); }
diff --git a/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/top/ToolbarControlContainer.java b/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/top/ToolbarControlContainer.java index 6ad32d2b8..876408f 100644 --- a/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/top/ToolbarControlContainer.java +++ b/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/top/ToolbarControlContainer.java
@@ -280,6 +280,14 @@ CaptureReadinessResult isReadyResult = mToolbar == null ? null : mToolbar.isReadyForTextureCapture(); + if (isReadyResult != null + && isReadyResult.blockReason == TopToolbarBlockCaptureReason.SNAPSHOT_SAME) { + // If our view was invalidated but no meaningful properties have changed (which is + // what SNAPSHOT_SAME implies), we can safely avoid re-checking until the next view + // invalidation. + setDirtyRectEmpty(); + } + CaptureReadinessResult.logCaptureReasonFromResult(isReadyResult); return isReadyResult == null ? false : isReadyResult.isReady; }
diff --git a/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/top/ToolbarControlContainerTest.java b/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/top/ToolbarControlContainerTest.java index 7c93023..955cfc81 100644 --- a/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/top/ToolbarControlContainerTest.java +++ b/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/top/ToolbarControlContainerTest.java
@@ -148,6 +148,7 @@ RecordHistogram.getHistogramValueCountForTesting( "Android.TopToolbar.BlockCaptureReason", TopToolbarBlockCaptureReason.SNAPSHOT_SAME)); + Assert.assertTrue(adapter.getDirtyRect().isEmpty()); } @Test
diff --git a/chrome/browser/ui/app_list/app_list_sort_browsertest.cc b/chrome/browser/ui/app_list/app_list_sort_browsertest.cc index 6c46f39..e3833390 100644 --- a/chrome/browser/ui/app_list/app_list_sort_browsertest.cc +++ b/chrome/browser/ui/app_list/app_list_sort_browsertest.cc
@@ -172,8 +172,7 @@ ASSERT_TRUE(client); client->UpdateProfile(); - // Since the ProductivityLauncher flag is enabled, the sort buttons will - // only be shown in tablet mode. + // Start in tablet mode. ash::ShellTestApi().SetTabletModeEnabledForTest(true); // Ensure async callbacks are run.
diff --git a/chrome/browser/ui/app_list/arc/arc_app_unittest.cc b/chrome/browser/ui/app_list/arc/arc_app_unittest.cc index bc671c2..0bfc84c 100644 --- a/chrome/browser/ui/app_list/arc/arc_app_unittest.cc +++ b/chrome/browser/ui/app_list/arc/arc_app_unittest.cc
@@ -2611,9 +2611,7 @@ } // Test that icon is correctly updated for suspended/non-suspended app. -// -// TODO(https://crbug.com/1211227): The test is flaky. -TEST_P(ArcAppModelBuilderTest, DISABLED_IconLoaderForSuspendedApps) { +TEST_P(ArcAppModelBuilderTest, IconLoaderForSuspendedApps) { std::vector<arc::mojom::AppInfoPtr> apps; apps.emplace_back(fake_apps()[0]->Clone()); const std::string app_id = ArcAppTest::GetAppId(*apps[0]); @@ -2640,8 +2638,7 @@ // is loaded and we only apply gray effect. apps[0]->suspended = true; SendPackageAppListRefreshed(apps[0]->package_name, apps); - EXPECT_EQ(update_count + 1, delegate.update_image_count()); - // No futher updates. + // One more update as suspended app icon turned grey. content::RunAllTasksUntilIdle(); EXPECT_EQ(update_count + 1, delegate.update_image_count());
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 eee5d6e0..8445f94 100644 --- a/chrome/browser/ui/app_list/arc/arc_app_utils.cc +++ b/chrome/browser/ui/app_list/arc/arc_app_utils.cc
@@ -38,6 +38,7 @@ #include "chrome/browser/ash/arc/boot_phase_monitor/arc_boot_phase_monitor_bridge.h" #include "chrome/browser/ash/arc/notification/arc_management_transition_notification.h" #include "chrome/browser/ash/arc/session/arc_session_manager.h" +#include "chrome/browser/ash/arc/window_predictor/window_predictor.h" #include "chrome/browser/ash/arc/window_predictor/window_predictor_utils.h" #include "chrome/browser/ash/login/login_pref_names.h" #include "chrome/browser/ash/policy/handlers/powerwash_requirements_checker.h" @@ -370,9 +371,9 @@ if (IsFixupWindowEnabled() && app_info->need_fixup) { // TODO(sstan): Use different UI after UX design finalized. - if (LaunchArcAppWithGhostWindow(profile, app_id, *app_info, event_flags, - user_action, GhostWindowType::kFixup, - window_info)) { + if (WindowPredictor::GetInstance()->LaunchArcAppWithGhostWindow( + profile, app_id, *app_info, event_flags, GhostWindowType::kFixup, + window_info)) { prefs->SetLastLaunchTime(app_id); return true; } @@ -380,9 +381,9 @@ return false; } else if (full_restore::features::IsArcWindowPredictorEnabled() && IsArcVmEnabled()) { - if (LaunchArcAppWithGhostWindow(profile, app_id, *app_info, event_flags, - user_action, GhostWindowType::kAppLaunch, - window_info)) { + if (WindowPredictor::GetInstance()->LaunchArcAppWithGhostWindow( + profile, app_id, *app_info, event_flags, + GhostWindowType::kAppLaunch, window_info)) { prefs->SetLastLaunchTime(app_id); return true; }
diff --git a/chrome/browser/ui/app_list/search/os_settings_provider.cc b/chrome/browser/ui/app_list/search/os_settings_provider.cc index ee843c2..6ed5850 100644 --- a/chrome/browser/ui/app_list/search/os_settings_provider.cc +++ b/chrome/browser/ui/app_list/search/os_settings_provider.cc
@@ -30,8 +30,8 @@ namespace app_list { namespace { -using SettingsResultPtr = chromeos::settings::mojom::SearchResultPtr; -using SettingsResultType = chromeos::settings::mojom::SearchResultType; +using SettingsResultPtr = ::ash::settings::mojom::SearchResultPtr; +using SettingsResultType = ::ash::settings::mojom::SearchResultType; using Setting = chromeos::settings::mojom::Setting; using Subpage = chromeos::settings::mojom::Subpage; using Section = chromeos::settings::mojom::Section; @@ -111,12 +111,11 @@ } // namespace -OsSettingsResult::OsSettingsResult( - Profile* profile, - const chromeos::settings::mojom::SearchResultPtr& result, - const double relevance_score, - const gfx::ImageSkia& icon, - const std::u16string& query) +OsSettingsResult::OsSettingsResult(Profile* profile, + const SettingsResultPtr& result, + const double relevance_score, + const gfx::ImageSkia& icon, + const std::u16string& query) : profile_(profile), url_path_(result->url_path_with_parameters) { set_id(kOsSettingsResultPrefix + url_path_); SetCategory(Category::kSettings); @@ -237,8 +236,7 @@ weak_factory_.InvalidateWeakPtrs(); search_handler_->Search( query, kNumRequestedResults, - chromeos::settings::mojom::ParentResultBehavior:: - kDoNotIncludeParentResults, + ash::settings::mojom::ParentResultBehavior::kDoNotIncludeParentResults, base::BindOnce(&OsSettingsProvider::OnSearchReturned, weak_factory_.GetWeakPtr(), query, start_time)); } @@ -250,7 +248,7 @@ void OsSettingsProvider::OnSearchReturned( const std::u16string& query, const base::TimeTicks& start_time, - std::vector<chromeos::settings::mojom::SearchResultPtr> sorted_results) { + std::vector<SettingsResultPtr> sorted_results) { DCHECK_LE(sorted_results.size(), kNumRequestedResults); SearchProvider::Results search_results; @@ -315,10 +313,9 @@ Start(last_query_); } -std::vector<chromeos::settings::mojom::SearchResultPtr> -OsSettingsProvider::FilterResults( +std::vector<SettingsResultPtr> OsSettingsProvider::FilterResults( const std::u16string& query, - const std::vector<chromeos::settings::mojom::SearchResultPtr>& results, + const std::vector<SettingsResultPtr>& results, const chromeos::settings::Hierarchy* hierarchy) { base::flat_set<std::string> seen_urls; base::flat_map<Subpage, double> seen_subpages;
diff --git a/chrome/browser/ui/app_list/search/os_settings_provider.h b/chrome/browser/ui/app_list/search/os_settings_provider.h index 85aea79..69adb856 100644 --- a/chrome/browser/ui/app_list/search/os_settings_provider.h +++ b/chrome/browser/ui/app_list/search/os_settings_provider.h
@@ -20,11 +20,14 @@ class Profile; +namespace ash::settings { +class SearchHandler; +} + namespace chromeos { namespace settings { class Hierarchy; class OsSettingsManager; -class SearchHandler; } // namespace settings } // namespace chromeos @@ -38,7 +41,7 @@ class OsSettingsResult : public ChromeSearchResult { public: OsSettingsResult(Profile* profile, - const chromeos::settings::mojom::SearchResultPtr& result, + const ash::settings::mojom::SearchResultPtr& result, double relevance_score, const gfx::ImageSkia& icon, const std::u16string& query); @@ -57,10 +60,9 @@ // Provider results for OS settings based on a search query. No results are // provided for zero-state. -class OsSettingsProvider - : public SearchProvider, - public apps::AppRegistryCache::Observer, - public chromeos::settings::mojom::SearchResultsObserver { +class OsSettingsProvider : public SearchProvider, + public apps::AppRegistryCache::Observer, + public ash::settings::mojom::SearchResultsObserver { public: explicit OsSettingsProvider(Profile* profile); ~OsSettingsProvider() override; @@ -85,7 +87,7 @@ void OnSearchReturned( const std::u16string& query, const base::TimeTicks& start_time, - std::vector<chromeos::settings::mojom::SearchResultPtr> results); + std::vector<ash::settings::mojom::SearchResultPtr> results); // Given a vector of results from the SearchHandler, filters them down to a // display-ready vector. It: @@ -104,9 +106,9 @@ // // So simply iterating down the vector while being careful about duplicates // and checking for alternate matches is enough. - std::vector<chromeos::settings::mojom::SearchResultPtr> FilterResults( + std::vector<ash::settings::mojom::SearchResultPtr> FilterResults( const std::u16string& query, - const std::vector<chromeos::settings::mojom::SearchResultPtr>& results, + const std::vector<ash::settings::mojom::SearchResultPtr>& results, const chromeos::settings::Hierarchy* hierarchy); void OnLoadIcon(apps::IconValuePtr icon_value); @@ -120,14 +122,14 @@ Profile* const profile_; chromeos::settings::OsSettingsManager* const settings_manager_; - chromeos::settings::SearchHandler* search_handler_; + ash::settings::SearchHandler* search_handler_; const chromeos::settings::Hierarchy* hierarchy_; apps::AppServiceProxy* app_service_proxy_; gfx::ImageSkia icon_; // Last query. It is reset when view is closed. std::u16string last_query_; - mojo::Receiver<chromeos::settings::mojom::SearchResultsObserver> + mojo::Receiver<ash::settings::mojom::SearchResultsObserver> search_results_observer_receiver_{this}; base::WeakPtrFactory<OsSettingsProvider> weak_factory_{this};
diff --git a/chrome/browser/ui/ash/app_access_notifier.cc b/chrome/browser/ui/ash/app_access_notifier.cc index 9ae6dee..66532ff 100644 --- a/chrome/browser/ui/ash/app_access_notifier.cc +++ b/chrome/browser/ui/ash/app_access_notifier.cc
@@ -132,7 +132,8 @@ base::MakeRefCounted<ash::PrivacyIndicatorsNotificationDelegate>( launch_app, launch_settings)); - ash::UpdatePrivacyIndicatorsView(is_camera_used, is_microphone_used); + ash::UpdatePrivacyIndicatorsView(app_id, is_camera_used, + is_microphone_used); } if (is_microphone_used) {
diff --git a/chrome/browser/ui/ash/projector/screencast_manager_browsertest.cc b/chrome/browser/ui/ash/projector/screencast_manager_browsertest.cc index 2af13431..9d5203c 100644 --- a/chrome/browser/ui/ash/projector/screencast_manager_browsertest.cc +++ b/chrome/browser/ui/ash/projector/screencast_manager_browsertest.cc
@@ -49,6 +49,8 @@ constexpr char kTestVideoFile[] = "tulip2.webm"; constexpr char kTestVideoDurationMilliesecond[] = "16682"; +#if !BUILDFLAG(ENABLE_CROS_PROJECTOR_APP) + void VerifyResponse(const content::EvalJsResult& result) { EXPECT_TRUE(result.error.empty()); @@ -67,6 +69,8 @@ EXPECT_EQ(*duration_millis, kTestVideoDurationMilliesecond); } +#endif // !BUILDFLAG(ENABLE_CROS_PROJECTOR_APP) + } // namespace using ScreencastManagerTest = SystemWebAppIntegrationTest;
diff --git a/chrome/browser/ui/ash/shelf/arc_shelf_spinner_item_controller.cc b/chrome/browser/ui/ash/shelf/arc_shelf_spinner_item_controller.cc index 93a6735d..ebd7f28 100644 --- a/chrome/browser/ui/ash/shelf/arc_shelf_spinner_item_controller.cc +++ b/chrome/browser/ui/ash/shelf/arc_shelf_spinner_item_controller.cc
@@ -57,7 +57,7 @@ window_info_->window_id > app_restore::kArcSessionIdOffsetForRestoredLaunching) { ash::app_restore::AppRestoreArcTaskHandler::GetForProfile(observed_profile_) - ->full_restore_arc_app_launch_handler() + ->GetFullRestoreArcAppLaunchHandler() ->LaunchApp(app_id()); std::move(callback).Run(ash::SHELF_ACTION_NEW_WINDOW_CREATED, {}); return;
diff --git a/chrome/browser/ui/autofill/autofill_popup_controller_unittest.cc b/chrome/browser/ui/autofill/autofill_popup_controller_unittest.cc index d29ceba5..ef7f777 100644 --- a/chrome/browser/ui/autofill/autofill_popup_controller_unittest.cc +++ b/chrome/browser/ui/autofill/autofill_popup_controller_unittest.cc
@@ -5,6 +5,7 @@ #include <stddef.h> #include <memory> +#include <utility> #include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" @@ -69,7 +70,7 @@ ~MockAutofillClient() override = default; PrefService* GetPrefs() override { - return const_cast<PrefService*>(base::as_const(*this).GetPrefs()); + return const_cast<PrefService*>(std::as_const(*this).GetPrefs()); } const PrefService* GetPrefs() const override { return prefs_.get(); }
diff --git a/chrome/browser/ui/autofill/chrome_autofill_client.cc b/chrome/browser/ui/autofill/chrome_autofill_client.cc index e100839c..2803eff 100644 --- a/chrome/browser/ui/autofill/chrome_autofill_client.cc +++ b/chrome/browser/ui/autofill/chrome_autofill_client.cc
@@ -197,7 +197,7 @@ } PrefService* ChromeAutofillClient::GetPrefs() { - return const_cast<PrefService*>(base::as_const(*this).GetPrefs()); + return const_cast<PrefService*>(std::as_const(*this).GetPrefs()); } const PrefService* ChromeAutofillClient::GetPrefs() const {
diff --git a/chrome/browser/ui/autofill_assistant/password_change/mock_password_change_run_display.h b/chrome/browser/ui/autofill_assistant/password_change/mock_password_change_run_display.h index 574df800..a78368b 100644 --- a/chrome/browser/ui/autofill_assistant/password_change/mock_password_change_run_display.h +++ b/chrome/browser/ui/autofill_assistant/password_change/mock_password_change_run_display.h
@@ -60,7 +60,8 @@ MOCK_METHOD(void, ShowStartingScreen, (const GURL&), (override)); MOCK_METHOD(void, ShowCompletionScreen, - (base::RepeatingClosure done_button_callback), + (autofill_assistant::password_change::FlowType flow_type, + base::RepeatingClosure done_button_callback), (override)); MOCK_METHOD(void, ShowErrorScreen, (), (override)); MOCK_METHOD(void, PauseProgressBarAnimation, (), (override));
diff --git a/chrome/browser/ui/autofill_assistant/password_change/password_change_run_controller.h b/chrome/browser/ui/autofill_assistant/password_change/password_change_run_controller.h index c44d77a..701b734 100644 --- a/chrome/browser/ui/autofill_assistant/password_change/password_change_run_controller.h +++ b/chrome/browser/ui/autofill_assistant/password_change/password_change_run_controller.h
@@ -37,6 +37,10 @@ autofill_assistant::password_change::ProgressStep progress_step; // Whether the icon animation on the progress bar is paused. bool progress_bar_animation_is_paused = false; + // The flow type (i.e. password change vs. password reset). It is used to + // decide which completion screen to display at the end. + autofill_assistant::password_change::FlowType flow_type = + autofill_assistant::password_change::FlowType::FLOW_TYPE_UNSPECIFIED; }; // Factory function to create the controller. @@ -80,7 +84,7 @@ // from the script controller. virtual void ShowStartingScreen(const GURL& url) = 0; - // Shows the ending screen, displayed after script completion. + // Shows the ending screen that is displayed after script completion. virtual void ShowCompletionScreen( base::RepeatingClosure done_button_callback) = 0;
diff --git a/chrome/browser/ui/autofill_assistant/password_change/password_change_run_display.h b/chrome/browser/ui/autofill_assistant/password_change/password_change_run_display.h index 7cca58c..67af254 100644 --- a/chrome/browser/ui/autofill_assistant/password_change/password_change_run_display.h +++ b/chrome/browser/ui/autofill_assistant/password_change/password_change_run_display.h
@@ -77,6 +77,7 @@ // Methods used to render the UI state before and after a script run. virtual void ShowStartingScreen(const GURL& url) = 0; virtual void ShowCompletionScreen( + autofill_assistant::password_change::FlowType flow_type, base::RepeatingClosure done_button_callback) = 0; virtual void ShowErrorScreen() = 0;
diff --git a/chrome/browser/ui/lacros/immersive_context_lacros.cc b/chrome/browser/ui/lacros/immersive_context_lacros.cc index dbc3fe5a4..1d95d4f 100644 --- a/chrome/browser/ui/lacros/immersive_context_lacros.cc +++ b/chrome/browser/ui/lacros/immersive_context_lacros.cc
@@ -8,7 +8,9 @@ #include "ui/aura/window.h" #include "ui/display/display.h" #include "ui/display/screen.h" +#include "ui/platform_window/extensions/wayland_extension.h" #include "ui/views/widget/desktop_aura/desktop_window_tree_host_lacros.h" +#include "ui/views/widget/widget.h" ImmersiveContextLacros::ImmersiveContextLacros() = default; @@ -16,7 +18,17 @@ void ImmersiveContextLacros::OnEnteringOrExitingImmersive( chromeos::ImmersiveFullscreenController* controller, - bool entering) {} + bool entering) { + aura::Window* window = controller->widget()->GetNativeWindow(); + + // Lacros is based on Ozone/Wayland, which uses ui::PlatformWindow and + // views::DesktopWindowTreeHostLacros. + auto* wayland_extension = + views::DesktopWindowTreeHostLacros::From(window->GetHost()) + ->GetWaylandExtension(); + + wayland_extension->SetImmersiveFullscreenStatus(entering); +} gfx::Rect ImmersiveContextLacros::GetDisplayBoundsInScreen( views::Widget* widget) {
diff --git a/chrome/browser/ui/startup/startup_browser_creator.cc b/chrome/browser/ui/startup/startup_browser_creator.cc index e058ff2..4be4bcf 100644 --- a/chrome/browser/ui/startup/startup_browser_creator.cc +++ b/chrome/browser/ui/startup/startup_browser_creator.cc
@@ -40,6 +40,7 @@ #include "chrome/browser/apps/app_service/app_service_proxy_factory.h" #include "chrome/browser/apps/platform_apps/app_load_service.h" #include "chrome/browser/apps/platform_apps/platform_app_launch.h" +#include "chrome/browser/browser_features.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/custom_handlers/protocol_handler_registry_factory.h" #include "chrome/browser/extensions/startup_helper.h" @@ -420,36 +421,35 @@ } #if !BUILDFLAG(IS_CHROMEOS_ASH) -StartupProfilePathInfo GetProfilePickerStartupProfilePathInfo() { - // To indicate that we want to show the profile picker, return the guest - // profile. - // TODO(https://crbug.com/1150326): Return an empty path instead of a guest - // profile path. - return {ProfileManager::GetGuestProfilePath(), - StartupProfileMode::kProfilePicker}; +base::FilePath GetProfilePickerStartupProfilePath() { + return base::FeatureList::IsEnabled(features::kObserverBasedPostProfileInit) + ? base::FilePath() + : ProfileManager::GetGuestProfilePath(); } #endif // !BUILDFLAG(IS_CHROMEOS_ASH) #if !BUILDFLAG(IS_CHROMEOS_ASH) StartupProfileInfo GetProfilePickerStartupProfileInfo() { - auto path_info = GetProfilePickerStartupProfilePathInfo(); - DCHECK_EQ(path_info.mode, StartupProfileMode::kProfilePicker); - - ProfileManager* profile_manager = g_browser_process->profile_manager(); - - // We can only show the profile picker this if the system profile - // (where the profile picker lives) also exists (or is creatable). + // We can only show the profile picker if the system profile (where the + // profile picker lives) also exists (or is creatable). // TODO(crbug.com/1271859): Remove unnecessary system profile check here. + ProfileManager* profile_manager = g_browser_process->profile_manager(); if (!profile_manager->GetProfile(ProfileManager::GetSystemProfilePath())) - return {nullptr, StartupProfileMode::kError}; + return {.profile = nullptr, .mode = StartupProfileMode::kError}; - Profile* guest_profile = profile_manager->GetProfile(path_info.path); - if (guest_profile) { + if (!base::FeatureList::IsEnabled(features::kObserverBasedPostProfileInit)) { + DCHECK_EQ(GetProfilePickerStartupProfilePath(), + ProfileManager::GetGuestProfilePath()); + Profile* guest_profile = + profile_manager->GetProfile(ProfileManager::GetGuestProfilePath()); + if (!guest_profile) + return {.profile = nullptr, .mode = StartupProfileMode::kError}; DCHECK(guest_profile->IsGuestSession()); - return {guest_profile, path_info.mode}; + return {.profile = guest_profile, + .mode = StartupProfileMode::kProfilePicker}; } - return {nullptr, StartupProfileMode::kError}; + return {.profile = nullptr, .mode = StartupProfileMode::kProfilePicker}; } #endif // !BUILDFLAG(IS_CHROMEOS_ASH) @@ -1509,9 +1509,8 @@ auto has_tabs = StartupTabProviderImpl().HasCommandLineTabs(command_line, cur_dir); if (has_tabs == CommandLineTabsPresent::kNo) { - StartupProfilePathInfo info = GetProfilePickerStartupProfilePathInfo(); - DCHECK_EQ(info.mode, StartupProfileMode::kProfilePicker); - return info; + return {.path = GetProfilePickerStartupProfilePath(), + .mode = StartupProfileMode::kProfilePicker}; } } #endif // !BUILDFLAG(IS_CHROMEOS_ASH)
diff --git a/chrome/browser/ui/startup/startup_browser_creator_browsertest.cc b/chrome/browser/ui/startup/startup_browser_creator_browsertest.cc index 5fc0721..baa96ed 100644 --- a/chrome/browser/ui/startup/startup_browser_creator_browsertest.cc +++ b/chrome/browser/ui/startup/startup_browser_creator_browsertest.cc
@@ -4024,6 +4024,12 @@ } else { EXPECT_EQ(1u, chrome::GetTotalBrowserCount()); } + + // No Guest profile was created. + for (const Profile* profile : + g_browser_process->profile_manager()->GetLoadedProfiles()) { + EXPECT_FALSE(profile->IsGuestSession()); + } } INSTANTIATE_TEST_SUITE_P(
diff --git a/chrome/browser/ui/views/autofill_assistant/password_change/password_change_run_view.cc b/chrome/browser/ui/views/autofill_assistant/password_change/password_change_run_view.cc index 977711b..78e7b6b2 100644 --- a/chrome/browser/ui/views/autofill_assistant/password_change/password_change_run_view.cc +++ b/chrome/browser/ui/views/autofill_assistant/password_change/password_change_run_view.cc
@@ -40,6 +40,7 @@ #include "ui/views/view.h" #include "url/gurl.h" +using autofill_assistant::password_change::FlowType; using autofill_assistant::password_change::TopIcon; namespace { @@ -378,21 +379,35 @@ } void PasswordChangeRunView::ShowCompletionScreen( + FlowType flow_type, base::RepeatingClosure done_button_callback) { - show_completion_screen_done_button_callback_ = - std::move(done_button_callback); + base::OnceClosure show_screen; + switch (flow_type) { + case FlowType::FLOW_TYPE_UNSPECIFIED: + case FlowType::FLOW_TYPE_PASSWORD_CHANGE: + show_screen = base::BindOnce( + &PasswordChangeRunView::OnShowCompletionScreenForPasswordChange, + base::Unretained(this), std::move(done_button_callback)); + break; + case FlowType::FLOW_TYPE_PASSWORD_RESET: + show_screen = base::BindOnce( + &PasswordChangeRunView::OnShowCompletionScreenForPasswordReset, + base::Unretained(this), std::move(done_button_callback)); + break; + } + CHECK(show_screen); // If the progress bar has finished its animation, run immediately. if (password_change_run_progress_->IsCompleted()) { - OnShowCompletionScreen(); + std::move(show_screen).Run(); } else { password_change_run_progress_->SetAnimationEndedCallback( - base::BindOnce(&PasswordChangeRunView::OnShowCompletionScreen, - base::Unretained(this))); + std::move(show_screen)); } } -void PasswordChangeRunView::OnShowCompletionScreen() { +void PasswordChangeRunView::OnShowCompletionScreenForPasswordChange( + base::RepeatingClosure done_button_callback) { SetTopIcon(TopIcon::TOP_ICON_CHANGED_PASSWORD); password_change_run_progress_->SetVisible(false); SetTitle(l10n_util::GetStringUTF16( @@ -424,7 +439,30 @@ auto* button_to_be_focused = button_container->AddChildView(CreateButton( l10n_util::GetStringUTF16( IDS_AUTOFILL_ASSISTANT_PASSWORD_CHANGE_SUCCESSFULLY_CHANGED_PASSWORD_CLOSE_SIDE_PANEL), - true, show_completion_screen_done_button_callback_)); + true, std::move(done_button_callback))); + + focus_on_button_timer_->Stop(); + focus_on_button_timer_->Start( + FROM_HERE, kFocusOnHighlightedButtonDelaySeconds, + base::BindOnce(&PasswordChangeRunView::FocusPromptButton, + base::Unretained(this), button_to_be_focused)); +} + +void PasswordChangeRunView::OnShowCompletionScreenForPasswordReset( + base::RepeatingClosure done_button_callback) { + SetTopIcon(TopIcon::TOP_ICON_PASSWORD_RESET_REQUESTED); + password_change_run_progress_->SetVisible(false); + SetTitle(l10n_util::GetStringUTF16( + IDS_AUTOFILL_ASSISTANT_PASSWORD_CHANGE_SUCCESSFULLY_RESET_PASSWORD_TITLE)); + + body_->RemoveAllChildViews(); + body_->AddChildView(std::make_unique<views::Separator>()); + + views::View* button_container = body_->AddChildView(CreateButtonContainer()); + auto* button_to_be_focused = button_container->AddChildView(CreateButton( + l10n_util::GetStringUTF16( + IDS_AUTOFILL_ASSISTANT_PASSWORD_CHANGE_SUCCESSFULLY_RESET_PASSWORD_CLOSE_SIDE_PANEL), + true, std::move(done_button_callback))); focus_on_button_timer_->Stop(); focus_on_button_timer_->Start(
diff --git a/chrome/browser/ui/views/autofill_assistant/password_change/password_change_run_view.h b/chrome/browser/ui/views/autofill_assistant/password_change/password_change_run_view.h index 13166ec..5b52e49 100644 --- a/chrome/browser/ui/views/autofill_assistant/password_change/password_change_run_view.h +++ b/chrome/browser/ui/views/autofill_assistant/password_change/password_change_run_view.h
@@ -80,6 +80,7 @@ void ClearPrompt() override; void ShowStartingScreen(const GURL& url) override; void ShowCompletionScreen( + autofill_assistant::password_change::FlowType flow_type, base::RepeatingClosure done_button_callback) override; void ShowErrorScreen() override; void PauseProgressBarAnimation() override; @@ -110,11 +111,17 @@ // Sets focus on the currently highlighted button (if any). void FocusPromptButton(views::MdTextButton* button); - // Method that updates the UI to render the completion screen. This is called - // only AFTER `password_change_run_progress_` is completed, both in terms of - // steps and animation. Runs `show_completion_screen_done_button_callback_` - // when user clicks on Done. - void OnShowCompletionScreen(); + // Updates the UI to show the completion screen for a successful password + // change. This method should not be called directly, but instead be triggered + // when `password_change_run_progress_` is complete. + // Runs `done_button_callback` if the user interacts with the "Done" button. + void OnShowCompletionScreenForPasswordChange( + base::RepeatingClosure done_button_callback); + + // Updates the UI to show the completion screen for a successful password + // reset. It behaves similarly to `OnShowCompletionScreenForPasswordChange`. + void OnShowCompletionScreenForPasswordReset( + base::RepeatingClosure done_button_callback); // The controller belonging to this view. base::WeakPtr<PasswordChangeRunController> controller_; @@ -135,8 +142,6 @@ // focus. std::unique_ptr<base::OneShotTimer> focus_on_button_timer_; - // Callback run when a user clicks Done after a successful run. - base::RepeatingClosure show_completion_screen_done_button_callback_; // Factory for weak pointers to this view. base::WeakPtrFactory<PasswordChangeRunView> weak_ptr_factory_{this}; };
diff --git a/chrome/browser/ui/views/bookmarks/bookmark_bubble_view_unittest.cc b/chrome/browser/ui/views/bookmarks/bookmark_bubble_view_unittest.cc index 92e0f5d..e35eedb6 100644 --- a/chrome/browser/ui/views/bookmarks/bookmark_bubble_view_unittest.cc +++ b/chrome/browser/ui/views/bookmarks/bookmark_bubble_view_unittest.cc
@@ -236,3 +236,61 @@ EXPECT_TRUE(price_tracking_view->IsToggleOn()); } #endif // !BUILDFLAG(IS_FUCHSIA) + +#if !BUILDFLAG(IS_FUCHSIA) +class PriceTrackingViewFeatureFlagTest + : public BookmarkBubbleViewTest, + public testing::WithParamInterface<bool> { + public: + PriceTrackingViewFeatureFlagTest() { + const bool is_feature_enabled = GetParam(); + if (is_feature_enabled) { + test_features_.InitAndEnableFeature(commerce::kShoppingList); + } else { + test_features_.InitAndDisableFeature(commerce::kShoppingList); + } + } + static std::string DescribeParams( + const ::testing::TestParamInfo<ParamType>& info) { + return info.param ? "ShoppingListEnabled" : "ShoppingListDisabled"; + } + + private: + base::test::ScopedFeatureList test_features_; +}; + +INSTANTIATE_TEST_SUITE_P(All, + PriceTrackingViewFeatureFlagTest, + testing::Bool(), + &PriceTrackingViewFeatureFlagTest::DescribeParams); + +TEST_P(PriceTrackingViewFeatureFlagTest, PriceTrackingViewCreation) { + commerce::MockShoppingService* mock_shopping_service = + static_cast<commerce::MockShoppingService*>( + commerce::ShoppingServiceFactory::GetForBrowserContext(profile())); + mock_shopping_service->SetResponseForGetProductInfoForUrl( + commerce::ProductInfo()); + + MockShoppingListUiTabHelper::CreateForWebContents( + browser()->tab_strip_model()->GetActiveWebContents()); + auto* mock_tab_helper_ = static_cast<MockShoppingListUiTabHelper*>( + MockShoppingListUiTabHelper::FromWebContents( + browser()->tab_strip_model()->GetActiveWebContents())); + const gfx::Image image = mock_tab_helper_->GetValidProductImage(); + ON_CALL(*mock_tab_helper_, GetProductImage) + .WillByDefault( + testing::ReturnRef(mock_tab_helper_->GetValidProductImage())); + + CreateBubbleView(); + + auto* price_tracking_view = GetPriceTrackingView(); + + const bool is_feature_enabled = GetParam(); + if (is_feature_enabled) { + EXPECT_TRUE(price_tracking_view); + } else { + EXPECT_FALSE(price_tracking_view); + } +} + +#endif // !BUILDFLAG(IS_FUCHSIA)
diff --git a/chrome/browser/ui/views/commerce/price_tracking_entry_point_feature_flag_browser_test.cc b/chrome/browser/ui/views/commerce/price_tracking_entry_point_feature_flag_browser_test.cc new file mode 100644 index 0000000..e308c64 --- /dev/null +++ b/chrome/browser/ui/views/commerce/price_tracking_entry_point_feature_flag_browser_test.cc
@@ -0,0 +1,98 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/views/commerce/price_tracking_icon_view.h" + +#include "chrome/browser/ui/browser_element_identifiers.h" +#include "chrome/browser/ui/commerce/price_tracking/shopping_list_ui_tab_helper.h" +#include "chrome/browser/ui/views/frame/browser_view.h" +#include "chrome/browser/ui/views/toolbar/toolbar_view.h" +#include "chrome/test/base/in_process_browser_test.h" +#include "components/commerce/core/commerce_feature_list.h" +#include "content/public/test/browser_test.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "ui/base/interaction/element_identifier.h" +#include "ui/base/interaction/element_tracker.h" +#include "ui/views/interaction/element_tracker_views.h" + +namespace { +const char kTestURL[] = "about:blank"; +} // namespace + +class PriceTrackingEntryPointFeatureFlagTest + : public InProcessBrowserTest, + public testing::WithParamInterface<bool> { + public: + PriceTrackingEntryPointFeatureFlagTest() { + const bool is_feature_enabled = GetParam(); + if (is_feature_enabled) { + test_features_.InitAndEnableFeature(commerce::kShoppingList); + } else { + test_features_.InitAndDisableFeature(commerce::kShoppingList); + } + } + + PriceTrackingEntryPointFeatureFlagTest( + const PriceTrackingEntryPointFeatureFlagTest&) = delete; + PriceTrackingEntryPointFeatureFlagTest& operator=( + const PriceTrackingEntryPointFeatureFlagTest&) = delete; + + ~PriceTrackingEntryPointFeatureFlagTest() override = default; + + static std::string DescribeParams( + const ::testing::TestParamInfo<ParamType>& info) { + return info.param ? "ShoppingListEnabled" : "ShoppingListDisabled"; + } + + PriceTrackingIconView* GetChip() { + auto* browser_view = BrowserView::GetBrowserViewForBrowser(browser()); + auto* location_bar_view = browser_view->toolbar()->location_bar(); + const ui::ElementContext context = + views::ElementTrackerViews::GetContextForView(location_bar_view); + views::View* matched_view = + views::ElementTrackerViews::GetInstance()->GetFirstMatchingView( + kPriceTrackingChipElementId, context); + + return matched_view + ? views::AsViewClass<PriceTrackingIconView>(matched_view) + : nullptr; + } + + private: + base::test::ScopedFeatureList test_features_; +}; + +INSTANTIATE_TEST_SUITE_P( + All, + PriceTrackingEntryPointFeatureFlagTest, + testing::Bool(), + &PriceTrackingEntryPointFeatureFlagTest::DescribeParams); + +IN_PROC_BROWSER_TEST_P(PriceTrackingEntryPointFeatureFlagTest, + ShoppingListUiTabHelperCreation) { + ASSERT_TRUE(AddTabAtIndex(0, GURL(kTestURL), ui::PAGE_TRANSITION_TYPED)); + + auto* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); + auto* tab_helper = + commerce::ShoppingListUiTabHelper::FromWebContents(web_contents); + + const bool is_feature_enabled = GetParam(); + if (is_feature_enabled) { + EXPECT_TRUE(tab_helper); + } else { + EXPECT_FALSE(tab_helper); + } +} + +IN_PROC_BROWSER_TEST_P(PriceTrackingEntryPointFeatureFlagTest, + PriceTrackingPageActionIconCreation) { + auto* chip = GetChip(); + + const bool is_feature_enabled = GetParam(); + if (is_feature_enabled) { + EXPECT_TRUE(chip); + } else { + EXPECT_FALSE(chip); + } +}
diff --git a/chrome/browser/ui/views/frame/immersive_mode_controller_chromeos.h b/chrome/browser/ui/views/frame/immersive_mode_controller_chromeos.h index f5f0ab37..9137d72 100644 --- a/chrome/browser/ui/views/frame/immersive_mode_controller_chromeos.h +++ b/chrome/browser/ui/views/frame/immersive_mode_controller_chromeos.h
@@ -71,8 +71,6 @@ intptr_t old) override; void OnWindowDestroying(aura::Window* window) override; - void EnableForWidget(views::Widget* widget, bool enabled); - chromeos::ImmersiveFullscreenController controller_; raw_ptr<BrowserView> browser_view_ = nullptr;
diff --git a/chrome/browser/ui/views/page_action/pwa_install_view_browsertest.cc b/chrome/browser/ui/views/page_action/pwa_install_view_browsertest.cc index 07f53295..d56c7aa 100644 --- a/chrome/browser/ui/views/page_action/pwa_install_view_browsertest.cc +++ b/chrome/browser/ui/views/page_action/pwa_install_view_browsertest.cc
@@ -703,7 +703,7 @@ StartNavigateToUrl( https_server_.GetURL("/banners/manifest_test_page.html?manifest=" "manifest_prefer_related_chrome_app.json")); - ASSERT_FALSE(app_banner_manager_->WaitForInstallableCheck()); + ASSERT_TRUE(app_banner_manager_->WaitForInstallableCheck()); EXPECT_FALSE(pwa_install_view_->GetVisible()); EXPECT_TRUE(base::EqualsASCII( @@ -745,7 +745,7 @@ StartNavigateToUrl(https_server_.GetURL( "/banners/manifest_test_page.html?manifest=" + intercept_request_path_)); - ASSERT_FALSE(app_banner_manager_->WaitForInstallableCheck()); + ASSERT_TRUE(app_banner_manager_->WaitForInstallableCheck()); EXPECT_FALSE(pwa_install_view_->GetVisible()); EXPECT_TRUE(base::EqualsASCII( @@ -816,7 +816,7 @@ StartNavigateToUrl( https_server_.GetURL("/banners/manifest_test_page.html?manifest=" "manifest_listing_related_android_app.json")); - ASSERT_FALSE(app_banner_manager_->WaitForInstallableCheck()); + ASSERT_TRUE(app_banner_manager_->WaitForInstallableCheck()); EXPECT_FALSE(pwa_install_view_->GetVisible()); EXPECT_TRUE(base::EqualsASCII(
diff --git a/chrome/browser/ui/views/page_info/about_this_site_side_panel_coordinator.cc b/chrome/browser/ui/views/page_info/about_this_site_side_panel_coordinator.cc index 9900a309..c4e119a1 100644 --- a/chrome/browser/ui/views/page_info/about_this_site_side_panel_coordinator.cc +++ b/chrome/browser/ui/views/page_info/about_this_site_side_panel_coordinator.cc
@@ -118,8 +118,12 @@ return; } + auto* browser_view = GetBrowserView(); + if (!browser_view) + return; + // If the side panel is open and shows the AboutThisSide panel, close it. - auto* side_panel_coordinator = GetBrowserView()->side_panel_coordinator(); + auto* side_panel_coordinator = browser_view->side_panel_coordinator(); if (side_panel_coordinator->GetCurrentEntryId() == SidePanelEntry::Id::kAboutThisSite) { side_panel_coordinator->Close();
diff --git a/chrome/browser/ui/views/page_info/page_info_bubble_view_unittest.cc b/chrome/browser/ui/views/page_info/page_info_bubble_view_unittest.cc index 2f66664..64c9c47 100644 --- a/chrome/browser/ui/views/page_info/page_info_bubble_view_unittest.cc +++ b/chrome/browser/ui/views/page_info/page_info_bubble_view_unittest.cc
@@ -6,6 +6,7 @@ #include "base/memory/raw_ptr.h" #include "base/strings/utf_string_conversions.h" +#include "base/test/metrics/histogram_tester.h" #include "base/test/values_test_util.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" @@ -1155,6 +1156,7 @@ // Test that texts on buttons are correct and there is no more views than // necessary. TEST_F(PageInfoBubbleViewCookiesSubpageTest, TextsOnButtonsAreCorrect) { + base::HistogramTester histogram_tester; // Create fake cookie information. PageInfoUI::CookiesNewInfo cookie_info; cookie_info.blocked_sites_count = 10; @@ -1198,6 +1200,10 @@ EXPECT_TRUE(blocking_third_party_cookies_row->GetVisible()); EXPECT_TRUE(fps_button->GetVisible()); EXPECT_TRUE(api_->cookies_dialog_button()->GetVisible()); + histogram_tester.ExpectBucketCount("Security.PageInfo.Cookies.HasFPSInfo", + false, 0); + histogram_tester.ExpectBucketCount("Security.PageInfo.Cookies.HasFPSInfo", + true, 1); // Check if buttons get hidden when permission changes. cookie_info.status = CookieControlsStatus::kDisabled; @@ -1206,6 +1212,11 @@ EXPECT_FALSE(blocking_third_party_cookies_row->GetVisible()); EXPECT_FALSE(fps_button->GetVisible()); EXPECT_EQ(kExpectedChildren, cookies_buttons_container->children().size()); + // Check the histogram count is not increased on permission changes + histogram_tester.ExpectBucketCount("Security.PageInfo.Cookies.HasFPSInfo", + false, 0); + histogram_tester.ExpectBucketCount("Security.PageInfo.Cookies.HasFPSInfo", + true, 1); // Check if buttons reappear when permission changes. cookie_info.status = CookieControlsStatus::kDisabledForSite; @@ -1214,4 +1225,9 @@ EXPECT_TRUE(blocking_third_party_cookies_row->GetVisible()); EXPECT_TRUE(fps_button->GetVisible()); EXPECT_EQ(kExpectedChildren, cookies_buttons_container->children().size()); + // Check the histogram count is not increased on permission changes + histogram_tester.ExpectBucketCount("Security.PageInfo.Cookies.HasFPSInfo", + false, 0); + histogram_tester.ExpectBucketCount("Security.PageInfo.Cookies.HasFPSInfo", + true, 1); }
diff --git a/chrome/browser/ui/views/page_info/page_info_cookies_content_view.cc b/chrome/browser/ui/views/page_info/page_info_cookies_content_view.cc index 6b209034..f8fd2585 100644 --- a/chrome/browser/ui/views/page_info/page_info_cookies_content_view.cc +++ b/chrome/browser/ui/views/page_info/page_info_cookies_content_view.cc
@@ -3,6 +3,7 @@ // found in the LICENSE file. #include "chrome/browser/ui/views/page_info/page_info_cookies_content_view.h" +#include "base/metrics/histogram_functions.h" #include "chrome/browser/ui/layout_constants.h" #include "chrome/browser/ui/views/chrome_layout_provider.h" #include "chrome/browser/ui/views/page_info/page_info_main_view.h" @@ -316,6 +317,11 @@ } else if (fps_button_) { fps_button_->SetVisible(false); } + if (!fps_histogram_recorded_) { + fps_histogram_recorded_ = true; + base::UmaHistogramBoolean("Security.PageInfo.Cookies.HasFPSInfo", + is_fps_allowed); + } } void PageInfoCookiesContentView::InitFpsButton(bool is_managed) {
diff --git a/chrome/browser/ui/views/page_info/page_info_cookies_content_view.h b/chrome/browser/ui/views/page_info/page_info_cookies_content_view.h index 0fb9100..5d9c922 100644 --- a/chrome/browser/ui/views/page_info/page_info_cookies_content_view.h +++ b/chrome/browser/ui/views/page_info/page_info_cookies_content_view.h
@@ -93,6 +93,11 @@ // The button that displays First-Party-Set information with a link to // 'All sites' settings page. raw_ptr<PageInfoHoverButton> fps_button_ = nullptr; + + // Used to keep track if it's the first time for this instance recording the + // FPS info histogram. Needed to not record the histogram each time page info + // status changed. + bool fps_histogram_recorded_ = false; }; #endif // CHROME_BROWSER_UI_VIEWS_PAGE_INFO_PAGE_INFO_COOKIES_CONTENT_VIEW_H_
diff --git a/chrome/browser/ui/views/permissions/permission_chip_interactive_test.cc b/chrome/browser/ui/views/permissions/permission_chip_interactive_test.cc index 40f129437..e6fcea3 100644 --- a/chrome/browser/ui/views/permissions/permission_chip_interactive_test.cc +++ b/chrome/browser/ui/views/permissions/permission_chip_interactive_test.cc
@@ -233,7 +233,7 @@ public ::testing::WithParamInterface<ChipFeatureConfig> { public: LocationBarIconOverrideTest() { - std::vector<base::Feature> disabled_features = { + std::vector<base::test::FeatureRef> disabled_features = { permissions::features::kPermissionChipGestureSensitive, permissions::features::kPermissionChipRequestTypeSensitive}; @@ -361,7 +361,7 @@ public ::testing::WithParamInterface<ChipFeatureConfig> { public: ConfirmationChipEnabledInteractiveTest() { - std::vector<base::Feature> disabled_features = { + std::vector<base::test::FeatureRef> disabled_features = { permissions::features::kPermissionChipGestureSensitive, permissions::features::kPermissionChipRequestTypeSensitive}; switch (GetParam()) {
diff --git a/chrome/browser/ui/views/site_data/page_specific_site_data_dialog.cc b/chrome/browser/ui/views/site_data/page_specific_site_data_dialog.cc index 893c21d..c12bf571 100644 --- a/chrome/browser/ui/views/site_data/page_specific_site_data_dialog.cc +++ b/chrome/browser/ui/views/site_data/page_specific_site_data_dialog.cc
@@ -207,8 +207,14 @@ sites.push_back(site.second); std::sort(sites.begin(), sites.end(), [](const auto& o1, const auto& o2) { - return GetContentSettingRowOrder(o1.setting) < - GetContentSettingRowOrder(o2.setting); + int o1_order = GetContentSettingRowOrder(o1.setting); + int o2_order = GetContentSettingRowOrder(o2.setting); + if (o1_order != o2_order) { + return o1_order < o2_order; + } + + // Sort sites with the same content setting alphabetically. + return o1.origin.host() < o2.origin.host(); }); return sites;
diff --git a/chrome/browser/ui/views/site_data/site_data_row_view.cc b/chrome/browser/ui/views/site_data/site_data_row_view.cc index 3fbb329..98d61bc 100644 --- a/chrome/browser/ui/views/site_data/site_data_row_view.cc +++ b/chrome/browser/ui/views/site_data/site_data_row_view.cc
@@ -219,11 +219,13 @@ menu_button_->GetAnchorBoundsInScreen(), views::MenuAnchorPosition::kTopRight, ui::MenuSourceType::MENU_SOURCE_MOUSE); + menu_button_->SetState(views::Button::ButtonState::STATE_PRESSED); } void SiteDataRowView::OnMenuClosed() { menu_runner_.reset(); dialog_model_.reset(); + menu_button_->SetState(views::Button::ButtonState::STATE_NORMAL); } void SiteDataRowView::OnDeleteIconClicked() {
diff --git a/chrome/browser/ui/views/status_bubble_views.cc b/chrome/browser/ui/views/status_bubble_views.cc index 7fea762a..3078e85 100644 --- a/chrome/browser/ui/views/status_bubble_views.cc +++ b/chrome/browser/ui/views/status_bubble_views.cc
@@ -790,7 +790,11 @@ position_.SetPoint(base_view_->GetMirroredXWithWidthInView(x, w), y); size_.SetSize(w, h); RepositionPopup(); - if (popup_.get() && contains_mouse_) + + // Initializing the `popup_` views::Widget can trigger a window manager work + // area change that calls into this function while `view_` is still null, so + // check both `popup_` and `view_`. + if (popup_.get() && view_ && contains_mouse_) AvoidMouse(last_mouse_moved_location_); }
diff --git a/chrome/browser/ui/web_applications/BUILD.gn b/chrome/browser/ui/web_applications/BUILD.gn index f10c06be..523ae57 100644 --- a/chrome/browser/ui/web_applications/BUILD.gn +++ b/chrome/browser/ui/web_applications/BUILD.gn
@@ -114,6 +114,7 @@ deps = [ "//chrome/app:command_ids", "//chrome/browser/browsing_data:constants", + "//chrome/browser/ui/web_applications/diagnostics:app_service_browser_tests", "//chrome/browser/web_applications", "//chrome/browser/web_applications:web_applications_test_support", "//chrome/test:test_support",
diff --git a/chrome/browser/ui/web_applications/diagnostics/BUILD.gn b/chrome/browser/ui/web_applications/diagnostics/BUILD.gn new file mode 100644 index 0000000..e0b5542 --- /dev/null +++ b/chrome/browser/ui/web_applications/diagnostics/BUILD.gn
@@ -0,0 +1,31 @@ +# Copyright 2022 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//chrome/browser/buildflags.gni") + +# On Lacros, these browser tests require Ash to be running. +source_set("app_service_browser_tests") { + testonly = true + + sources = [ "web_app_icon_health_checks_browsertest.cc" ] + + defines = [ "HAS_OUT_OF_PROC_TEST_RUNNER" ] + + deps = [ + "//chrome/app:command_ids", + "//chrome/browser/web_applications", + "//chrome/browser/web_applications:web_applications_test_support", + "//chrome/test:test_support", + "//chrome/test:test_support_ui", + "//components/services/app_service/public/cpp:intents", + ] + + if (is_chromeos_lacros) { + deps += [ + "//chrome/test:lacros_test_support_ui", + "//chromeos/lacros", + "//chromeos/lacros:test_support", + ] + } +}
diff --git a/chrome/browser/ui/web_applications/diagnostics/callback_utils.h b/chrome/browser/ui/web_applications/diagnostics/callback_utils.h new file mode 100644 index 0000000..7353af0 --- /dev/null +++ b/chrome/browser/ui/web_applications/diagnostics/callback_utils.h
@@ -0,0 +1,88 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_WEB_APPLICATIONS_DIAGNOSTICS_CALLBACK_UTILS_H_ +#define CHROME_BROWSER_UI_WEB_APPLICATIONS_DIAGNOSTICS_CALLBACK_UTILS_H_ + +#include "base/callback.h" + +namespace web_app { + +// RunChainedCallbacks() runs multiple callbacks chained together by +// successively binding the final callback as parameter to the one before it +// until the entire sequence has been bound together. +// +// +// Example usage: +// +// class ImageAlterationManager { +// public: +// void PromptUserToAlterImage(base::FilePath image_path, +// double alter_amount, +// base::OnceClosure callback) { +// auto weak_ptr = weak_ptr_factory_.GetWeakPtr(); +// RunChainedCallbacks( +// base::BindOnce(&ImageAlterationManager::LoadImage, weak_ptr, +// image_path), +// base::BindOnce(&ImageAlterationManager::AlterImage, weak_ptr, +// alter_amount), +// base::BindOnce(&ImageAlterationManager::ConfirmWithUser, weak_ptr), +// base::BindOnce(&ImageAlterationManager::MaybeWriteImage, weak_ptr, +// image_path), +// std::move(callback)); +// } +// +// private: +// void LoadImage(base::FilePath image_path, +// base::OnceCallback<void(SkBitmap)> callback); +// void AlterImage(base::OnceCallback<void(SkBitmap)> callback, +// double alter_amount, +// SkBitmap image); +// void ConfirmWithUser(base::OnceCallback<void(SkBitmap, bool)> callback, +// SkBitmap image); +// void MaybeWriteImage(base::FilePath image_path, +// base::OnceClosure callback, +// SkBitmap image, +// bool user_confirmed); +// +// base::WeakPtrFactory<ImageAlterationManager> weak_ptr_factory_{this}; +// }; +// +// +// The alternate way to write PromptUserToAlterImage() without +// RunChainedCallbacks would be: +// +// base::BindOnce( +// &ImageAlterationManager::LoadImage, weak_ptr, image_path, +// base::BindOnce( +// &ImageAlterationManager::AlterImage, weak_ptr, alter_amount, +// base::BindOnce( +// &ImageAlterationManager::ConfirmImageWithUser, weak_ptr, +// base::BindOnce(&ImageAlterationManager::MaybeWriteImage, +// weak_ptr, image_path, std::move(callback))))); +// +// RunChainedCallbacks() avoids messy indented nesting of multiple +// base::BindOnce()s. + +template <typename Callback> +Callback ChainCallbacks(Callback&& callback) { + return std::forward<Callback>(callback); +} + +template <typename FirstCallback, typename... NextCallbacks> +decltype(auto) ChainCallbacks(FirstCallback&& first_callback, + NextCallbacks&&... next_callbacks) { + return base::BindOnce(std::forward<FirstCallback>(first_callback), + ChainCallbacks<NextCallbacks...>( + std::forward<NextCallbacks>(next_callbacks)...)); +} + +template <typename... Callbacks> +decltype(auto) RunChainedCallbacks(Callbacks&&... callbacks) { + return ChainCallbacks(std::forward<Callbacks>(callbacks)...).Run(); +} + +} // namespace web_app + +#endif // CHROME_BROWSER_UI_WEB_APPLICATIONS_DIAGNOSTICS_CALLBACK_UTILS_H_
diff --git a/chrome/browser/ui/web_applications/diagnostics/web_app_icon_diagnostic.cc b/chrome/browser/ui/web_applications/diagnostics/web_app_icon_diagnostic.cc new file mode 100644 index 0000000..e87641240 --- /dev/null +++ b/chrome/browser/ui/web_applications/diagnostics/web_app_icon_diagnostic.cc
@@ -0,0 +1,95 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/web_applications/diagnostics/web_app_icon_diagnostic.h" + +#include "base/strings/utf_string_conversions.h" +#include "chrome/browser/ui/web_applications/diagnostics/callback_utils.h" +#include "chrome/browser/web_applications/web_app.h" +#include "chrome/browser/web_applications/web_app_icon_generator.h" +#include "chrome/browser/web_applications/web_app_provider.h" +#include "chrome/browser/web_applications/web_app_registrar.h" +#include "ui/gfx/skia_util.h" + +namespace web_app { + +WebAppIconDiagnostic::WebAppIconDiagnostic(Profile* profile, AppId app_id) + : profile_(profile), + app_id_(std::move(app_id)), + provider_(WebAppProvider::GetForLocalAppsUnchecked(profile_.get())), + app_(provider_->registrar().GetAppById(app_id_)) {} + +WebAppIconDiagnostic::~WebAppIconDiagnostic() = default; + +void WebAppIconDiagnostic::Run( + base::OnceCallback<void(absl::optional<Result>)> result_callback) { + result_callback_ = std::move(result_callback); + + if (!app_) { + CallResultCallback(); + return; + } + + const SortedSizesPx& downloaded_icon_sizes = + app_->downloaded_icon_sizes(IconPurpose::ANY); + if (!downloaded_icon_sizes.empty()) + icon_size_ = *downloaded_icon_sizes.begin(); + + result_.emplace(); + result_->has_empty_downloaded_icon_sizes = downloaded_icon_sizes.empty(); + result_->has_generated_icon_flag = app_->is_generated_icon(); + + RunChainedCallbacks( + base::BindOnce(&WebAppIconDiagnostic::LoadIconFromProvider, GetWeakPtr()), + + base::BindOnce(&WebAppIconDiagnostic::DiagnoseGeneratedOrEmptyIconBitmap, + GetWeakPtr()), + + base::BindOnce(&WebAppIconDiagnostic::CallResultCallback, GetWeakPtr())); +} + +base::WeakPtr<WebAppIconDiagnostic> WebAppIconDiagnostic::GetWeakPtr() { + return weak_ptr_factory_.GetWeakPtr(); +} + +void WebAppIconDiagnostic::CallResultCallback() { + std::move(result_callback_).Run(std::move(result_)); +} + +void WebAppIconDiagnostic::LoadIconFromProvider( + WebAppIconManager::ReadIconWithPurposeCallback callback) { + if (!icon_size_) { + std::move(callback).Run(IconPurpose::ANY, SkBitmap()); + return; + } + + provider_->icon_manager().ReadSmallestIcon( + app_id_, std::vector<IconPurpose>{IconPurpose::ANY}, *icon_size_, + std::move(callback)); +} + +void WebAppIconDiagnostic::DiagnoseGeneratedOrEmptyIconBitmap( + base::OnceClosure done_callback, + IconPurpose purpose, + SkBitmap icon_bitmap) { + if (icon_bitmap.drawsNothing()) { + result_->has_empty_icon_bitmap = true; + std::move(done_callback).Run(); + return; + } + + DCHECK(icon_size_); + SkBitmap generated_icon_bitmap = GenerateBitmap( + *icon_size_, GenerateIconLetterFromAppName( + base::UTF8ToUTF16(app_->untranslated_name()))); + result_->has_generated_icon_bitmap = + gfx::BitmapsAreEqual(icon_bitmap, generated_icon_bitmap); + + result_->has_generated_icon_flag_false_negative = + !result_->has_generated_icon_flag && result_->has_generated_icon_bitmap; + + std::move(done_callback).Run(); +} + +} // namespace web_app
diff --git a/chrome/browser/ui/web_applications/diagnostics/web_app_icon_diagnostic.h b/chrome/browser/ui/web_applications/diagnostics/web_app_icon_diagnostic.h new file mode 100644 index 0000000..39271f8 --- /dev/null +++ b/chrome/browser/ui/web_applications/diagnostics/web_app_icon_diagnostic.h
@@ -0,0 +1,66 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_WEB_APPLICATIONS_DIAGNOSTICS_WEB_APP_ICON_DIAGNOSTIC_H_ +#define CHROME_BROWSER_UI_WEB_APPLICATIONS_DIAGNOSTICS_WEB_APP_ICON_DIAGNOSTIC_H_ + +#include "base/callback_forward.h" +#include "base/memory/raw_ptr.h" +#include "base/memory/weak_ptr.h" +#include "chrome/browser/web_applications/web_app_icon_manager.h" +#include "chrome/browser/web_applications/web_app_id.h" +#include "third_party/abseil-cpp/absl/types/optional.h" + +class Profile; + +namespace web_app { + +class WebAppProvider; +class WebApp; + +// Runs a series of icon health checks for |app_id|. +class WebAppIconDiagnostic { + public: + struct Result { + bool has_empty_downloaded_icon_sizes = false; + bool has_generated_icon_flag = false; + bool has_generated_icon_flag_false_negative = false; + bool has_generated_icon_bitmap = false; + bool has_empty_icon_bitmap = false; + // TODO(https://crbug.com/1353659): Add more checks. + }; + + WebAppIconDiagnostic(Profile* profile, AppId app_id); + ~WebAppIconDiagnostic(); + + void Run(base::OnceCallback<void(absl::optional<Result>)> result_callback); + + private: + base::WeakPtr<WebAppIconDiagnostic> GetWeakPtr(); + + void CallResultCallback(); + + void LoadIconFromProvider( + WebAppIconManager::ReadIconWithPurposeCallback callback); + void DiagnoseGeneratedOrEmptyIconBitmap(base::OnceClosure done_callback, + IconPurpose purpose, + SkBitmap icon_bitmap); + + const raw_ptr<Profile> profile_; + const AppId app_id_; + + const raw_ptr<WebAppProvider> provider_; + const raw_ptr<const WebApp> app_; + + absl::optional<SquareSizePx> icon_size_; + + absl::optional<Result> result_; + base::OnceCallback<void(absl::optional<Result>)> result_callback_; + + base::WeakPtrFactory<WebAppIconDiagnostic> weak_ptr_factory_{this}; +}; + +} // namespace web_app + +#endif // CHROME_BROWSER_UI_WEB_APPLICATIONS_DIAGNOSTICS_WEB_APP_ICON_DIAGNOSTIC_H_
diff --git a/chrome/browser/ui/web_applications/diagnostics/web_app_icon_health_checks.cc b/chrome/browser/ui/web_applications/diagnostics/web_app_icon_health_checks.cc new file mode 100644 index 0000000..76430f24 --- /dev/null +++ b/chrome/browser/ui/web_applications/diagnostics/web_app_icon_health_checks.cc
@@ -0,0 +1,113 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/web_applications/diagnostics/web_app_icon_health_checks.h" + +#include "base/barrier_closure.h" +#include "base/bind.h" +#include "base/logging.h" +#include "base/metrics/histogram_functions.h" +#include "base/ranges/algorithm.h" +#include "base/run_loop.h" +#include "chrome/browser/web_applications/app_service/web_app_publisher_helper.h" +#include "chrome/browser/web_applications/web_app.h" +#include "chrome/browser/web_applications/web_app_provider.h" +#include "chrome/browser/web_applications/web_app_registrar.h" + +namespace web_app { + +WebAppIconHealthChecks::WebAppIconHealthChecks(Profile* profile) + : profile_(profile), + app_type_(WebAppPublisherHelper::GetWebAppType()), + web_apps_published_event_(profile, app_type_) {} + +WebAppIconHealthChecks::~WebAppIconHealthChecks() = default; + +void WebAppIconHealthChecks::Start(base::OnceClosure done_callback) { + DCHECK(!done_callback_); + done_callback_ = std::move(done_callback); + web_apps_published_event_.Post( + base::BindOnce(&WebAppIconHealthChecks::RunDiagnostics, GetWeakPtr())); +} + +base::WeakPtr<WebAppIconHealthChecks> WebAppIconHealthChecks::GetWeakPtr() { + return weak_ptr_factory_.GetWeakPtr(); +} + +void WebAppIconHealthChecks::Shutdown() { + running_diagnostics_.clear(); +} + +void WebAppIconHealthChecks::OnWebAppWillBeUninstalled(const AppId& app_id) { + if (running_diagnostics_.erase(app_id) > 0) + run_complete_callback_.Run(); +} + +void WebAppIconHealthChecks::OnWebAppInstallManagerDestroyed() {} + +void WebAppIconHealthChecks::RunDiagnostics() { + WebAppProvider* provider = + WebAppProvider::GetForLocalAppsUnchecked(profile_.get()); + + install_manager_observation_.Observe(&provider->install_manager()); + + std::vector<AppId> app_ids = provider->registrar().GetAppIds(); + run_complete_callback_ = base::BarrierClosure( + app_ids.size(), + base::BindOnce(&WebAppIconHealthChecks::RecordDiagnosticResults, + GetWeakPtr())); + + for (const AppId& app_id : app_ids) { + WebAppIconDiagnostic* diagnostic = + running_diagnostics_ + .insert_or_assign(app_id, std::make_unique<WebAppIconDiagnostic>( + profile_.get(), app_id)) + .first->second.get(); + diagnostic->Run(base::BindOnce( + &WebAppIconHealthChecks::SaveDiagnosticForApp, GetWeakPtr(), app_id)); + } +} + +void WebAppIconHealthChecks::SaveDiagnosticForApp( + AppId app_id, + absl::optional<WebAppIconDiagnostic::Result> result) { + running_diagnostics_.erase(app_id); + if (result) + results_.push_back(*std::move(result)); + run_complete_callback_.Run(); +} + +void WebAppIconHealthChecks::RecordDiagnosticResults() { + install_manager_observation_.Reset(); + + using Result = WebAppIconDiagnostic::Result; + auto count = [&](auto member) { + return base::ranges::count(results_, true, member); + }; + + base::UmaHistogramCounts100("WebApp.Icon.AppsWithEmptyDownloadedIconSizes", + count(&Result::has_empty_downloaded_icon_sizes)); + base::UmaHistogramCounts100("WebApp.Icon.AppsWithGeneratedIconFlag", + count(&Result::has_generated_icon_flag)); + base::UmaHistogramCounts100("WebApp.Icon.AppsWithGeneratedIconBitmap", + count(&Result::has_generated_icon_bitmap)); + base::UmaHistogramCounts100( + "WebApp.Icon.AppsWithGeneratedIconFlagFalseNegative", + count(&Result::has_generated_icon_flag_false_negative)); + base::UmaHistogramCounts100("WebApp.Icon.AppsWithEmptyIconBitmap", + count(&Result::has_empty_icon_bitmap)); + // TODO(https://crbug.com/1353659): + // Measure: + // - Bitmap: + // - WebApp.Icon.AppsWithFallbackGreyBox + // - WebApp.Icon.AppsWithEmptyBitmapFile + // - Aggregate: + // - WebApp.Icon.AppsWithBrokenState + // - WebApp.Icon.AppsWithBrokenStateForInstallSource + // - WebApp.Icon.AppsWithBrokenStateOnShelf + + std::move(done_callback_).Run(); +} + +} // namespace web_app
diff --git a/chrome/browser/ui/web_applications/diagnostics/web_app_icon_health_checks.h b/chrome/browser/ui/web_applications/diagnostics/web_app_icon_health_checks.h new file mode 100644 index 0000000..b50ae34 --- /dev/null +++ b/chrome/browser/ui/web_applications/diagnostics/web_app_icon_health_checks.h
@@ -0,0 +1,64 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_WEB_APPLICATIONS_DIAGNOSTICS_WEB_APP_ICON_HEALTH_CHECKS_H_ +#define CHROME_BROWSER_UI_WEB_APPLICATIONS_DIAGNOSTICS_WEB_APP_ICON_HEALTH_CHECKS_H_ + +#include "base/callback_forward.h" +#include "base/memory/raw_ptr.h" +#include "base/memory/weak_ptr.h" +#include "chrome/browser/ui/web_applications/diagnostics/app_type_initialized_event.h" +#include "chrome/browser/ui/web_applications/diagnostics/web_app_icon_diagnostic.h" +#include "chrome/browser/web_applications/web_app_constants.h" +#include "chrome/browser/web_applications/web_app_id.h" +#include "chrome/browser/web_applications/web_app_install_manager.h" + +class Profile; + +namespace web_app { + +// Runs a suite of icon diagnostics on all installed web app icons at start up +// (triggered by WebAppMetrics) and records aggregate metrics for any broken +// states detected. +class WebAppIconHealthChecks : public WebAppInstallManagerObserver { + public: + explicit WebAppIconHealthChecks(Profile* profile); + ~WebAppIconHealthChecks() override; + + void Start(base::OnceClosure done_callback); + + base::WeakPtr<WebAppIconHealthChecks> GetWeakPtr(); + + void Shutdown(); + + // WebAppInstallManagerObserver: + void OnWebAppWillBeUninstalled(const AppId& app_id) override; + void OnWebAppInstallManagerDestroyed() override; + + private: + void RunDiagnostics(); + void SaveDiagnosticForApp( + AppId app_id, + absl::optional<WebAppIconDiagnostic::Result> result); + void RecordDiagnosticResults(); + + raw_ptr<Profile> profile_; + apps::AppType app_type_; + AppTypeInitializedEvent web_apps_published_event_; + + base::flat_map<AppId, std::unique_ptr<WebAppIconDiagnostic>> + running_diagnostics_; + base::RepeatingClosure run_complete_callback_; + std::vector<WebAppIconDiagnostic::Result> results_; + base::OnceClosure done_callback_; + + base::ScopedObservation<WebAppInstallManager, WebAppInstallManagerObserver> + install_manager_observation_{this}; + + base::WeakPtrFactory<WebAppIconHealthChecks> weak_ptr_factory_{this}; +}; + +} // namespace web_app + +#endif // CHROME_BROWSER_UI_WEB_APPLICATIONS_DIAGNOSTICS_WEB_APP_ICON_HEALTH_CHECKS_H_
diff --git a/chrome/browser/ui/web_applications/diagnostics/web_app_icon_health_checks_browsertest.cc b/chrome/browser/ui/web_applications/diagnostics/web_app_icon_health_checks_browsertest.cc new file mode 100644 index 0000000..e9c56bc3 --- /dev/null +++ b/chrome/browser/ui/web_applications/diagnostics/web_app_icon_health_checks_browsertest.cc
@@ -0,0 +1,137 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include <memory> +#include <utility> + +#include "base/test/bind.h" +#include "base/test/metrics/histogram_tester.h" +#include "chrome/browser/ui/browser.h" +#include "chrome/browser/ui/web_applications/test/web_app_browsertest_util.h" +#include "chrome/browser/ui/web_applications/web_app_metrics.h" +#include "chrome/browser/web_applications/os_integration/os_integration_manager.h" +#include "chrome/browser/web_applications/test/app_registry_cache_waiter.h" +#include "chrome/browser/web_applications/test/web_app_install_test_utils.h" +#include "chrome/browser/web_applications/web_app_id.h" +#include "chrome/browser/web_applications/web_app_provider.h" +#include "chrome/browser/web_applications/web_app_registry_update.h" +#include "chrome/test/base/in_process_browser_test.h" +#include "content/public/test/browser_test.h" + +namespace web_app { + +// TODO(https://crbug.com/1353659): Enable tests on Lacros. +// This feature depends on +// https://chromium-review.googlesource.com/c/chromium/src/+/3867152 landing +// to be able to work in Lacros. Currently Lacros doesn't know when the web app +// publisher has been initialised. + +#if !BUILDFLAG(IS_CHROMEOS_LACROS) + +class WebAppIconHealthChecksBrowserTest : public InProcessBrowserTest { + public: + WebAppIconHealthChecksBrowserTest() { + WebAppMetrics::DisableAutomaticIconHealthChecksForTesting(); + } + + ~WebAppIconHealthChecksBrowserTest() override = default; + + void SetUpOnMainThread() override { + InProcessBrowserTest::SetUpOnMainThread(); + ASSERT_TRUE(embedded_test_server()->Start()); + } + + Profile* profile() { return browser()->profile(); } + + ScopedRegistryUpdate CreateUpdateScope() { + return ScopedRegistryUpdate( + &WebAppProvider::GetForTest(profile())->sync_bridge()); + } + + void RunIconChecksWithMetricExpectations( + WebAppIconDiagnostic::Result expected_result) { + base::HistogramTester histogram_tester; + + base::RunLoop run_loop; + WebAppMetrics::Get(profile())->icon_health_checks_for_testing().Start( + run_loop.QuitClosure()); + run_loop.Run(); + + auto check_histogram = [&](const char* histogram, bool subresult) { + histogram_tester.ExpectUniqueSample(histogram, subresult, 1); + }; + check_histogram("WebApp.Icon.AppsWithEmptyDownloadedIconSizes", + expected_result.has_empty_downloaded_icon_sizes); + check_histogram("WebApp.Icon.AppsWithGeneratedIconFlag", + expected_result.has_generated_icon_flag); + check_histogram("WebApp.Icon.AppsWithGeneratedIconBitmap", + expected_result.has_generated_icon_bitmap); + check_histogram("WebApp.Icon.AppsWithGeneratedIconFlagFalseNegative", + expected_result.has_generated_icon_flag_false_negative); + check_histogram("WebApp.Icon.AppsWithEmptyIconBitmap", + expected_result.has_empty_icon_bitmap); + } + + AppId InstallWebAppAndAwaitAppService(const char* path) { + AppId app_id = + InstallWebAppFromPage(browser(), embedded_test_server()->GetURL(path)); + AppReadinessWaiter(profile(), app_id, apps::Readiness::kReady).Await(); + return app_id; + } + + OsIntegrationManager::ScopedSuppressForTesting os_hooks_supress_; +}; + +IN_PROC_BROWSER_TEST_F(WebAppIconHealthChecksBrowserTest, HealthyIcons) { + InstallWebAppAndAwaitAppService("/web_apps/basic.html"); + RunIconChecksWithMetricExpectations({}); +} + +IN_PROC_BROWSER_TEST_F(WebAppIconHealthChecksBrowserTest, + MissingDownloadedIconSizes) { + AppId app_id = InstallWebAppAndAwaitAppService("/web_apps/basic.html"); + CreateUpdateScope()->UpdateApp(app_id)->SetDownloadedIconSizes( + IconPurpose::ANY, {}); + RunIconChecksWithMetricExpectations( + {.has_empty_downloaded_icon_sizes = true, .has_empty_icon_bitmap = true}); +} + +IN_PROC_BROWSER_TEST_F(WebAppIconHealthChecksBrowserTest, GeneratedIcon) { + InstallWebAppAndAwaitAppService("/web_apps/get_manifest.html?no_icons.json"); + RunIconChecksWithMetricExpectations( + {.has_generated_icon_flag = true, .has_generated_icon_bitmap = true}); +} + +IN_PROC_BROWSER_TEST_F(WebAppIconHealthChecksBrowserTest, + GeneratedIconFlagFalseNegative) { + AppId app_id = InstallWebAppAndAwaitAppService( + "/web_apps/get_manifest.html?no_icons.json"); + // In https://crbug.com/1317922 manifest update erroneously set + // is_generated_icon to false. + CreateUpdateScope()->UpdateApp(app_id)->SetIsGeneratedIcon(false); + RunIconChecksWithMetricExpectations( + {.has_generated_icon_flag_false_negative = true, + .has_generated_icon_bitmap = true}); +} + +IN_PROC_BROWSER_TEST_F(WebAppIconHealthChecksBrowserTest, PRE_EmptyIconBitmap) { + AppId app_id = InstallWebAppAndAwaitAppService("/web_apps/basic.html"); + RunIconChecksWithMetricExpectations({}); + + // Delete the icons. + base::RunLoop run_loop; + WebAppProvider::GetForTest(profile())->icon_manager().DeleteData( + app_id, + base::BindLambdaForTesting([&](bool success) { run_loop.Quit(); })); + run_loop.Run(); + + // Restart to reload the app. +} +IN_PROC_BROWSER_TEST_F(WebAppIconHealthChecksBrowserTest, EmptyIconBitmap) { + RunIconChecksWithMetricExpectations({.has_empty_icon_bitmap = true}); +} + +#endif // !BUILDFLAG(IS_CHROMEOS_LACROS) + +} // namespace web_app
diff --git a/chrome/browser/ui/web_applications/web_app_metrics.cc b/chrome/browser/ui/web_applications/web_app_metrics.cc index a59055e2..259bea1 100644 --- a/chrome/browser/ui/web_applications/web_app_metrics.cc +++ b/chrome/browser/ui/web_applications/web_app_metrics.cc
@@ -5,10 +5,12 @@ #include "chrome/browser/ui/web_applications/web_app_metrics.h" #include "base/bind.h" +#include "base/callback_helpers.h" #include "base/debug/dump_without_crashing.h" #include "base/metrics/histogram_functions.h" #include "base/power_monitor/power_monitor.h" #include "base/time/time.h" +#include "chrome/browser/after_startup_task_utils.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_finder.h" @@ -20,6 +22,7 @@ #include "chrome/browser/web_applications/web_app_provider.h" #include "chrome/browser/web_applications/web_app_tab_helper.h" #include "chrome/browser/web_applications/web_app_ui_manager.h" +#include "chrome/common/chrome_features.h" #include "components/site_engagement/content/engagement_type.h" #include "components/site_engagement/content/site_engagement_service.h" #include "components/webapps/browser/banners/app_banner_manager.h" @@ -33,6 +36,8 @@ namespace { +bool g_disable_automatic_icon_health_checks_for_testing = false; + // Max amount of time to record as a session. If a session exceeds this length, // treat it as invalid (0 time). // TODO (crbug.com/1081187): Use an idle timeout instead. @@ -67,15 +72,29 @@ return WebAppMetricsFactory::GetForProfile(profile); } +// static +void WebAppMetrics::DisableAutomaticIconHealthChecksForTesting() { + g_disable_automatic_icon_health_checks_for_testing = true; +} + WebAppMetrics::WebAppMetrics(Profile* profile) : SiteEngagementObserver( site_engagement::SiteEngagementService::Get(profile)), profile_(profile), + icon_health_checks_(profile), browser_tab_strip_tracker_(this, nullptr) { browser_tab_strip_tracker_.Init(); base::PowerMonitor::AddPowerSuspendObserver(this); BrowserList::AddObserver(this); + if (base::FeatureList::IsEnabled(features::kDesktopPWAsIconHealthChecks) && + !g_disable_automatic_icon_health_checks_for_testing) { + AfterStartupTaskUtils::PostTask( + FROM_HERE, base::ThreadTaskRunnerHandle::Get(), + base::BindOnce(&WebAppIconHealthChecks::Start, + icon_health_checks_.GetWeakPtr(), base::DoNothing())); + } + WebAppProvider* provider = WebAppProvider::GetForLocalAppsUnchecked(profile_); DCHECK(provider); provider->on_registry_ready().Post(
diff --git a/chrome/browser/ui/web_applications/web_app_metrics.h b/chrome/browser/ui/web_applications/web_app_metrics.h index 222b29a..5b175fc 100644 --- a/chrome/browser/ui/web_applications/web_app_metrics.h +++ b/chrome/browser/ui/web_applications/web_app_metrics.h
@@ -12,6 +12,7 @@ #include "base/time/time.h" #include "chrome/browser/ui/browser_tab_strip_tracker.h" #include "chrome/browser/ui/tabs/tab_strip_model_observer.h" +#include "chrome/browser/ui/web_applications/diagnostics/web_app_icon_health_checks.h" #include "chrome/browser/web_applications/web_app_id.h" #include "components/keyed_service/core/keyed_service.h" #include "components/site_engagement/content/site_engagement_observer.h" @@ -37,6 +38,8 @@ public: static WebAppMetrics* Get(Profile* profile); + static void DisableAutomaticIconHealthChecksForTesting(); + explicit WebAppMetrics(Profile* profile); WebAppMetrics(const WebAppMetrics&) = delete; WebAppMetrics& operator=(const WebAppMetrics&) = delete; @@ -78,6 +81,10 @@ void RemoveBrowserListObserverForTesting(); void CountUserInstalledAppsForTesting(); + WebAppIconHealthChecks& icon_health_checks_for_testing() { + return icon_health_checks_; + } + private: void CountUserInstalledApps(); enum class TabSwitching { @@ -99,6 +106,8 @@ const raw_ptr<Profile> profile_; + WebAppIconHealthChecks icon_health_checks_; + BrowserTabStripTracker browser_tab_strip_tracker_; base::WeakPtrFactory<WebAppMetrics> weak_ptr_factory_{this};
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 c532f2c..5576336 100644 --- a/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc +++ b/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc
@@ -18,6 +18,7 @@ #include "build/chromeos_buildflags.h" #include "chrome/browser/about_flags.h" #include "chrome/browser/accessibility/accessibility_ui.h" +#include "chrome/browser/ash/web_applications/files_internals_ui_delegate.h" #include "chrome/browser/buildflags.h" #include "chrome/browser/devtools/devtools_ui_bindings.h" #include "chrome/browser/history/history_service_factory.h" @@ -190,6 +191,8 @@ #include "ash/webui/eche_app_ui/url_constants.h" #include "ash/webui/file_manager/file_manager_ui.h" #include "ash/webui/file_manager/url_constants.h" +#include "ash/webui/files_internals/files_internals.h" +#include "ash/webui/files_internals/url_constants.h" #include "ash/webui/firmware_update_ui/firmware_update_app_ui.h" #include "ash/webui/firmware_update_ui/url_constants.h" #include "ash/webui/guest_os_installer/guest_os_installer_ui.h" @@ -568,6 +571,13 @@ } template <> +WebUIController* NewWebUI<ash::FilesInternalsUI>(WebUI* web_ui, + const GURL& url) { + return new ash::FilesInternalsUI( + web_ui, std::make_unique<ChromeFilesInternalsUIDelegate>()); +} + +template <> WebUIController* NewWebUI<ash::OSFeedbackUI>(WebUI* web_ui, const GURL& url) { Profile* profile = Profile::FromWebUI(web_ui); return new ash::OSFeedbackUI( @@ -999,6 +1009,8 @@ return &NewWebUI<chromeos::CryptohomeUI>; if (url.host_piece() == chrome::kChromeUIDriveInternalsHost) return &NewWebUI<chromeos::DriveInternalsUI>; + if (url.host_piece() == ash::kChromeUIFilesInternalsHost) + return &NewWebUI<ash::FilesInternalsUI>; if (url.host_piece() == chrome::kChromeUILauncherInternalsHost) return &NewWebUI<chromeos::LauncherInternalsUI>; if (url.host_piece() == ash::kChromeUIHelpAppHost) @@ -1583,6 +1595,7 @@ GURL(chrome::kOsUICrashesURL), GURL(chrome::kOsUICreditsURL), GURL(chrome::kChromeUIBorealisCreditsURL), + GURL(chrome::kChromeUICloudUploadURL), GURL(chrome::kChromeUICrostiniCreditsURL), GURL(chrome::kChromeUICrostiniInstallerUrl), GURL(chrome::kChromeUICrostiniUpgraderUrl), @@ -1594,7 +1607,7 @@ GURL(chrome::kChromeUIEmojiPickerURL), GURL(chrome::kOsUIEmojiPickerURL), GURL(ash::file_manager::kChromeUIFileManagerURL), - GURL(chrome::kChromeUICloudUploadURL), + GURL(ash::kChromeUIFilesInternalsURL), GURL(chrome::kChromeUIFlagsURL), GURL(chrome::kOsUIFlagsURL), GURL(chrome::kOsUIGpuURL),
diff --git a/chrome/browser/ui/webui/chromeos/login/consolidated_consent_screen_handler.cc b/chrome/browser/ui/webui/chromeos/login/consolidated_consent_screen_handler.cc index 28e3484..e6b8bbe3 100644 --- a/chrome/browser/ui/webui/chromeos/login/consolidated_consent_screen_handler.cc +++ b/chrome/browser/ui/webui/chromeos/login/consolidated_consent_screen_handler.cc
@@ -45,10 +45,6 @@ IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_TITLE); builder->Add("consolidatedConsentUsageOptIn", IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_OWNER); - builder->Add("consolidatedConsentUsageOptInChild", - IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_CHILD_OWNER); - builder->Add("consolidatedConsentUsageOptInArcDisabled", - IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_ARC_DISABLED_OWNER); builder->Add("consolidatedConsentUsageOptInLearnMoreLink", IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_LINK); builder->Add("consolidatedConsentBackupOptInTitle",
diff --git a/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.cc b/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.cc index 4bae430..f9c83b1 100644 --- a/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.cc +++ b/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.cc
@@ -228,14 +228,14 @@ } } -void UpdateAuthParams(base::Value* params) { +void UpdateAuthParams(base::Value::Dict& params) { CrosSettings* cros_settings = CrosSettings::Get(); bool allow_new_user = true; cros_settings->GetBoolean(kAccountsPrefAllowNewUser, &allow_new_user); // nosignup flow if new users are not allowed. if (!allow_new_user) - params->SetStringKey("flow", "nosignup"); + params.Set("flow", "nosignup"); } bool ShouldCheckUserTypeBeforeAllowing() { @@ -275,25 +275,22 @@ return certificate_provider_service->pin_dialog_manager(); } -base::Value MakeSecurityTokenPinDialogParameters( +base::Value::Dict MakeSecurityTokenPinDialogParameters( bool enable_user_input, security_token_pin::ErrorLabel error_label, int attempts_left) { - base::Value params(base::Value::Type::DICTIONARY); + base::Value::Dict params; - params.SetBoolKey("enableUserInput", enable_user_input); - params.SetBoolKey("hasError", - error_label != security_token_pin::ErrorLabel::kNone); - params.SetStringKey( - "formattedError", - GenerateErrorMessage(error_label, attempts_left, enable_user_input)); + params.Set("enableUserInput", enable_user_input); + params.Set("hasError", error_label != security_token_pin::ErrorLabel::kNone); + params.Set("formattedError", GenerateErrorMessage(error_label, attempts_left, + enable_user_input)); if (attempts_left == -1) { - params.SetStringKey("formattedAttemptsLeft", std::u16string()); + params.Set("formattedAttemptsLeft", std::u16string()); } else { - params.SetStringKey( - "formattedAttemptsLeft", - GenerateErrorMessage(security_token_pin::ErrorLabel::kNone, - attempts_left, true)); + params.Set("formattedAttemptsLeft", + GenerateErrorMessage(security_token_pin::ErrorLabel::kNone, + attempts_left, true)); } return params; } @@ -407,27 +404,27 @@ const std::string& partition_name, const std::string* platform_version, const bool* collect_stats_consent) { - base::Value params(base::Value::Type::DICTIONARY); + base::Value::Dict params; // TODO(https://crbug.com/1338102): Looks like `forceReload` isn't used // anywhere further. Remove? - params.SetBoolKey("forceReload", context.force_reload); - params.SetStringKey("gaiaId", context.gaia_id); - params.SetBoolKey("readOnlyEmail", true); - params.SetStringKey("email", context.email); + params.Set("forceReload", context.force_reload); + params.Set("gaiaId", context.gaia_id); + params.Set("readOnlyEmail", true); + params.Set("email", context.email); - UpdateAuthParams(¶ms); + UpdateAuthParams(params); screen_mode_ = GetGaiaScreenMode(context.email); - params.SetIntKey("screenMode", screen_mode_); + params.Set("screenMode", screen_mode_); const std::string app_locale = g_browser_process->GetApplicationLocale(); if (!app_locale.empty()) - params.SetStringKey("hl", app_locale); + params.Set("hl", app_locale); std::string realm(GetRealm()); if (!realm.empty()) { - params.SetStringKey("realm", realm); + params.Set("realm", realm); } const std::string enterprise_enrollment_domain( @@ -436,22 +433,20 @@ const std::string sso_profile(GetSSOProfile()); if (!enterprise_enrollment_domain.empty()) { - params.SetStringKey("enterpriseEnrollmentDomain", - enterprise_enrollment_domain); + params.Set("enterpriseEnrollmentDomain", enterprise_enrollment_domain); } if (!sso_profile.empty()) { - params.SetStringKey("ssoProfile", sso_profile); + params.Set("ssoProfile", sso_profile); } if (!enterprise_domain_manager.empty()) { - params.SetStringKey("enterpriseDomainManager", enterprise_domain_manager); + params.Set("enterpriseDomainManager", enterprise_domain_manager); } - params.SetBoolKey("enterpriseManagedDevice", - g_browser_process->platform_part() - ->browser_policy_connector_ash() - ->IsDeviceEnterpriseManaged()); + params.Set("enterpriseManagedDevice", g_browser_process->platform_part() + ->browser_policy_connector_ash() + ->IsDeviceEnterpriseManaged()); const AccountId& owner_account_id = user_manager::UserManager::Get()->GetOwnerAccountId(); - params.SetBoolKey("hasDeviceOwner", owner_account_id.is_valid()); + params.Set("hasDeviceOwner", owner_account_id.is_valid()); if (owner_account_id.is_valid() && !::features::IsParentAccessCodeForOnlineLoginEnabled()) { // Some Autotest policy tests appear to wipe the user list in Local State @@ -460,50 +455,47 @@ user_manager::UserManager::Get()->FindUser(owner_account_id); if (owner_user && owner_user->GetType() == user_manager::UserType::USER_TYPE_CHILD) { - params.SetStringKey("obfuscatedOwnerId", owner_account_id.GetGaiaId()); + params.Set("obfuscatedOwnerId", owner_account_id.GetGaiaId()); } } - params.SetStringKey("chromeType", GetChromeType()); - params.SetStringKey("clientId", - GaiaUrls::GetInstance()->oauth2_chrome_client_id()); - params.SetStringKey("clientVersion", version_info::GetVersionNumber()); + params.Set("chromeType", GetChromeType()); + params.Set("clientId", GaiaUrls::GetInstance()->oauth2_chrome_client_id()); + params.Set("clientVersion", version_info::GetVersionNumber()); if (!platform_version->empty()) - params.SetStringKey("platformVersion", *platform_version); + params.Set("platformVersion", *platform_version); // Extended stable channel is not supported on Chrome OS Ash. - params.SetStringKey("releaseChannel", chrome::GetChannelName( - chrome::WithExtendedStable(false))); - params.SetStringKey("endpointGen", kEndpointGen); + params.Set("releaseChannel", + chrome::GetChannelName(chrome::WithExtendedStable(false))); + params.Set("endpointGen", kEndpointGen); std::string email_domain; if (CrosSettings::Get()->GetString(kAccountsPrefLoginScreenDomainAutoComplete, &email_domain) && !email_domain.empty()) { - params.SetStringKey("emailDomain", email_domain); + params.Set("emailDomain", email_domain); } - params.SetStringKey("gaiaUrl", GaiaUrls::GetInstance()->gaia_url().spec()); + params.Set("gaiaUrl", GaiaUrls::GetInstance()->gaia_url().spec()); switch (gaia_path_) { case GaiaPath::kDefault: // Use the default gaia signin path embedded/setup/v2/chromeos which is // set in authenticator.js break; case GaiaPath::kChildSignup: - params.SetStringKey("gaiaPath", - GaiaUrls::GetInstance() - ->embedded_setup_chromeos_kid_signup_url() - .path() - .substr(1)); + params.Set("gaiaPath", GaiaUrls::GetInstance() + ->embedded_setup_chromeos_kid_signup_url() + .path() + .substr(1)); break; case GaiaPath::kChildSignin: - params.SetStringKey("gaiaPath", - GaiaUrls::GetInstance() - ->embedded_setup_chromeos_kid_signin_url() - .path() - .substr(1)); + params.Set("gaiaPath", GaiaUrls::GetInstance() + ->embedded_setup_chromeos_kid_signin_url() + .path() + .substr(1)); break; case GaiaPath::kReauth: - params.SetStringKey( + params.Set( "gaiaPath", GaiaUrls::GetInstance()->embedded_reauth_chromeos_url().path().substr( 1)); @@ -513,25 +505,24 @@ // We only send `chromeos_board` Gaia URL parameter if user has opted into // sending device statistics. if (*collect_stats_consent) - params.SetStringKey("lsbReleaseBoard", base::SysInfo::GetLsbReleaseBoard()); + params.Set("lsbReleaseBoard", base::SysInfo::GetLsbReleaseBoard()); - params.SetStringKey("webviewPartitionName", partition_name); + params.Set("webviewPartitionName", partition_name); signin_partition_name_ = partition_name; - params.SetBoolKey("extractSamlPasswordAttributes", - login::ExtractSamlPasswordAttributesEnabled()); + params.Set("extractSamlPasswordAttributes", + login::ExtractSamlPasswordAttributesEnabled()); if (public_saml_url_fetcher_) { - params.SetBoolKey("startsOnSamlPage", true); + params.Set("startsOnSamlPage", true); DCHECK(base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kPublicAccountsSamlAclUrl)); std::string saml_acl_url = base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( switches::kPublicAccountsSamlAclUrl); - params.SetStringKey("samlAclUrl", saml_acl_url); + params.Set("samlAclUrl", saml_acl_url); if (public_saml_url_fetcher_->FetchSucceeded()) { - params.SetStringKey("frameUrl", - public_saml_url_fetcher_->GetRedirectUrl()); + params.Set("frameUrl", public_saml_url_fetcher_->GetRedirectUrl()); } else { LoginDisplayHost::default_host()->GetSigninUI()->ShowSigninError( SigninError::kFailedToFetchSamlRedirect, /*details=*/std::string()); @@ -550,8 +541,8 @@ // Enable the new endpoint for supervised account for now. We might expand // it to other account type in the future. if (is_child_account) { - params.SetBoolKey("isSupervisedUser", is_child_account); - params.SetBoolKey( + params.Set("isSupervisedUser", is_child_account); + params.Set( "isDeviceOwner", account_id == user_manager::UserManager::Get()->GetOwnerAccountId()); } @@ -559,15 +550,15 @@ if (ash::features::IsCryptohomeRecoveryFlowEnabled() && !gaia_reauth_request_token_.empty()) { - params.SetStringKey("rart", gaia_reauth_request_token_); + params.Set("rart", gaia_reauth_request_token_); } PrefService* local_state = g_browser_process->local_state(); if (local_state->IsManagedPreference( ash::prefs::kUrlParameterToAutofillSAMLUsername)) { - params.SetStringKey("urlParameterToAutofillSAMLUsername", - local_state->GetString( - ash::prefs::kUrlParameterToAutofillSAMLUsername)); + params.Set("urlParameterToAutofillSAMLUsername", + local_state->GetString( + ash::prefs::kUrlParameterToAutofillSAMLUsername)); } was_security_token_pin_canceled_ = false; @@ -1324,15 +1315,15 @@ } void GaiaScreenHandler::ShowAllowlistCheckFailedError() { - base::DictionaryValue params; - params.SetBoolKey("enterpriseManaged", g_browser_process->platform_part() - ->browser_policy_connector_ash() - ->IsDeviceEnterpriseManaged()); + base::Value::Dict params; + params.Set("enterpriseManaged", g_browser_process->platform_part() + ->browser_policy_connector_ash() + ->IsDeviceEnterpriseManaged()); bool family_link_allowed = false; CrosSettings::Get()->GetBoolean(kAccountsPrefFamilyLinkAccountsAllowed, &family_link_allowed); - params.SetBoolKey("familyLinkAllowed", family_link_allowed); + params.Set("familyLinkAllowed", family_link_allowed); CallExternalAPI("showAllowlistCheckFailedError", std::move(params)); }
diff --git a/chrome/browser/ui/webui/intro/intro_ui.cc b/chrome/browser/ui/webui/intro/intro_ui.cc index 92da7ec7..bf932a5 100644 --- a/chrome/browser/ui/webui/intro/intro_ui.cc +++ b/chrome/browser/ui/webui/intro/intro_ui.cc
@@ -11,10 +11,37 @@ #include "chrome/common/webui_url_constants.h" #include "chrome/grit/intro_resources.h" #include "chrome/grit/intro_resources_map.h" +#include "components/signin/public/base/signin_buildflags.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui_data_source.h" -namespace {} // namespace +#if BUILDFLAG(ENABLE_DICE_SUPPORT) +#include "chrome/grit/chromium_strings.h" +#include "chrome/grit/generated_resources.h" +#endif + +namespace { + +void AddStrings(content::WebUIDataSource* html_source) { +#if BUILDFLAG(ENABLE_DICE_SUPPORT) + static constexpr webui::LocalizedString kLocalizedStrings[] = { + {"pageTitle", IDS_FRE_SIGN_IN_TITLE}, + {"pageSubtitle", IDS_FRE_SIGN_IN_SUBTITLE}, + {"devicesCardTitle", IDS_FRE_DEVICES_CARD_TITLE}, + {"devicesCardDescription", IDS_FRE_DEVICES_CARD_DESCRIPTION}, + {"securityCardTitle", IDS_FRE_SECURITY_CARD_TITLE}, + {"securityCardDescription", IDS_FRE_SECURITY_CARD_DESCRIPTION}, + {"backupCardTitle", IDS_FRE_BACKUP_CARD_TITLE}, + {"backupCardDescription", IDS_FRE_BACKUP_CARD_DESCRIPTION}, + {"declineSignInButtonTitle", IDS_FRE_DECLINE_SIGN_IN_BUTTON_TITLE}, + {"acceptSignInButtonTitle", IDS_FRE_ACCEPT_SIGN_IN_BUTTON_TITLE}, + }; + + html_source->AddLocalizedStrings(kLocalizedStrings); +#endif +} + +} // namespace IntroUI::IntroUI(content::WebUI* web_ui) : content::WebUIController(web_ui) { DCHECK(base::FeatureList::IsEnabled(kForYouFre)); @@ -27,6 +54,8 @@ webui::SetupWebUIDataSource( source, base::make_span(kIntroResources, kIntroResourcesSize), IDR_INTRO_INTRO_HTML); + + AddStrings(source); } IntroUI::~IntroUI() = default;
diff --git a/chrome/browser/ui/webui/new_tab_page/new_tab_page_ui.cc b/chrome/browser/ui/webui/new_tab_page/new_tab_page_ui.cc index 5ed7f90..e0304c1 100644 --- a/chrome/browser/ui/webui/new_tab_page/new_tab_page_ui.cc +++ b/chrome/browser/ui/webui/new_tab_page/new_tab_page_ui.cc
@@ -137,8 +137,11 @@ "modulesCartStepOneUseStaticContent", commerce::kNtpChromeCartModuleDiscountConsentNtpStepOneUseStaticContent .Get()); - source->AddLocalizedString("modulesCartStepOneStaticContent", - IDS_NTP_CART_DISCOUNT_STEP_ONE_CONTENT); + // This does not have a raw string resource. + source->AddString( + "modulesCartStepOneStaticContent", + commerce::kNtpChromeCartModuleDiscountConsentNtpStepOneStaticContent + .Get()); AddRawStringOrDefault( source, "modulesCartConsentStepOneOneMerchantContent",
diff --git a/chrome/browser/ui/webui/settings/ash/about_section.cc b/chrome/browser/ui/webui/settings/ash/about_section.cc index cd5bc957..01572b8 100644 --- a/chrome/browser/ui/webui/settings/ash/about_section.cc +++ b/chrome/browser/ui/webui/settings/ash/about_section.cc
@@ -44,6 +44,14 @@ namespace chromeos { namespace settings { + +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom { +using ::ash::settings::mojom::SearchResultDefaultRank; +using ::ash::settings::mojom::SearchResultIcon; +using ::ash::settings::mojom::SearchResultType; +} // namespace mojom + namespace { const std::vector<SearchConcept>& GetAboutSearchConcepts() {
diff --git a/chrome/browser/ui/webui/settings/ash/about_section.h b/chrome/browser/ui/webui/settings/ash/about_section.h index ad23fdd..c38f2e7 100644 --- a/chrome/browser/ui/webui/settings/ash/about_section.h +++ b/chrome/browser/ui/webui/settings/ash/about_section.h
@@ -8,6 +8,8 @@ #include "base/values.h" #include "build/branding_buildflags.h" #include "chrome/browser/ui/webui/settings/ash/os_settings_section.h" +// TODO(https://crbug.com/1164001): move to forward declaration +#include "chrome/browser/ui/webui/settings/ash/search/search_tag_registry.h" #include "components/prefs/pref_change_registrar.h" #include "components/user_manager/user_manager.h" @@ -18,8 +20,6 @@ namespace chromeos { namespace settings { -class SearchTagRegistry; - // Provides UI strings and search tags for the settings "About Chrome OS" page. class AboutSection : public OsSettingsSection { public: @@ -37,7 +37,7 @@ void AddHandlers(content::WebUI* web_ui) override; int GetSectionNameMessageId() const override; mojom::Section GetSection() const override; - mojom::SearchResultIcon GetSectionIcon() const override; + ash::settings::mojom::SearchResultIcon GetSectionIcon() const override; std::string GetSectionPath() const override; bool LogMetric(mojom::Setting setting, base::Value& value) const override; void RegisterHierarchy(HierarchyGenerator* generator) const override;
diff --git a/chrome/browser/ui/webui/settings/ash/accessibility_section.cc b/chrome/browser/ui/webui/settings/ash/accessibility_section.cc index de4a2b24..9ee1032 100644 --- a/chrome/browser/ui/webui/settings/ash/accessibility_section.cc +++ b/chrome/browser/ui/webui/settings/ash/accessibility_section.cc
@@ -45,6 +45,14 @@ namespace chromeos { namespace settings { + +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom { +using ::ash::settings::mojom::SearchResultDefaultRank; +using ::ash::settings::mojom::SearchResultIcon; +using ::ash::settings::mojom::SearchResultType; +} // namespace mojom + namespace { const std::vector<SearchConcept>& GetA11ySearchConcepts() {
diff --git a/chrome/browser/ui/webui/settings/ash/accessibility_section.h b/chrome/browser/ui/webui/settings/ash/accessibility_section.h index 9086c21b..14d656d 100644 --- a/chrome/browser/ui/webui/settings/ash/accessibility_section.h +++ b/chrome/browser/ui/webui/settings/ash/accessibility_section.h
@@ -7,6 +7,8 @@ #include "base/values.h" #include "chrome/browser/ui/webui/settings/ash/os_settings_section.h" +// TODO(https://crbug.com/1164001): move to forward declaration +#include "chrome/browser/ui/webui/settings/ash/search/search_tag_registry.h" #include "components/prefs/pref_change_registrar.h" #include "content/public/browser/tts_controller.h" #include "extensions/browser/extension_registry.h" @@ -21,8 +23,6 @@ namespace chromeos { namespace settings { -class SearchTagRegistry; - // Provides UI strings and search tags for Accessibility settings. class AccessibilitySection : public OsSettingsSection, public content::VoicesChangedDelegate, @@ -39,7 +39,7 @@ void AddHandlers(content::WebUI* web_ui) override; int GetSectionNameMessageId() const override; mojom::Section GetSection() const override; - mojom::SearchResultIcon GetSectionIcon() const override; + ash::settings::mojom::SearchResultIcon GetSectionIcon() const override; std::string GetSectionPath() const override; bool LogMetric(mojom::Setting setting, base::Value& value) const override; void RegisterHierarchy(HierarchyGenerator* generator) const override;
diff --git a/chrome/browser/ui/webui/settings/ash/apps_section.cc b/chrome/browser/ui/webui/settings/ash/apps_section.cc index 1076734..40c157f 100644 --- a/chrome/browser/ui/webui/settings/ash/apps_section.cc +++ b/chrome/browser/ui/webui/settings/ash/apps_section.cc
@@ -38,6 +38,14 @@ namespace chromeos { namespace settings { + +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom { +using ::ash::settings::mojom::SearchResultDefaultRank; +using ::ash::settings::mojom::SearchResultIcon; +using ::ash::settings::mojom::SearchResultType; +} // namespace mojom + namespace { const std::vector<SearchConcept>& GetAppsSearchConcepts() {
diff --git a/chrome/browser/ui/webui/settings/ash/apps_section.h b/chrome/browser/ui/webui/settings/ash/apps_section.h index cf83e8e..37c2536 100644 --- a/chrome/browser/ui/webui/settings/ash/apps_section.h +++ b/chrome/browser/ui/webui/settings/ash/apps_section.h
@@ -10,6 +10,8 @@ #include "chrome/browser/apps/app_service/app_service_proxy_forward.h" #include "chrome/browser/ui/app_list/arc/arc_app_list_prefs.h" #include "chrome/browser/ui/webui/settings/ash/os_settings_section.h" +// TODO(https://crbug.com/1164001): move to forward declaration +#include "chrome/browser/ui/webui/settings/ash/search/search_tag_registry.h" #include "components/prefs/pref_change_registrar.h" class PrefService; @@ -21,8 +23,6 @@ namespace chromeos { namespace settings { -class SearchTagRegistry; - // Provides UI strings and search tags for Apps settings. class AppsSection : public OsSettingsSection, public ArcAppListPrefs::Observer, @@ -41,7 +41,7 @@ void AddHandlers(content::WebUI* web_ui) override; int GetSectionNameMessageId() const override; mojom::Section GetSection() const override; - mojom::SearchResultIcon GetSectionIcon() const override; + ash::settings::mojom::SearchResultIcon GetSectionIcon() const override; std::string GetSectionPath() const override; bool LogMetric(mojom::Setting setting, base::Value& value) const override; void RegisterHierarchy(HierarchyGenerator* generator) const override;
diff --git a/chrome/browser/ui/webui/settings/ash/bluetooth_section.cc b/chrome/browser/ui/webui/settings/ash/bluetooth_section.cc index 95cf4f2..b75d193 100644 --- a/chrome/browser/ui/webui/settings/ash/bluetooth_section.cc +++ b/chrome/browser/ui/webui/settings/ash/bluetooth_section.cc
@@ -36,6 +36,14 @@ namespace chromeos { namespace settings { + +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom { +using ::ash::settings::mojom::SearchResultDefaultRank; +using ::ash::settings::mojom::SearchResultIcon; +using ::ash::settings::mojom::SearchResultType; +} // namespace mojom + namespace { const std::vector<SearchConcept>& GetBluetoothSearchConcepts() {
diff --git a/chrome/browser/ui/webui/settings/ash/bluetooth_section.h b/chrome/browser/ui/webui/settings/ash/bluetooth_section.h index b6a99a5..283357a 100644 --- a/chrome/browser/ui/webui/settings/ash/bluetooth_section.h +++ b/chrome/browser/ui/webui/settings/ash/bluetooth_section.h
@@ -9,6 +9,8 @@ #include "base/memory/weak_ptr.h" #include "base/values.h" #include "chrome/browser/ui/webui/settings/ash/os_settings_section.h" +// TODO(https://crbug.com/1164001): move to forward declaration +#include "chrome/browser/ui/webui/settings/ash/search/search_tag_registry.h" #include "device/bluetooth/bluetooth_adapter.h" class PrefChangeRegistrar; @@ -21,8 +23,6 @@ namespace chromeos { namespace settings { -class SearchTagRegistry; - // Provides UI strings and search tags for Bluetooth settings. Different search // tags are registered depending on whether the device has a Bluetooth chip and // whether it is turned on or off. @@ -40,7 +40,7 @@ void AddHandlers(content::WebUI* web_ui) override; int GetSectionNameMessageId() const override; mojom::Section GetSection() const override; - mojom::SearchResultIcon GetSectionIcon() const override; + ash::settings::mojom::SearchResultIcon GetSectionIcon() const override; std::string GetSectionPath() const override; bool LogMetric(mojom::Setting setting, base::Value& value) const override; void RegisterHierarchy(HierarchyGenerator* generator) const override;
diff --git a/chrome/browser/ui/webui/settings/ash/crostini_section.cc b/chrome/browser/ui/webui/settings/ash/crostini_section.cc index 730b5369..a9044bf3 100644 --- a/chrome/browser/ui/webui/settings/ash/crostini_section.cc +++ b/chrome/browser/ui/webui/settings/ash/crostini_section.cc
@@ -34,6 +34,14 @@ namespace chromeos { namespace settings { + +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom { +using ::ash::settings::mojom::SearchResultDefaultRank; +using ::ash::settings::mojom::SearchResultIcon; +using ::ash::settings::mojom::SearchResultType; +} // namespace mojom + namespace { const std::vector<SearchConcept>& GetCrostiniOptedInSearchConcepts() {
diff --git a/chrome/browser/ui/webui/settings/ash/crostini_section.h b/chrome/browser/ui/webui/settings/ash/crostini_section.h index d4bb50e6..67e6087 100644 --- a/chrome/browser/ui/webui/settings/ash/crostini_section.h +++ b/chrome/browser/ui/webui/settings/ash/crostini_section.h
@@ -7,6 +7,8 @@ #include "base/values.h" #include "chrome/browser/ui/webui/settings/ash/os_settings_section.h" +// TODO(https://crbug.com/1164001): move to forward declaration +#include "chrome/browser/ui/webui/settings/ash/search/search_tag_registry.h" #include "components/prefs/pref_change_registrar.h" namespace content { @@ -16,8 +18,6 @@ namespace chromeos { namespace settings { -class SearchTagRegistry; - // Provides UI strings and search tags for Crostini settings. Search tags are // only added if Crostini is available, and subpage search tags are added only // when those subpages are available. @@ -34,7 +34,7 @@ void AddHandlers(content::WebUI* web_ui) override; int GetSectionNameMessageId() const override; mojom::Section GetSection() const override; - mojom::SearchResultIcon GetSectionIcon() const override; + ash::settings::mojom::SearchResultIcon GetSectionIcon() const override; std::string GetSectionPath() const override; bool LogMetric(mojom::Setting setting, base::Value& value) const override; void RegisterHierarchy(HierarchyGenerator* generator) const override;
diff --git a/chrome/browser/ui/webui/settings/ash/date_time_section.cc b/chrome/browser/ui/webui/settings/ash/date_time_section.cc index 76d7b0b..cc3e36b 100644 --- a/chrome/browser/ui/webui/settings/ash/date_time_section.cc +++ b/chrome/browser/ui/webui/settings/ash/date_time_section.cc
@@ -24,6 +24,14 @@ namespace chromeos { namespace settings { + +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom { +using ::ash::settings::mojom::SearchResultDefaultRank; +using ::ash::settings::mojom::SearchResultIcon; +using ::ash::settings::mojom::SearchResultType; +} // namespace mojom + namespace { const std::vector<SearchConcept>& GetDateTimeSearchConcepts() {
diff --git a/chrome/browser/ui/webui/settings/ash/date_time_section.h b/chrome/browser/ui/webui/settings/ash/date_time_section.h index 27a3204..f6b537d4 100644 --- a/chrome/browser/ui/webui/settings/ash/date_time_section.h +++ b/chrome/browser/ui/webui/settings/ash/date_time_section.h
@@ -7,6 +7,8 @@ #include "base/values.h" #include "chrome/browser/ui/webui/settings/ash/os_settings_section.h" +// TODO(https://crbug.com/1164001): move to forward declaration +#include "chrome/browser/ui/webui/settings/ash/search/search_tag_registry.h" namespace content { class WebUIDataSource; @@ -15,8 +17,6 @@ namespace chromeos { namespace settings { -class SearchTagRegistry; - // Provides UI strings and search tags for Date and Time settings. class DateTimeSection : public OsSettingsSection { public: @@ -29,7 +29,7 @@ void AddHandlers(content::WebUI* web_ui) override; int GetSectionNameMessageId() const override; mojom::Section GetSection() const override; - mojom::SearchResultIcon GetSectionIcon() const override; + ash::settings::mojom::SearchResultIcon GetSectionIcon() const override; std::string GetSectionPath() const override; bool LogMetric(mojom::Setting setting, base::Value& value) const override; void RegisterHierarchy(HierarchyGenerator* generator) const override;
diff --git a/chrome/browser/ui/webui/settings/ash/device_section.cc b/chrome/browser/ui/webui/settings/ash/device_section.cc index 581c719..4e89340b 100644 --- a/chrome/browser/ui/webui/settings/ash/device_section.cc +++ b/chrome/browser/ui/webui/settings/ash/device_section.cc
@@ -40,6 +40,14 @@ namespace chromeos { namespace settings { + +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom { +using ::ash::settings::mojom::SearchResultDefaultRank; +using ::ash::settings::mojom::SearchResultIcon; +using ::ash::settings::mojom::SearchResultType; +} // namespace mojom + namespace { const std::vector<SearchConcept>& GetDeviceSearchConcepts() {
diff --git a/chrome/browser/ui/webui/settings/ash/device_section.h b/chrome/browser/ui/webui/settings/ash/device_section.h index a8a259f..6c8da0b 100644 --- a/chrome/browser/ui/webui/settings/ash/device_section.h +++ b/chrome/browser/ui/webui/settings/ash/device_section.h
@@ -12,6 +12,8 @@ #include "base/values.h" #include "chrome/browser/ash/system/pointer_device_observer.h" #include "chrome/browser/ui/webui/settings/ash/os_settings_section.h" +// TODO(https://crbug.com/1164001): move to forward declaration +#include "chrome/browser/ui/webui/settings/ash/search/search_tag_registry.h" #include "chromeos/crosapi/mojom/cros_display_config.mojom.h" #include "chromeos/dbus/power/power_manager_client.h" #include "mojo/public/cpp/bindings/associated_receiver.h" @@ -28,8 +30,6 @@ namespace chromeos { namespace settings { -class SearchTagRegistry; - // Provides UI strings and search tags for Device settings. class DeviceSection : public OsSettingsSection, public system::PointerDeviceObserver::Observer, @@ -49,7 +49,7 @@ void AddHandlers(content::WebUI* web_ui) override; int GetSectionNameMessageId() const override; mojom::Section GetSection() const override; - mojom::SearchResultIcon GetSectionIcon() const override; + ash::settings::mojom::SearchResultIcon GetSectionIcon() const override; std::string GetSectionPath() const override; bool LogMetric(mojom::Setting setting, base::Value& value) const override; void RegisterHierarchy(HierarchyGenerator* generator) const override;
diff --git a/chrome/browser/ui/webui/settings/ash/fake_hierarchy.cc b/chrome/browser/ui/webui/settings/ash/fake_hierarchy.cc index 9853968..8b8d84e 100644 --- a/chrome/browser/ui/webui/settings/ash/fake_hierarchy.cc +++ b/chrome/browser/ui/webui/settings/ash/fake_hierarchy.cc
@@ -11,6 +11,13 @@ namespace chromeos { namespace settings { +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom { +using ::ash::settings::mojom::SearchResultDefaultRank; +using ::ash::settings::mojom::SearchResultIcon; +using ::ash::settings::mojom::SearchResultType; +} // namespace mojom + FakeHierarchy::FakeHierarchy(const OsSettingsSections* sections) : Hierarchy(sections) {}
diff --git a/chrome/browser/ui/webui/settings/ash/fake_hierarchy.h b/chrome/browser/ui/webui/settings/ash/fake_hierarchy.h index 1655e08..ddc5677 100644 --- a/chrome/browser/ui/webui/settings/ash/fake_hierarchy.h +++ b/chrome/browser/ui/webui/settings/ash/fake_hierarchy.h
@@ -26,8 +26,8 @@ int name_message_id, mojom::Section section, mojom::Subpage subpage, - mojom::SearchResultIcon icon, - mojom::SearchResultDefaultRank default_rank, + ash::settings::mojom::SearchResultIcon icon, + ash::settings::mojom::SearchResultDefaultRank default_rank, const std::string& url_path_with_parameters, absl::optional<mojom::Subpage> parent_subpage = absl::nullopt); void AddSettingMetadata( @@ -39,7 +39,7 @@ // Hierarchy: std::string ModifySearchResultUrl( mojom::Section section, - mojom::SearchResultType type, + ash::settings::mojom::SearchResultType type, OsSettingsIdentifier id, const std::string& url_to_modify) const override; }; @@ -47,4 +47,9 @@ } // namespace settings } // namespace chromeos +// TODO(https://crbug.com/1164001): remove when it moved to ash. +namespace ash::settings { +using ::chromeos::settings::FakeHierarchy; +} + #endif // CHROME_BROWSER_UI_WEBUI_SETTINGS_ASH_FAKE_HIERARCHY_H_
diff --git a/chrome/browser/ui/webui/settings/ash/fake_os_settings_section.cc b/chrome/browser/ui/webui/settings/ash/fake_os_settings_section.cc index b8f600d..3b4b2aab 100644 --- a/chrome/browser/ui/webui/settings/ash/fake_os_settings_section.cc +++ b/chrome/browser/ui/webui/settings/ash/fake_os_settings_section.cc
@@ -11,6 +11,13 @@ namespace chromeos { namespace settings { +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom { +using ::ash::settings::mojom::SearchResultDefaultRank; +using ::ash::settings::mojom::SearchResultIcon; +using ::ash::settings::mojom::SearchResultType; +} // namespace mojom + FakeOsSettingsSection::FakeOsSettingsSection(mojom::Section section) : section_(section) {}
diff --git a/chrome/browser/ui/webui/settings/ash/fake_os_settings_section.h b/chrome/browser/ui/webui/settings/ash/fake_os_settings_section.h index b0805bd..960100db 100644 --- a/chrome/browser/ui/webui/settings/ash/fake_os_settings_section.h +++ b/chrome/browser/ui/webui/settings/ash/fake_os_settings_section.h
@@ -38,7 +38,7 @@ mojom::Section GetSection() const override; // These functions return arbitrary dummy values. - mojom::SearchResultIcon GetSectionIcon() const override; + ash::settings::mojom::SearchResultIcon GetSectionIcon() const override; std::string GetSectionPath() const override; bool LogMetric(mojom::Setting setting, base::Value& value) const override; @@ -46,7 +46,7 @@ // the URL is "networkDetails" and the section is mojom::Section::kNetwork, // the returned URL is "Section::kNetwork::networkDetails". std::string ModifySearchResultUrl( - mojom::SearchResultType type, + ash::settings::mojom::SearchResultType type, OsSettingsIdentifier id, const std::string& url_to_modify) const override;
diff --git a/chrome/browser/ui/webui/settings/ash/fake_os_settings_sections.h b/chrome/browser/ui/webui/settings/ash/fake_os_settings_sections.h index 6ec65f7..7313e8b 100644 --- a/chrome/browser/ui/webui/settings/ash/fake_os_settings_sections.h +++ b/chrome/browser/ui/webui/settings/ash/fake_os_settings_sections.h
@@ -23,4 +23,9 @@ } // namespace settings } // namespace chromeos +// TODO(https://crbug.com/1164001): remove when it moved to ash. +namespace ash::settings { +using ::chromeos::settings::FakeOsSettingsSections; +} + #endif // CHROME_BROWSER_UI_WEBUI_SETTINGS_ASH_FAKE_OS_SETTINGS_SECTIONS_H_
diff --git a/chrome/browser/ui/webui/settings/ash/files_section.cc b/chrome/browser/ui/webui/settings/ash/files_section.cc index 7140afd..c839803 100644 --- a/chrome/browser/ui/webui/settings/ash/files_section.cc +++ b/chrome/browser/ui/webui/settings/ash/files_section.cc
@@ -20,6 +20,14 @@ namespace chromeos { namespace settings { + +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom { +using ::ash::settings::mojom::SearchResultDefaultRank; +using ::ash::settings::mojom::SearchResultIcon; +using ::ash::settings::mojom::SearchResultType; +} // namespace mojom + namespace { const std::vector<SearchConcept>& GetFilesSearchConcepts() {
diff --git a/chrome/browser/ui/webui/settings/ash/files_section.h b/chrome/browser/ui/webui/settings/ash/files_section.h index 79419b2f..026a6213 100644 --- a/chrome/browser/ui/webui/settings/ash/files_section.h +++ b/chrome/browser/ui/webui/settings/ash/files_section.h
@@ -7,6 +7,8 @@ #include "base/values.h" #include "chrome/browser/ui/webui/settings/ash/os_settings_section.h" +// TODO(https://crbug.com/1164001): move to forward declaration +#include "chrome/browser/ui/webui/settings/ash/search/search_tag_registry.h" namespace content { class WebUIDataSource; @@ -15,8 +17,6 @@ namespace chromeos { namespace settings { -class SearchTagRegistry; - // Provides UI strings and search tags for Files settings. class FilesSection : public OsSettingsSection { public: @@ -29,7 +29,7 @@ void AddHandlers(content::WebUI* web_ui) override; int GetSectionNameMessageId() const override; mojom::Section GetSection() const override; - mojom::SearchResultIcon GetSectionIcon() const override; + ash::settings::mojom::SearchResultIcon GetSectionIcon() const override; std::string GetSectionPath() const override; bool LogMetric(mojom::Setting setting, base::Value& value) const override; void RegisterHierarchy(HierarchyGenerator* generator) const override;
diff --git a/chrome/browser/ui/webui/settings/ash/hierarchy.cc b/chrome/browser/ui/webui/settings/ash/hierarchy.cc index 9b81843..9b7cf6d 100644 --- a/chrome/browser/ui/webui/settings/ash/hierarchy.cc +++ b/chrome/browser/ui/webui/settings/ash/hierarchy.cc
@@ -15,6 +15,17 @@ namespace chromeos { namespace settings { + +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom { +using ::ash::settings::mojom::SearchResult; +using ::ash::settings::mojom::SearchResultDefaultRank; +using ::ash::settings::mojom::SearchResultIcon; +using ::ash::settings::mojom::SearchResultIdentifier; +using ::ash::settings::mojom::SearchResultPtr; +using ::ash::settings::mojom::SearchResultType; +} // namespace mojom + namespace { // Used to generate localized names.
diff --git a/chrome/browser/ui/webui/settings/ash/hierarchy.h b/chrome/browser/ui/webui/settings/ash/hierarchy.h index 8189e383..c8e2e78 100644 --- a/chrome/browser/ui/webui/settings/ash/hierarchy.h +++ b/chrome/browser/ui/webui/settings/ash/hierarchy.h
@@ -55,7 +55,8 @@ // tag as the search result text. |relevance_score| must be passed by the // client, since this result is being created manually instead of via query // matching. - mojom::SearchResultPtr ToSearchResult(double relevance_score) const; + ash::settings::mojom::SearchResultPtr ToSearchResult( + double relevance_score) const; private: mojom::Section section_; @@ -67,8 +68,8 @@ SubpageMetadata(int name_message_id, mojom::Section section, mojom::Subpage subpage, - mojom::SearchResultIcon icon, - mojom::SearchResultDefaultRank default_rank, + ash::settings::mojom::SearchResultIcon icon, + ash::settings::mojom::SearchResultDefaultRank default_rank, const std::string& url_path_with_parameters, const Hierarchy* hierarchy); ~SubpageMetadata(); @@ -83,7 +84,8 @@ // tag as the search result text. |relevance_score| must be passed by the // client, since this result is being created manually instead of via query // matching. - mojom::SearchResultPtr ToSearchResult(double relevance_score) const; + ash::settings::mojom::SearchResultPtr ToSearchResult( + double relevance_score) const; private: mojom::Subpage subpage_; @@ -93,10 +95,10 @@ int name_message_id_; // Icon used for this subpage. - mojom::SearchResultIcon icon_; + ash::settings::mojom::SearchResultIcon icon_; // Default rank; used to order returned results. - mojom::SearchResultDefaultRank default_rank_; + ash::settings::mojom::SearchResultDefaultRank default_rank_; // Static URL path, which may need to be modified via // |modify_url_callback_|. @@ -158,7 +160,7 @@ virtual std::string ModifySearchResultUrl( mojom::Section section, - mojom::SearchResultType type, + ash::settings::mojom::SearchResultType type, OsSettingsIdentifier id, const std::string& url_to_modify) const; @@ -168,4 +170,9 @@ } // namespace settings } // namespace chromeos +// TODO(https://crbug.com/1164001): remove when it moved to ash. +namespace ash::settings { +using ::chromeos::settings::Hierarchy; +} + #endif // CHROME_BROWSER_UI_WEBUI_SETTINGS_ASH_HIERARCHY_H_
diff --git a/chrome/browser/ui/webui/settings/ash/internet_section.cc b/chrome/browser/ui/webui/settings/ash/internet_section.cc index 1ed6eadf..54e44e6 100644 --- a/chrome/browser/ui/webui/settings/ash/internet_section.cc +++ b/chrome/browser/ui/webui/settings/ash/internet_section.cc
@@ -34,6 +34,14 @@ namespace chromeos { namespace settings { + +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom { +using ::ash::settings::mojom::SearchResultDefaultRank; +using ::ash::settings::mojom::SearchResultIcon; +using ::ash::settings::mojom::SearchResultType; +} // namespace mojom + namespace { // These values are persisted to logs. Entries should not be renumbered
diff --git a/chrome/browser/ui/webui/settings/ash/internet_section.h b/chrome/browser/ui/webui/settings/ash/internet_section.h index 6ddb7baa..c8c9214d 100644 --- a/chrome/browser/ui/webui/settings/ash/internet_section.h +++ b/chrome/browser/ui/webui/settings/ash/internet_section.h
@@ -10,6 +10,8 @@ #include "base/values.h" #include "chrome/browser/ui/webui/settings/ash/os_settings_section.h" +// TODO(https://crbug.com/1164001): move to forward declaration +#include "chrome/browser/ui/webui/settings/ash/search/search_tag_registry.h" #include "chromeos/services/network_config/public/cpp/cros_network_config_observer.h" #include "mojo/public/cpp/bindings/receiver.h" #include "mojo/public/cpp/bindings/remote.h" @@ -24,8 +26,6 @@ namespace chromeos { namespace settings { -class SearchTagRegistry; - class InternetSection : public OsSettingsSection, public network_config::CrosNetworkConfigObserver { public: @@ -38,12 +38,12 @@ void AddHandlers(content::WebUI* web_ui) override; int GetSectionNameMessageId() const override; mojom::Section GetSection() const override; - mojom::SearchResultIcon GetSectionIcon() const override; + ash::settings::mojom::SearchResultIcon GetSectionIcon() const override; std::string GetSectionPath() const override; bool LogMetric(mojom::Setting setting, base::Value& value) const override; void RegisterHierarchy(HierarchyGenerator* generator) const override; std::string ModifySearchResultUrl( - mojom::SearchResultType type, + ash::settings::mojom::SearchResultType type, OsSettingsIdentifier id, const std::string& url_to_modify) const override;
diff --git a/chrome/browser/ui/webui/settings/ash/kerberos_section.cc b/chrome/browser/ui/webui/settings/ash/kerberos_section.cc index fc374ee..d0c7bef 100644 --- a/chrome/browser/ui/webui/settings/ash/kerberos_section.cc +++ b/chrome/browser/ui/webui/settings/ash/kerberos_section.cc
@@ -14,6 +14,14 @@ namespace chromeos { namespace settings { + +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom { +using ::ash::settings::mojom::SearchResultDefaultRank; +using ::ash::settings::mojom::SearchResultIcon; +using ::ash::settings::mojom::SearchResultType; +} // namespace mojom + namespace { // Provides search tags that are always available when the feature is enabled by
diff --git a/chrome/browser/ui/webui/settings/ash/kerberos_section.h b/chrome/browser/ui/webui/settings/ash/kerberos_section.h index 35b0be2..d3e33ad 100644 --- a/chrome/browser/ui/webui/settings/ash/kerberos_section.h +++ b/chrome/browser/ui/webui/settings/ash/kerberos_section.h
@@ -8,6 +8,8 @@ #include "base/values.h" #include "chrome/browser/ash/kerberos/kerberos_credentials_manager.h" #include "chrome/browser/ui/webui/settings/ash/os_settings_section.h" +// TODO(https://crbug.com/1164001): move to forward declaration +#include "chrome/browser/ui/webui/settings/ash/search/search_tag_registry.h" class Profile; @@ -18,8 +20,6 @@ namespace chromeos { namespace settings { -class SearchTagRegistry; - // Provides UI strings and search tags for Kerberos settings. Search tags are // only added if the feature is enabled by policy. class KerberosSection : public OsSettingsSection, @@ -36,7 +36,7 @@ void AddHandlers(content::WebUI* web_ui) override; int GetSectionNameMessageId() const override; mojom::Section GetSection() const override; - mojom::SearchResultIcon GetSectionIcon() const override; + ash::settings::mojom::SearchResultIcon GetSectionIcon() const override; std::string GetSectionPath() const override; bool LogMetric(mojom::Setting setting, base::Value& value) const override; void RegisterHierarchy(HierarchyGenerator* generator) const override;
diff --git a/chrome/browser/ui/webui/settings/ash/languages_section.cc b/chrome/browser/ui/webui/settings/ash/languages_section.cc index 2f0f0b0f..77bbbbcd0 100644 --- a/chrome/browser/ui/webui/settings/ash/languages_section.cc +++ b/chrome/browser/ui/webui/settings/ash/languages_section.cc
@@ -28,6 +28,14 @@ namespace chromeos { namespace settings { + +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom { +using ::ash::settings::mojom::SearchResultDefaultRank; +using ::ash::settings::mojom::SearchResultIcon; +using ::ash::settings::mojom::SearchResultType; +} // namespace mojom + namespace { const std::vector<SearchConcept>& GetLanguagesPageSearchConceptsV2() {
diff --git a/chrome/browser/ui/webui/settings/ash/languages_section.h b/chrome/browser/ui/webui/settings/ash/languages_section.h index 72d58e6..60ddd7f6 100644 --- a/chrome/browser/ui/webui/settings/ash/languages_section.h +++ b/chrome/browser/ui/webui/settings/ash/languages_section.h
@@ -7,6 +7,8 @@ #include "base/values.h" #include "chrome/browser/ui/webui/settings/ash/os_settings_section.h" +// TODO(https://crbug.com/1164001): move to forward declaration +#include "chrome/browser/ui/webui/settings/ash/search/search_tag_registry.h" #include "components/prefs/pref_change_registrar.h" namespace content { @@ -16,8 +18,6 @@ namespace chromeos { namespace settings { -class SearchTagRegistry; - // Provides UI strings and search tags for Languages & Input settings. Search // tags for some input features (e.g., Smart Inputs) are used only when // the relevant features are enabled. @@ -34,7 +34,7 @@ void AddHandlers(content::WebUI* web_ui) override; int GetSectionNameMessageId() const override; mojom::Section GetSection() const override; - mojom::SearchResultIcon GetSectionIcon() const override; + ash::settings::mojom::SearchResultIcon GetSectionIcon() const override; std::string GetSectionPath() const override; bool LogMetric(mojom::Setting setting, base::Value& value) const override; void RegisterHierarchy(HierarchyGenerator* generator) const override;
diff --git a/chrome/browser/ui/webui/settings/ash/main_section.cc b/chrome/browser/ui/webui/settings/ash/main_section.cc index 0466155..22235205 100644 --- a/chrome/browser/ui/webui/settings/ash/main_section.cc +++ b/chrome/browser/ui/webui/settings/ash/main_section.cc
@@ -22,6 +22,7 @@ #include "chrome/browser/ui/webui/plural_string_handler.h" #include "chrome/browser/ui/webui/policy_indicator_localized_strings_provider.h" #include "chrome/browser/ui/webui/settings/ash/os_settings_features_util.h" +#include "chrome/browser/ui/webui/settings/ash/search/search_tag_registry.h" #include "chrome/browser/ui/webui/settings/browser_lifetime_handler.h" #include "chrome/browser/ui/webui/webui_util.h" #include "chrome/common/chrome_features.h" @@ -40,6 +41,12 @@ namespace chromeos { namespace settings { + +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom { +using ::ash::settings::mojom::SearchResultIcon; +} + namespace { void AddSearchInSettingsStrings(content::WebUIDataSource* html_source) {
diff --git a/chrome/browser/ui/webui/settings/ash/main_section.h b/chrome/browser/ui/webui/settings/ash/main_section.h index 8bd87818..d66bfd7 100644 --- a/chrome/browser/ui/webui/settings/ash/main_section.h +++ b/chrome/browser/ui/webui/settings/ash/main_section.h
@@ -22,7 +22,8 @@ // since they only apply to specific pages/settings. class MainSection : public OsSettingsSection { public: - MainSection(Profile* profile, SearchTagRegistry* search_tag_registry); + MainSection(Profile* profile, + ash::settings::SearchTagRegistry* search_tag_registry); ~MainSection() override; private: @@ -31,7 +32,7 @@ void AddHandlers(content::WebUI* web_ui) override; int GetSectionNameMessageId() const override; mojom::Section GetSection() const override; - mojom::SearchResultIcon GetSectionIcon() const override; + ash::settings::mojom::SearchResultIcon GetSectionIcon() const override; std::string GetSectionPath() const override; bool LogMetric(mojom::Setting setting, base::Value& value) const override; void RegisterHierarchy(HierarchyGenerator* generator) const override;
diff --git a/chrome/browser/ui/webui/settings/ash/multidevice_section.cc b/chrome/browser/ui/webui/settings/ash/multidevice_section.cc index 950e5f2..99968b4a 100644 --- a/chrome/browser/ui/webui/settings/ash/multidevice_section.cc +++ b/chrome/browser/ui/webui/settings/ash/multidevice_section.cc
@@ -41,6 +41,14 @@ namespace chromeos { namespace settings { + +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom { +using ::ash::settings::mojom::SearchResultDefaultRank; +using ::ash::settings::mojom::SearchResultIcon; +using ::ash::settings::mojom::SearchResultType; +} // namespace mojom + namespace { using Feature = ::ash::multidevice_setup::mojom::Feature;
diff --git a/chrome/browser/ui/webui/settings/ash/multidevice_section.h b/chrome/browser/ui/webui/settings/ash/multidevice_section.h index e99c492..0a65403 100644 --- a/chrome/browser/ui/webui/settings/ash/multidevice_section.h +++ b/chrome/browser/ui/webui/settings/ash/multidevice_section.h
@@ -14,6 +14,8 @@ // TODO(https://crbug.com/1164001): move to forward declaration. #include "chrome/browser/ash/android_sms/android_sms_service.h" #include "chrome/browser/ui/webui/nearby_share/public/mojom/nearby_share_settings.mojom.h" +// TODO(https://crbug.com/1164001): move to forward declaration +#include "chrome/browser/ui/webui/settings/ash/search/search_tag_registry.h" #include "components/prefs/pref_change_registrar.h" class PrefService; @@ -25,8 +27,6 @@ namespace chromeos { namespace settings { -class SearchTagRegistry; - // Provides UI strings and search tags for MultiDevice settings. Different // search tags are registered depending on whether MultiDevice features are // allowed and whether the user has opted into the suite of features. @@ -52,7 +52,7 @@ void AddHandlers(content::WebUI* web_ui) override; int GetSectionNameMessageId() const override; mojom::Section GetSection() const override; - mojom::SearchResultIcon GetSectionIcon() const override; + ash::settings::mojom::SearchResultIcon GetSectionIcon() const override; std::string GetSectionPath() const override; bool LogMetric(mojom::Setting setting, base::Value& value) const override; void RegisterHierarchy(HierarchyGenerator* generator) const override;
diff --git a/chrome/browser/ui/webui/settings/ash/os_settings_identifier.h b/chrome/browser/ui/webui/settings/ash/os_settings_identifier.h index 35a9aac..91d4ef3 100644 --- a/chrome/browser/ui/webui/settings/ash/os_settings_identifier.h +++ b/chrome/browser/ui/webui/settings/ash/os_settings_identifier.h
@@ -21,4 +21,9 @@ } // namespace settings } // namespace chromeos +// TODO(https://crbug.com/1164001): remove when it moved to ash. +namespace ash::settings { +using ::chromeos::settings::OsSettingsIdentifier; +} + #endif // CHROME_BROWSER_UI_WEBUI_SETTINGS_ASH_OS_SETTINGS_IDENTIFIER_H_
diff --git a/chrome/browser/ui/webui/settings/ash/os_settings_manager.h b/chrome/browser/ui/webui/settings/ash/os_settings_manager.h index c508f35..243502d 100644 --- a/chrome/browser/ui/webui/settings/ash/os_settings_manager.h +++ b/chrome/browser/ui/webui/settings/ash/os_settings_manager.h
@@ -22,6 +22,10 @@ #include "chrome/browser/ash/printing/cups_printers_manager.h" // TODO(https://crbug.com/1164001): move to forward declaration #include "chrome/browser/ui/webui/settings/ash/os_apps_page/app_notification_handler.h" +// TODO(https://crbug.com/1164001): move to forward declaration +#include "chrome/browser/ui/webui/settings/ash/search/search_handler.h" +// TODO(https://crbug.com/1164001): move to forward declaration +#include "chrome/browser/ui/webui/settings/ash/search/search_tag_registry.h" // TODO(https://crbug.com/1164001): forward declare when moved ash #include "chromeos/ash/components/local_search_service/public/cpp/local_search_service_proxy.h" #include "components/keyed_service/core/keyed_service.h" @@ -47,8 +51,6 @@ class Hierarchy; class OsSettingsSections; -class SearchHandler; -class SearchTagRegistry; class SettingsUserActionTracker; // Manager for the Chrome OS settings page. This class is implemented as a
diff --git a/chrome/browser/ui/webui/settings/ash/os_settings_section.cc b/chrome/browser/ui/webui/settings/ash/os_settings_section.cc index 6372ebc..e53c90cf 100644 --- a/chrome/browser/ui/webui/settings/ash/os_settings_section.cc +++ b/chrome/browser/ui/webui/settings/ash/os_settings_section.cc
@@ -8,12 +8,22 @@ #include "base/check.h" #include "base/strings/utf_string_conversions.h" #include "base/system/sys_info.h" +#include "chrome/browser/ui/webui/settings/ash/search/search_tag_registry.h" #include "chrome/grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" namespace chromeos { namespace settings { +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom { +using ::ash::settings::mojom::SearchResult; +using ::ash::settings::mojom::SearchResultDefaultRank; +using ::ash::settings::mojom::SearchResultIdentifier; +using ::ash::settings::mojom::SearchResultPtr; +using ::ash::settings::mojom::SearchResultType; +} // namespace mojom + // static constexpr const char OsSettingsSection::kSettingIdUrlParam[];
diff --git a/chrome/browser/ui/webui/settings/ash/os_settings_section.h b/chrome/browser/ui/webui/settings/ash/os_settings_section.h index 3bc30a36..0437eca 100644 --- a/chrome/browser/ui/webui/settings/ash/os_settings_section.h +++ b/chrome/browser/ui/webui/settings/ash/os_settings_section.h
@@ -18,6 +18,10 @@ class Profile; +namespace ash::settings { +class SearchTagRegistry; +} + namespace content { class WebUI; class WebUIDataSource; @@ -26,8 +30,6 @@ namespace chromeos { namespace settings { -class SearchTagRegistry; - // Represents one top-level section of the settings app (i.e., one item on the // settings UI navigation). // @@ -61,8 +63,8 @@ virtual void RegisterTopLevelSubpage( int name_message_id, mojom::Subpage subpage, - mojom::SearchResultIcon icon, - mojom::SearchResultDefaultRank default_rank, + ash::settings::mojom::SearchResultIcon icon, + ash::settings::mojom::SearchResultDefaultRank default_rank, const std::string& url_path_with_parameters) = 0; // Registers a subpage whose parent is another subpage in this section. @@ -70,8 +72,8 @@ int name_message_id, mojom::Subpage subpage, mojom::Subpage parent_subpage, - mojom::SearchResultIcon icon, - mojom::SearchResultDefaultRank default_rank, + ash::settings::mojom::SearchResultIcon icon, + ash::settings::mojom::SearchResultDefaultRank default_rank, const std::string& url_path_with_parameters) = 0; // Registers a setting embedded directly in the section (i.e., not within a @@ -114,7 +116,7 @@ virtual mojom::Section GetSection() const = 0; // Provides the icon for this section. - virtual mojom::SearchResultIcon GetSectionIcon() const = 0; + virtual ash::settings::mojom::SearchResultIcon GetSectionIcon() const = 0; // Provides the path for this section. virtual std::string GetSectionPath() const = 0; @@ -134,14 +136,14 @@ // function simply returns |url_to_modify|, which provides functionality for // static URLs. virtual std::string ModifySearchResultUrl( - mojom::SearchResultType type, + ash::settings::mojom::SearchResultType type, OsSettingsIdentifier id, const std::string& url_to_modify) const; // Generates a search result corresponding to this section. |relevance_score| // must be passed by the client, since this result is being created manually // instead of via query matching. - mojom::SearchResultPtr GenerateSectionSearchResult( + ash::settings::mojom::SearchResultPtr GenerateSectionSearchResult( double relevance_score) const; static std::u16string GetHelpUrlWithBoard(const std::string& original_url); @@ -152,14 +154,15 @@ const base::span<const mojom::Setting>& settings, HierarchyGenerator* generator); - OsSettingsSection(Profile* profile, SearchTagRegistry* search_tag_registry); + OsSettingsSection(Profile* profile, + ash::settings::SearchTagRegistry* search_tag_registry); // Used by tests. OsSettingsSection(); Profile* profile() { return profile_; } const Profile* profile() const { return profile_; } - SearchTagRegistry* registry() { return search_tag_registry_; } + ash::settings::SearchTagRegistry* registry() { return search_tag_registry_; } private: FRIEND_TEST_ALL_PREFIXES(OsSettingsSectionTest, Section); @@ -171,15 +174,21 @@ // If type is Setting, adds the kSettingIdUrlParam to the query parameter // and returns the deep linked url. Doesn't modify url otherwise. - static std::string GetDefaultModifiedUrl(mojom::SearchResultType type, - OsSettingsIdentifier id, - const std::string& url_to_modify); + static std::string GetDefaultModifiedUrl( + ash::settings::mojom::SearchResultType type, + OsSettingsIdentifier id, + const std::string& url_to_modify); Profile* profile_; - SearchTagRegistry* search_tag_registry_; + ash::settings::SearchTagRegistry* search_tag_registry_; }; } // namespace settings } // namespace chromeos +// TODO(https://crbug.com/1164001): remove when it moved to ash. +namespace ash::settings { +using ::chromeos::settings::OsSettingsSection; +} + #endif // CHROME_BROWSER_UI_WEBUI_SETTINGS_ASH_OS_SETTINGS_SECTION_H_
diff --git a/chrome/browser/ui/webui/settings/ash/os_settings_section_unittest.cc b/chrome/browser/ui/webui/settings/ash/os_settings_section_unittest.cc index c32da97..546395a 100644 --- a/chrome/browser/ui/webui/settings/ash/os_settings_section_unittest.cc +++ b/chrome/browser/ui/webui/settings/ash/os_settings_section_unittest.cc
@@ -10,6 +10,13 @@ namespace chromeos { namespace settings { +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom { +using ::ash::settings::mojom::SearchResultDefaultRank; +using ::ash::settings::mojom::SearchResultIcon; +using ::ash::settings::mojom::SearchResultType; +} // namespace mojom + TEST(OsSettingsSectionTest, Section) { // Sections should not incur modification. EXPECT_EQ("internet", OsSettingsSection::GetDefaultModifiedUrl(
diff --git a/chrome/browser/ui/webui/settings/ash/os_settings_sections.h b/chrome/browser/ui/webui/settings/ash/os_settings_sections.h index 32af365..7a403f1 100644 --- a/chrome/browser/ui/webui/settings/ash/os_settings_sections.h +++ b/chrome/browser/ui/webui/settings/ash/os_settings_sections.h
@@ -43,7 +43,7 @@ public: OsSettingsSections( Profile* profile, - SearchTagRegistry* search_tag_registry, + ash::settings::SearchTagRegistry* search_tag_registry, multidevice_setup::MultiDeviceSetupClient* multidevice_setup_client, phonehub::PhoneHubManager* phone_hub_manager, syncer::SyncService* sync_service, @@ -76,4 +76,9 @@ } // namespace settings } // namespace chromeos +// TODO(https://crbug.com/1164001): remove when it moved to ash. +namespace ash::settings { +using ::chromeos::settings::OsSettingsSections; +} + #endif // CHROME_BROWSER_UI_WEBUI_SETTINGS_ASH_OS_SETTINGS_SECTIONS_H_
diff --git a/chrome/browser/ui/webui/settings/ash/os_settings_ui.cc b/chrome/browser/ui/webui/settings/ash/os_settings_ui.cc index 6adc9d2..d98bafc 100644 --- a/chrome/browser/ui/webui/settings/ash/os_settings_ui.cc +++ b/chrome/browser/ui/webui/settings/ash/os_settings_ui.cc
@@ -62,6 +62,12 @@ namespace chromeos { namespace settings { +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom { +using ::ash::settings::mojom::SearchHandler; +using ::ash::settings::mojom::UserActionRecorder; +} // namespace mojom + // static void OSSettingsUI::RegisterProfilePrefs( user_prefs::PrefRegistrySyncable* registry) {
diff --git a/chrome/browser/ui/webui/settings/ash/os_settings_ui.h b/chrome/browser/ui/webui/settings/ash/os_settings_ui.h index db248a9..23e427a1 100644 --- a/chrome/browser/ui/webui/settings/ash/os_settings_ui.h +++ b/chrome/browser/ui/webui/settings/ash/os_settings_ui.h
@@ -27,6 +27,10 @@ #include "ui/webui/mojo_web_ui_controller.h" #include "ui/webui/resources/cr_components/app_management/app_management.mojom-forward.h" +namespace ash::settings::mojom { +class SearchHandler; +} + namespace user_prefs { class PrefRegistrySyncable; } // namespace user_prefs @@ -34,10 +38,6 @@ namespace chromeos { namespace settings { -namespace mojom { -class SearchHandler; -} // namespace mojom - // The WebUI handler for chrome://os-settings. class OSSettingsUI : public ui::MojoWebUIController { public: @@ -74,11 +74,13 @@ // Instantiates implementor of the mojom::UserActionRecorder mojo interface // passing the pending receiver that will be internally bound. - void BindInterface(mojo::PendingReceiver<mojom::UserActionRecorder> receiver); + void BindInterface( + mojo::PendingReceiver<ash::settings::mojom::UserActionRecorder> receiver); // Instantiates implementor of the mojom::SearchHandler mojo interface // passing the pending receiver that will be internally bound. - void BindInterface(mojo::PendingReceiver<mojom::SearchHandler> receiver); + void BindInterface( + mojo::PendingReceiver<ash::settings::mojom::SearchHandler> receiver); // Instantiates implementor of the personalization app mojom::SearchHandler // mojo interface passing the pending receiver that will be internally bound. @@ -130,7 +132,8 @@ WebuiLoadTimer webui_load_timer_; - std::unique_ptr<mojom::UserActionRecorder> user_action_recorder_; + std::unique_ptr<ash::settings::mojom::UserActionRecorder> + user_action_recorder_; std::unique_ptr<AppManagementPageHandlerFactory> app_management_page_handler_factory_;
diff --git a/chrome/browser/ui/webui/settings/ash/people_section.cc b/chrome/browser/ui/webui/settings/ash/people_section.cc index 06db1bf..77d1103a 100644 --- a/chrome/browser/ui/webui/settings/ash/people_section.cc +++ b/chrome/browser/ui/webui/settings/ash/people_section.cc
@@ -64,6 +64,14 @@ namespace chromeos { namespace settings { + +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom { +using ::ash::settings::mojom::SearchResultDefaultRank; +using ::ash::settings::mojom::SearchResultIcon; +using ::ash::settings::mojom::SearchResultType; +} // namespace mojom + namespace { using ::ash::IsAccountManagerAvailable; @@ -105,50 +113,6 @@ return *tags; } -const std::vector<SearchConcept>& GetNonCategorizedSyncSearchConcepts() { - static const base::NoDestructor<std::vector<SearchConcept>> tags({ - {IDS_OS_SETTINGS_TAG_SYNC_AND_GOOGLE_SERVICES, - mojom::kSyncSetupSubpagePath, - mojom::SearchResultIcon::kSync, - mojom::SearchResultDefaultRank::kMedium, - mojom::SearchResultType::kSubpage, - {.subpage = mojom::Subpage::kSyncSetup}}, - {IDS_OS_SETTINGS_TAG_SYNC_MANAGEMENT, - mojom::kSyncDeprecatedAdvancedSubpagePath, - mojom::SearchResultIcon::kSync, - mojom::SearchResultDefaultRank::kMedium, - mojom::SearchResultType::kSubpage, - {.subpage = mojom::Subpage::kSyncDeprecatedAdvanced}}, - {IDS_OS_SETTINGS_TAG_SYNC_ENCRYPTION_OPTIONS, - mojom::kSyncSetupSubpagePath, - mojom::SearchResultIcon::kSync, - mojom::SearchResultDefaultRank::kMedium, - mojom::SearchResultType::kSetting, - {.setting = mojom::Setting::kNonSplitSyncEncryptionOptions}, - {IDS_OS_SETTINGS_TAG_SYNC_ENCRYPTION_OPTIONS_ALT1, - SearchConcept::kAltTagEnd}}, - {IDS_OS_SETTINGS_TAG_AUTOCOMPLETE_SEARCHES_AND_URLS, - mojom::kSyncSetupSubpagePath, - mojom::SearchResultIcon::kSync, - mojom::SearchResultDefaultRank::kMedium, - mojom::SearchResultType::kSetting, - {.setting = mojom::Setting::kAutocompleteSearchesAndUrls}}, - {IDS_OS_SETTINGS_TAG_MAKE_SEARCHES_AND_BROWSER_BETTER, - mojom::kSyncSetupSubpagePath, - mojom::SearchResultIcon::kSync, - mojom::SearchResultDefaultRank::kMedium, - mojom::SearchResultType::kSetting, - {.setting = mojom::Setting::kMakeSearchesAndBrowsingBetter}}, - {IDS_OS_SETTINGS_TAG_GOOGLE_DRIVE_SEARCH_SUGGESTIONS, - mojom::kSyncSetupSubpagePath, - mojom::SearchResultIcon::kSync, - mojom::SearchResultDefaultRank::kMedium, - mojom::SearchResultType::kSetting, - {.setting = mojom::Setting::kGoogleDriveSearchSuggestions}}, - }); - return *tags; -} - const std::vector<SearchConcept>& GetCategorizedSyncSearchConcepts() { static const base::NoDestructor<std::vector<SearchConcept>> tags({ {IDS_OS_SETTINGS_TAG_SYNC,
diff --git a/chrome/browser/ui/webui/settings/ash/people_section.h b/chrome/browser/ui/webui/settings/ash/people_section.h index b8470f2..36b6682 100644 --- a/chrome/browser/ui/webui/settings/ash/people_section.h +++ b/chrome/browser/ui/webui/settings/ash/people_section.h
@@ -9,6 +9,8 @@ #include "base/scoped_observation.h" #include "base/values.h" #include "chrome/browser/ui/webui/settings/ash/os_settings_section.h" +// TODO(https://crbug.com/1164001): move to forward declaration +#include "chrome/browser/ui/webui/settings/ash/search/search_tag_registry.h" #include "components/account_manager_core/account.h" #include "components/account_manager_core/account_manager_facade.h" #include "components/account_manager_core/chromeos/account_manager.h" @@ -39,8 +41,6 @@ namespace settings { -class SearchTagRegistry; - // Provides UI strings and search tags for People settings. Search tags are only // added for non-guest sessions. // @@ -64,7 +64,7 @@ void AddHandlers(content::WebUI* web_ui) override; int GetSectionNameMessageId() const override; mojom::Section GetSection() const override; - mojom::SearchResultIcon GetSectionIcon() const override; + ash::settings::mojom::SearchResultIcon GetSectionIcon() const override; std::string GetSectionPath() const override; bool LogMetric(mojom::Setting setting, base::Value& value) const override; void RegisterHierarchy(HierarchyGenerator* generator) const override;
diff --git a/chrome/browser/ui/webui/settings/ash/personalization_section.cc b/chrome/browser/ui/webui/settings/ash/personalization_section.cc index e1389384..3844bb6 100644 --- a/chrome/browser/ui/webui/settings/ash/personalization_section.cc +++ b/chrome/browser/ui/webui/settings/ash/personalization_section.cc
@@ -14,6 +14,11 @@ namespace chromeos::settings { +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom { +using ::ash::settings::mojom::SearchResultIcon; +} + PersonalizationSection::PersonalizationSection( Profile* profile, SearchTagRegistry* search_tag_registry,
diff --git a/chrome/browser/ui/webui/settings/ash/personalization_section.h b/chrome/browser/ui/webui/settings/ash/personalization_section.h index 9584fab1..540fa0a 100644 --- a/chrome/browser/ui/webui/settings/ash/personalization_section.h +++ b/chrome/browser/ui/webui/settings/ash/personalization_section.h
@@ -7,6 +7,8 @@ #include "base/values.h" #include "chrome/browser/ui/webui/settings/ash/os_settings_section.h" +// TODO(https://crbug.com/1164001): move to forward declaration +#include "chrome/browser/ui/webui/settings/ash/search/search_tag_registry.h" #include "components/prefs/pref_change_registrar.h" class PrefService; @@ -18,8 +20,6 @@ namespace chromeos { namespace settings { -class SearchTagRegistry; - // Provides UI strings and search tags for Personalization settings. Search tags // are only added when not in guest mode, and Ambient mode settings are added // depending on whether the feature is allowed and enabled. @@ -36,7 +36,7 @@ void AddHandlers(content::WebUI* web_ui) override; int GetSectionNameMessageId() const override; mojom::Section GetSection() const override; - mojom::SearchResultIcon GetSectionIcon() const override; + ash::settings::mojom::SearchResultIcon GetSectionIcon() const override; std::string GetSectionPath() const override; bool LogMetric(mojom::Setting setting, base::Value& value) const override; void RegisterHierarchy(HierarchyGenerator* generator) const override;
diff --git a/chrome/browser/ui/webui/settings/ash/printing_section.cc b/chrome/browser/ui/webui/settings/ash/printing_section.cc index 9fa8108..d261755 100644 --- a/chrome/browser/ui/webui/settings/ash/printing_section.cc +++ b/chrome/browser/ui/webui/settings/ash/printing_section.cc
@@ -18,6 +18,14 @@ namespace chromeos { namespace settings { + +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom { +using ::ash::settings::mojom::SearchResultDefaultRank; +using ::ash::settings::mojom::SearchResultIcon; +using ::ash::settings::mojom::SearchResultType; +} // namespace mojom + namespace { const std::vector<SearchConcept>& GetPrintingSearchConcepts() {
diff --git a/chrome/browser/ui/webui/settings/ash/printing_section.h b/chrome/browser/ui/webui/settings/ash/printing_section.h index 3cbcbd7c..5dccfce 100644 --- a/chrome/browser/ui/webui/settings/ash/printing_section.h +++ b/chrome/browser/ui/webui/settings/ash/printing_section.h
@@ -8,6 +8,8 @@ #include "base/values.h" #include "chrome/browser/ash/printing/cups_printers_manager.h" #include "chrome/browser/ui/webui/settings/ash/os_settings_section.h" +// TODO(https://crbug.com/1164001): move to forward declaration +#include "chrome/browser/ui/webui/settings/ash/search/search_tag_registry.h" namespace content { class WebUIDataSource; @@ -16,8 +18,6 @@ namespace chromeos { namespace settings { -class SearchTagRegistry; - // Provides UI strings and search tags for Printing settings. class PrintingSection : public OsSettingsSection, public CupsPrintersManager::Observer { @@ -33,7 +33,7 @@ void AddHandlers(content::WebUI* web_ui) override; int GetSectionNameMessageId() const override; mojom::Section GetSection() const override; - mojom::SearchResultIcon GetSectionIcon() const override; + ash::settings::mojom::SearchResultIcon GetSectionIcon() const override; std::string GetSectionPath() const override; bool LogMetric(mojom::Setting setting, base::Value& value) const override; void RegisterHierarchy(HierarchyGenerator* generator) const override;
diff --git a/chrome/browser/ui/webui/settings/ash/privacy_section.cc b/chrome/browser/ui/webui/settings/ash/privacy_section.cc index 4371a4eb..580e67e4 100644 --- a/chrome/browser/ui/webui/settings/ash/privacy_section.cc +++ b/chrome/browser/ui/webui/settings/ash/privacy_section.cc
@@ -35,6 +35,14 @@ namespace chromeos { namespace settings { + +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom { +using ::ash::settings::mojom::SearchResultDefaultRank; +using ::ash::settings::mojom::SearchResultIcon; +using ::ash::settings::mojom::SearchResultType; +} // namespace mojom + namespace { const std::vector<SearchConcept>& GetPrivacySearchConcepts() {
diff --git a/chrome/browser/ui/webui/settings/ash/privacy_section.h b/chrome/browser/ui/webui/settings/ash/privacy_section.h index 5c65284..020bdec0 100644 --- a/chrome/browser/ui/webui/settings/ash/privacy_section.h +++ b/chrome/browser/ui/webui/settings/ash/privacy_section.h
@@ -7,6 +7,8 @@ #include "base/values.h" #include "chrome/browser/ui/webui/settings/ash/os_settings_section.h" +// TODO(https://crbug.com/1164001): move to forward declaration +#include "chrome/browser/ui/webui/settings/ash/search/search_tag_registry.h" #include "components/prefs/pref_change_registrar.h" class PrefService; @@ -18,8 +20,6 @@ namespace chromeos { namespace settings { -class SearchTagRegistry; - // Provides UI strings and search tags for Privacy settings. Note that some // search tags are added only for official Google Chrome OS builds. class PrivacySection : public OsSettingsSection { @@ -35,7 +35,7 @@ void AddLoadTimeData(content::WebUIDataSource* html_source) override; int GetSectionNameMessageId() const override; mojom::Section GetSection() const override; - mojom::SearchResultIcon GetSectionIcon() const override; + ash::settings::mojom::SearchResultIcon GetSectionIcon() const override; std::string GetSectionPath() const override; bool LogMetric(mojom::Setting setting, base::Value& value) const override; void RegisterHierarchy(HierarchyGenerator* generator) const override;
diff --git a/chrome/browser/ui/webui/settings/ash/reset_section.cc b/chrome/browser/ui/webui/settings/ash/reset_section.cc index 400a786..6630a8b6 100644 --- a/chrome/browser/ui/webui/settings/ash/reset_section.cc +++ b/chrome/browser/ui/webui/settings/ash/reset_section.cc
@@ -19,6 +19,14 @@ namespace chromeos { namespace settings { + +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom { +using ::ash::settings::mojom::SearchResultDefaultRank; +using ::ash::settings::mojom::SearchResultIcon; +using ::ash::settings::mojom::SearchResultType; +} // namespace mojom + namespace { const std::vector<SearchConcept>& GetResetSearchConcepts() {
diff --git a/chrome/browser/ui/webui/settings/ash/reset_section.h b/chrome/browser/ui/webui/settings/ash/reset_section.h index 74a1487..dafeafb5 100644 --- a/chrome/browser/ui/webui/settings/ash/reset_section.h +++ b/chrome/browser/ui/webui/settings/ash/reset_section.h
@@ -7,6 +7,8 @@ #include "base/values.h" #include "chrome/browser/ui/webui/settings/ash/os_settings_section.h" +// TODO(https://crbug.com/1164001): move to forward declaration +#include "chrome/browser/ui/webui/settings/ash/search/search_tag_registry.h" namespace content { class WebUIDataSource; @@ -15,8 +17,6 @@ namespace chromeos { namespace settings { -class SearchTagRegistry; - // Provides UI strings and search tags for Reset settings. Note that search tags // are only added when powerwashing is allowed, since currently this is the only // setting in the Reset section. @@ -31,7 +31,7 @@ void AddHandlers(content::WebUI* web_ui) override; int GetSectionNameMessageId() const override; mojom::Section GetSection() const override; - mojom::SearchResultIcon GetSectionIcon() const override; + ash::settings::mojom::SearchResultIcon GetSectionIcon() const override; std::string GetSectionPath() const override; bool LogMetric(mojom::Setting setting, base::Value& value) const override; void RegisterHierarchy(HierarchyGenerator* generator) const override;
diff --git a/chrome/browser/ui/webui/settings/ash/search/per_session_settings_user_action_tracker.cc b/chrome/browser/ui/webui/settings/ash/search/per_session_settings_user_action_tracker.cc index 1064820..4e29e58 100644 --- a/chrome/browser/ui/webui/settings/ash/search/per_session_settings_user_action_tracker.cc +++ b/chrome/browser/ui/webui/settings/ash/search/per_session_settings_user_action_tracker.cc
@@ -6,8 +6,7 @@ #include "base/metrics/histogram_functions.h" -namespace chromeos { -namespace settings { +namespace ash::settings { namespace { @@ -120,5 +119,4 @@ num_searches_since_start_time_ = 0u; } -} // namespace settings -} // namespace chromeos +} // namespace ash::settings
diff --git a/chrome/browser/ui/webui/settings/ash/search/per_session_settings_user_action_tracker.h b/chrome/browser/ui/webui/settings/ash/search/per_session_settings_user_action_tracker.h index 019a0030..0ee3042 100644 --- a/chrome/browser/ui/webui/settings/ash/search/per_session_settings_user_action_tracker.h +++ b/chrome/browser/ui/webui/settings/ash/search/per_session_settings_user_action_tracker.h
@@ -9,8 +9,7 @@ #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/receiver.h" -namespace chromeos { -namespace settings { +namespace ash::settings { // Records user actions which measure the effort required to change a setting. // This class is only meant to track actions from an individual settings @@ -61,7 +60,11 @@ base::TimeTicks last_blur_timestamp_; }; -} // namespace settings -} // namespace chromeos +} // namespace ash::settings + +// TODO(https://crbug.com/1164001): remove when the migration is finished. +namespace chromeos::settings { +using ::ash::settings::PerSessionSettingsUserActionTracker; +} #endif // CHROME_BROWSER_UI_WEBUI_SETTINGS_ASH_SEARCH_PER_SESSION_SETTINGS_USER_ACTION_TRACKER_H_
diff --git a/chrome/browser/ui/webui/settings/ash/search/per_session_settings_user_action_tracker_unittest.cc b/chrome/browser/ui/webui/settings/ash/search/per_session_settings_user_action_tracker_unittest.cc index 1294c86..aa678f31 100644 --- a/chrome/browser/ui/webui/settings/ash/search/per_session_settings_user_action_tracker_unittest.cc +++ b/chrome/browser/ui/webui/settings/ash/search/per_session_settings_user_action_tracker_unittest.cc
@@ -9,8 +9,7 @@ #include "base/time/time.h" #include "testing/gtest/include/gtest/gtest.h" -namespace chromeos { -namespace settings { +namespace ash::settings { class PerSessionSettingsUserActionTrackerTest : public testing::Test { protected: @@ -172,5 +171,4 @@ /*count=*/1); } -} // namespace settings. -} // namespace chromeos. +} // namespace ash::settings
diff --git a/chrome/browser/ui/webui/settings/ash/search/search.mojom b/chrome/browser/ui/webui/settings/ash/search/search.mojom index 8a2224a1..1c5c3890c 100644 --- a/chrome/browser/ui/webui/settings/ash/search/search.mojom +++ b/chrome/browser/ui/webui/settings/ash/search/search.mojom
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -module chromeos.settings.mojom; +module ash.settings.mojom; import "chrome/browser/ui/webui/settings/chromeos/constants/routes.mojom"; import "chrome/browser/ui/webui/settings/chromeos/constants/setting.mojom"; @@ -49,9 +49,9 @@ // Identifier for the result; each result describes one section, subpage, or // setting. union SearchResultIdentifier { - Section section; - Subpage subpage; - Setting setting; + chromeos.settings.mojom.Section section; + chromeos.settings.mojom.Subpage subpage; + chromeos.settings.mojom.Setting setting; }; // Search result metadata.
diff --git a/chrome/browser/ui/webui/settings/ash/search/search_concept.h b/chrome/browser/ui/webui/settings/ash/search/search_concept.h index 9ed2979..23006b4 100644 --- a/chrome/browser/ui/webui/settings/ash/search/search_concept.h +++ b/chrome/browser/ui/webui/settings/ash/search/search_concept.h
@@ -11,8 +11,7 @@ #include "chrome/browser/ui/webui/settings/chromeos/constants/routes.mojom.h" #include "chrome/browser/ui/webui/settings/chromeos/constants/setting.mojom.h" -namespace chromeos { -namespace settings { +namespace ash::settings { // Represents a potential search result. In this context, "concept" refers to // the fact that this search result represents an idea which may be described @@ -65,7 +64,11 @@ int alt_tag_ids[kMaxAltTagsPerConcept] = {kAltTagEnd}; }; -} // namespace settings -} // namespace chromeos +} // namespace ash::settings + +// TODO(https://crbug.com/1164001): remove when the migration is finished. +namespace chromeos::settings { +using ::ash::settings::SearchConcept; +} #endif // CHROME_BROWSER_UI_WEBUI_SETTINGS_ASH_SEARCH_SEARCH_CONCEPT_H_
diff --git a/chrome/browser/ui/webui/settings/ash/search/search_handler.cc b/chrome/browser/ui/webui/settings/ash/search/search_handler.cc index 2cf7f45..2c79913 100644 --- a/chrome/browser/ui/webui/settings/ash/search/search_handler.cc +++ b/chrome/browser/ui/webui/settings/ash/search/search_handler.cc
@@ -15,14 +15,16 @@ #include "chromeos/ash/components/local_search_service/public/cpp/local_search_service_proxy.h" #include "ui/base/l10n/l10n_util.h" -namespace chromeos { -namespace settings { +namespace ash::settings { + +namespace mojom { +using ::chromeos::settings::mojom::Section; +using ::chromeos::settings::mojom::Setting; +using ::chromeos::settings::mojom::Subpage; +} // namespace mojom namespace { -// TODO(https://crbug.com/1164001): remove after migrating this file to ns ash. -namespace local_search_service = ::ash::local_search_service; - bool ContainsSectionResult(const std::vector<mojom::SearchResultPtr>& results, mojom::Section section) { return base::ranges::any_of(results, [section](const auto& result) { @@ -337,5 +339,4 @@ return static_cast<int32_t>(first->type) < static_cast<int32_t>(second->type); } -} // namespace settings -} // namespace chromeos +} // namespace ash::settings
diff --git a/chrome/browser/ui/webui/settings/ash/search/search_handler.h b/chrome/browser/ui/webui/settings/ash/search/search_handler.h index 56a666a..80e6370 100644 --- a/chrome/browser/ui/webui/settings/ash/search/search_handler.h +++ b/chrome/browser/ui/webui/settings/ash/search/search_handler.h
@@ -8,6 +8,10 @@ #include <vector> #include "base/gtest_prod_util.h" +// TODO(https://crbug.com/1164001): move to forward declaration +#include "chrome/browser/ui/webui/settings/ash/hierarchy.h" +// TODO(https://crbug.com/1164001): move to forward declaration +#include "chrome/browser/ui/webui/settings/ash/os_settings_sections.h" #include "chrome/browser/ui/webui/settings/ash/search/search.mojom.h" #include "chrome/browser/ui/webui/settings/ash/search/search_tag_registry.h" #include "chromeos/ash/components/local_search_service/public/cpp/local_search_service_proxy.h" @@ -19,12 +23,8 @@ #include "mojo/public/cpp/bindings/remote_set.h" #include "third_party/abseil-cpp/absl/types/optional.h" -namespace chromeos { +namespace ash::settings { -namespace settings { - -class Hierarchy; -class OsSettingsSections; struct SearchConcept; // Handles search queries for Chrome OS settings. Search() is expected to be @@ -85,20 +85,20 @@ std::vector<mojom::SearchResultPtr>::iterator AddSectionResultIfPossible( const std::vector<mojom::SearchResultPtr>::iterator& position, const mojom::SearchResultPtr& child_result, - mojom::Section section, + chromeos::settings::mojom::Section section, std::vector<mojom::SearchResultPtr>* results) const; std::vector<mojom::SearchResultPtr>::iterator AddSubpageResultIfPossible( const std::vector<mojom::SearchResultPtr>::iterator& position, const mojom::SearchResultPtr& child_result, - mojom::Subpage subpage, + chromeos::settings::mojom::Subpage subpage, double relevance_score, std::vector<mojom::SearchResultPtr>* results) const; mojom::SearchResultPtr ResultToSearchResult( const local_search_service::Result& result) const; std::string GetModifiedUrl(const SearchConcept& search_concept, - mojom::Section section) const; + chromeos::settings::mojom::Section section) const; // Returns true if |first| should be ranked before |second|. static bool CompareSearchResults(const mojom::SearchResultPtr& first, @@ -107,7 +107,7 @@ SearchTagRegistry* search_tag_registry_; OsSettingsSections* sections_; Hierarchy* hierarchy_; - mojo::Remote<ash::local_search_service::mojom::Index> index_remote_; + mojo::Remote<local_search_service::mojom::Index> index_remote_; // Note: Expected to have multiple clients, so ReceiverSet/RemoteSet are used. mojo::ReceiverSet<mojom::SearchHandler> receivers_; @@ -116,7 +116,11 @@ base::WeakPtrFactory<SearchHandler> weak_ptr_factory_{this}; }; -} // namespace settings -} // namespace chromeos +} // namespace ash::settings + +// TODO(https://crbug.com/1164001): remove when the migration is finished. +namespace chromeos::settings { +using ::ash::settings::SearchHandler; +} #endif // CHROME_BROWSER_UI_WEBUI_SETTINGS_ASH_SEARCH_SEARCH_HANDLER_H_
diff --git a/chrome/browser/ui/webui/settings/ash/search/search_handler_unittest.cc b/chrome/browser/ui/webui/settings/ash/search/search_handler_unittest.cc index 3705c7ee..867bd31 100644 --- a/chrome/browser/ui/webui/settings/ash/search/search_handler_unittest.cc +++ b/chrome/browser/ui/webui/settings/ash/search/search_handler_unittest.cc
@@ -18,8 +18,15 @@ #include "testing/gtest/include/gtest/gtest.h" #include "ui/base/l10n/l10n_util.h" -namespace chromeos { -namespace settings { +namespace ash::settings { + +namespace mojom { +using ::chromeos::settings::mojom::kPrintingDetailsSubpagePath; +using ::chromeos::settings::mojom::Section; +using ::chromeos::settings::mojom::Setting; +using ::chromeos::settings::mojom::Subpage; +} // namespace mojom + namespace { class FakeObserver : public mojom::SearchResultsObserver { @@ -307,5 +314,4 @@ SearchHandler::CompareSearchResults(a, b)); } -} // namespace settings -} // namespace chromeos +} // namespace ash::settings
diff --git a/chrome/browser/ui/webui/settings/ash/search/search_result_icon.mojom b/chrome/browser/ui/webui/settings/ash/search/search_result_icon.mojom index 2cd939eb6..3338389 100644 --- a/chrome/browser/ui/webui/settings/ash/search/search_result_icon.mojom +++ b/chrome/browser/ui/webui/settings/ash/search/search_result_icon.mojom
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -module chromeos.settings.mojom; +module ash.settings.mojom; // Icon types associated with a settings search result. enum SearchResultIcon {
diff --git a/chrome/browser/ui/webui/settings/ash/search/search_tag_registry.cc b/chrome/browser/ui/webui/settings/ash/search/search_tag_registry.cc index d03e67d5..5583bc4 100644 --- a/chrome/browser/ui/webui/settings/ash/search/search_tag_registry.cc +++ b/chrome/browser/ui/webui/settings/ash/search/search_tag_registry.cc
@@ -14,14 +14,10 @@ #include "chromeos/ash/components/local_search_service/public/cpp/local_search_service_proxy.h" #include "ui/base/l10n/l10n_util.h" -namespace chromeos { -namespace settings { +namespace ash::settings { namespace { -// TODO(https://crbug.com/1164001): remove after migrating this file to ns ash. -namespace local_search_service = ::ash::local_search_service; - std::vector<int> GetMessageIds(const SearchConcept* search_concept) { // Start with only the canonical ID. std::vector<int> alt_tag_message_ids{search_concept->canonical_message_id}; @@ -216,5 +212,4 @@ NotifyRegistryUpdated(); } -} // namespace settings -} // namespace chromeos +} // namespace ash::settings
diff --git a/chrome/browser/ui/webui/settings/ash/search/search_tag_registry.h b/chrome/browser/ui/webui/settings/ash/search/search_tag_registry.h index fdaec675..80113ca 100644 --- a/chrome/browser/ui/webui/settings/ash/search/search_tag_registry.h +++ b/chrome/browser/ui/webui/settings/ash/search/search_tag_registry.h
@@ -17,9 +17,7 @@ #include "chromeos/ash/components/local_search_service/public/mojom/index.mojom.h" #include "mojo/public/cpp/bindings/remote.h" -namespace chromeos { - -namespace settings { +namespace ash::settings { struct SearchConcept; @@ -87,14 +85,14 @@ void AddSearchTags(const std::vector<const SearchConcept*>& search_tags); void RemoveSearchTags(const std::vector<const SearchConcept*>& search_tags); - std::vector<ash::local_search_service::Data> ConceptVectorToDataVector( + std::vector<local_search_service::Data> ConceptVectorToDataVector( const std::vector<const SearchConcept*>& search_tags); void NotifyRegistryUpdated(); void NotifyRegistryAdded(); void NotifyRegistryDeleted(uint32_t /*num_deleted*/); // Index used by the LocalSearchService for string matching. - mojo::Remote<ash::local_search_service::mojom::Index> index_remote_; + mojo::Remote<local_search_service::mojom::Index> index_remote_; // In-memory cache of all results which have been added to the // LocalSearchService. Contents are kept in sync with |index_remote_|. @@ -105,7 +103,11 @@ base::WeakPtrFactory<SearchTagRegistry> weak_ptr_factory_{this}; }; -} // namespace settings -} // namespace chromeos +} // namespace ash::settings + +// TODO(https://crbug.com/1164001): remove when the migration is finished. +namespace chromeos::settings { +using ::ash::settings::SearchTagRegistry; +} #endif // CHROME_BROWSER_UI_WEBUI_SETTINGS_ASH_SEARCH_SEARCH_TAG_REGISTRY_H_
diff --git a/chrome/browser/ui/webui/settings/ash/search/search_tag_registry_unittest.cc b/chrome/browser/ui/webui/settings/ash/search/search_tag_registry_unittest.cc index cc110d8..6b0ea832 100644 --- a/chrome/browser/ui/webui/settings/ash/search/search_tag_registry_unittest.cc +++ b/chrome/browser/ui/webui/settings/ash/search/search_tag_registry_unittest.cc
@@ -13,14 +13,16 @@ #include "chromeos/ash/components/local_search_service/public/mojom/index.mojom.h" #include "testing/gtest/include/gtest/gtest.h" -namespace chromeos { -namespace settings { +namespace ash::settings { + +namespace mojom { +using ::chromeos::settings::mojom::kPrintingDetailsSubpagePath; +using ::chromeos::settings::mojom::Setting; +using ::chromeos::settings::mojom::Subpage; +} // namespace mojom namespace { -// TODO(https://crbug.com/1164001): remove after migrating this file to ns ash. -namespace local_search_service = ::ash::local_search_service; - class FakeObserver : public SearchTagRegistry::Observer { public: FakeObserver() = default; @@ -154,5 +156,4 @@ ASSERT_FALSE(add_printer_concept); } -} // namespace settings -} // namespace chromeos +} // namespace ash::settings
diff --git a/chrome/browser/ui/webui/settings/ash/search/user_action_recorder.mojom b/chrome/browser/ui/webui/settings/ash/search/user_action_recorder.mojom index 3f9fd4f8..f1d67c11 100644 --- a/chrome/browser/ui/webui/settings/ash/search/user_action_recorder.mojom +++ b/chrome/browser/ui/webui/settings/ash/search/user_action_recorder.mojom
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -module chromeos.settings.mojom; +module ash.settings.mojom; import "chrome/browser/ui/webui/settings/chromeos/constants/setting.mojom"; @@ -40,5 +40,6 @@ // setting was changed to. |value| can be null when the corresponding // setting doesn't actually change a value, such as the open wallpaper // setting. - RecordSettingChangeWithDetails(Setting setting, SettingChangeValue? value); + RecordSettingChangeWithDetails(chromeos.settings.mojom.Setting setting, + SettingChangeValue? value); };
diff --git a/chrome/browser/ui/webui/settings/ash/search_section.cc b/chrome/browser/ui/webui/settings/ash/search_section.cc index 5ac9a0e..4e37715 100644 --- a/chrome/browser/ui/webui/settings/ash/search_section.cc +++ b/chrome/browser/ui/webui/settings/ash/search_section.cc
@@ -34,6 +34,14 @@ namespace chromeos { namespace settings { + +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom { +using ::ash::settings::mojom::SearchResultDefaultRank; +using ::ash::settings::mojom::SearchResultIcon; +using ::ash::settings::mojom::SearchResultType; +} // namespace mojom + namespace { bool ShouldShowQuickAnswersSettings() {
diff --git a/chrome/browser/ui/webui/settings/ash/search_section.h b/chrome/browser/ui/webui/settings/ash/search_section.h index d006f54..d376ac8 100644 --- a/chrome/browser/ui/webui/settings/ash/search_section.h +++ b/chrome/browser/ui/webui/settings/ash/search_section.h
@@ -8,6 +8,8 @@ #include "ash/public/cpp/assistant/assistant_state_base.h" #include "base/values.h" #include "chrome/browser/ui/webui/settings/ash/os_settings_section.h" +// TODO(https://crbug.com/1164001): move to forward declaration +#include "chrome/browser/ui/webui/settings/ash/search/search_tag_registry.h" #include "chromeos/components/quick_answers/public/cpp/quick_answers_state.h" namespace content { @@ -17,8 +19,6 @@ namespace chromeos { namespace settings { -class SearchTagRegistry; - // Provides UI strings and search tags for Search & Assistant settings. Search // tags for Assistant settings are added/removed depending on whether the // feature and relevant flags are enabled/disabled. @@ -35,7 +35,7 @@ void AddHandlers(content::WebUI* web_ui) override; int GetSectionNameMessageId() const override; mojom::Section GetSection() const override; - mojom::SearchResultIcon GetSectionIcon() const override; + ash::settings::mojom::SearchResultIcon GetSectionIcon() const override; std::string GetSectionPath() const override; bool LogMetric(mojom::Setting setting, base::Value& value) const override; void RegisterHierarchy(HierarchyGenerator* generator) const override;
diff --git a/chrome/browser/ui/webui/settings/ash/settings_user_action_tracker.cc b/chrome/browser/ui/webui/settings/ash/settings_user_action_tracker.cc index 8ac1f5ad..f5d2e18 100644 --- a/chrome/browser/ui/webui/settings/ash/settings_user_action_tracker.cc +++ b/chrome/browser/ui/webui/settings/ash/settings_user_action_tracker.cc
@@ -15,6 +15,11 @@ namespace chromeos { namespace settings { +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom { +using ::ash::settings::mojom::UserActionRecorder; +} + SettingsUserActionTracker::SettingsUserActionTracker( Hierarchy* hierarchy, OsSettingsSections* sections) @@ -73,7 +78,7 @@ void SettingsUserActionTracker::RecordSettingChangeWithDetails( mojom::Setting setting, - mojom::SettingChangeValuePtr value) { + ash::settings::mojom::SettingChangeValuePtr value) { per_session_tracker_->RecordSettingChange(); // Get the primary section location of the changed setting and log the metric.
diff --git a/chrome/browser/ui/webui/settings/ash/settings_user_action_tracker.h b/chrome/browser/ui/webui/settings/ash/settings_user_action_tracker.h index 7e72dc5..6fe2118 100644 --- a/chrome/browser/ui/webui/settings/ash/settings_user_action_tracker.h +++ b/chrome/browser/ui/webui/settings/ash/settings_user_action_tracker.h
@@ -23,7 +23,8 @@ // Records user actions within Settings. Utilizes a per session tracker that // measures the user's effort required to change a setting. Eventually uses // a per section tracker to record metrics in each section. -class SettingsUserActionTracker : public mojom::UserActionRecorder { +class SettingsUserActionTracker + : public ash::settings::mojom::UserActionRecorder { public: SettingsUserActionTracker(Hierarchy* hierarchy, OsSettingsSections* sections); SettingsUserActionTracker(const SettingsUserActionTracker& other) = delete; @@ -32,7 +33,8 @@ ~SettingsUserActionTracker() override; void BindInterface( - mojo::PendingReceiver<mojom::UserActionRecorder> pending_receiver); + mojo::PendingReceiver<ash::settings::mojom::UserActionRecorder> + pending_receiver); private: // For unit tests. @@ -60,7 +62,7 @@ void RecordSettingChange() override; void RecordSettingChangeWithDetails( mojom::Setting setting, - mojom::SettingChangeValuePtr value) override; + ash::settings::mojom::SettingChangeValuePtr value) override; void EndCurrentSession(); void OnBindingDisconnected(); @@ -69,7 +71,7 @@ OsSettingsSections* sections_; std::unique_ptr<PerSessionSettingsUserActionTracker> per_session_tracker_; - mojo::Receiver<mojom::UserActionRecorder> receiver_{this}; + mojo::Receiver<ash::settings::mojom::UserActionRecorder> receiver_{this}; }; } // namespace settings
diff --git a/chrome/browser/ui/webui/settings/ash/settings_user_action_tracker_unittest.cc b/chrome/browser/ui/webui/settings/ash/settings_user_action_tracker_unittest.cc index be67cef8..2059ae9 100644 --- a/chrome/browser/ui/webui/settings/ash/settings_user_action_tracker_unittest.cc +++ b/chrome/browser/ui/webui/settings/ash/settings_user_action_tracker_unittest.cc
@@ -17,6 +17,11 @@ namespace chromeos { namespace settings { +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom { +using ::ash::settings::mojom::SettingChangeValue; +} + class SettingsUserActionTrackerTest : public testing::Test { protected: SettingsUserActionTrackerTest()
diff --git a/chrome/browser/web_applications/web_app_registry_update.cc b/chrome/browser/web_applications/web_app_registry_update.cc index 6077e67..935eb8e 100644 --- a/chrome/browser/web_applications/web_app_registry_update.cc +++ b/chrome/browser/web_applications/web_app_registry_update.cc
@@ -73,8 +73,11 @@ ScopedRegistryUpdate::ScopedRegistryUpdate(WebAppSyncBridge* sync_bridge) : update_(sync_bridge->BeginUpdate()), sync_bridge_(sync_bridge) {} +ScopedRegistryUpdate::ScopedRegistryUpdate(ScopedRegistryUpdate&&) = default; + ScopedRegistryUpdate::~ScopedRegistryUpdate() { - sync_bridge_->CommitUpdate(std::move(update_), base::DoNothing()); + if (update_) + sync_bridge_->CommitUpdate(std::move(update_), base::DoNothing()); } } // namespace web_app
diff --git a/chrome/browser/web_applications/web_app_registry_update.h b/chrome/browser/web_applications/web_app_registry_update.h index d7d2362..78acb08 100644 --- a/chrome/browser/web_applications/web_app_registry_update.h +++ b/chrome/browser/web_applications/web_app_registry_update.h
@@ -67,6 +67,7 @@ class ScopedRegistryUpdate { public: explicit ScopedRegistryUpdate(WebAppSyncBridge* sync_bridge); + ScopedRegistryUpdate(ScopedRegistryUpdate&&); ScopedRegistryUpdate(const ScopedRegistryUpdate&) = delete; ScopedRegistryUpdate& operator=(const ScopedRegistryUpdate&) = delete; ~ScopedRegistryUpdate();
diff --git a/chrome/build/linux.pgo.txt b/chrome/build/linux.pgo.txt index 7ab8b0b..13cd68f 100644 --- a/chrome/build/linux.pgo.txt +++ b/chrome/build/linux.pgo.txt
@@ -1 +1 @@ -chrome-linux-main-1665079202-7023387ea6d9b155f5bf276d37aaee45d8e4e559.profdata +chrome-linux-main-1665122034-781bbdb6b3c59ea087989e3e8f6b2df91a5bdb30.profdata
diff --git a/chrome/build/mac.pgo.txt b/chrome/build/mac.pgo.txt index 9e5d4ef7..4797337 100644 --- a/chrome/build/mac.pgo.txt +++ b/chrome/build/mac.pgo.txt
@@ -1 +1 @@ -chrome-mac-main-1665079202-71539a052d8b80420de7a07b5718236a0dce8233.profdata +chrome-mac-main-1665122034-e1f44598c7725908d55b55ae2e47f2ed39be71a8.profdata
diff --git a/chrome/build/win32.pgo.txt b/chrome/build/win32.pgo.txt index 4ab4df91..758f5c8f 100644 --- a/chrome/build/win32.pgo.txt +++ b/chrome/build/win32.pgo.txt
@@ -1 +1 @@ -chrome-win32-main-1665068388-3f21d5503e3cb7da97a5d42826036b711ac3c054.profdata +chrome-win32-main-1665122034-2c5cb2b803dd4a4445d9622a3ebcc5ac20a1893f.profdata
diff --git a/chrome/build/win64.pgo.txt b/chrome/build/win64.pgo.txt index 7335e65..d95620b 100644 --- a/chrome/build/win64.pgo.txt +++ b/chrome/build/win64.pgo.txt
@@ -1 +1 @@ -chrome-win64-main-1665068388-23f0579d8f25b08d33566ed2e69bb850ccff8b94.profdata +chrome-win64-main-1665132952-6d3e8e5b2d995af7223421632e3be31e142edbee.profdata
diff --git a/chrome/common/chromeos/extensions/api/_permission_features.json b/chrome/common/chromeos/extensions/api/_permission_features.json index 3626e837..5cd15b80 100644 --- a/chrome/common/chromeos/extensions/api/_permission_features.json +++ b/chrome/common/chromeos/extensions/api/_permission_features.json
@@ -27,5 +27,11 @@ "extension_types": [ "chromeos_system_extension" ] + }, + "os.telemetry.network_info": { + "channel": "stable", + "extension_types": [ + "chromeos_system_extension" + ] } }
diff --git a/chrome/common/chromeos/extensions/chromeos_system_extensions_api_permissions.cc b/chrome/common/chromeos/extensions/chromeos_system_extensions_api_permissions.cc index 1846961..e6685ce 100644 --- a/chrome/common/chromeos/extensions/chromeos_system_extensions_api_permissions.cc +++ b/chrome/common/chromeos/extensions/chromeos_system_extensions_api_permissions.cc
@@ -26,7 +26,8 @@ {APIPermissionID::kChromeOSTelemetry, "os.telemetry"}, {APIPermissionID::kChromeOSTelemetrySerialNumber, "os.telemetry.serial_number"}, -}; + {APIPermissionID::kChromeOSTelemetryNetworkInformation, + "os.telemetry.network_info"}}; } // namespace
diff --git a/chrome/common/extensions/api/file_manager_private.idl b/chrome/common/extensions/api/file_manager_private.idl index 63ec8be8..fa0bf1b 100644 --- a/chrome/common/extensions/api/file_manager_private.idl +++ b/chrome/common/extensions/api/file_manager_private.idl
@@ -92,7 +92,8 @@ error_invalid_archive, error_need_password, error_in_progress, - error_cancelled + error_cancelled, + error_busy }; // Filesystem to format to.
diff --git a/chrome/common/extensions/api/input_method_private.json b/chrome/common/extensions/api/input_method_private.json index ba2f06dc..72934be7 100644 --- a/chrome/common/extensions/api/input_method_private.json +++ b/chrome/common/extensions/api/input_method_private.json
@@ -836,6 +836,12 @@ ] } ] + }, + { + "name" : "notifyInputMethodReadyForTesting", + "type" : "function", + "description" : "Notifies Chrome that the current input method is ready to accept key events from Tast.", + "parameters": [] } ], "events": [
diff --git a/chrome/common/extensions/permissions/chrome_permission_message_rules.cc b/chrome/common/extensions/permissions/chrome_permission_message_rules.cc index 662d6174..649fc08 100644 --- a/chrome/common/extensions/permissions/chrome_permission_message_rules.cc +++ b/chrome/common/extensions/permissions/chrome_permission_message_rules.cc
@@ -17,6 +17,7 @@ #include "base/strings/utf_string_conversions.h" #include "chrome/grit/generated_resources.h" #include "components/device_signals/core/common/signals_features.h" +#include "extensions/common/mojom/api_permission_id.mojom.h" #include "ui/base/l10n/l10n_util.h" using extensions::mojom::APIPermissionID; @@ -751,7 +752,9 @@ {IDS_EXTENSION_PROMPT_WARNING_CHROMEOS_TELEMETRY_SERIAL_NUMBER, {APIPermissionID::kChromeOSTelemetrySerialNumber}, {}}, - }; + {IDS_EXTENSION_PROMPT_WARNING_CHROMEOS_TELEMETRY_NETWORK_INFORMATION, + {APIPermissionID::kChromeOSTelemetryNetworkInformation}, + {}}}; return std::vector<ChromePermissionMessageRule>( std::make_move_iterator(std::begin(rules_arr)),
diff --git a/chrome/common/privacy_budget/privacy_budget_features.h b/chrome/common/privacy_budget/privacy_budget_features.h index ba98bf2f..3fc7e41 100644 --- a/chrome/common/privacy_budget/privacy_budget_features.h +++ b/chrome/common/privacy_budget/privacy_budget_features.h
@@ -92,8 +92,12 @@ extern const base::FeatureParam<int> kIdentifiabilityStudyExpectedSurfaceCount; // Surface types allowed in the random assignment. If the parameter is empty or -// invalid all types can be sampled. This does not have any effect on meta -// surfaces (type 7), which are sampled in any case. +// invalid all types can be sampled. + +// This does not have any effect on meta surfaces (type 7), nor on reserved +// surfaces (type 0), which are sampled in any case. In particular, enabling +// random sampling and setting this parameter to "0" is a valid way to only +// enable the meta surfaces experiment. // // Parameter name: "AllowedRandomTypes" // Parameter type: Comma separated list of decimal integers, each of which
diff --git a/chrome/elevation_service/elevator.h b/chrome/elevation_service/elevator.h index 40d7920..2fd7226 100644 --- a/chrome/elevation_service/elevator.h +++ b/chrome/elevation_service/elevator.h
@@ -39,19 +39,19 @@ IElevatorChromeDev, IElevatorChromeCanary> { public: - const HRESULT kErrorCouldNotObtainCallingProcess = + static constexpr HRESULT kErrorCouldNotObtainCallingProcess = MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0xA001); - const HRESULT kErrorCouldNotGenerateValidationData = + static constexpr HRESULT kErrorCouldNotGenerateValidationData = MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0xA002); - const HRESULT kErrorCouldNotDecryptWithUserContext = + static constexpr HRESULT kErrorCouldNotDecryptWithUserContext = MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0xA003); - const HRESULT kErrorCouldNotDecryptWithSystemContext = + static constexpr HRESULT kErrorCouldNotDecryptWithSystemContext = MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0xA004); - const HRESULT kErrorCouldNotEncryptWithUserContext = + static constexpr HRESULT kErrorCouldNotEncryptWithUserContext = MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0xA005); - const HRESULT kErrorCouldNotEncryptWithSystemContext = + static constexpr HRESULT kErrorCouldNotEncryptWithSystemContext = MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0xA006); - const HRESULT kValidationDidNotPass = + static constexpr HRESULT kValidationDidNotPass = MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0xA007); Elevator() = default;
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index b4521e3..01aadec 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -562,7 +562,6 @@ public_deps += [ "//ash", "//ash:test_support", - "//ash/components/tpm", "//ash/constants", "//ash/public/cpp:test_support", "//chrome/browser/ash", @@ -572,6 +571,7 @@ "//chromeos/ash/components/dbus/userdataauth", "//chromeos/ash/components/install_attributes:test_support", "//chromeos/ash/components/settings", + "//chromeos/ash/components/tpm", "//chromeos/dbus/tpm_manager", "//chromeos/login/login_state", "//components/exo", @@ -3338,6 +3338,7 @@ "../browser/ui/views/certificate_selector_dialog_browsertest.cc", "../browser/ui/views/collected_cookies_views_browsertest.cc", "../browser/ui/views/commerce/ntp_discount_consent_dialog_view_browsertest.cc", + "../browser/ui/views/commerce/price_tracking_entry_point_feature_flag_browser_test.cc", "../browser/ui/views/commerce/price_tracking_icon_view_browsertest.cc", "../browser/ui/views/desktop_capture/desktop_media_picker_views_browsertest.cc", "../browser/ui/views/extensions/extension_install_blocked_dialog_view_browsertest.cc",
diff --git a/chrome/test/data/extensions/api_test/file_system_provider/service_worker/BUILD.gn b/chrome/test/data/extensions/api_test/file_system_provider/service_worker/BUILD.gn index 197a114..dccd794 100644 --- a/chrome/test/data/extensions/api_test/file_system_provider/service_worker/BUILD.gn +++ b/chrome/test/data/extensions/api_test/file_system_provider/service_worker/BUILD.gn
@@ -6,13 +6,18 @@ js_type_check("closure_compile") { deps = [ ":service_worker" ] - closure_flags = - strict_error_checking_closure_args + [ "language_in=ECMASCRIPT_2020" ] + closure_flags = strict_error_checking_closure_args + [ + "language_in=ECMASCRIPT_2020", + "js_module_root=../../chrome/test/data/extensions/", + "browser_resolver_prefix_replacements=/_test_resources/=./", + ] } # Group for type checking. js_library("service_worker") { sources = [ + "copy_entry/sw.js", + "copy_entry/test.js", "helpers.js", "provider.js", "read_file/sw.js",
diff --git a/chrome/test/data/extensions/api_test/file_system_provider/service_worker/copy_entry/test.js b/chrome/test/data/extensions/api_test/file_system_provider/service_worker/copy_entry/test.js index b2a09119..d49be92a 100644 --- a/chrome/test/data/extensions/api_test/file_system_provider/service_worker/copy_entry/test.js +++ b/chrome/test/data/extensions/api_test/file_system_provider/service_worker/copy_entry/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 {mountTestFileSystem, remoteProvider} from '/_test_resources/api_test/file_system_provider/service_worker/helpers.js'; +import {mountTestFileSystem} from '/_test_resources/api_test/file_system_provider/service_worker/helpers.js'; // For shared constants. import {TestFileSystemProvider} from '/_test_resources/api_test/file_system_provider/service_worker/provider.js'; @@ -10,18 +10,7 @@ async function main() { await navigator.serviceWorker.ready; - const {fileSystem} = await mountTestFileSystem(); - - /** - * @param {string} path - * @param {{create: boolean, exclusive: boolean}} options - * @returns {!Promise<!FileEntry>} - */ - const getFileEntry = (path, options) => { - return new Promise( - (resolve, reject) => - fileSystem.root.getFile(path, options, resolve, reject)); - }; + const fileSystem = await mountTestFileSystem(); const srcPath = TestFileSystemProvider.FILE_READ_SUCCESS; const dstPath = srcPath + '-copy'; @@ -30,11 +19,12 @@ // Copy an existing file to a non-existing destination. Should succeed. async function copyEntrySuccess() { try { - const sourceEntry = await getFileEntry(srcPath, {create: false}); + const sourceEntry = + await fileSystem.getFileEntry(srcPath, {create: false}); chrome.test.assertFalse(sourceEntry.isDirectory); const targetEntry = await new Promise( - (resolve, reject) => - sourceEntry.copyTo(fileSystem.root, dstPath, resolve, reject)); + (resolve, reject) => sourceEntry.copyTo( + fileSystem.fileSystem.root, dstPath, resolve, reject)); chrome.test.assertEq(dstPath, targetEntry.name); chrome.test.assertFalse(targetEntry.isDirectory); chrome.test.succeed(); @@ -46,12 +36,13 @@ // Should fail. async function copyEntryExistsError() { try { - const sourceEntry = await getFileEntry(srcPath, {create: false}); + const sourceEntry = + await fileSystem.getFileEntry(srcPath, {create: false}); chrome.test.assertFalse(sourceEntry.isDirectory); try { await new Promise( (resolve, reject) => sourceEntry.copyTo( - fileSystem.root, dstPath, resolve, reject)); + fileSystem.fileSystem.root, dstPath, resolve, reject)); chrome.test.fail('Succeeded, but should fail.'); } catch (e) { chrome.test.assertEq('InvalidModificationError', e.name);
diff --git a/chrome/test/data/extensions/api_test/file_system_provider/service_worker/helpers.js b/chrome/test/data/extensions/api_test/file_system_provider/service_worker/helpers.js index 50c3a4a..947d342 100644 --- a/chrome/test/data/extensions/api_test/file_system_provider/service_worker/helpers.js +++ b/chrome/test/data/extensions/api_test/file_system_provider/service_worker/helpers.js
@@ -8,7 +8,7 @@ * @param {...?} args * @returns {!Promise<?>} */ -export async function promisifyWithLastError(fn, ...args) { +async function promisifyWithLastError(fn, ...args) { return new Promise((resolve, reject) => { fn(...args, (result) => { if (chrome.runtime.lastError) { @@ -43,15 +43,11 @@ }; /** - * Mounts a testing file system and calls the callback in case of a success. - * On failure, the current test case is failed on an assertion. - * * @param {number=} openedFilesLimit Limit of opened files at once. If 0 or * unspecified, then not limited. - * @returns {!Promise<{fileSystem: !Object, volumeId: string}>} mounted - * filesystem and its volume ID. + * @returns {!Promise<!FileSystem>} mounted filesystem instance. */ -export async function mountTestFileSystem(openedFilesLimit) { +async function mount(openedFilesLimit) { const fileSystemId = TestFileSystemProvider.FILESYSTEM_ID; const options = { fileSystemId, @@ -72,9 +68,54 @@ if (!fileSystem) { throw new Error(`filesystem not found for volume: ${volumeInfo.volumeId}`); } - return {fileSystem, volumeId: volumeInfo.volumeId}; + return fileSystem; }; +export class MountedTestFileSystem { + /** @param {!FileSystem} fileSystem */ + constructor(fileSystem) { + /** @type {!FileSystem} */ + this.fileSystem = fileSystem; + } + + /** + * Unmount and mount the test filesystem with a new open file limit. + * + * @param {number} openedFilesLimit + */ + async remount(openedFilesLimit) { + await promisifyWithLastError(chrome.fileSystemProvider.unmount, { + fileSystemId: TestFileSystemProvider.FILESYSTEM_ID, + }); + this.fileSystem = await mount(openedFilesLimit); + } + + /** + * Get a file entry from the root of the mounted filesystem. + * + * @param {string} path + * @param {{create: (boolean|undefined), exclusive: (boolean|undefined)}} + * options + * @returns {!Promise<!FileEntry>} + */ + async getFileEntry(path, options) { + return new Promise( + (resolve, reject) => + this.fileSystem.root.getFile(path, options, resolve, reject)); + } +}; + +/** + * Create a mounted test filesystem instance. + * + * @param {number=} openedFilesLimit Limit of opened files at once. If 0 or + * unspecified, then not limited. + * @return {!Promise<!MountedTestFileSystem>} + */ +export async function mountTestFileSystem(openedFilesLimit) { + return new MountedTestFileSystem(await mount(openedFilesLimit)); +} + /** * @suppress {checkTypes} * @returns {string} request ID
diff --git a/chrome/test/data/extensions/api_test/file_system_provider/service_worker/provider.js b/chrome/test/data/extensions/api_test/file_system_provider/service_worker/provider.js index 99f50ab..1bb02fe9 100644 --- a/chrome/test/data/extensions/api_test/file_system_provider/service_worker/provider.js +++ b/chrome/test/data/extensions/api_test/file_system_provider/service_worker/provider.js
@@ -154,14 +154,16 @@ } setUpProviderListeners() { + this.setHandlerEnabled('onAbortRequested', true); + this.setHandlerEnabled('onAddWatcherRequested', true); + this.setHandlerEnabled('onCloseFileRequested', true); + this.setHandlerEnabled('onCopyEntryRequested', true); + this.setHandlerEnabled('onCreateFileRequested', true); this.setHandlerEnabled('onGetMetadataRequested', true); this.setHandlerEnabled('onOpenFileRequested', true); - this.setHandlerEnabled('onCloseFileRequested', true); - this.setHandlerEnabled('onCreateFileRequested', true); this.setHandlerEnabled('onReadFileRequested', true); + this.setHandlerEnabled('onRemoveWatcherRequested', true); this.setHandlerEnabled('onWriteFileRequested', true); - this.setHandlerEnabled('onAbortRequested', true); - this.setHandlerEnabled('onCopyEntryRequested', true); } /** @@ -306,6 +308,140 @@ this.stalledRequests = {}; } + onAbortRequested(options, onSuccess, onError) { + this.recordEvent('onAbortRequested', options); + if (options.fileSystemId !== this.fileSystemId) { + onError(chrome.fileSystemProvider.ProviderError.SECURITY); + return; + } + + onSuccess(); + } + + /** + * FSP: implementation for adding an entry watcher. + * + * @param {!chrome.fileSystemProvider.AddWatcherRequestedOptions} options + * Options. + * @param {function()} onSuccess Success callback. + * @param {function(string)} onError Error callback with an error code. + */ + onAddWatcherRequested(options, onSuccess, onError) { + if (options.fileSystemId !== this.fileSystemId) { + onError(chrome.fileSystemProvider.ProviderError.SECURITY); + return; + } + + if (options.entryPath in this.files) { + onSuccess(); + return; + } + + onError(chrome.fileSystemProvider.ProviderError.NOT_FOUND); + }; + + + /** + * FSP: implementation for the file close request event. The file, + * previously opened with <code>openRequestId</code> will be closed. + * + * @param {!chrome.fileSystemProvider.CloseFileRequestedOptions} options + * Options. + * @param {function()} onSuccess Success callback. + * @param {function(chrome.fileSystemProvider.ProviderError)} onError Error + * callback. + */ + onCloseFileRequested(options, onSuccess, onError) { + this.recordEvent('onCloseFileRequested', options); + + if (options.fileSystemId !== this.fileSystemId || + !this.openedFiles[options.openRequestId]) { + onError(chrome.fileSystemProvider.ProviderError.SECURITY); + return; + } + + delete this.openedFiles[options.openRequestId]; + onSuccess(); + }; + + /** + * FSP: implementation of copying an entry within the same file system. + * + * @param {!chrome.fileSystemProvider.CopyEntryRequestedOptions} options + * Options. + * @param {function()} onSuccess Success callback + * @param {function(chrome.fileSystemProvider.ProviderError)} onError Error + * callback with an error code. + */ + onCopyEntryRequested(options, onSuccess, onError) { + if (options.fileSystemId !== this.fileSystemId) { + onError(chrome.fileSystemProvider.ProviderError.SECURITY); + return; + } + + if (options.sourcePath === '/') { + onError(chrome.fileSystemProvider.ProviderError.INVALID_OPERATION); + return; + } + + if (!(options.sourcePath in this.files)) { + onError(chrome.fileSystemProvider.ProviderError.NOT_FOUND); + return; + } + + if (options.targetPath in this.files) { + onError(chrome.fileSystemProvider.ProviderError.EXISTS); + return; + } + + // Copy the metadata, but change the 'name' field. + const source = this.files[options.sourcePath]; + /** @suppress {undefinedVars} */ + const dest = structuredClone(source); + dest.name = options.targetPath.split('/').pop(); + this.files[options.targetPath] = dest; + + onSuccess(); + } + + /** + * FSP: implementation for the file create request event. + * + * @param {!chrome.fileSystemProvider.CreateFileRequestedOptions} options + * Options. + * @param {function()} onSuccess Success callback + * @param {function(chrome.fileSystemProvider.ProviderError)} onError Error + * callback with an error code. + */ + onCreateFileRequested(options, onSuccess, onError) { + if (options.fileSystemId !== this.fileSystemId) { + onError(chrome.fileSystemProvider.ProviderError.SECURITY); + return; + } + + if (options.filePath === '/') { + onError(chrome.fileSystemProvider.ProviderError.INVALID_OPERATION); + return; + } + + if (options.filePath in this.files) { + onError(chrome.fileSystemProvider.ProviderError.EXISTS); + return; + } + + this.files[options.filePath] = { + metadata: { + isDirectory: false, + name: options.filePath.split('/').pop(), + size: 0, + modificationTime: new Date() + }, + contents: '', + }; + + onSuccess(); + }; + /** * FSP: implementation for the metadata request event. * @@ -367,67 +503,6 @@ }; /** - * FSP: implementation for the file close request event. The file, - * previously opened with <code>openRequestId</code> will be closed. - * - * @param {!chrome.fileSystemProvider.CloseFileRequestedOptions} options - * Options. - * @param {function()} onSuccess Success callback. - * @param {function(chrome.fileSystemProvider.ProviderError)} onError Error - * callback. - */ - onCloseFileRequested(options, onSuccess, onError) { - this.recordEvent('onCloseFileRequested', options); - - if (options.fileSystemId !== this.fileSystemId || - !this.openedFiles[options.openRequestId]) { - onError(chrome.fileSystemProvider.ProviderError.SECURITY); - return; - } - - delete this.openedFiles[options.openRequestId]; - onSuccess(); - }; - - /** - * FSP: implementation for the file create request event. - * - * @param {!chrome.fileSystemProvider.CreateFileRequestedOptions} options - * Options. - * @param {function()} onSuccess Success callback - * @param {function(chrome.fileSystemProvider.ProviderError)} onError Error - * callback with an error code. - */ - onCreateFileRequested(options, onSuccess, onError) { - if (options.fileSystemId !== this.fileSystemId) { - onError(chrome.fileSystemProvider.ProviderError.SECURITY); - return; - } - - if (options.filePath === '/') { - onError(chrome.fileSystemProvider.ProviderError.INVALID_OPERATION); - return; - } - - if (options.filePath in this.files) { - onError(chrome.fileSystemProvider.ProviderError.EXISTS); - return; - } - - this.files[options.filePath] = { - metadata: { - isDirectory: false, - name: options.filePath.split('/').pop(), - size: 0, - modificationTime: new Date() - }, - contents: '', - }; - - onSuccess(); - }; - - /** * FSP: requests reading contents of a file, previously opened with <code> * openRequestId</code>. * @@ -489,6 +564,28 @@ } /** + * FSP: implementation for removing an entry watcher. + * + * @param {!chrome.fileSystemProvider.AddWatcherRequestedOptions} options + * Options. + * @param {function()} onSuccess Success callback. + * @param {function(string)} onError Error callback with an error code. + */ + onRemoveWatcherRequested(options, onSuccess, onError) { + if (options.fileSystemId !== this.fileSystemId) { + onError(chrome.fileSystemProvider.ProviderError.SECURITY); + return; + } + + if (options.entryPath in this.files) { + onSuccess(); + return; + } + + onError(chrome.fileSystemProvider.ProviderError.NOT_FOUND); + }; + + /** * FSP: requests writing contents to a file, previously opened with <code> * openRequestId</code>. * @@ -551,100 +648,6 @@ metadata.size = newContents.length; onSuccess(); } - - onAbortRequested(options, onSuccess, onError) { - this.recordEvent('onAbortRequested', options); - if (options.fileSystemId !== this.fileSystemId) { - onError('SECURITY'); // enum ProviderError. - return; - } - - onSuccess(); - } - - /** - * FSP: implementation of copying an entry within the same file system. - * - * @param {!chrome.fileSystemProvider.CopyEntryRequestedOptions} options - * Options. - * @param {function()} onSuccess Success callback - * @param {function(chrome.fileSystemProvider.ProviderError)} onError Error - * callback with an error code. - */ - onCopyEntryRequested(options, onSuccess, onError) { - if (options.fileSystemId !== this.fileSystemId) { - onError(chrome.fileSystemProvider.ProviderError.SECURITY); - return; - } - - if (options.sourcePath === '/') { - onError(chrome.fileSystemProvider.ProviderError.INVALID_OPERATION); - return; - } - - if (!(options.sourcePath in this.files)) { - onError(chrome.fileSystemProvider.ProviderError.NOT_FOUND); - return; - } - - if (options.targetPath in this.files) { - onError(chrome.fileSystemProvider.ProviderError.EXISTS); - return; - } - - // Copy the metadata, but change the 'name' field. - const source = this.files[options.sourcePath]; - /** @suppress {undefinedVars} */ - const dest = structuredClone(source); - dest.name = options.targetPath.split('/').pop(); - this.files[options.targetPath] = dest; - - onSuccess(); - } - - /** - * FSP: implementation for adding an entry watcher. - * - * @param {!chrome.fileSystemProvider.AddWatcherRequestedOptions} options - * Options. - * @param {function()} onSuccess Success callback. - * @param {function(string)} onError Error callback with an error code. - */ - onAddWatcherRequested(options, onSuccess, onError) { - if (options.fileSystemId !== this.fileSystemId) { - onError('SECURITY'); // enum ProviderError. - return; - } - - if (options.entryPath in this.files) { - onSuccess(); - return; - } - - onError('NOT_FOUND'); // enum ProviderError. - }; - - /** - * FSP: implementation for removing an entry watcher. - * - * @param {!chrome.fileSystemProvider.AddWatcherRequestedOptions} options - * Options. - * @param {function()} onSuccess Success callback. - * @param {function(string)} onError Error callback with an error code. - */ - onRemoveWatcherRequested(options, onSuccess, onError) { - if (options.fileSystemId !== this.fileSystemId) { - onError('SECURITY'); // enum ProviderError. - return; - } - - if (options.entryPath in this.files) { - onSuccess(); - return; - } - - onError('NOT_FOUND'); // enum ProviderError. - }; }; /**
diff --git a/chrome/test/data/extensions/api_test/file_system_provider/service_worker/read_file/test.js b/chrome/test/data/extensions/api_test/file_system_provider/service_worker/read_file/test.js index 797259f..3c35b75 100644 --- a/chrome/test/data/extensions/api_test/file_system_provider/service_worker/read_file/test.js +++ b/chrome/test/data/extensions/api_test/file_system_provider/service_worker/read_file/test.js
@@ -1,7 +1,7 @@ // 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 {mountTestFileSystem, promisifyWithLastError, remoteProvider} from '/_test_resources/api_test/file_system_provider/service_worker/helpers.js'; +import {mountTestFileSystem, remoteProvider} from '/_test_resources/api_test/file_system_provider/service_worker/helpers.js'; // For shared constants. import {TestFileSystemProvider} from '/_test_resources/api_test/file_system_provider/service_worker/provider.js'; @@ -37,41 +37,15 @@ return {reader, promise}; } -/** - * Unmounts and remounts a test filesystem with a different opened files limit. - * - * @param {number} openedFilesLimit Limit of opened files at once. If 0, then - * not limited. - * @returns {!Promise<{fileSystem: !Object, volumeId: string}>} mounted - * filesystem and its volume ID. - */ -async function remountTestFileSystem(openedFilesLimit) { - await promisifyWithLastError(chrome.fileSystemProvider.unmount, { - fileSystemId: TestFileSystemProvider.FILESYSTEM_ID, - }); - return mountTestFileSystem(openedFilesLimit); -} - async function main() { await navigator.serviceWorker.ready; - let {fileSystem} = await mountTestFileSystem(); - - /** - * @param {string} path - * @param {{create: boolean}} options - * @returns {!Promise<!FileEntry>} - */ - const getFileEntry = (path, options) => { - return new Promise( - (resolve, reject) => - fileSystem.root.getFile(path, options, resolve, reject)); - }; + const fileSystem = await mountTestFileSystem(); chrome.test.runTests([ // Read contents of a file. This file exists, so it should succeed. async function readFileSuccess() { try { - const fileEntry = await getFileEntry( + const fileEntry = await fileSystem.getFileEntry( TestFileSystemProvider.FILE_READ_SUCCESS, {create: false}, ); @@ -87,14 +61,13 @@ // Read contents of a file multiple times at once. Verify that there is at // most as many opened files at once as permitted per limit. async function readFileWithOpenedFilesLimitSuccess() { - fileSystem = - (await remountTestFileSystem(/*openedFilesLimit=*/ 2)).fileSystem; + await fileSystem.remount(/*openedFilesLimit=*/ 2); try { // Start N read requests in parallel. const N = 20; const reads = []; for (let i = 0; i < N; i++) { - const fileEntry = await getFileEntry( + const fileEntry = await fileSystem.getFileEntry( TestFileSystemProvider.FILE_STALL_READ, {create: false}); const file = await openFile(fileEntry); reads.push(readTextFromFile(file)); @@ -124,10 +97,9 @@ // Read contents of a file, but with an error on the way. This should // result in an error. async function readFileError() { - fileSystem = - (await remountTestFileSystem(/*openedFilesLimit=*/ 0)).fileSystem; + await fileSystem.remount(/*openedFilesLimit=*/ 0); try { - const fileEntry = await getFileEntry( + const fileEntry = await fileSystem.getFileEntry( TestFileSystemProvider.FILE_FAIL, {create: false}, ); @@ -149,7 +121,7 @@ async function abortReadingSuccess() { await remoteProvider.resetState(); try { - const fileEntry = await getFileEntry( + const fileEntry = await fileSystem.getFileEntry( TestFileSystemProvider.FILE_BLOCKS_FOREVER, {create: false}, ); @@ -180,7 +152,7 @@ await remoteProvider.resetState(); await remoteProvider.setHandlerEnabled('onAbortRequested', false); try { - const fileEntry = await getFileEntry( + const fileEntry = await fileSystem.getFileEntry( TestFileSystemProvider.FILE_BLOCKS_FOREVER, {create: false, exclusive: false}, ); @@ -209,15 +181,14 @@ // opened files at once. This is a regression test for: crbug.com/519063. async function abortOpenedAndReopenSuccess() { await remoteProvider.resetState(); - fileSystem = - (await remountTestFileSystem(/*openedFilesLimit=*/ 1)).fileSystem; + await fileSystem.remount(/*openedFilesLimit=*/ 1); await remoteProvider.setHandlerEnabled('onAbortRequested', false); try { - const fileEntry1 = await getFileEntry( + const fileEntry1 = await fileSystem.getFileEntry( TestFileSystemProvider.FILE_STALL_OPEN, {create: false, exclusive: false}, ); - const fileEntry2 = await getFileEntry( + const fileEntry2 = await fileSystem.getFileEntry( TestFileSystemProvider.FILE_READ_SUCCESS, {create: false, exclusive: false}, );
diff --git a/chrome/test/data/extensions/api_test/file_system_provider/service_worker/write_file/test.js b/chrome/test/data/extensions/api_test/file_system_provider/service_worker/write_file/test.js index 92777ad9..d5eeeffd 100644 --- a/chrome/test/data/extensions/api_test/file_system_provider/service_worker/write_file/test.js +++ b/chrome/test/data/extensions/api_test/file_system_provider/service_worker/write_file/test.js
@@ -68,25 +68,13 @@ contents: TestFileSystemProvider.INITIAL_TEXT, }, }); - - const {fileSystem} = await mountTestFileSystem(); - - /** - * @param {string} path - * @param {{create: boolean, exclusive: boolean}} options - * @returns {!Promise<!FileEntry>} - */ - const getFileEntry = (path, options) => { - return new Promise( - (resolve, reject) => - fileSystem.root.getFile(path, options, resolve, reject)); - }; + const fileSystem = await mountTestFileSystem(); chrome.test.runTests([ // Write contents to a non-existing file. It should succeed. async function writeNewFileSuccess() { try { - const fileEntry = await getFileEntry( + const fileEntry = await fileSystem.getFileEntry( TESTING_NEW_FILE_NAME, {create: true, exclusive: true}); await writeTextToFile( @@ -104,7 +92,7 @@ // Overwrite contents in an existing file. It should succeed. async function overwriteFileSuccess() { try { - const fileEntry = await getFileEntry( + const fileEntry = await fileSystem.getFileEntry( TESTING_TIRAMISU_FILE_NAME, {create: true, exclusive: false}); await writeTextToFile( @@ -122,7 +110,7 @@ // Append contents to an existing file. It should succeed. async function appendFileSuccess() { try { - const fileEntry = await getFileEntry( + const fileEntry = await fileSystem.getFileEntry( TESTING_TIRAMISU_FILE_NAME, {create: false, exclusive: false}); const fileWriter = await createWriter(fileEntry); @@ -142,7 +130,7 @@ // Replace contents in an existing file. It should succeed. async function replaceFileSuccess() { try { - const fileEntry = await getFileEntry( + const fileEntry = await fileSystem.getFileEntry( TESTING_TIRAMISU_FILE_NAME, {create: false, exclusive: false}); const fileWriter = await createWriter(fileEntry); @@ -164,7 +152,7 @@ // Write bytes to a broken file. This should result in an error. async function writeBrokenFileError() { try { - const fileEntry = await getFileEntry( + const fileEntry = await fileSystem.getFileEntry( TestFileSystemProvider.FILE_FAIL, {create: false, exclusive: false}); const fileWriter = await createWriter(fileEntry); @@ -187,7 +175,7 @@ let writePromise; try { // A write to this file will be stuck forever. - const fileEntry = await getFileEntry( + const fileEntry = await fileSystem.getFileEntry( TestFileSystemProvider.FILE_BLOCKS_FOREVER, {create: false, exclusive: false}); const fileWriter = await createWriter(fileEntry);
diff --git a/chrome/test/data/extensions/manifest_tests/chromeos_system_extension_asus.json b/chrome/test/data/extensions/manifest_tests/chromeos_system_extension_asus.json index c705ce51..fedc8d0 100644 --- a/chrome/test/data/extensions/manifest_tests/chromeos_system_extension_asus.json +++ b/chrome/test/data/extensions/manifest_tests/chromeos_system_extension_asus.json
@@ -6,7 +6,8 @@ "permissions": [ "os.diagnostics", "os.telemetry", - "os.telemetry.serial_number" + "os.telemetry.serial_number", + "os.telemetry.network_info" ], "chromeos_system_extension": {}, "externally_connectable": {
diff --git a/chrome/test/data/extensions/manifest_tests/chromeos_system_extension_google.json b/chrome/test/data/extensions/manifest_tests/chromeos_system_extension_google.json index 7c75263..cce687f 100644 --- a/chrome/test/data/extensions/manifest_tests/chromeos_system_extension_google.json +++ b/chrome/test/data/extensions/manifest_tests/chromeos_system_extension_google.json
@@ -11,7 +11,8 @@ "os.telemetry" ], "optional_permissions": [ - "os.telemetry.serial_number" + "os.telemetry.serial_number", + "os.telemetry.network_info" ], "chromeos_system_extension": {}, "externally_connectable": {
diff --git a/chrome/test/data/extensions/manifest_tests/chromeos_system_extension_hp.json b/chrome/test/data/extensions/manifest_tests/chromeos_system_extension_hp.json index 9d979d0e..20c3299 100644 --- a/chrome/test/data/extensions/manifest_tests/chromeos_system_extension_hp.json +++ b/chrome/test/data/extensions/manifest_tests/chromeos_system_extension_hp.json
@@ -6,7 +6,8 @@ "permissions": [ "os.diagnostics", "os.telemetry", - "os.telemetry.serial_number" + "os.telemetry.serial_number", + "os.telemetry.network_info" ], "chromeos_system_extension": {}, "externally_connectable": {
diff --git a/chrome/test/data/web_apps/no_icons.json b/chrome/test/data/web_apps/no_icons.json new file mode 100644 index 0000000..06807544 --- /dev/null +++ b/chrome/test/data/web_apps/no_icons.json
@@ -0,0 +1,6 @@ +{ + "name": "No icons", + "start_url": ".", + "theme_color": "blue", + "icons": [] +}
diff --git a/chrome/test/data/webui/settings/chromeos/fake_settings_search_handler.js b/chrome/test/data/webui/settings/chromeos/fake_settings_search_handler.js index 1a4b1c67..839965f 100644 --- a/chrome/test/data/webui/settings/chromeos/fake_settings_search_handler.js +++ b/chrome/test/data/webui/settings/chromeos/fake_settings_search_handler.js
@@ -8,19 +8,19 @@ /** * Fake implementation of chromeos.settings.mojom.SettingsSearchHandlerRemote. * - * @implements {chromeos.settings.mojom.SearchHandlerInterface} + * @implements {ash.settings.mojom.SearchHandlerInterface} */ export class FakeSettingsSearchHandler { constructor() { - /** @private {!Array<chromeos.settings.mojom.SearchResult>} */ + /** @private {!Array<ash.settings.mojom.SearchResult>} */ this.fakeResults_ = []; - /** @private {!chromeos.settings.mojom.SearchResultsObserverInterface} */ + /** @private {!ash.settings.mojom.SearchResultsObserverInterface} */ this.observer_; } /** - * @param {!Array<chromeos.settings.mojom.SearchResult>} results Fake + * @param {!Array<ash.settings.mojom.SearchResult>} results Fake * results that will be returned when Search() is called. */ setFakeResults(results) {
diff --git a/chrome/test/data/webui/settings/chromeos/fake_user_action_recorder.js b/chrome/test/data/webui/settings/chromeos/fake_user_action_recorder.js index 217ee92..fc30766 100644 --- a/chrome/test/data/webui/settings/chromeos/fake_user_action_recorder.js +++ b/chrome/test/data/webui/settings/chromeos/fake_user_action_recorder.js
@@ -4,13 +4,13 @@ /** * @fileoverview Fake implementation of - * chromeos.settings.mojom.UserActionRecorderRemote for testing. + * ash.settings.mojom.UserActionRecorderRemote for testing. */ /** - * Fake implementation of chromeos.settings.mojom.UserActionRecorderRemote. + * Fake implementation of ash.settings.mojom.UserActionRecorderRemote. * - * @implements {chromeos.settings.mojom.UserActionRecorderInterface} + * @implements {ash.settings.mojom.UserActionRecorderInterface} */ export class FakeUserActionRecorder { constructor() {
diff --git a/chrome/updater/external_constants_builder_unittest.cc b/chrome/updater/external_constants_builder_unittest.cc index 70a3c7f..d8abbaf 100644 --- a/chrome/updater/external_constants_builder_unittest.cc +++ b/chrome/updater/external_constants_builder_unittest.cc
@@ -8,8 +8,6 @@ #include <vector> #include "base/files/file_path.h" -#include "base/files/file_util.h" -#include "base/logging.h" #include "base/memory/scoped_refptr.h" #include "base/values.h" #include "build/build_config.h" @@ -18,45 +16,32 @@ #include "chrome/updater/external_constants_builder.h" #include "chrome/updater/external_constants_default.h" #include "chrome/updater/external_constants_override.h" +#include "chrome/updater/test_scope.h" +#include "chrome/updater/unittest_util.h" #include "chrome/updater/updater_branding.h" -#include "chrome/updater/updater_scope.h" #include "chrome/updater/util.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "url/gurl.h" namespace updater { -namespace { - -void DeleteOverridesFile() { - const absl::optional<base::FilePath> target = - GetBaseDataDirectory(GetUpdaterScope()); - if (!target) { - LOG(ERROR) << "Could not get base directory to clean out overrides file."; - return; - } - if (!base::DeleteFile(target->AppendASCII(kDevOverrideFileName))) { - // Note: base::DeleteFile returns `true` if there is no such file, which - // is what we want; "file already doesn't exist" is not an error here. - LOG(ERROR) << "Could not delete override file."; - } -} - -} // namespace class ExternalConstantsBuilderTests : public ::testing::Test { protected: - void SetUp() override; - void TearDown() override; + void SetUp() override { + EXPECT_TRUE( + test::DeleteFileAndEmptyParentDirectories(overrides_file_path_)); + } + void TearDown() override { + EXPECT_TRUE( + test::DeleteFileAndEmptyParentDirectories(overrides_file_path_)); + } + + private: + // This test runs non-elevated. + const absl::optional<base::FilePath> overrides_file_path_ = + test::GetOverrideFilePath(UpdaterScope::kUser); }; -void ExternalConstantsBuilderTests::SetUp() { - DeleteOverridesFile(); -} - -void ExternalConstantsBuilderTests::TearDown() { - DeleteOverridesFile(); -} - TEST_F(ExternalConstantsBuilderTests, TestOverridingNothing) { EXPECT_TRUE(ExternalConstantsBuilder().Overwrite());
diff --git a/chrome/updater/test/integration_test_commands.h b/chrome/updater/test/integration_test_commands.h index 5829a27f..77909edc 100644 --- a/chrome/updater/test/integration_test_commands.h +++ b/chrome/updater/test/integration_test_commands.h
@@ -29,6 +29,7 @@ : public base::RefCountedThreadSafe<IntegrationTestCommands> { public: virtual void EnterTestMode(const GURL& url) const = 0; + virtual void ExitTestMode() const = 0; virtual void SetGroupPolicies(const base::Value::Dict& values) const = 0; virtual void Clean() const = 0; virtual void ExpectClean() const = 0;
diff --git a/chrome/updater/test/integration_test_commands_system.cc b/chrome/updater/test/integration_test_commands_system.cc index 3ba6014..221026c2 100644 --- a/chrome/updater/test/integration_test_commands_system.cc +++ b/chrome/updater/test/integration_test_commands_system.cc
@@ -81,6 +81,8 @@ RunCommand("enter_test_mode", {Param("url", url.spec())}); } + void ExitTestMode() const override { RunCommand("exit_test_mode"); } + void SetGroupPolicies(const base::Value::Dict& values) const override { RunCommand("set_group_policies", {Param("values", StringFromValue(base::Value(values.Clone())))});
diff --git a/chrome/updater/test/integration_test_commands_user.cc b/chrome/updater/test/integration_test_commands_user.cc index 10d658a..649a7bf 100644 --- a/chrome/updater/test/integration_test_commands_user.cc +++ b/chrome/updater/test/integration_test_commands_user.cc
@@ -61,6 +61,10 @@ updater::test::EnterTestMode(url); } + void ExitTestMode() const override { + updater::test::ExitTestMode(updater_scope_); + } + void ExpectSelfUpdateSequence(ScopedServer* test_server) const override { updater::test::ExpectSelfUpdateSequence(updater_scope_, test_server); }
diff --git a/chrome/updater/test/integration_tests.cc b/chrome/updater/test/integration_tests.cc index 08dfafb..cc2b3ba 100644 --- a/chrome/updater/test/integration_tests.cc +++ b/chrome/updater/test/integration_tests.cc
@@ -52,8 +52,8 @@ // TODO(noahrose): Enable tests once updater is implemented for Linux #if !BUILDFLAG(IS_LINUX) -namespace updater { -namespace test { + +namespace updater::test { namespace { #if BUILDFLAG(IS_WIN) || !defined(COMPONENT_BUILD) @@ -103,6 +103,7 @@ } void TearDown() override { + ExitTestMode(); ExpectClean(); PrintLog(); // TODO(crbug.com/1159189): Use a specific test output directory @@ -138,6 +139,8 @@ void EnterTestMode(const GURL& url) { test_commands_->EnterTestMode(url); } + void ExitTestMode() { test_commands_->ExitTestMode(); } + void SetGroupPolicies(const base::Value::Dict& values) { test_commands_->SetGroupPolicies(values); } @@ -340,6 +343,9 @@ // See crbug.com/1112527. #if BUILDFLAG(IS_WIN) || !defined(COMPONENT_BUILD) +// Tests the setup and teardown of the fixture. +TEST_F(IntegrationTest, DoNothing) {} + TEST_F(IntegrationTest, InstallUninstall) { Install(); EXPECT_TRUE(WaitForUpdaterExit()); @@ -926,6 +932,6 @@ #endif // BUILDFLAG(IS_WIN) || !defined(COMPONENT_BUILD) -} // namespace test -} // namespace updater +} // namespace updater::test + #endif // !BUILDFLAG(IS_LINUX)
diff --git a/chrome/updater/test/integration_tests_helper.cc b/chrome/updater/test/integration_tests_helper.cc index 7721448..3591ff1 100644 --- a/chrome/updater/test/integration_tests_helper.cc +++ b/chrome/updater/test/integration_tests_helper.cc
@@ -230,6 +230,7 @@ // then use the With* helper functions to provide its arguments. {"clean", WithSystemScope(Wrap(&Clean))}, {"enter_test_mode", WithSwitch("url", Wrap(&EnterTestMode))}, + {"exit_test_mode", WithSystemScope(Wrap(&ExitTestMode))}, {"set_group_policies", WithSwitch("values", Wrap(&SetGroupPolicies))}, {"expect_active_updater", WithSystemScope(Wrap(&ExpectActiveUpdater))}, {"expect_registered",
diff --git a/chrome/updater/test/integration_tests_impl.cc b/chrome/updater/test/integration_tests_impl.cc index e509852..b1fd516 100644 --- a/chrome/updater/test/integration_tests_impl.cc +++ b/chrome/updater/test/integration_tests_impl.cc
@@ -177,6 +177,10 @@ } // namespace +void ExitTestMode(UpdaterScope scope) { + DeleteFileAndEmptyParentDirectories(GetOverrideFilePath(scope)); +} + int CountDirectoryFiles(const base::FilePath& dir) { base::FileEnumerator it(dir, false, base::FileEnumerator::FILES); int res = 0;
diff --git a/chrome/updater/test/integration_tests_impl.h b/chrome/updater/test/integration_tests_impl.h index 2bdbfe6..2a8fa280 100644 --- a/chrome/updater/test/integration_tests_impl.h +++ b/chrome/updater/test/integration_tests_impl.h
@@ -65,6 +65,10 @@ // CUP). void EnterTestMode(const GURL& url); +// Takes the updater our of the test mode by deleting the external constants +// JSON file. +void ExitTestMode(UpdaterScope scope); + // Sets the external constants for group policies. void SetGroupPolicies(const base::Value::Dict& values);
diff --git a/chrome/updater/unittest_util.cc b/chrome/updater/unittest_util.cc index 9cea5482..b7df85b 100644 --- a/chrome/updater/unittest_util.cc +++ b/chrome/updater/unittest_util.cc
@@ -8,14 +8,19 @@ #include <utility> #include "base/files/file_path.h" +#include "base/files/file_util.h" #include "base/memory/scoped_refptr.h" #include "base/process/kill.h" #include "base/process/process_iterator.h" #include "base/strings/strcat.h" #include "base/time/time.h" +#include "chrome/updater/constants.h" #include "chrome/updater/policy/manager.h" #include "chrome/updater/policy/service.h" +#include "chrome/updater/updater_scope.h" +#include "chrome/updater/util.h" #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/abseil-cpp/absl/types/optional.h" namespace updater::test { @@ -49,4 +54,30 @@ : "?.?"; } +absl::optional<base::FilePath> GetOverrideFilePath(UpdaterScope scope) { + const absl::optional<base::FilePath> data_dir = GetBaseDataDirectory(scope); + return data_dir + ? absl::make_optional(data_dir->AppendASCII(kDevOverrideFileName)) + : absl::nullopt; +} + +bool DeleteFileAndEmptyParentDirectories( + const absl::optional<base::FilePath>& file_path) { + struct Local { + // Deletes recursively `dir` and its parents up, if dir is empty + // and until one non-empty parent directory is found. + static bool DeleteDirsIfEmpty(const base::FilePath& dir) { + if (!base::DirectoryExists(dir) || !base::IsDirectoryEmpty(dir)) + return true; + if (!base::DeleteFile(dir)) + return false; + return DeleteDirsIfEmpty(dir.DirName()); + } + }; + + if (!file_path || !base::DeleteFile(*file_path)) + return false; + return Local::DeleteDirsIfEmpty(file_path->DirName()); +} + } // namespace updater::test
diff --git a/chrome/updater/unittest_util.h b/chrome/updater/unittest_util.h index 48420ea..bd5600d 100644 --- a/chrome/updater/unittest_util.h +++ b/chrome/updater/unittest_util.h
@@ -9,13 +9,16 @@ #include "base/files/file_path.h" #include "base/memory/scoped_refptr.h" +#include "third_party/abseil-cpp/absl/types/optional.h" namespace base { class TimeDelta; +class FilePath; } namespace updater { class PolicyService; +enum class UpdaterScope; } namespace updater::test { @@ -43,6 +46,18 @@ // if the test name is not available. std::string GetTestName(); +// Get the path for external constants override file. This is the JSON file in +// the updater data directory. +absl::optional<base::FilePath> GetOverrideFilePath(UpdaterScope scope); + +// Deletes the file and its parent directories, if the parent directories are +// empty. Returns true if: +// - the file and the directories are deleted. +// - the file does not exist. +// - the directory is not empty. +bool DeleteFileAndEmptyParentDirectories( + const absl::optional<base::FilePath>& file_path); + } // namespace updater::test #endif // CHROME_UPDATER_UNITTEST_UTIL_H_
diff --git a/chrome/updater/unittest_util_unittest.cc b/chrome/updater/unittest_util_unittest.cc index 4a6960bb..833fa89 100644 --- a/chrome/updater/unittest_util_unittest.cc +++ b/chrome/updater/unittest_util_unittest.cc
@@ -4,11 +4,15 @@ #include "chrome/updater/unittest_util.h" +#include "base/files/file_path.h" +#include "base/files/file_util.h" +#include "base/files/scoped_temp_dir.h" #include "base/logging.h" #include "base/path_service.h" #include "base/test/test_timeouts.h" #include "build/build_config.h" #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/abseil-cpp/absl/types/optional.h" #if BUILDFLAG(IS_WIN) #include "chrome/updater/win/test/test_executables.h" @@ -69,4 +73,22 @@ << TestTimeouts::test_launcher_timeout().InMilliseconds(); } +TEST(UnitTestUtil, DeleteFileAndEmptyParentDirectories) { + EXPECT_FALSE(DeleteFileAndEmptyParentDirectories(absl::nullopt)); + + const base::FilePath path_not_found(FILE_PATH_LITERAL("path-not-found")); + EXPECT_TRUE(DeleteFileAndEmptyParentDirectories(path_not_found)); + + // Create and delete the following path "some_dir/dir_in_dir/file_in_dir". + base::ScopedTempDir temp_dir; + ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); + base::FilePath dir_in_dir; + EXPECT_TRUE(base::CreateTemporaryDirInDir( + temp_dir.GetPath(), FILE_PATH_LITERAL("UnitTestUtil"), &dir_in_dir)); + base::FilePath file_in_dir; + EXPECT_TRUE(CreateTemporaryFileInDir(dir_in_dir, &file_in_dir)); + EXPECT_TRUE(DeleteFileAndEmptyParentDirectories(file_in_dir)); + EXPECT_FALSE(base::DirectoryExists(temp_dir.GetPath())); +} + } // namespace updater::test
diff --git a/chrome/utility/BUILD.gn b/chrome/utility/BUILD.gn index dbd58da1..dd88ca1 100644 --- a/chrome/utility/BUILD.gn +++ b/chrome/utility/BUILD.gn
@@ -185,7 +185,6 @@ "//ash/services/ime:lib", "//ash/services/ime/public/mojom", "//ash/services/nearby/public/mojom:mojom", - "//ash/services/quick_pair", "//ash/services/recording", "//chrome/services/file_util", "//chrome/services/sharing", @@ -194,6 +193,7 @@ "//chromeos/ash/components/local_search_service/public/mojom", "//chromeos/ash/components/trash_service", "//chromeos/ash/components/trash_service/public/mojom", + "//chromeos/ash/services/quick_pair", "//chromeos/services/tts", "//chromeos/services/tts/public/mojom", ]
diff --git a/chrome/utility/DEPS b/chrome/utility/DEPS index 2debe7f..75db82a7 100644 --- a/chrome/utility/DEPS +++ b/chrome/utility/DEPS
@@ -3,7 +3,6 @@ "+ash/services/ime/public/mojom", "+ash/services/nearby", "+ash/services/recording/recording_service.h", - "+ash/services/quick_pair/quick_pair_service.h", "+chrome/grit", "+chrome/installer/util", "+chrome/services/ipp_parser/ipp_parser.h", @@ -36,6 +35,7 @@ "+chromeos/ash/services/assistant", "+chromeos/ash/services/assistant/audio_decoder", "+chromeos/ash/services/libassistant/libassistant_service.h", + "+chromeos/ash/services/quick_pair/quick_pair_service.h", "+chromeos/components/quick_answers/public", "+chromeos/services/tts", "+components/crash/core/common/crash_keys.h",
diff --git a/chrome/utility/services.cc b/chrome/utility/services.cc index e82e76d..b405b8c 100644 --- a/chrome/utility/services.cc +++ b/chrome/utility/services.cc
@@ -121,7 +121,6 @@ #include "ash/services/ime/ime_service.h" #include "ash/services/ime/public/mojom/input_engine.mojom.h" #include "ash/services/nearby/public/mojom/sharing.mojom.h" // nogncheck -#include "ash/services/quick_pair/quick_pair_service.h" #include "ash/services/recording/recording_service.h" #include "chrome/services/sharing/sharing_impl.h" #include "chromeos/ash/components/assistant/buildflags.h" // nogncheck @@ -129,6 +128,7 @@ #include "chromeos/ash/components/local_search_service/public/mojom/local_search_service.mojom.h" #include "chromeos/ash/components/trash_service/public/mojom/trash_service.mojom.h" #include "chromeos/ash/components/trash_service/trash_service_impl.h" +#include "chromeos/ash/services/quick_pair/quick_pair_service.h" #include "chromeos/services/tts/public/mojom/tts_service.mojom.h" #include "chromeos/services/tts/tts_service.h"
diff --git a/chrome/version.gni b/chrome/version.gni index 59c55bcc..8e73c2d 100644 --- a/chrome/version.gni +++ b/chrome/version.gni
@@ -166,6 +166,7 @@ "ChromeModern: $chrome_modern_version_code", "Monochrome: $monochrome_version_code", "TrichromeChrome: $trichrome_version_code", + "TrichromeChromeOpenBeta: $trichrome_beta_version_code", "AndroidWebviewStable: $webview_stable_version_code", "AndroidWebviewBeta: $webview_beta_version_code", "AndroidWebviewDev: $webview_dev_version_code", @@ -181,6 +182,10 @@ "TrichromeChrome3264: $trichrome_32_64_version_code", "TrichromeChrome6432: $trichrome_64_32_version_code", "TrichromeChrome64: $trichrome_64_version_code", + "TrichromeChrome32OpenBeta: $trichrome_32_beta_version_code", + "TrichromeChrome3264OpenBeta: $trichrome_32_64_beta_version_code", + "TrichromeChrome6432OpenBeta: $trichrome_64_32_beta_version_code", + "TrichromeChrome64OpenBeta: $trichrome_64_beta_version_code", "AndroidWebview32Stable: $webview_32_stable_version_code", "AndroidWebview32Beta: $webview_32_beta_version_code", "AndroidWebview32Dev: $webview_32_dev_version_code",
diff --git a/chromeos/ash/components/BUILD.gn b/chromeos/ash/components/BUILD.gn index 7b7f0bb..6338b011 100644 --- a/chromeos/ash/components/BUILD.gn +++ b/chromeos/ash/components/BUILD.gn
@@ -41,6 +41,7 @@ "//chromeos/ash/components/string_matching:unit_tests", "//chromeos/ash/components/sync_wifi:unit_tests", "//chromeos/ash/components/timezone:unit_tests", + "//chromeos/ash/components/tpm:unit_tests", "//chromeos/ash/components/trash_service:unit_tests", "//chromeos/components/sensors:ash_unit_tests", ]
diff --git a/chromeos/ash/components/dbus/cros_disks/cros_disks_client.cc b/chromeos/ash/components/dbus/cros_disks/cros_disks_client.cc index a3a100a..def6754 100644 --- a/chromeos/ash/components/dbus/cros_disks/cros_disks_client.cc +++ b/chromeos/ash/components/dbus/cros_disks/cros_disks_client.cc
@@ -115,15 +115,17 @@ return MountError::kUnsupportedFilesystem; case cros_disks::MOUNT_ERROR_INVALID_ARCHIVE: return MountError::kInvalidArchive; - case cros_disks::MOUNT_ERROR_UNSUPPORTED_ARCHIVE: - // TODO(amistry): Add MOUNT_ERROR_UNSUPPORTED_ARCHIVE. - return MountError::kUnknown; case cros_disks::MOUNT_ERROR_NEED_PASSWORD: + case cros_disks::MOUNT_ERROR_NEED_PASSWORD_EX: return MountError::kNeedPassword; case cros_disks::MOUNT_ERROR_IN_PROGRESS: + case cros_disks::MOUNT_ERROR_IN_PROGRESS_EX: return MountError::kInProgress; case cros_disks::MOUNT_ERROR_CANCELLED: + case cros_disks::MOUNT_ERROR_CANCELLED_EX: return MountError::kCancelled; + case cros_disks::MOUNT_ERROR_BUSY: + return MountError::kBusy; default: LOG(ERROR) << "Unrecognised mount error code " << mount_error; return MountError::kUnknown; @@ -698,6 +700,7 @@ PRINT_ERROR(kNeedPassword) PRINT_ERROR(kInProgress) PRINT_ERROR(kCancelled) + PRINT_ERROR(kBusy) #undef PRINT_ERROR }
diff --git a/chromeos/ash/components/dbus/cros_disks/cros_disks_client.h b/chromeos/ash/components/dbus/cros_disks/cros_disks_client.h index 6cd1cf0..497a1d6 100644 --- a/chromeos/ash/components/dbus/cros_disks/cros_disks_client.h +++ b/chromeos/ash/components/dbus/cros_disks/cros_disks_client.h
@@ -83,7 +83,8 @@ kNeedPassword = 17, kInProgress = 18, kCancelled = 19, - kMaxValue = 19, + kBusy = 20, + kMaxValue = 20, }; // Output operator for logging.
diff --git a/chromeos/ash/components/dbus/userdataauth/fake_install_attributes_client.cc b/chromeos/ash/components/dbus/userdataauth/fake_install_attributes_client.cc index b9dc3054..552b7968e 100644 --- a/chromeos/ash/components/dbus/userdataauth/fake_install_attributes_client.cc +++ b/chromeos/ash/components/dbus/userdataauth/fake_install_attributes_client.cc
@@ -199,7 +199,8 @@ &cache_file) && base::PathExists(cache_file); DCHECK(file_exists); - // Mostly copied from ash/components/tpm/install_attributes.cc. + // Mostly copied from + // chromeos/ash/components/install_attributes/install_attributes.cc. std::string file_blob; if (!base::ReadFileToStringWithMaxSize(cache_file, &file_blob, kInstallAttributesFileMaxSize)) {
diff --git a/chromeos/ash/components/string_matching/BUILD.gn b/chromeos/ash/components/string_matching/BUILD.gn index 47c83d0..c3f477d 100644 --- a/chromeos/ash/components/string_matching/BUILD.gn +++ b/chromeos/ash/components/string_matching/BUILD.gn
@@ -15,8 +15,8 @@ "diacritic_utils.h", "fuzzy_tokenized_string_match.cc", "fuzzy_tokenized_string_match.h", - "prefix_matcher_new.cc", - "prefix_matcher_new.h", + "prefix_matcher.cc", + "prefix_matcher.h", "sequence_matcher.cc", "sequence_matcher.h", "term_break_iterator.cc", @@ -47,7 +47,7 @@ "acronym_matcher_unittest.cc", "diacritic_utils_unittest.cc", "fuzzy_tokenized_string_match_unittest.cc", - "prefix_matcher_new_unittest.cc", + "prefix_matcher_unittest.cc", "sequence_matcher_unittest.cc", "term_break_iterator_unittest.cc", "tokenized_string_char_iterator_unittest.cc",
diff --git a/chromeos/ash/components/string_matching/fuzzy_tokenized_string_match.cc b/chromeos/ash/components/string_matching/fuzzy_tokenized_string_match.cc index 8c780f67c48..4dc21af 100644 --- a/chromeos/ash/components/string_matching/fuzzy_tokenized_string_match.cc +++ b/chromeos/ash/components/string_matching/fuzzy_tokenized_string_match.cc
@@ -17,7 +17,7 @@ #include "base/strings/string_util.h" #include "chromeos/ash/components/string_matching/acronym_matcher.h" #include "chromeos/ash/components/string_matching/diacritic_utils.h" -#include "chromeos/ash/components/string_matching/prefix_matcher_new.h" +#include "chromeos/ash/components/string_matching/prefix_matcher.h" #include "chromeos/ash/components/string_matching/sequence_matcher.h" #include "third_party/abseil-cpp/absl/types/optional.h" @@ -209,7 +209,7 @@ double FuzzyTokenizedStringMatch::PrefixMatcher(const TokenizedString& query, const TokenizedString& text, bool use_acronym_matcher) { - string_matching::PrefixMatcherNew match(query, text); + string_matching::PrefixMatcher match(query, text); match.Match(); double relevance = 0.0;
diff --git a/chromeos/ash/components/string_matching/prefix_matcher_new.cc b/chromeos/ash/components/string_matching/prefix_matcher.cc similarity index 93% rename from chromeos/ash/components/string_matching/prefix_matcher_new.cc rename to chromeos/ash/components/string_matching/prefix_matcher.cc index 1bae69b..7c7cc45 100644 --- a/chromeos/ash/components/string_matching/prefix_matcher_new.cc +++ b/chromeos/ash/components/string_matching/prefix_matcher.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 "chromeos/ash/components/string_matching/prefix_matcher_new.h" +#include "chromeos/ash/components/string_matching/prefix_matcher.h" #include <cstddef> #include <queue> @@ -24,8 +24,6 @@ MatchInfo::~MatchInfo() = default; } // namespace -// TODO(crbug.com/1336160): Replace PrefixMatcher with PrefixMatcherNew -// // PrefixMatcher: // // The factors below are applied when the current char of query matches @@ -53,12 +51,12 @@ // // kNoMatchScore is a relevance score that represents no match. -PrefixMatcherNew::PrefixMatcherNew(const TokenizedString& query, - const TokenizedString& text) +PrefixMatcher::PrefixMatcher(const TokenizedString& query, + const TokenizedString& text) : query_(query), text_(text) {} -PrefixMatcherNew::~PrefixMatcherNew() = default; +PrefixMatcher::~PrefixMatcher() = default; -bool PrefixMatcherNew::Match() { +bool PrefixMatcher::Match() { MatchInfo sentence_match_info; SentencePrefixMatch(sentence_match_info); MatchInfo token_match_info; @@ -73,7 +71,7 @@ return relevance_ > 0.0; } -void PrefixMatcherNew::SentencePrefixMatch(MatchInfo& sentence_match_info) { +void PrefixMatcher::SentencePrefixMatch(MatchInfo& sentence_match_info) { // Since we are concatenating the tokens, we do not have whitespace // separation, and so we have to be careful with index calculation later on. std::u16string query_sentence = base::StrCat(query_.tokens()); @@ -133,7 +131,7 @@ } } -void PrefixMatcherNew::TokenPrefixMatch(MatchInfo& token_match_info) { +void PrefixMatcher::TokenPrefixMatch(MatchInfo& token_match_info) { const size_t num_query_token = query_.tokens().size(); const size_t num_text_token = text_.tokens().size(); @@ -189,10 +187,9 @@ token_match_info.relevance = kNoMatchScore; } -void PrefixMatcherNew::UpdateInfoForTokenPrefixMatch( - size_t query_pos, - size_t text_pos, - MatchInfo& token_match_info) { +void PrefixMatcher::UpdateInfoForTokenPrefixMatch(size_t query_pos, + size_t text_pos, + MatchInfo& token_match_info) { const size_t hit_start_pos = text_.mappings()[text_pos].start(); const size_t hit_end_pos = text_.mappings()[text_pos].start() + query_.tokens()[query_pos].size();
diff --git a/chromeos/ash/components/string_matching/prefix_matcher_new.h b/chromeos/ash/components/string_matching/prefix_matcher.h similarity index 90% rename from chromeos/ash/components/string_matching/prefix_matcher_new.h rename to chromeos/ash/components/string_matching/prefix_matcher.h index 4c3a41cd..522e1be 100644 --- a/chromeos/ash/components/string_matching/prefix_matcher_new.h +++ b/chromeos/ash/components/string_matching/prefix_matcher.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 CHROMEOS_ASH_COMPONENTS_STRING_MATCHING_PREFIX_MATCHER_NEW_H_ -#define CHROMEOS_ASH_COMPONENTS_STRING_MATCHING_PREFIX_MATCHER_NEW_H_ +#ifndef CHROMEOS_ASH_COMPONENTS_STRING_MATCHING_PREFIX_MATCHER_H_ +#define CHROMEOS_ASH_COMPONENTS_STRING_MATCHING_PREFIX_MATCHER_H_ #include "chromeos/ash/components/string_matching/tokenized_string.h" #include "ui/gfx/range/range.h" @@ -46,15 +46,15 @@ // PrefixMatcher matches the chars of a given query as prefix of tokens in // a given text. We give some specific scoring examples in the .cc file. -class PrefixMatcherNew { +class PrefixMatcher { public: typedef std::vector<gfx::Range> Hits; - PrefixMatcherNew(const TokenizedString& query, const TokenizedString& text); - ~PrefixMatcherNew(); + PrefixMatcher(const TokenizedString& query, const TokenizedString& text); + ~PrefixMatcher(); - PrefixMatcherNew(const PrefixMatcherNew&) = delete; - PrefixMatcherNew& operator=(const PrefixMatcherNew&) = delete; + PrefixMatcher(const PrefixMatcher&) = delete; + PrefixMatcher& operator=(const PrefixMatcher&) = delete; // Return true if we found either sentence prefix matching or token prefix // matching. If no full match is found, return false. @@ -117,4 +117,4 @@ } // namespace ash::string_matching -#endif // CHROMEOS_ASH_COMPONENTS_STRING_MATCHING_PREFIX_MATCHER_NEW_H_ +#endif // CHROMEOS_ASH_COMPONENTS_STRING_MATCHING_PREFIX_MATCHER_H_
diff --git a/chromeos/ash/components/string_matching/prefix_matcher_new_unittest.cc b/chromeos/ash/components/string_matching/prefix_matcher_unittest.cc similarity index 72% rename from chromeos/ash/components/string_matching/prefix_matcher_new_unittest.cc rename to chromeos/ash/components/string_matching/prefix_matcher_unittest.cc index a55fede..0c24955 100644 --- a/chromeos/ash/components/string_matching/prefix_matcher_new_unittest.cc +++ b/chromeos/ash/components/string_matching/prefix_matcher_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 "chromeos/ash/components/string_matching/prefix_matcher_new.h" +#include "chromeos/ash/components/string_matching/prefix_matcher.h" #include "chromeos/ash/components/string_matching/tokenized_string.h" #include "testing/gtest/include/gtest/gtest.h" @@ -20,7 +20,7 @@ } // namespace -class PrefixMatcherNewTest : public testing::Test {}; +class PrefixMatcherTest : public testing::Test {}; // Note on expected score calculations: // @@ -32,197 +32,197 @@ // When a query does not successfully match to a text, the overall expected // score is `kNoMatchScore`. -TEST_F(PrefixMatcherNewTest, ExactMatch) { +TEST_F(PrefixMatcherTest, ExactMatch) { TokenizedString query(u"abc def"); TokenizedString text(u"abc def"); - PrefixMatcherNew pm(query, text); + PrefixMatcher pm(query, text); pm.Match(); double expected_score = kIsPrefixCharScore * 6; EXPECT_NEAR(pm.relevance(), expected_score, kAbsError); } -TEST_F(PrefixMatcherNewTest, ExactPrefixMatch) { +TEST_F(PrefixMatcherTest, ExactPrefixMatch) { TokenizedString query(u"abc def"); TokenizedString text(u"abc defgh ijklm"); - PrefixMatcherNew pm(query, text); + PrefixMatcher pm(query, text); pm.Match(); double expected_score = kIsPrefixCharScore * 6; EXPECT_NEAR(pm.relevance(), expected_score, kAbsError); } -TEST_F(PrefixMatcherNewTest, ExactPrefixMatchFirstToken) { +TEST_F(PrefixMatcherTest, ExactPrefixMatchFirstToken) { TokenizedString query(u"ab"); TokenizedString text(u"abc def"); - PrefixMatcherNew pm(query, text); + PrefixMatcher pm(query, text); pm.Match(); double expected_score = kIsPrefixCharScore * 2; EXPECT_NEAR(pm.relevance(), expected_score, kAbsError); } -TEST_F(PrefixMatcherNewTest, ExactPrefixMatchNonFirstToken) { +TEST_F(PrefixMatcherTest, ExactPrefixMatchNonFirstToken) { TokenizedString query(u"de"); TokenizedString text(u"abc def"); - PrefixMatcherNew pm(query, text); + PrefixMatcher pm(query, text); pm.Match(); double expected_score = kIsFrontOfTokenCharScore + kIsWeakHitCharScore; EXPECT_NEAR(pm.relevance(), expected_score, kAbsError); } -TEST_F(PrefixMatcherNewTest, AcronymMatchFirstTokenMatchConsideredNonMatch) { +TEST_F(PrefixMatcherTest, AcronymMatchFirstTokenMatchConsideredNonMatch) { TokenizedString query(u"abc"); TokenizedString text(u"axx bxx cxx dxx exx"); - PrefixMatcherNew pm(query, text); + PrefixMatcher pm(query, text); pm.Match(); double expected_score = kNoMatchScore; EXPECT_NEAR(pm.relevance(), expected_score, kAbsError); } -TEST_F(PrefixMatcherNewTest, AcronymMatchNonFirstTokenMatchConsideredNonMatch) { +TEST_F(PrefixMatcherTest, AcronymMatchNonFirstTokenMatchConsideredNonMatch) { TokenizedString query(u"bcd"); TokenizedString text(u"axx bxx cxx dxx exx"); - PrefixMatcherNew pm(query, text); + PrefixMatcher pm(query, text); pm.Match(); double expected_score = kNoMatchScore; EXPECT_NEAR(pm.relevance(), expected_score, kAbsError); } -TEST_F(PrefixMatcherNewTest, AcronymMatchNonConsecutiveConsideredNonMatch) { +TEST_F(PrefixMatcherTest, AcronymMatchNonConsecutiveConsideredNonMatch) { TokenizedString query(u"acd"); TokenizedString text(u"axx bxx cxx dxx exx"); - PrefixMatcherNew pm(query, text); + PrefixMatcher pm(query, text); pm.Match(); double expected_score = kNoMatchScore; EXPECT_NEAR(pm.relevance(), expected_score, kAbsError); } -TEST_F(PrefixMatcherNewTest, MixedAcronymAndPrefixMatchingConsideredNonMatch) { +TEST_F(PrefixMatcherTest, MixedAcronymAndPrefixMatchingConsideredNonMatch) { TokenizedString query(u"adefg"); TokenizedString text(u"abc def ghi"); - PrefixMatcherNew pm(query, text); + PrefixMatcher pm(query, text); pm.Match(); double expected_score = kNoMatchScore; EXPECT_NEAR(pm.relevance(), expected_score, kAbsError); } -TEST_F(PrefixMatcherNewTest, FinalPartialTokenConsideredMatch) { +TEST_F(PrefixMatcherTest, FinalPartialTokenConsideredMatch) { TokenizedString query(u"abc de"); TokenizedString text(u"abc def"); - PrefixMatcherNew pm(query, text); + PrefixMatcher pm(query, text); pm.Match(); double expected_score = kIsPrefixCharScore * 5; EXPECT_NEAR(pm.relevance(), expected_score, kAbsError); } -TEST_F(PrefixMatcherNewTest, NonFinalPartialTokenConsideredNonMatch) { +TEST_F(PrefixMatcherTest, NonFinalPartialTokenConsideredNonMatch) { TokenizedString query(u"abce"); TokenizedString text(u"a bcd e"); - PrefixMatcherNew pm(query, text); + PrefixMatcher pm(query, text); pm.Match(); double expected_score = kNoMatchScore; EXPECT_NEAR(pm.relevance(), expected_score, kAbsError); } -TEST_F(PrefixMatcherNewTest, ExactPrefixMatchDiscrete) { +TEST_F(PrefixMatcherTest, ExactPrefixMatchDiscrete) { TokenizedString query(u"abc ghi"); TokenizedString text(u"abc def ghi"); - PrefixMatcherNew pm(query, text); + PrefixMatcher pm(query, text); pm.Match(); double expected_score = kIsPrefixCharScore * 3 + kIsFrontOfTokenCharScore + kIsWeakHitCharScore * 2; EXPECT_NEAR(pm.relevance(), expected_score, kAbsError); } -TEST_F(PrefixMatcherNewTest, ExactPrefixMatchDiscreteNonFirstToken) { +TEST_F(PrefixMatcherTest, ExactPrefixMatchDiscreteNonFirstToken) { TokenizedString query(u"abc ghi"); TokenizedString text(u"jkl abc def ghi"); - PrefixMatcherNew pm(query, text); + PrefixMatcher pm(query, text); pm.Match(); double expected_score = kIsFrontOfTokenCharScore * 2 + kIsWeakHitCharScore * 4; EXPECT_NEAR(pm.relevance(), expected_score, kAbsError); } -TEST_F(PrefixMatcherNewTest, ExactPrefixMatchOrderVariation) { +TEST_F(PrefixMatcherTest, ExactPrefixMatchOrderVariation) { TokenizedString query(u"ghi abc"); TokenizedString text(u"abc ghi"); - PrefixMatcherNew pm(query, text); + PrefixMatcher pm(query, text); pm.Match(); double expected_score = kIsFrontOfTokenCharScore * 2 + kIsWeakHitCharScore * 4; EXPECT_NEAR(pm.relevance(), expected_score, kAbsError); } -TEST_F(PrefixMatcherNewTest, ExactPrefixMatchOrderVariationNonFirstToken) { +TEST_F(PrefixMatcherTest, ExactPrefixMatchOrderVariationNonFirstToken) { TokenizedString query(u"ghi abc"); TokenizedString text(u"jkl abc ghi"); - PrefixMatcherNew pm(query, text); + PrefixMatcher pm(query, text); pm.Match(); double expected_score = kIsFrontOfTokenCharScore * 2 + kIsWeakHitCharScore * 4; EXPECT_NEAR(pm.relevance(), expected_score, kAbsError); } -TEST_F(PrefixMatcherNewTest, ExactPrefixMatchOrderVariationAndDiscrete) { +TEST_F(PrefixMatcherTest, ExactPrefixMatchOrderVariationAndDiscrete) { TokenizedString query(u"ghi abc"); TokenizedString text(u"jkl abc def ghi"); - PrefixMatcherNew pm(query, text); + PrefixMatcher pm(query, text); pm.Match(); double expected_score = kIsFrontOfTokenCharScore * 2 + kIsWeakHitCharScore * 4; EXPECT_NEAR(pm.relevance(), expected_score, kAbsError); } -TEST_F(PrefixMatcherNewTest, SentencePrefixMatch) { +TEST_F(PrefixMatcherTest, SentencePrefixMatch) { TokenizedString query(u"abcd"); TokenizedString text(u"a bcd e"); - PrefixMatcherNew pm(query, text); + PrefixMatcher pm(query, text); pm.Match(); double expected_score = kIsPrefixCharScore * 4; EXPECT_NEAR(pm.relevance(), expected_score, kAbsError); } -TEST_F(PrefixMatcherNewTest, SentencePrefixMatchNotInFront) { +TEST_F(PrefixMatcherTest, SentencePrefixMatchNotInFront) { TokenizedString query(u"abcd"); TokenizedString text(u"fgh a bcd e"); - PrefixMatcherNew pm(query, text); + PrefixMatcher pm(query, text); pm.Match(); double expected_score = (kIsFrontOfTokenCharScore + kIsWeakHitCharScore) * 2; EXPECT_NEAR(pm.relevance(), expected_score, kAbsError); } -TEST_F(PrefixMatcherNewTest, CaseSentencePrefixMatchPreferred) { +TEST_F(PrefixMatcherTest, CaseSentencePrefixMatchPreferred) { TokenizedString query(u"abc def"); TokenizedString text(u"abcdef abc def"); - PrefixMatcherNew pm(query, text); + PrefixMatcher pm(query, text); pm.Match(); double expected_score = kIsPrefixCharScore * 6; EXPECT_NEAR(pm.relevance(), expected_score, kAbsError); } -TEST_F(PrefixMatcherNewTest, CaseTokenPrefixMatchPreferred) { +TEST_F(PrefixMatcherTest, CaseTokenPrefixMatchPreferred) { TokenizedString query(u"abc def"); TokenizedString text(u"def abc abcdef"); - PrefixMatcherNew pm(query, text); + PrefixMatcher pm(query, text); pm.Match(); double expected_score = kIsFrontOfTokenCharScore * 2 + kIsWeakHitCharScore * 4;
diff --git a/chromeos/ash/components/string_matching/tokenized_string_match.cc b/chromeos/ash/components/string_matching/tokenized_string_match.cc index a559758f..6b1e1987 100644 --- a/chromeos/ash/components/string_matching/tokenized_string_match.cc +++ b/chromeos/ash/components/string_matching/tokenized_string_match.cc
@@ -10,7 +10,7 @@ #include "base/i18n/string_search.h" #include "base/strings/string_util.h" -#include "chromeos/ash/components/string_matching/prefix_matcher_new.h" +#include "chromeos/ash/components/string_matching/prefix_matcher.h" namespace ash::string_matching { @@ -46,7 +46,7 @@ return true; } - PrefixMatcherNew matcher(query, text); + PrefixMatcher matcher(query, text); if (matcher.Match()) { relevance_ = matcher.relevance(); hits_.assign(matcher.hits().begin(), matcher.hits().end());
diff --git a/ash/components/tpm/BUILD.gn b/chromeos/ash/components/tpm/BUILD.gn similarity index 94% rename from ash/components/tpm/BUILD.gn rename to chromeos/ash/components/tpm/BUILD.gn index a8e9977..a2d6e4c4 100644 --- a/ash/components/tpm/BUILD.gn +++ b/chromeos/ash/components/tpm/BUILD.gn
@@ -2,9 +2,9 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -import("//ash/components/tpm/buildflags.gni") import("//build/buildflag_header.gni") import("//build/config/chromeos/ui_mode.gni") +import("//chromeos/ash/components/tpm/buildflags.gni") import("//testing/test.gni") assert(is_chromeos_ash) @@ -15,7 +15,7 @@ } component("tpm") { - defines = [ "IS_ASH_COMPONENTS_TPM_IMPL" ] + defines = [ "IS_CHROMEOS_ASH_COMPONENTS_TPM_IMPL" ] deps = [ ":buildflags", "//base",
diff --git a/ash/components/tpm/DEPS b/chromeos/ash/components/tpm/DEPS similarity index 85% rename from ash/components/tpm/DEPS rename to chromeos/ash/components/tpm/DEPS index 176ab9871..1f91555 100644 --- a/ash/components/tpm/DEPS +++ b/chromeos/ash/components/tpm/DEPS
@@ -4,14 +4,10 @@ "+base", "+chromeos/ash/components/cryptohome", "+chromeos/ash/components/dbus", - "+chromeos/dbus", + "+chromeos/dbus/tpm_manager", "+chromeos/login/login_state", "+components/account_id", - "+components/policy/proto", "+crypto", - "+google_apis/gaia", - "+testing", - "+third_party/cros_system_api", # Abseil features must be allowlisted explicitly for now. See # //styleguide/c++/c++11.html. Allowed features' headers will be listed @@ -25,3 +21,9 @@ '+third_party/abseil-cpp/absl/types/variant.h', '+third_party/abseil-cpp/absl/utility/utility.h', ] + +specific_include_rules = { + ".*test\.cc": [ + "+testing", + ] +}
diff --git a/ash/components/tpm/buildflags.gni b/chromeos/ash/components/tpm/buildflags.gni similarity index 100% rename from ash/components/tpm/buildflags.gni rename to chromeos/ash/components/tpm/buildflags.gni
diff --git a/ash/components/tpm/prepare_tpm.cc b/chromeos/ash/components/tpm/prepare_tpm.cc similarity index 97% rename from ash/components/tpm/prepare_tpm.cc rename to chromeos/ash/components/tpm/prepare_tpm.cc index d87d4e6..f1cd565d 100644 --- a/ash/components/tpm/prepare_tpm.cc +++ b/chromeos/ash/components/tpm/prepare_tpm.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 "ash/components/tpm/prepare_tpm.h" +#include "chromeos/ash/components/tpm/prepare_tpm.h" #include <utility>
diff --git a/ash/components/tpm/prepare_tpm.h b/chromeos/ash/components/tpm/prepare_tpm.h similarity index 71% rename from ash/components/tpm/prepare_tpm.h rename to chromeos/ash/components/tpm/prepare_tpm.h index 79c7b166..a1ee6fd 100644 --- a/ash/components/tpm/prepare_tpm.h +++ b/chromeos/ash/components/tpm/prepare_tpm.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 ASH_COMPONENTS_TPM_PREPARE_TPM_H_ -#define ASH_COMPONENTS_TPM_PREPARE_TPM_H_ +#ifndef CHROMEOS_ASH_COMPONENTS_TPM_PREPARE_TPM_H_ +#define CHROMEOS_ASH_COMPONENTS_TPM_PREPARE_TPM_H_ #include "base/callback.h" #include "base/component_export.h" @@ -16,9 +16,9 @@ // interrupted TPM initialization triggered upon showing EULA screen, triggers // TPM initialization process. When the preparation process is done, invoke // `preparation_finished_callback`. -void COMPONENT_EXPORT(ASH_COMPONENTS_TPM) - PrepareTpm(base::OnceClosure preparation_finished_callback); +COMPONENT_EXPORT(CHROMEOS_ASH_COMPONENTS_TPM) +void PrepareTpm(base::OnceClosure preparation_finished_callback); } // namespace ash -#endif // ASH_COMPONENTS_TPM_PREPARE_TPM_H_ +#endif // CHROMEOS_ASH_COMPONENTS_TPM_PREPARE_TPM_H_
diff --git a/ash/components/tpm/prepare_tpm_unittest.cc b/chromeos/ash/components/tpm/prepare_tpm_unittest.cc similarity index 97% rename from ash/components/tpm/prepare_tpm_unittest.cc rename to chromeos/ash/components/tpm/prepare_tpm_unittest.cc index 2e9486c..52cc5b1 100644 --- a/ash/components/tpm/prepare_tpm_unittest.cc +++ b/chromeos/ash/components/tpm/prepare_tpm_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 "ash/components/tpm/prepare_tpm.h" +#include "chromeos/ash/components/tpm/prepare_tpm.h" #include "base/run_loop.h" #include "base/test/task_environment.h"
diff --git a/ash/components/tpm/tpm_token_info_getter.cc b/chromeos/ash/components/tpm/tpm_token_info_getter.cc similarity index 97% rename from ash/components/tpm/tpm_token_info_getter.cc rename to chromeos/ash/components/tpm/tpm_token_info_getter.cc index ff13576..db173fb1 100644 --- a/ash/components/tpm/tpm_token_info_getter.cc +++ b/chromeos/ash/components/tpm/tpm_token_info_getter.cc
@@ -2,13 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "ash/components/tpm/tpm_token_info_getter.h" +#include "chromeos/ash/components/tpm/tpm_token_info_getter.h" #include <stdint.h> #include <utility> -#include "ash/components/tpm/buildflags.h" #include "base/bind.h" #include "base/location.h" #include "base/logging.h" @@ -16,6 +15,7 @@ #include "base/task/task_runner.h" #include "chromeos/ash/components/cryptohome/cryptohome_parameters.h" #include "chromeos/ash/components/dbus/userdataauth/userdataauth_client.h" +#include "chromeos/ash/components/tpm/buildflags.h" #include "chromeos/dbus/tpm_manager/tpm_manager.pb.h" #include "chromeos/dbus/tpm_manager/tpm_manager_client.h"
diff --git a/ash/components/tpm/tpm_token_info_getter.h b/chromeos/ash/components/tpm/tpm_token_info_getter.h similarity index 92% rename from ash/components/tpm/tpm_token_info_getter.h rename to chromeos/ash/components/tpm/tpm_token_info_getter.h index ac8bdc7..7783b1ad 100644 --- a/ash/components/tpm/tpm_token_info_getter.h +++ b/chromeos/ash/components/tpm/tpm_token_info_getter.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 ASH_COMPONENTS_TPM_TPM_TOKEN_INFO_GETTER_H_ -#define ASH_COMPONENTS_TPM_TPM_TOKEN_INFO_GETTER_H_ +#ifndef CHROMEOS_ASH_COMPONENTS_TPM_TPM_TOKEN_INFO_GETTER_H_ +#define CHROMEOS_ASH_COMPONENTS_TPM_TPM_TOKEN_INFO_GETTER_H_ #include <memory> #include <string> @@ -27,7 +27,7 @@ // Class for getting a user or the system TPM token info from cryptohome during // TPM token loading. -class COMPONENT_EXPORT(ASH_COMPONENTS_TPM) TPMTokenInfoGetter { +class COMPONENT_EXPORT(CHROMEOS_ASH_COMPONENTS_TPM) TPMTokenInfoGetter { public: using TpmTokenInfoCallback = base::OnceCallback<void( absl::optional<user_data_auth::TpmTokenInfo> token_info)>; @@ -61,10 +61,7 @@ } private: - enum Type { - TYPE_SYSTEM, - TYPE_USER - }; + enum Type { TYPE_SYSTEM, TYPE_USER }; enum State { STATE_INITIAL, @@ -126,4 +123,4 @@ } // namespace ash -#endif // ASH_COMPONENTS_TPM_TPM_TOKEN_INFO_GETTER_H_ +#endif // CHROMEOS_ASH_COMPONENTS_TPM_TPM_TOKEN_INFO_GETTER_H_
diff --git a/ash/components/tpm/tpm_token_info_getter_unittest.cc b/chromeos/ash/components/tpm/tpm_token_info_getter_unittest.cc similarity index 99% rename from ash/components/tpm/tpm_token_info_getter_unittest.cc rename to chromeos/ash/components/tpm/tpm_token_info_getter_unittest.cc index c2981f3e..633d600a 100644 --- a/ash/components/tpm/tpm_token_info_getter_unittest.cc +++ b/chromeos/ash/components/tpm/tpm_token_info_getter_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 "ash/components/tpm/tpm_token_info_getter.h" +#include "chromeos/ash/components/tpm/tpm_token_info_getter.h" #include <stdint.h>
diff --git a/ash/components/tpm/tpm_token_loader.cc b/chromeos/ash/components/tpm/tpm_token_loader.cc similarity index 97% rename from ash/components/tpm/tpm_token_loader.cc rename to chromeos/ash/components/tpm/tpm_token_loader.cc index 1cea5ea..4a1bb44 100644 --- a/ash/components/tpm/tpm_token_loader.cc +++ b/chromeos/ash/components/tpm/tpm_token_loader.cc
@@ -2,11 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "ash/components/tpm/tpm_token_loader.h" +#include "chromeos/ash/components/tpm/tpm_token_loader.h" #include <algorithm> -#include "ash/components/tpm/tpm_token_info_getter.h" #include "base/bind.h" #include "base/location.h" #include "base/logging.h" @@ -15,6 +14,7 @@ #include "base/task/sequenced_task_runner.h" #include "base/task/single_thread_task_runner.h" #include "base/threading/thread_task_runner_handle.h" +#include "chromeos/ash/components/tpm/tpm_token_info_getter.h" #include "crypto/nss_util.h" namespace ash {
diff --git a/ash/components/tpm/tpm_token_loader.h b/chromeos/ash/components/tpm/tpm_token_loader.h similarity index 93% rename from ash/components/tpm/tpm_token_loader.h rename to chromeos/ash/components/tpm/tpm_token_loader.h index 448e3434..58bddd21 100644 --- a/ash/components/tpm/tpm_token_loader.h +++ b/chromeos/ash/components/tpm/tpm_token_loader.h
@@ -2,20 +2,20 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef ASH_COMPONENTS_TPM_TPM_TOKEN_LOADER_H_ -#define ASH_COMPONENTS_TPM_TPM_TOKEN_LOADER_H_ +#ifndef CHROMEOS_ASH_COMPONENTS_TPM_TPM_TOKEN_LOADER_H_ +#define CHROMEOS_ASH_COMPONENTS_TPM_TPM_TOKEN_LOADER_H_ #include <memory> #include <string> #include <vector> -#include "ash/components/tpm/tpm_token_info_getter.h" #include "base/callback_forward.h" #include "base/component_export.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "base/threading/thread_checker.h" #include "chromeos/ash/components/dbus/userdataauth/userdataauth_client.h" +#include "chromeos/ash/components/tpm/tpm_token_info_getter.h" #include "chromeos/login/login_state/login_state.h" #include "third_party/abseil-cpp/absl/types/optional.h" @@ -31,7 +31,7 @@ // When the TPM token is loaded, or if the TPM should stay disabled for the // session, the observers are notified using |OnTPMTokenReady|. // Note: This currently initializes the token with the hard coded default id 0. -class COMPONENT_EXPORT(ASH_COMPONENTS_TPM) TPMTokenLoader +class COMPONENT_EXPORT(CHROMEOS_ASH_COMPONENTS_TPM) TPMTokenLoader : public LoginState::Observer { public: enum TPMTokenStatus { @@ -138,4 +138,4 @@ } // namespace ash -#endif // ASH_COMPONENTS_TPM_TPM_TOKEN_LOADER_H_ +#endif // CHROMEOS_ASH_COMPONENTS_TPM_TPM_TOKEN_LOADER_H_
diff --git a/chromeos/ash/services/BUILD.gn b/chromeos/ash/services/BUILD.gn index e48721f..bfea585 100644 --- a/chromeos/ash/services/BUILD.gn +++ b/chromeos/ash/services/BUILD.gn
@@ -17,6 +17,7 @@ source_set("unit_tests") { testonly = true deps = [ + "//ash:test_support", "//chromeos/ash/services/assistant:tests", "//chromeos/ash/services/bluetooth_config:unit_tests", "//chromeos/ash/services/cellular_setup:unit_tests", @@ -25,6 +26,7 @@ "//chromeos/ash/services/cros_healthd/public/cpp:unit_tests", "//chromeos/ash/services/federated/public/cpp:unit_tests", "//chromeos/ash/services/hotspot_config:unit_tests", + "//chromeos/ash/services/quick_pair:unit_tests", "//chromeos/services/machine_learning/public/cpp:ash_unit_tests", ]
diff --git a/chromeos/ash/services/federated/public/cpp/fake_service_connection.cc b/chromeos/ash/services/federated/public/cpp/fake_service_connection.cc index c6aeefc0..2cd1b403 100644 --- a/chromeos/ash/services/federated/public/cpp/fake_service_connection.cc +++ b/chromeos/ash/services/federated/public/cpp/fake_service_connection.cc
@@ -29,5 +29,9 @@ return; } +void FakeServiceConnectionImpl::StartScheduling() { + return; +} + } // namespace federated } // namespace ash
diff --git a/chromeos/ash/services/federated/public/cpp/fake_service_connection.h b/chromeos/ash/services/federated/public/cpp/fake_service_connection.h index 57154e8..3ccc8eb5 100644 --- a/chromeos/ash/services/federated/public/cpp/fake_service_connection.h +++ b/chromeos/ash/services/federated/public/cpp/fake_service_connection.h
@@ -39,6 +39,7 @@ receiver) override; void ReportExample(const std::string& client_name, chromeos::federated::mojom::ExamplePtr example) override; + void StartScheduling() override; private: mojo::ReceiverSet<chromeos::federated::mojom::FederatedService> receivers_;
diff --git a/chromeos/ash/services/federated/public/cpp/service_connection.cc b/chromeos/ash/services/federated/public/cpp/service_connection.cc index 4698a24..1ef066b 100644 --- a/chromeos/ash/services/federated/public/cpp/service_connection.cc +++ b/chromeos/ash/services/federated/public/cpp/service_connection.cc
@@ -5,6 +5,7 @@ #include "chromeos/ash/services/federated/public/cpp/service_connection.h" #include "base/bind.h" +#include "base/feature_list.h" #include "base/no_destructor.h" #include "base/sequence_checker.h" #include "chromeos/ash/components/dbus/federated/federated_client.h" @@ -18,6 +19,9 @@ namespace federated { namespace { +BASE_FEATURE(kShouldFederatedScheduleTasks, + "ShouldFederatedScheduleTasks", + base::FEATURE_DISABLED_BY_DEFAULT); ServiceConnection* g_fake_service_connection_for_testing = nullptr; @@ -95,6 +99,10 @@ platform_channel.TakeRemoteEndpoint().TakePlatformHandle().TakeFD(), base::BindOnce(&ServiceConnectionImpl::OnBootstrapMojoConnectionResponse, base::Unretained(this))); + + if (base::FeatureList::IsEnabled(kShouldFederatedScheduleTasks)) { + federated_service_->StartScheduling(); + } } void ServiceConnectionImpl::OnMojoDisconnect() {
diff --git a/chromeos/ash/services/federated/public/mojom/federated_service.mojom b/chromeos/ash/services/federated/public/mojom/federated_service.mojom index d8bd8734..2fe7ecfe 100644 --- a/chromeos/ash/services/federated/public/mojom/federated_service.mojom +++ b/chromeos/ash/services/federated/public/mojom/federated_service.mojom
@@ -22,7 +22,11 @@ // Stores `example` in cryptohome-backed storage for use during future // scheduled federated analytics or ML model training, identified by - // `client_id`. + // `client_name`. // Examples are deleted when they are used for federated analytics/training. ReportExample@1(string client_name, Example example); + + // Starts scheduling federated training tasks if they are not scheduled yet, + // otherwise does nothing. + StartScheduling@2(); };
diff --git a/ash/services/quick_pair/BUILD.gn b/chromeos/ash/services/quick_pair/BUILD.gn similarity index 83% rename from ash/services/quick_pair/BUILD.gn rename to chromeos/ash/services/quick_pair/BUILD.gn index e5d56783..aa7778d 100644 --- a/ash/services/quick_pair/BUILD.gn +++ b/chromeos/ash/services/quick_pair/BUILD.gn
@@ -28,8 +28,8 @@ deps = [ "//ash/quick_pair/common", - "//ash/services/quick_pair/public/cpp", - "//ash/services/quick_pair/public/mojom", + "//chromeos/ash/services/quick_pair/public/cpp", + "//chromeos/ash/services/quick_pair/public/mojom", "//crypto:crypto", "//device/bluetooth", "//mojo/public/cpp/bindings", @@ -47,9 +47,9 @@ ] deps = [ - "//ash/services/quick_pair/public/cpp", - "//ash/services/quick_pair/public/mojom", "//base/test:test_support", + "//chromeos/ash/services/quick_pair/public/cpp", + "//chromeos/ash/services/quick_pair/public/mojom", "//testing/gtest", ] } @@ -70,10 +70,10 @@ ":quick_pair", "//ash/quick_pair/common:test_support", "//ash/quick_pair/fast_pair_handshake", - "//ash/services/quick_pair/public/cpp", - "//ash/services/quick_pair/public/cpp:unit_tests", - "//ash/services/quick_pair/public/mojom", "//base/test:test_support", + "//chromeos/ash/services/quick_pair/public/cpp", + "//chromeos/ash/services/quick_pair/public/cpp:unit_tests", + "//chromeos/ash/services/quick_pair/public/mojom", "//testing/gmock", "//testing/gtest", ] @@ -84,8 +84,8 @@ deps = [ ":quick_pair", "//ash/quick_pair/common", - "//ash/services/quick_pair/public/mojom", "//base/test:test_support", + "//chromeos/ash/services/quick_pair/public/mojom", "//device/bluetooth/public/cpp", "//mojo/core/embedder", ]
diff --git a/ash/services/quick_pair/DEPS b/chromeos/ash/services/quick_pair/DEPS similarity index 79% rename from ash/services/quick_pair/DEPS rename to chromeos/ash/services/quick_pair/DEPS index 083ad4ea..9f24d64 100644 --- a/ash/services/quick_pair/DEPS +++ b/chromeos/ash/services/quick_pair/DEPS
@@ -1,6 +1,7 @@ include_rules = [ "+ash/quick_pair", "+crypto/openssl_util.h", + "+device/bluetooth/public/cpp", "+mojo/core/embedder", "+third_party/boringssl/src/include", ]
diff --git a/ash/services/quick_pair/DIR_METADATA b/chromeos/ash/services/quick_pair/DIR_METADATA similarity index 100% rename from ash/services/quick_pair/DIR_METADATA rename to chromeos/ash/services/quick_pair/DIR_METADATA
diff --git a/ash/services/quick_pair/OWNERS b/chromeos/ash/services/quick_pair/OWNERS similarity index 100% rename from ash/services/quick_pair/OWNERS rename to chromeos/ash/services/quick_pair/OWNERS
diff --git a/ash/services/quick_pair/fast_pair_data_parser.cc b/chromeos/ash/services/quick_pair/fast_pair_data_parser.cc similarity index 98% rename from ash/services/quick_pair/fast_pair_data_parser.cc rename to chromeos/ash/services/quick_pair/fast_pair_data_parser.cc index 70893172..e7a4f3e 100644 --- a/ash/services/quick_pair/fast_pair_data_parser.cc +++ b/chromeos/ash/services/quick_pair/fast_pair_data_parser.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 "ash/services/quick_pair/fast_pair_data_parser.h" +#include "chromeos/ash/services/quick_pair/fast_pair_data_parser.h" #include <algorithm> #include <cstdint> @@ -10,14 +10,14 @@ #include "ash/quick_pair/common/fast_pair/fast_pair_decoder.h" #include "ash/quick_pair/common/logging.h" -#include "ash/services/quick_pair/fast_pair_decryption.h" -#include "ash/services/quick_pair/public/cpp/battery_notification.h" -#include "ash/services/quick_pair/public/cpp/not_discoverable_advertisement.h" -#include "ash/services/quick_pair/public/mojom/fast_pair_data_parser.mojom.h" #include "base/base64.h" #include "base/containers/circular_deque.h" #include "base/containers/flat_map.h" #include "base/strings/string_number_conversions.h" +#include "chromeos/ash/services/quick_pair/fast_pair_decryption.h" +#include "chromeos/ash/services/quick_pair/public/cpp/battery_notification.h" +#include "chromeos/ash/services/quick_pair/public/cpp/not_discoverable_advertisement.h" +#include "chromeos/ash/services/quick_pair/public/mojom/fast_pair_data_parser.mojom.h" #include "crypto/openssl_util.h" #include "device/bluetooth/public/cpp/bluetooth_address.h" #include "mojo/public/cpp/bindings/pending_receiver.h"
diff --git a/ash/services/quick_pair/fast_pair_data_parser.h b/chromeos/ash/services/quick_pair/fast_pair_data_parser.h similarity index 91% rename from ash/services/quick_pair/fast_pair_data_parser.h rename to chromeos/ash/services/quick_pair/fast_pair_data_parser.h index 339a9b3..e40f20d 100644 --- a/ash/services/quick_pair/fast_pair_data_parser.h +++ b/chromeos/ash/services/quick_pair/fast_pair_data_parser.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 ASH_SERVICES_QUICK_PAIR_FAST_PAIR_DATA_PARSER_H_ -#define ASH_SERVICES_QUICK_PAIR_FAST_PAIR_DATA_PARSER_H_ +#ifndef CHROMEOS_ASH_SERVICES_QUICK_PAIR_FAST_PAIR_DATA_PARSER_H_ +#define CHROMEOS_ASH_SERVICES_QUICK_PAIR_FAST_PAIR_DATA_PARSER_H_ #include <stddef.h> #include <stdint.h> @@ -11,8 +11,8 @@ #include <array> #include <vector> -#include "ash/services/quick_pair/public/mojom/fast_pair_data_parser.mojom.h" #include "base/containers/span.h" +#include "chromeos/ash/services/quick_pair/public/mojom/fast_pair_data_parser.mojom.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/receiver.h" @@ -94,4 +94,4 @@ } // namespace quick_pair } // namespace ash -#endif // ASH_SERVICES_QUICK_PAIR_FAST_PAIR_DATA_PARSER_H_ +#endif // CHROMEOS_ASH_SERVICES_QUICK_PAIR_FAST_PAIR_DATA_PARSER_H_
diff --git a/ash/services/quick_pair/fast_pair_data_parser_fuzzer.cc b/chromeos/ash/services/quick_pair/fast_pair_data_parser_fuzzer.cc similarity index 93% rename from ash/services/quick_pair/fast_pair_data_parser_fuzzer.cc rename to chromeos/ash/services/quick_pair/fast_pair_data_parser_fuzzer.cc index e841174..7153c90 100644 --- a/ash/services/quick_pair/fast_pair_data_parser_fuzzer.cc +++ b/chromeos/ash/services/quick_pair/fast_pair_data_parser_fuzzer.cc
@@ -2,19 +2,19 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "ash/services/quick_pair/fast_pair_data_parser.h" +#include "chromeos/ash/services/quick_pair/fast_pair_data_parser.h" #include <fuzzer/FuzzedDataProvider.h> #include <stddef.h> #include <stdint.h> #include "ash/quick_pair/common/logging.h" -#include "ash/services/quick_pair/public/mojom/fast_pair_data_parser.mojom.h" #include "base/callback_helpers.h" #include "base/command_line.h" #include "base/no_destructor.h" #include "base/test/task_environment.h" #include "base/test/test_timeouts.h" +#include "chromeos/ash/services/quick_pair/public/mojom/fast_pair_data_parser.mojom.h" #include "mojo/core/embedder/embedder.h" #include "mojo/public/cpp/bindings/remote.h"
diff --git a/ash/services/quick_pair/fast_pair_data_parser_unittest.cc b/chromeos/ash/services/quick_pair/fast_pair_data_parser_unittest.cc similarity index 98% rename from ash/services/quick_pair/fast_pair_data_parser_unittest.cc rename to chromeos/ash/services/quick_pair/fast_pair_data_parser_unittest.cc index a5e37a29..807dbf0e 100644 --- a/ash/services/quick_pair/fast_pair_data_parser_unittest.cc +++ b/chromeos/ash/services/quick_pair/fast_pair_data_parser_unittest.cc
@@ -2,21 +2,21 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "ash/services/quick_pair/fast_pair_data_parser.h" +#include "chromeos/ash/services/quick_pair/fast_pair_data_parser.h" #include <stddef.h> #include <iterator> #include "ash/quick_pair/common/fast_pair/fast_pair_service_data_creator.h" -#include "ash/services/quick_pair/public/cpp/decrypted_passkey.h" -#include "ash/services/quick_pair/public/cpp/decrypted_response.h" -#include "ash/services/quick_pair/public/cpp/fast_pair_message_type.h" -#include "ash/services/quick_pair/public/cpp/not_discoverable_advertisement.h" -#include "ash/services/quick_pair/public/mojom/fast_pair_data_parser.mojom.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" #include "base/test/bind.h" #include "base/test/task_environment.h" +#include "chromeos/ash/services/quick_pair/public/cpp/decrypted_passkey.h" +#include "chromeos/ash/services/quick_pair/public/cpp/decrypted_response.h" +#include "chromeos/ash/services/quick_pair/public/cpp/fast_pair_message_type.h" +#include "chromeos/ash/services/quick_pair/public/cpp/not_discoverable_advertisement.h" +#include "chromeos/ash/services/quick_pair/public/mojom/fast_pair_data_parser.mojom.h" #include "mojo/public/cpp/bindings/remote.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/abseil-cpp/absl/types/optional.h"
diff --git a/ash/services/quick_pair/fast_pair_decryption.cc b/chromeos/ash/services/quick_pair/fast_pair_decryption.cc similarity index 94% rename from ash/services/quick_pair/fast_pair_decryption.cc rename to chromeos/ash/services/quick_pair/fast_pair_decryption.cc index 885731c2..640c5454 100644 --- a/ash/services/quick_pair/fast_pair_decryption.cc +++ b/chromeos/ash/services/quick_pair/fast_pair_decryption.cc
@@ -2,11 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "ash/services/quick_pair/fast_pair_decryption.h" +#include "chromeos/ash/services/quick_pair/fast_pair_decryption.h" -#include "ash/services/quick_pair/public/cpp/decrypted_passkey.h" -#include "ash/services/quick_pair/public/cpp/decrypted_response.h" #include "base/check.h" +#include "chromeos/ash/services/quick_pair/public/cpp/decrypted_passkey.h" +#include "chromeos/ash/services/quick_pair/public/cpp/decrypted_response.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/boringssl/src/include/openssl/aes.h"
diff --git a/ash/services/quick_pair/fast_pair_decryption.h b/chromeos/ash/services/quick_pair/fast_pair_decryption.h similarity index 69% rename from ash/services/quick_pair/fast_pair_decryption.h rename to chromeos/ash/services/quick_pair/fast_pair_decryption.h index e1b6af3..5f7f6b3 100644 --- a/ash/services/quick_pair/fast_pair_decryption.h +++ b/chromeos/ash/services/quick_pair/fast_pair_decryption.h
@@ -2,14 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef ASH_SERVICES_QUICK_PAIR_FAST_PAIR_DECRYPTION_H_ -#define ASH_SERVICES_QUICK_PAIR_FAST_PAIR_DECRYPTION_H_ +#ifndef CHROMEOS_ASH_SERVICES_QUICK_PAIR_FAST_PAIR_DECRYPTION_H_ +#define CHROMEOS_ASH_SERVICES_QUICK_PAIR_FAST_PAIR_DECRYPTION_H_ #include <array> #include <string> -#include "ash/services/quick_pair/public/cpp/decrypted_passkey.h" -#include "ash/services/quick_pair/public/cpp/decrypted_response.h" +#include "chromeos/ash/services/quick_pair/public/cpp/decrypted_passkey.h" +#include "chromeos/ash/services/quick_pair/public/cpp/decrypted_response.h" #include "third_party/abseil-cpp/absl/types/optional.h" namespace ash { @@ -30,4 +30,4 @@ } // namespace quick_pair } // namespace ash -#endif // ASH_SERVICES_QUICK_PAIR_FAST_PAIR_DECRYPTION_H_ +#endif // CHROMEOS_ASH_SERVICES_QUICK_PAIR_FAST_PAIR_DECRYPTION_H_
diff --git a/ash/services/quick_pair/fast_pair_decryption_fuzzer.cc b/chromeos/ash/services/quick_pair/fast_pair_decryption_fuzzer.cc similarity index 96% rename from ash/services/quick_pair/fast_pair_decryption_fuzzer.cc rename to chromeos/ash/services/quick_pair/fast_pair_decryption_fuzzer.cc index e17f762..ae052d7d 100644 --- a/ash/services/quick_pair/fast_pair_decryption_fuzzer.cc +++ b/chromeos/ash/services/quick_pair/fast_pair_decryption_fuzzer.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 "ash/services/quick_pair/fast_pair_decryption.h" +#include "chromeos/ash/services/quick_pair/fast_pair_decryption.h" #include <fuzzer/FuzzedDataProvider.h> #include <stddef.h>
diff --git a/ash/services/quick_pair/fast_pair_decryption_unittest.cc b/chromeos/ash/services/quick_pair/fast_pair_decryption_unittest.cc similarity index 97% rename from ash/services/quick_pair/fast_pair_decryption_unittest.cc rename to chromeos/ash/services/quick_pair/fast_pair_decryption_unittest.cc index 5e43142..063ed17 100644 --- a/ash/services/quick_pair/fast_pair_decryption_unittest.cc +++ b/chromeos/ash/services/quick_pair/fast_pair_decryption_unittest.cc
@@ -2,12 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "ash/services/quick_pair/fast_pair_decryption.h" +#include "chromeos/ash/services/quick_pair/fast_pair_decryption.h" #include <array> #include "ash/quick_pair/fast_pair_handshake/fast_pair_encryption.h" -#include "ash/services/quick_pair/public/cpp/fast_pair_message_type.h" +#include "chromeos/ash/services/quick_pair/public/cpp/fast_pair_message_type.h" #include "testing/gtest/include/gtest/gtest.h" namespace ash {
diff --git a/ash/services/quick_pair/mock_quick_pair_process_manager.cc b/chromeos/ash/services/quick_pair/mock_quick_pair_process_manager.cc similarity index 87% rename from ash/services/quick_pair/mock_quick_pair_process_manager.cc rename to chromeos/ash/services/quick_pair/mock_quick_pair_process_manager.cc index a65e014..8fddd63 100644 --- a/ash/services/quick_pair/mock_quick_pair_process_manager.cc +++ b/chromeos/ash/services/quick_pair/mock_quick_pair_process_manager.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 "ash/services/quick_pair/mock_quick_pair_process_manager.h" +#include "chromeos/ash/services/quick_pair/mock_quick_pair_process_manager.h" namespace ash { namespace quick_pair {
diff --git a/ash/services/quick_pair/mock_quick_pair_process_manager.h b/chromeos/ash/services/quick_pair/mock_quick_pair_process_manager.h similarity index 72% rename from ash/services/quick_pair/mock_quick_pair_process_manager.h rename to chromeos/ash/services/quick_pair/mock_quick_pair_process_manager.h index 55e6136..b811f395a 100644 --- a/ash/services/quick_pair/mock_quick_pair_process_manager.h +++ b/chromeos/ash/services/quick_pair/mock_quick_pair_process_manager.h
@@ -2,13 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef ASH_SERVICES_QUICK_PAIR_MOCK_QUICK_PAIR_PROCESS_MANAGER_H_ -#define ASH_SERVICES_QUICK_PAIR_MOCK_QUICK_PAIR_PROCESS_MANAGER_H_ +#ifndef CHROMEOS_ASH_SERVICES_QUICK_PAIR_MOCK_QUICK_PAIR_PROCESS_MANAGER_H_ +#define CHROMEOS_ASH_SERVICES_QUICK_PAIR_MOCK_QUICK_PAIR_PROCESS_MANAGER_H_ #include <memory> -#include "ash/services/quick_pair/public/mojom/fast_pair_data_parser.mojom.h" -#include "ash/services/quick_pair/public/mojom/quick_pair_service.mojom.h" -#include "ash/services/quick_pair/quick_pair_process_manager.h" + +#include "chromeos/ash/services/quick_pair/public/mojom/fast_pair_data_parser.mojom.h" +#include "chromeos/ash/services/quick_pair/public/mojom/quick_pair_service.mojom.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process_manager.h" #include "testing/gmock/include/gmock/gmock.h" namespace ash { @@ -44,4 +45,4 @@ } // namespace quick_pair } // namespace ash -#endif // ASH_SERVICES_QUICK_PAIR_MOCK_QUICK_PAIR_PROCESS_MANAGER_H_ +#endif // CHROMEOS_ASH_SERVICES_QUICK_PAIR_MOCK_QUICK_PAIR_PROCESS_MANAGER_H_
diff --git a/ash/services/quick_pair/public/cpp/BUILD.gn b/chromeos/ash/services/quick_pair/public/cpp/BUILD.gn similarity index 100% rename from ash/services/quick_pair/public/cpp/BUILD.gn rename to chromeos/ash/services/quick_pair/public/cpp/BUILD.gn
diff --git a/ash/services/quick_pair/public/cpp/DEPS b/chromeos/ash/services/quick_pair/public/cpp/DEPS similarity index 100% rename from ash/services/quick_pair/public/cpp/DEPS rename to chromeos/ash/services/quick_pair/public/cpp/DEPS
diff --git a/ash/services/quick_pair/public/cpp/account_key_filter.cc b/chromeos/ash/services/quick_pair/public/cpp/account_key_filter.cc similarity index 94% rename from ash/services/quick_pair/public/cpp/account_key_filter.cc rename to chromeos/ash/services/quick_pair/public/cpp/account_key_filter.cc index 5a34d90..109db85e 100644 --- a/ash/services/quick_pair/public/cpp/account_key_filter.cc +++ b/chromeos/ash/services/quick_pair/public/cpp/account_key_filter.cc
@@ -2,13 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "ash/services/quick_pair/public/cpp/account_key_filter.h" +#include "chromeos/ash/services/quick_pair/public/cpp/account_key_filter.h" #include <math.h> #include <cstddef> #include <iterator> -#include "ash/services/quick_pair/public/cpp/not_discoverable_advertisement.h" +#include "chromeos/ash/services/quick_pair/public/cpp/not_discoverable_advertisement.h" #include "crypto/sha2.h" namespace ash {
diff --git a/ash/services/quick_pair/public/cpp/account_key_filter.h b/chromeos/ash/services/quick_pair/public/cpp/account_key_filter.h similarity index 83% rename from ash/services/quick_pair/public/cpp/account_key_filter.h rename to chromeos/ash/services/quick_pair/public/cpp/account_key_filter.h index 874bddc..036ba06 100644 --- a/ash/services/quick_pair/public/cpp/account_key_filter.h +++ b/chromeos/ash/services/quick_pair/public/cpp/account_key_filter.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 ASH_SERVICES_QUICK_PAIR_PUBLIC_CPP_ACCOUNT_KEY_FILTER_H_ -#define ASH_SERVICES_QUICK_PAIR_PUBLIC_CPP_ACCOUNT_KEY_FILTER_H_ +#ifndef CHROMEOS_ASH_SERVICES_QUICK_PAIR_PUBLIC_CPP_ACCOUNT_KEY_FILTER_H_ +#define CHROMEOS_ASH_SERVICES_QUICK_PAIR_PUBLIC_CPP_ACCOUNT_KEY_FILTER_H_ #include <vector> @@ -37,4 +37,4 @@ } // namespace quick_pair } // namespace ash -#endif // ASH_SERVICES_QUICK_PAIR_PUBLIC_CPP_ACCOUNT_KEY_FILTER_H_ +#endif // CHROMEOS_ASH_SERVICES_QUICK_PAIR_PUBLIC_CPP_ACCOUNT_KEY_FILTER_H_
diff --git a/ash/services/quick_pair/public/cpp/account_key_filter_unittest.cc b/chromeos/ash/services/quick_pair/public/cpp/account_key_filter_unittest.cc similarity index 97% rename from ash/services/quick_pair/public/cpp/account_key_filter_unittest.cc rename to chromeos/ash/services/quick_pair/public/cpp/account_key_filter_unittest.cc index ee165cb..ca01f5c 100644 --- a/ash/services/quick_pair/public/cpp/account_key_filter_unittest.cc +++ b/chromeos/ash/services/quick_pair/public/cpp/account_key_filter_unittest.cc
@@ -2,7 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "ash/services/quick_pair/public/cpp/account_key_filter.h" +#include "chromeos/ash/services/quick_pair/public/cpp/account_key_filter.h" + #include <cstdint> #include <iterator>
diff --git a/ash/services/quick_pair/public/cpp/battery_notification.cc b/chromeos/ash/services/quick_pair/public/cpp/battery_notification.cc similarity index 97% rename from ash/services/quick_pair/public/cpp/battery_notification.cc rename to chromeos/ash/services/quick_pair/public/cpp/battery_notification.cc index 42b7b22..2e6c00bd 100644 --- a/ash/services/quick_pair/public/cpp/battery_notification.cc +++ b/chromeos/ash/services/quick_pair/public/cpp/battery_notification.cc
@@ -2,11 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "chromeos/ash/services/quick_pair/public/cpp/battery_notification.h" + #include <cstdint> #include <vector> -#include "ash/services/quick_pair/public/cpp/battery_notification.h" - #include "base/logging.h" #include "third_party/abseil-cpp/absl/types/optional.h"
diff --git a/ash/services/quick_pair/public/cpp/battery_notification.h b/chromeos/ash/services/quick_pair/public/cpp/battery_notification.h similarity index 87% rename from ash/services/quick_pair/public/cpp/battery_notification.h rename to chromeos/ash/services/quick_pair/public/cpp/battery_notification.h index 9833f20f..d8224b8 100644 --- a/ash/services/quick_pair/public/cpp/battery_notification.h +++ b/chromeos/ash/services/quick_pair/public/cpp/battery_notification.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 ASH_SERVICES_QUICK_PAIR_PUBLIC_CPP_BATTERY_NOTIFICATION_H_ -#define ASH_SERVICES_QUICK_PAIR_PUBLIC_CPP_BATTERY_NOTIFICATION_H_ +#ifndef CHROMEOS_ASH_SERVICES_QUICK_PAIR_PUBLIC_CPP_BATTERY_NOTIFICATION_H_ +#define CHROMEOS_ASH_SERVICES_QUICK_PAIR_PUBLIC_CPP_BATTERY_NOTIFICATION_H_ #include <cstdint> @@ -60,4 +60,4 @@ } // namespace quick_pair } // namespace ash -#endif // ASH_SERVICES_QUICK_PAIR_PUBLIC_CPP_BATTERY_NOTIFICATION_H_ +#endif // CHROMEOS_ASH_SERVICES_QUICK_PAIR_PUBLIC_CPP_BATTERY_NOTIFICATION_H_
diff --git a/ash/services/quick_pair/public/cpp/decrypted_passkey.cc b/chromeos/ash/services/quick_pair/public/cpp/decrypted_passkey.cc similarity index 91% rename from ash/services/quick_pair/public/cpp/decrypted_passkey.cc rename to chromeos/ash/services/quick_pair/public/cpp/decrypted_passkey.cc index 002e7e6..981bfbe3 100644 --- a/ash/services/quick_pair/public/cpp/decrypted_passkey.cc +++ b/chromeos/ash/services/quick_pair/public/cpp/decrypted_passkey.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 "ash/services/quick_pair/public/cpp/decrypted_passkey.h" +#include "chromeos/ash/services/quick_pair/public/cpp/decrypted_passkey.h" namespace ash { namespace quick_pair {
diff --git a/ash/services/quick_pair/public/cpp/decrypted_passkey.h b/chromeos/ash/services/quick_pair/public/cpp/decrypted_passkey.h similarity index 77% rename from ash/services/quick_pair/public/cpp/decrypted_passkey.h rename to chromeos/ash/services/quick_pair/public/cpp/decrypted_passkey.h index dfcfd85..a9952dd 100644 --- a/ash/services/quick_pair/public/cpp/decrypted_passkey.h +++ b/chromeos/ash/services/quick_pair/public/cpp/decrypted_passkey.h
@@ -2,15 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef ASH_SERVICES_QUICK_PAIR_PUBLIC_CPP_DECRYPTED_PASSKEY_H_ -#define ASH_SERVICES_QUICK_PAIR_PUBLIC_CPP_DECRYPTED_PASSKEY_H_ +#ifndef CHROMEOS_ASH_SERVICES_QUICK_PAIR_PUBLIC_CPP_DECRYPTED_PASSKEY_H_ +#define CHROMEOS_ASH_SERVICES_QUICK_PAIR_PUBLIC_CPP_DECRYPTED_PASSKEY_H_ #include <stddef.h> #include <stdint.h> #include <array> -#include "ash/services/quick_pair/public/cpp/fast_pair_message_type.h" +#include "chromeos/ash/services/quick_pair/public/cpp/fast_pair_message_type.h" inline constexpr int kDecryptedPasskeySaltByteSize = 12; @@ -38,4 +38,4 @@ } // namespace quick_pair } // namespace ash -#endif // ASH_SERVICES_QUICK_PAIR_PUBLIC_CPP_DECRYPTED_PASSKEY_H_ +#endif // CHROMEOS_ASH_SERVICES_QUICK_PAIR_PUBLIC_CPP_DECRYPTED_PASSKEY_H_
diff --git a/ash/services/quick_pair/public/cpp/decrypted_response.cc b/chromeos/ash/services/quick_pair/public/cpp/decrypted_response.cc similarity index 92% rename from ash/services/quick_pair/public/cpp/decrypted_response.cc rename to chromeos/ash/services/quick_pair/public/cpp/decrypted_response.cc index 6380ce2..a5c42af 100644 --- a/ash/services/quick_pair/public/cpp/decrypted_response.cc +++ b/chromeos/ash/services/quick_pair/public/cpp/decrypted_response.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 "ash/services/quick_pair/public/cpp/decrypted_response.h" +#include "chromeos/ash/services/quick_pair/public/cpp/decrypted_response.h" namespace ash { namespace quick_pair {
diff --git a/ash/services/quick_pair/public/cpp/decrypted_response.h b/chromeos/ash/services/quick_pair/public/cpp/decrypted_response.h similarity index 79% rename from ash/services/quick_pair/public/cpp/decrypted_response.h rename to chromeos/ash/services/quick_pair/public/cpp/decrypted_response.h index 7e55ef38..1f8c885 100644 --- a/ash/services/quick_pair/public/cpp/decrypted_response.h +++ b/chromeos/ash/services/quick_pair/public/cpp/decrypted_response.h
@@ -2,15 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef ASH_SERVICES_QUICK_PAIR_PUBLIC_CPP_DECRYPTED_RESPONSE_H_ -#define ASH_SERVICES_QUICK_PAIR_PUBLIC_CPP_DECRYPTED_RESPONSE_H_ +#ifndef CHROMEOS_ASH_SERVICES_QUICK_PAIR_PUBLIC_CPP_DECRYPTED_RESPONSE_H_ +#define CHROMEOS_ASH_SERVICES_QUICK_PAIR_PUBLIC_CPP_DECRYPTED_RESPONSE_H_ #include <stddef.h> #include <stdint.h> #include <array> -#include "ash/services/quick_pair/public/cpp/fast_pair_message_type.h" +#include "chromeos/ash/services/quick_pair/public/cpp/fast_pair_message_type.h" inline constexpr int kDecryptedResponseAddressByteSize = 6; inline constexpr int kDecryptedResponseSaltByteSize = 9; @@ -40,4 +40,4 @@ } // namespace quick_pair } // namespace ash -#endif // ASH_SERVICES_QUICK_PAIR_PUBLIC_CPP_DECRYPTED_RESPONSE_H_ +#endif // CHROMEOS_ASH_SERVICES_QUICK_PAIR_PUBLIC_CPP_DECRYPTED_RESPONSE_H_
diff --git a/ash/services/quick_pair/public/cpp/fast_pair_message_type.h b/chromeos/ash/services/quick_pair/public/cpp/fast_pair_message_type.h similarity index 68% rename from ash/services/quick_pair/public/cpp/fast_pair_message_type.h rename to chromeos/ash/services/quick_pair/public/cpp/fast_pair_message_type.h index 78b8029..db3f4af 100644 --- a/ash/services/quick_pair/public/cpp/fast_pair_message_type.h +++ b/chromeos/ash/services/quick_pair/public/cpp/fast_pair_message_type.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 ASH_SERVICES_QUICK_PAIR_PUBLIC_CPP_FAST_PAIR_MESSAGE_TYPE_H_ -#define ASH_SERVICES_QUICK_PAIR_PUBLIC_CPP_FAST_PAIR_MESSAGE_TYPE_H_ +#ifndef CHROMEOS_ASH_SERVICES_QUICK_PAIR_PUBLIC_CPP_FAST_PAIR_MESSAGE_TYPE_H_ +#define CHROMEOS_ASH_SERVICES_QUICK_PAIR_PUBLIC_CPP_FAST_PAIR_MESSAGE_TYPE_H_ namespace ash { namespace quick_pair { @@ -23,4 +23,4 @@ } // namespace quick_pair } // namespace ash -#endif // ASH_SERVICES_QUICK_PAIR_PUBLIC_CPP_FAST_PAIR_MESSAGE_TYPE_H_ +#endif // CHROMEOS_ASH_SERVICES_QUICK_PAIR_PUBLIC_CPP_FAST_PAIR_MESSAGE_TYPE_H_
diff --git a/ash/services/quick_pair/public/cpp/not_discoverable_advertisement.cc b/chromeos/ash/services/quick_pair/public/cpp/not_discoverable_advertisement.cc similarity index 93% rename from ash/services/quick_pair/public/cpp/not_discoverable_advertisement.cc rename to chromeos/ash/services/quick_pair/public/cpp/not_discoverable_advertisement.cc index 1ff83611..f4004707 100644 --- a/ash/services/quick_pair/public/cpp/not_discoverable_advertisement.cc +++ b/chromeos/ash/services/quick_pair/public/cpp/not_discoverable_advertisement.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 "ash/services/quick_pair/public/cpp/not_discoverable_advertisement.h" +#include "chromeos/ash/services/quick_pair/public/cpp/not_discoverable_advertisement.h" namespace ash { namespace quick_pair {
diff --git a/ash/services/quick_pair/public/cpp/not_discoverable_advertisement.h b/chromeos/ash/services/quick_pair/public/cpp/not_discoverable_advertisement.h similarity index 78% rename from ash/services/quick_pair/public/cpp/not_discoverable_advertisement.h rename to chromeos/ash/services/quick_pair/public/cpp/not_discoverable_advertisement.h index 62c7a95..f9586df 100644 --- a/ash/services/quick_pair/public/cpp/not_discoverable_advertisement.h +++ b/chromeos/ash/services/quick_pair/public/cpp/not_discoverable_advertisement.h
@@ -2,13 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef ASH_SERVICES_QUICK_PAIR_PUBLIC_CPP_NOT_DISCOVERABLE_ADVERTISEMENT_H_ -#define ASH_SERVICES_QUICK_PAIR_PUBLIC_CPP_NOT_DISCOVERABLE_ADVERTISEMENT_H_ +#ifndef CHROMEOS_ASH_SERVICES_QUICK_PAIR_PUBLIC_CPP_NOT_DISCOVERABLE_ADVERTISEMENT_H_ +#define CHROMEOS_ASH_SERVICES_QUICK_PAIR_PUBLIC_CPP_NOT_DISCOVERABLE_ADVERTISEMENT_H_ #include <cstdint> #include <vector> -#include "ash/services/quick_pair/public/cpp/battery_notification.h" +#include "chromeos/ash/services/quick_pair/public/cpp/battery_notification.h" #include "third_party/abseil-cpp/absl/types/optional.h" namespace ash { @@ -38,4 +38,4 @@ } // namespace quick_pair } // namespace ash -#endif // ASH_SERVICES_QUICK_PAIR_PUBLIC_CPP_NOT_DISCOVERABLE_ADVERTISEMENT_H_ +#endif // CHROMEOS_ASH_SERVICES_QUICK_PAIR_PUBLIC_CPP_NOT_DISCOVERABLE_ADVERTISEMENT_H_
diff --git a/ash/services/quick_pair/public/mojom/BUILD.gn b/chromeos/ash/services/quick_pair/public/mojom/BUILD.gn similarity index 78% rename from ash/services/quick_pair/public/mojom/BUILD.gn rename to chromeos/ash/services/quick_pair/public/mojom/BUILD.gn index 386dbd1..ed7343c 100644 --- a/ash/services/quick_pair/public/mojom/BUILD.gn +++ b/chromeos/ash/services/quick_pair/public/mojom/BUILD.gn
@@ -36,11 +36,13 @@ cpp = "::ash::quick_pair::NotDiscoverableAdvertisement" }, ] - traits_headers = - [ "//ash/services/quick_pair/public/mojom/fast_pair_traits.h" ] - traits_sources = - [ "//ash/services/quick_pair/public/mojom/fast_pair_traits.cc" ] - traits_public_deps = [ "//ash/services/quick_pair/public/cpp" ] + traits_headers = [ + "//chromeos/ash/services/quick_pair/public/mojom/fast_pair_traits.h", + ] + traits_sources = [ + "//chromeos/ash/services/quick_pair/public/mojom/fast_pair_traits.cc", + ] + traits_public_deps = [ "//chromeos/ash/services/quick_pair/public/cpp" ] }, ] }
diff --git a/ash/services/quick_pair/public/mojom/OWNERS b/chromeos/ash/services/quick_pair/public/mojom/OWNERS similarity index 100% rename from ash/services/quick_pair/public/mojom/OWNERS rename to chromeos/ash/services/quick_pair/public/mojom/OWNERS
diff --git a/ash/services/quick_pair/public/mojom/fast_pair_data_parser.mojom b/chromeos/ash/services/quick_pair/public/mojom/fast_pair_data_parser.mojom similarity index 100% rename from ash/services/quick_pair/public/mojom/fast_pair_data_parser.mojom rename to chromeos/ash/services/quick_pair/public/mojom/fast_pair_data_parser.mojom
diff --git a/ash/services/quick_pair/public/mojom/fast_pair_traits.cc b/chromeos/ash/services/quick_pair/public/mojom/fast_pair_traits.cc similarity index 97% rename from ash/services/quick_pair/public/mojom/fast_pair_traits.cc rename to chromeos/ash/services/quick_pair/public/mojom/fast_pair_traits.cc index ee9cc61..7c2106a 100644 --- a/ash/services/quick_pair/public/mojom/fast_pair_traits.cc +++ b/chromeos/ash/services/quick_pair/public/mojom/fast_pair_traits.cc
@@ -2,11 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "ash/services/quick_pair/public/mojom/fast_pair_traits.h" +#include "chromeos/ash/services/quick_pair/public/mojom/fast_pair_traits.h" #include <algorithm> #include <cstdint> #include <vector> + #include "mojo/public/cpp/bindings/struct_traits.h" #include "third_party/abseil-cpp/absl/types/optional.h"
diff --git a/ash/services/quick_pair/public/mojom/fast_pair_traits.h b/chromeos/ash/services/quick_pair/public/mojom/fast_pair_traits.h similarity index 84% rename from ash/services/quick_pair/public/mojom/fast_pair_traits.h rename to chromeos/ash/services/quick_pair/public/mojom/fast_pair_traits.h index 32fe11b..24826a5e 100644 --- a/ash/services/quick_pair/public/mojom/fast_pair_traits.h +++ b/chromeos/ash/services/quick_pair/public/mojom/fast_pair_traits.h
@@ -2,19 +2,19 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef ASH_SERVICES_QUICK_PAIR_PUBLIC_MOJOM_FAST_PAIR_TRAITS_H_ -#define ASH_SERVICES_QUICK_PAIR_PUBLIC_MOJOM_FAST_PAIR_TRAITS_H_ +#ifndef CHROMEOS_ASH_SERVICES_QUICK_PAIR_PUBLIC_MOJOM_FAST_PAIR_TRAITS_H_ +#define CHROMEOS_ASH_SERVICES_QUICK_PAIR_PUBLIC_MOJOM_FAST_PAIR_TRAITS_H_ #include <algorithm> #include <cstdint> #include <vector> -#include "ash/services/quick_pair/public/cpp/battery_notification.h" -#include "ash/services/quick_pair/public/cpp/decrypted_passkey.h" -#include "ash/services/quick_pair/public/cpp/decrypted_response.h" -#include "ash/services/quick_pair/public/cpp/fast_pair_message_type.h" -#include "ash/services/quick_pair/public/cpp/not_discoverable_advertisement.h" -#include "ash/services/quick_pair/public/mojom/fast_pair_data_parser.mojom-shared.h" +#include "chromeos/ash/services/quick_pair/public/cpp/battery_notification.h" +#include "chromeos/ash/services/quick_pair/public/cpp/decrypted_passkey.h" +#include "chromeos/ash/services/quick_pair/public/cpp/decrypted_response.h" +#include "chromeos/ash/services/quick_pair/public/cpp/fast_pair_message_type.h" +#include "chromeos/ash/services/quick_pair/public/cpp/not_discoverable_advertisement.h" +#include "chromeos/ash/services/quick_pair/public/mojom/fast_pair_data_parser.mojom-shared.h" #include "mojo/public/cpp/bindings/enum_traits.h" #include "mojo/public/cpp/bindings/struct_traits.h" #include "third_party/abseil-cpp/absl/types/optional.h" @@ -139,4 +139,4 @@ } // namespace mojo -#endif // ASH_SERVICES_QUICK_PAIR_PUBLIC_MOJOM_FAST_PAIR_TRAITS_H_ +#endif // CHROMEOS_ASH_SERVICES_QUICK_PAIR_PUBLIC_MOJOM_FAST_PAIR_TRAITS_H_
diff --git a/ash/services/quick_pair/public/mojom/quick_pair_service.mojom b/chromeos/ash/services/quick_pair/public/mojom/quick_pair_service.mojom similarity index 86% rename from ash/services/quick_pair/public/mojom/quick_pair_service.mojom rename to chromeos/ash/services/quick_pair/public/mojom/quick_pair_service.mojom index 7d7e264..10099383 100644 --- a/ash/services/quick_pair/public/mojom/quick_pair_service.mojom +++ b/chromeos/ash/services/quick_pair/public/mojom/quick_pair_service.mojom
@@ -4,7 +4,7 @@ module ash.quick_pair.mojom; -import "ash/services/quick_pair/public/mojom/fast_pair_data_parser.mojom"; +import "chromeos/ash/services/quick_pair/public/mojom/fast_pair_data_parser.mojom"; import "sandbox/policy/mojom/sandbox.mojom"; // Interface for Quick Pair related services. Lives in a sandboxed utility
diff --git a/ash/services/quick_pair/quick_pair_process.cc b/chromeos/ash/services/quick_pair/quick_pair_process.cc similarity index 92% rename from ash/services/quick_pair/quick_pair_process.cc rename to chromeos/ash/services/quick_pair/quick_pair_process.cc index 6713ce8..9052bbec 100644 --- a/ash/services/quick_pair/quick_pair_process.cc +++ b/chromeos/ash/services/quick_pair/quick_pair_process.cc
@@ -2,17 +2,17 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "ash/services/quick_pair/quick_pair_process_manager.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process_manager.h" #include "ash/quick_pair/common/logging.h" -#include "ash/services/quick_pair/public/cpp/decrypted_passkey.h" -#include "ash/services/quick_pair/public/cpp/decrypted_response.h" -#include "ash/services/quick_pair/public/cpp/not_discoverable_advertisement.h" -#include "ash/services/quick_pair/public/mojom/fast_pair_data_parser.mojom.h" -#include "ash/services/quick_pair/quick_pair_process.h" #include "base/bind.h" #include "base/callback.h" #include "base/callback_helpers.h" +#include "chromeos/ash/services/quick_pair/public/cpp/decrypted_passkey.h" +#include "chromeos/ash/services/quick_pair/public/cpp/decrypted_response.h" +#include "chromeos/ash/services/quick_pair/public/cpp/not_discoverable_advertisement.h" +#include "chromeos/ash/services/quick_pair/public/mojom/fast_pair_data_parser.mojom.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process.h" namespace ash { namespace quick_pair {
diff --git a/ash/services/quick_pair/quick_pair_process.h b/chromeos/ash/services/quick_pair/quick_pair_process.h similarity index 89% rename from ash/services/quick_pair/quick_pair_process.h rename to chromeos/ash/services/quick_pair/quick_pair_process.h index 0798096..15b525a4 100644 --- a/ash/services/quick_pair/quick_pair_process.h +++ b/chromeos/ash/services/quick_pair/quick_pair_process.h
@@ -2,14 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef ASH_SERVICES_QUICK_PAIR_QUICK_PAIR_PROCESS_H_ -#define ASH_SERVICES_QUICK_PAIR_QUICK_PAIR_PROCESS_H_ +#ifndef CHROMEOS_ASH_SERVICES_QUICK_PAIR_QUICK_PAIR_PROCESS_H_ +#define CHROMEOS_ASH_SERVICES_QUICK_PAIR_QUICK_PAIR_PROCESS_H_ #include <cstdint> #include <memory> -#include "ash/services/quick_pair/quick_pair_process_manager.h" #include "base/callback_forward.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process_manager.h" #include "third_party/abseil-cpp/absl/types/optional.h" namespace ash { @@ -73,4 +73,4 @@ } // namespace quick_pair } // namespace ash -#endif // ASH_SERVICES_QUICK_PAIR_QUICK_PAIR_PROCESS_H_ +#endif // CHROMEOS_ASH_SERVICES_QUICK_PAIR_QUICK_PAIR_PROCESS_H_
diff --git a/ash/services/quick_pair/quick_pair_process_manager.cc b/chromeos/ash/services/quick_pair/quick_pair_process_manager.cc similarity index 90% rename from ash/services/quick_pair/quick_pair_process_manager.cc rename to chromeos/ash/services/quick_pair/quick_pair_process_manager.cc index 42bb1a7c..a72da3a 100644 --- a/ash/services/quick_pair/quick_pair_process_manager.cc +++ b/chromeos/ash/services/quick_pair/quick_pair_process_manager.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 "ash/services/quick_pair/quick_pair_process_manager.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process_manager.h" #include <ostream>
diff --git a/ash/services/quick_pair/quick_pair_process_manager.h b/chromeos/ash/services/quick_pair/quick_pair_process_manager.h similarity index 80% rename from ash/services/quick_pair/quick_pair_process_manager.h rename to chromeos/ash/services/quick_pair/quick_pair_process_manager.h index 437bbf8d..b03e6e5 100644 --- a/ash/services/quick_pair/quick_pair_process_manager.h +++ b/chromeos/ash/services/quick_pair/quick_pair_process_manager.h
@@ -2,16 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef ASH_SERVICES_QUICK_PAIR_QUICK_PAIR_PROCESS_MANAGER_H_ -#define ASH_SERVICES_QUICK_PAIR_QUICK_PAIR_PROCESS_MANAGER_H_ +#ifndef CHROMEOS_ASH_SERVICES_QUICK_PAIR_QUICK_PAIR_PROCESS_MANAGER_H_ +#define CHROMEOS_ASH_SERVICES_QUICK_PAIR_QUICK_PAIR_PROCESS_MANAGER_H_ #include <memory> #include <ostream> -#include "ash/services/quick_pair/public/mojom/fast_pair_data_parser.mojom-forward.h" -#include "ash/services/quick_pair/public/mojom/fast_pair_data_parser.mojom.h" -#include "ash/services/quick_pair/public/mojom/quick_pair_service.mojom-forward.h" #include "base/callback_forward.h" +#include "chromeos/ash/services/quick_pair/public/mojom/fast_pair_data_parser.mojom-forward.h" +#include "chromeos/ash/services/quick_pair/public/mojom/fast_pair_data_parser.mojom.h" +#include "chromeos/ash/services/quick_pair/public/mojom/quick_pair_service.mojom-forward.h" #include "mojo/public/cpp/bindings/shared_remote.h" namespace ash { @@ -64,4 +64,4 @@ } // namespace quick_pair } // namespace ash -#endif // ASH_SERVICES_QUICK_PAIR_QUICK_PAIR_PROCESS_MANAGER_H_ +#endif // CHROMEOS_ASH_SERVICES_QUICK_PAIR_QUICK_PAIR_PROCESS_MANAGER_H_
diff --git a/ash/services/quick_pair/quick_pair_process_manager_impl.cc b/chromeos/ash/services/quick_pair/quick_pair_process_manager_impl.cc similarity index 95% rename from ash/services/quick_pair/quick_pair_process_manager_impl.cc rename to chromeos/ash/services/quick_pair/quick_pair_process_manager_impl.cc index 0cbf0fb..52162fa 100644 --- a/ash/services/quick_pair/quick_pair_process_manager_impl.cc +++ b/chromeos/ash/services/quick_pair/quick_pair_process_manager_impl.cc
@@ -2,16 +2,17 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "ash/services/quick_pair/quick_pair_process_manager_impl.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process_manager_impl.h" + #include <memory> #include "ash/quick_pair/common/logging.h" #include "ash/quick_pair/common/quick_pair_browser_delegate.h" -#include "ash/services/quick_pair/public/mojom/fast_pair_data_parser.mojom.h" -#include "ash/services/quick_pair/quick_pair_process_shutdown_controller.h" #include "base/bind.h" #include "base/threading/sequenced_task_runner_handle.h" #include "base/unguessable_token.h" +#include "chromeos/ash/services/quick_pair/public/mojom/fast_pair_data_parser.mojom.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process_shutdown_controller.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/pending_remote.h"
diff --git a/ash/services/quick_pair/quick_pair_process_manager_impl.h b/chromeos/ash/services/quick_pair/quick_pair_process_manager_impl.h similarity index 82% rename from ash/services/quick_pair/quick_pair_process_manager_impl.h rename to chromeos/ash/services/quick_pair/quick_pair_process_manager_impl.h index 805364e..5de3be3e 100644 --- a/ash/services/quick_pair/quick_pair_process_manager_impl.h +++ b/chromeos/ash/services/quick_pair/quick_pair_process_manager_impl.h
@@ -2,18 +2,18 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef ASH_SERVICES_QUICK_PAIR_QUICK_PAIR_PROCESS_MANAGER_IMPL_H_ -#define ASH_SERVICES_QUICK_PAIR_QUICK_PAIR_PROCESS_MANAGER_IMPL_H_ +#ifndef CHROMEOS_ASH_SERVICES_QUICK_PAIR_QUICK_PAIR_PROCESS_MANAGER_IMPL_H_ +#define CHROMEOS_ASH_SERVICES_QUICK_PAIR_QUICK_PAIR_PROCESS_MANAGER_IMPL_H_ #include <memory> -#include "ash/services/quick_pair/public/mojom/fast_pair_data_parser.mojom.h" -#include "ash/services/quick_pair/public/mojom/quick_pair_service.mojom.h" -#include "ash/services/quick_pair/quick_pair_process_manager.h" #include "base/callback_forward.h" #include "base/containers/flat_map.h" #include "base/memory/weak_ptr.h" #include "base/unguessable_token.h" +#include "chromeos/ash/services/quick_pair/public/mojom/fast_pair_data_parser.mojom.h" +#include "chromeos/ash/services/quick_pair/public/mojom/quick_pair_service.mojom.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process_manager.h" #include "mojo/public/cpp/bindings/remote.h" #include "mojo/public/cpp/bindings/shared_remote.h" @@ -74,4 +74,4 @@ } // namespace quick_pair } // namespace ash -#endif // ASH_SERVICES_QUICK_PAIR_QUICK_PAIR_PROCESS_MANAGER_IMPL_H_ +#endif // CHROMEOS_ASH_SERVICES_QUICK_PAIR_QUICK_PAIR_PROCESS_MANAGER_IMPL_H_
diff --git a/ash/services/quick_pair/quick_pair_process_manager_impl_unittest.cc b/chromeos/ash/services/quick_pair/quick_pair_process_manager_impl_unittest.cc similarity index 92% rename from ash/services/quick_pair/quick_pair_process_manager_impl_unittest.cc rename to chromeos/ash/services/quick_pair/quick_pair_process_manager_impl_unittest.cc index 079f6ce..d35f69a 100644 --- a/ash/services/quick_pair/quick_pair_process_manager_impl_unittest.cc +++ b/chromeos/ash/services/quick_pair/quick_pair_process_manager_impl_unittest.cc
@@ -2,16 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "ash/services/quick_pair/quick_pair_process_manager_impl.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process_manager_impl.h" #include <memory> #include "ash/quick_pair/common/mock_quick_pair_browser_delegate.h" -#include "ash/services/quick_pair/quick_pair_process_manager.h" -#include "ash/services/quick_pair/quick_pair_process_shutdown_controller.h" #include "base/callback.h" #include "base/callback_helpers.h" #include "base/test/mock_callback.h" #include "base/test/task_environment.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process_manager.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process_shutdown_controller.h" #include "testing/gtest/include/gtest/gtest.h" namespace ash {
diff --git a/ash/services/quick_pair/quick_pair_process_shutdown_controller.cc b/chromeos/ash/services/quick_pair/quick_pair_process_shutdown_controller.cc similarity index 89% rename from ash/services/quick_pair/quick_pair_process_shutdown_controller.cc rename to chromeos/ash/services/quick_pair/quick_pair_process_shutdown_controller.cc index e59ec06..c8261ea 100644 --- a/ash/services/quick_pair/quick_pair_process_shutdown_controller.cc +++ b/chromeos/ash/services/quick_pair/quick_pair_process_shutdown_controller.cc
@@ -2,7 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "ash/services/quick_pair/quick_pair_process_shutdown_controller.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process_shutdown_controller.h" + #include "base/callback_forward.h" #include "base/memory/ptr_util.h"
diff --git a/ash/services/quick_pair/quick_pair_process_shutdown_controller.h b/chromeos/ash/services/quick_pair/quick_pair_process_shutdown_controller.h similarity index 81% rename from ash/services/quick_pair/quick_pair_process_shutdown_controller.h rename to chromeos/ash/services/quick_pair/quick_pair_process_shutdown_controller.h index 293e800..c275795b 100644 --- a/ash/services/quick_pair/quick_pair_process_shutdown_controller.h +++ b/chromeos/ash/services/quick_pair/quick_pair_process_shutdown_controller.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 ASH_SERVICES_QUICK_PAIR_QUICK_PAIR_PROCESS_SHUTDOWN_CONTROLLER_H_ -#define ASH_SERVICES_QUICK_PAIR_QUICK_PAIR_PROCESS_SHUTDOWN_CONTROLLER_H_ +#ifndef CHROMEOS_ASH_SERVICES_QUICK_PAIR_QUICK_PAIR_PROCESS_SHUTDOWN_CONTROLLER_H_ +#define CHROMEOS_ASH_SERVICES_QUICK_PAIR_QUICK_PAIR_PROCESS_SHUTDOWN_CONTROLLER_H_ #include "base/callback.h" #include "base/timer/timer.h" @@ -38,4 +38,4 @@ } // namespace quick_pair } // namespace ash -#endif // ASH_SERVICES_QUICK_PAIR_QUICK_PAIR_PROCESS_SHUTDOWN_CONTROLLER_H_ +#endif // CHROMEOS_ASH_SERVICES_QUICK_PAIR_QUICK_PAIR_PROCESS_SHUTDOWN_CONTROLLER_H_
diff --git a/ash/services/quick_pair/quick_pair_process_shutdown_controller_unittest.cc b/chromeos/ash/services/quick_pair/quick_pair_process_shutdown_controller_unittest.cc similarity index 94% rename from ash/services/quick_pair/quick_pair_process_shutdown_controller_unittest.cc rename to chromeos/ash/services/quick_pair/quick_pair_process_shutdown_controller_unittest.cc index 43703ab..9fb7985e 100644 --- a/ash/services/quick_pair/quick_pair_process_shutdown_controller_unittest.cc +++ b/chromeos/ash/services/quick_pair/quick_pair_process_shutdown_controller_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 "ash/services/quick_pair/quick_pair_process_shutdown_controller.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process_shutdown_controller.h" #include "base/memory/weak_ptr.h" #include "base/run_loop.h"
diff --git a/ash/services/quick_pair/quick_pair_process_unittest.cc b/chromeos/ash/services/quick_pair/quick_pair_process_unittest.cc similarity index 92% rename from ash/services/quick_pair/quick_pair_process_unittest.cc rename to chromeos/ash/services/quick_pair/quick_pair_process_unittest.cc index 6b62e7b..13d6e54 100644 --- a/ash/services/quick_pair/quick_pair_process_unittest.cc +++ b/chromeos/ash/services/quick_pair/quick_pair_process_unittest.cc
@@ -2,22 +2,22 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "ash/services/quick_pair/quick_pair_process.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process.h" #include <cstdint> #include <vector> #include "ash/quick_pair/fast_pair_handshake/fast_pair_encryption.h" -#include "ash/services/quick_pair/fast_pair_data_parser.h" -#include "ash/services/quick_pair/public/cpp/decrypted_passkey.h" -#include "ash/services/quick_pair/public/cpp/decrypted_response.h" -#include "ash/services/quick_pair/public/cpp/not_discoverable_advertisement.h" -#include "ash/services/quick_pair/quick_pair_process_manager.h" -#include "ash/services/quick_pair/quick_pair_process_manager_impl.h" #include "base/callback_helpers.h" #include "base/run_loop.h" #include "base/test/bind.h" #include "base/test/task_environment.h" +#include "chromeos/ash/services/quick_pair/fast_pair_data_parser.h" +#include "chromeos/ash/services/quick_pair/public/cpp/decrypted_passkey.h" +#include "chromeos/ash/services/quick_pair/public/cpp/decrypted_response.h" +#include "chromeos/ash/services/quick_pair/public/cpp/not_discoverable_advertisement.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process_manager.h" +#include "chromeos/ash/services/quick_pair/quick_pair_process_manager_impl.h" #include "mojo/public/cpp/bindings/shared_remote.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/ash/services/quick_pair/quick_pair_service.cc b/chromeos/ash/services/quick_pair/quick_pair_service.cc similarity index 71% rename from ash/services/quick_pair/quick_pair_service.cc rename to chromeos/ash/services/quick_pair/quick_pair_service.cc index 6bf4dfe..66fe560 100644 --- a/ash/services/quick_pair/quick_pair_service.cc +++ b/chromeos/ash/services/quick_pair/quick_pair_service.cc
@@ -2,13 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "ash/services/quick_pair/quick_pair_service.h" +#include "chromeos/ash/services/quick_pair/quick_pair_service.h" #include <memory> -#include "ash/services/quick_pair/fast_pair_data_parser.h" -#include "ash/services/quick_pair/public/mojom/fast_pair_data_parser.mojom-forward.h" -#include "ash/services/quick_pair/public/mojom/quick_pair_service.mojom.h" +#include "chromeos/ash/services/quick_pair/fast_pair_data_parser.h" +#include "chromeos/ash/services/quick_pair/public/mojom/fast_pair_data_parser.mojom-forward.h" +#include "chromeos/ash/services/quick_pair/public/mojom/quick_pair_service.mojom.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/receiver.h"
diff --git a/ash/services/quick_pair/quick_pair_service.h b/chromeos/ash/services/quick_pair/quick_pair_service.h similarity index 76% rename from ash/services/quick_pair/quick_pair_service.h rename to chromeos/ash/services/quick_pair/quick_pair_service.h index 1a75fe6d..723a73e 100644 --- a/ash/services/quick_pair/quick_pair_service.h +++ b/chromeos/ash/services/quick_pair/quick_pair_service.h
@@ -2,12 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef ASH_SERVICES_QUICK_PAIR_QUICK_PAIR_SERVICE_H_ -#define ASH_SERVICES_QUICK_PAIR_QUICK_PAIR_SERVICE_H_ +#ifndef CHROMEOS_ASH_SERVICES_QUICK_PAIR_QUICK_PAIR_SERVICE_H_ +#define CHROMEOS_ASH_SERVICES_QUICK_PAIR_QUICK_PAIR_SERVICE_H_ #include <memory> -#include "ash/services/quick_pair/public/mojom/fast_pair_data_parser.mojom-forward.h" -#include "ash/services/quick_pair/public/mojom/quick_pair_service.mojom.h" + +#include "chromeos/ash/services/quick_pair/public/mojom/fast_pair_data_parser.mojom-forward.h" +#include "chromeos/ash/services/quick_pair/public/mojom/quick_pair_service.mojom.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/receiver.h" @@ -43,4 +44,4 @@ } // namespace quick_pair } // namespace ash -#endif // ASH_SERVICES_QUICK_PAIR_QUICK_PAIR_SERVICE_H_ +#endif // CHROMEOS_ASH_SERVICES_QUICK_PAIR_QUICK_PAIR_SERVICE_H_
diff --git a/ash/services/quick_pair/quick_pair_service_unittest.cc b/chromeos/ash/services/quick_pair/quick_pair_service_unittest.cc similarity index 92% rename from ash/services/quick_pair/quick_pair_service_unittest.cc rename to chromeos/ash/services/quick_pair/quick_pair_service_unittest.cc index 0e415d5e..2d99f15 100644 --- a/ash/services/quick_pair/quick_pair_service_unittest.cc +++ b/chromeos/ash/services/quick_pair/quick_pair_service_unittest.cc
@@ -2,12 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "ash/services/quick_pair/quick_pair_service.h" +#include "chromeos/ash/services/quick_pair/quick_pair_service.h" -#include "ash/services/quick_pair/public/mojom/fast_pair_data_parser.mojom.h" #include "base/bind.h" #include "base/test/task_environment.h" #include "base/threading/sequenced_task_runner_handle.h" +#include "chromeos/ash/services/quick_pair/public/mojom/fast_pair_data_parser.mojom.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "mojo/public/cpp/bindings/remote.h"
diff --git a/chromeos/crosapi/mojom/test_controller.mojom b/chromeos/crosapi/mojom/test_controller.mojom index a006d1cb..f44ef01 100644 --- a/chromeos/crosapi/mojom/test_controller.mojom +++ b/chromeos/crosapi/mojom/test_controller.mojom
@@ -138,8 +138,8 @@ // This interface is implemented by Ash-Chrome. // This interface provides tests a mechanism to mutate or query ash. // In the future, this interface may merge with an automation or a11y interface. -// Next version: 20 -// Next method id: 31 +// Next version: 21 +// Next method id: 32 [Stable, Uuid="1f93f9d7-e466-466c-a675-c21b48cf30d3"] interface TestController { // Clicks the middle of the views element identified by |element_name|. @@ -310,4 +310,8 @@ // Launches an app from the Launcher grid. [MinVersion=19] LaunchAppFromAppList@30(string app_id); + + // Clear App Service state, including from any previously installed apps. + [MinVersion=20] + ReinitializeAppService@31() => (); };
diff --git a/chromeos/profiles/atom.afdo.newest.txt b/chromeos/profiles/atom.afdo.newest.txt index e04fcaa..714af43 100644 --- a/chromeos/profiles/atom.afdo.newest.txt +++ b/chromeos/profiles/atom.afdo.newest.txt
@@ -1 +1 @@ -chromeos-chrome-amd64-atom-108-5323.0-1664790676-benchmark-108.0.5338.0-r1-redacted.afdo.xz +chromeos-chrome-amd64-atom-108-5323.0-1664790676-benchmark-108.0.5338.0-r2-redacted.afdo.xz
diff --git a/chromeos/profiles/bigcore.afdo.newest.txt b/chromeos/profiles/bigcore.afdo.newest.txt index 914edb7..d104842 100644 --- a/chromeos/profiles/bigcore.afdo.newest.txt +++ b/chromeos/profiles/bigcore.afdo.newest.txt
@@ -1 +1 @@ -chromeos-chrome-amd64-bigcore-108-5304.10-1664791506-benchmark-108.0.5338.0-r1-redacted.afdo.xz +chromeos-chrome-amd64-bigcore-108-5304.10-1664791506-benchmark-108.0.5338.0-r2-redacted.afdo.xz
diff --git a/chromeos/ui/frame/BUILD.gn b/chromeos/ui/frame/BUILD.gn index 30fecd6..fe437d4 100644 --- a/chromeos/ui/frame/BUILD.gn +++ b/chromeos/ui/frame/BUILD.gn
@@ -69,7 +69,6 @@ "//skia", "//ui/aura", "//ui/base", - "//ui/platform_window", "//ui/strings:ui_strings_grit", "//ui/views", "//ui/views/window/vector_icons",
diff --git a/chromeos/ui/frame/DEPS b/chromeos/ui/frame/DEPS index 4534f77..421fa94 100644 --- a/chromeos/ui/frame/DEPS +++ b/chromeos/ui/frame/DEPS
@@ -6,7 +6,6 @@ "+ui/display", "+ui/events", "+ui/gfx", - "+ui/platform_window", "+ui/strings/grit/ui_strings.h", "+ui/views", "+ui/wm/public",
diff --git a/chromeos/ui/frame/immersive/immersive_fullscreen_controller.cc b/chromeos/ui/frame/immersive/immersive_fullscreen_controller.cc index 6093040a..b9a3ce5 100644 --- a/chromeos/ui/frame/immersive/immersive_fullscreen_controller.cc +++ b/chromeos/ui/frame/immersive/immersive_fullscreen_controller.cc
@@ -27,11 +27,6 @@ #include "ui/views/view.h" #include "ui/views/widget/widget.h" -#if BUILDFLAG(IS_CHROMEOS_LACROS) -#include "ui/platform_window/extensions/wayland_extension.h" -#include "ui/views/widget/desktop_aura/desktop_window_tree_host_lacros.h" -#endif - DEFINE_UI_CLASS_PROPERTY_TYPE(chromeos::ImmersiveFullscreenController*) namespace chromeos { @@ -285,14 +280,7 @@ // static void ImmersiveFullscreenController::EnableForWidget(views::Widget* widget, bool enabled) { -#if BUILDFLAG(IS_CHROMEOS_LACROS) - auto* wayland_extension = views::DesktopWindowTreeHostLacros::From( - widget->GetNativeWindow()->GetHost()) - ->GetWaylandExtension(); - wayland_extension->SetImmersiveFullscreenStatus(enabled); -#else widget->GetNativeWindow()->SetProperty(kImmersiveIsActive, enabled); -#endif } // static
diff --git a/components/android_autofill/browser/test_support/autofill_provider_test_helper.cc b/components/android_autofill/browser/test_support/autofill_provider_test_helper.cc index 080ec55..84040ff 100644 --- a/components/android_autofill/browser/test_support/autofill_provider_test_helper.cc +++ b/components/android_autofill/browser/test_support/autofill_provider_test_helper.cc
@@ -2,8 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "base/ranges/algorithm.h" #include "components/android_autofill/browser/test_support/jni_headers/AutofillProviderTestHelper_jni.h" +#include <iterator> #include <string> #include "base/android/jni_array.h" @@ -80,7 +82,7 @@ for (size_t i = 0; i < field_ids.size(); ++i) { for (auto form_field_data : formData.fields) { if (form_field_data.id_attribute == field_ids[i]) { - autofill::test::AddFieldSuggestionToForm( + autofill::test::AddFieldPredictionToForm( form_field_data, static_cast<autofill::ServerFieldType>(field_types[i]), form_suggestion); @@ -135,8 +137,15 @@ for (size_t i = 0; i < field_ids.size(); ++i) { for (auto form_field_data : formData.fields) { if (form_field_data.id_attribute == field_ids[i]) { + std::vector<ServerFieldType> server_field_types( + field_types[i].size()); + base::ranges::transform(field_types[i], + std::back_inserter(server_field_types), + [](int type) -> ServerFieldType { + return ServerFieldType(type); + }); autofill::test::AddFieldPredictionsToForm( - form_field_data, field_types[i], form_suggestion); + form_field_data, server_field_types, form_suggestion); found_fields_count++; break; }
diff --git a/components/autofill/core/browser/autocomplete_history_manager_unittest.cc b/components/autofill/core/browser/autocomplete_history_manager_unittest.cc index c8cea8b..984cc237 100644 --- a/components/autofill/core/browser/autocomplete_history_manager_unittest.cc +++ b/components/autofill/core/browser/autocomplete_history_manager_unittest.cc
@@ -53,7 +53,7 @@ ~MockAutofillClient() override = default; PrefService* GetPrefs() override { - return const_cast<PrefService*>(base::as_const(*this).GetPrefs()); + return const_cast<PrefService*>(std::as_const(*this).GetPrefs()); } const PrefService* GetPrefs() const override { return prefs_.get(); }
diff --git a/components/autofill/core/browser/autofill_manager.cc b/components/autofill/core/browser/autofill_manager.cc index 0ed9963..3d0a5e6 100644 --- a/components/autofill/core/browser/autofill_manager.cc +++ b/components/autofill/core/browser/autofill_manager.cc
@@ -187,42 +187,55 @@ return; } + struct AsyncContext { + AsyncContext( + std::map<FormGlobalId, std::unique_ptr<FormStructure>> form_structures, + LogManager* log_manager) + : form_structures(std::move(form_structures)), + log_manager(IsLoggingActive(log_manager) + ? LogManager::CreateBuffering() + : nullptr) {} + std::map<FormGlobalId, std::unique_ptr<FormStructure>> form_structures; + std::unique_ptr<BufferingLogManager> log_manager; + }; + // To be run on a different task (must not access global or member // variables). - // TODO(crbug.com/1309848): We can't pass a UKM logger and a LogManager - // because they're member variables. To be fixed. - auto RunHeuristics = [](std::map<FormGlobalId, std::unique_ptr<FormStructure>> - form_structures) { + // TODO(crbug.com/1309848): We can't pass a UKM logger because it's a member + // variable. To be fixed. + auto RunHeuristics = [](AsyncContext context) { SCOPED_UMA_HISTOGRAM_TIMER( "Autofill.Timing.OnLanguageDetermined.RunHeuristics"); - for (auto& [id, form_structure] : form_structures) { + for (auto& [id, form_structure] : context.form_structures) { form_structure->DetermineHeuristicTypes( - /*form_interactions_ukm_logger=*/nullptr, - /*log_manager=*/nullptr); + /*form_interactions_ukm_logger=*/nullptr, context.log_manager.get()); } - return form_structures; + return context; }; // To be run on the main thread (accesses member variables). auto UpdateCache = [](base::WeakPtr<AutofillManager> self, - std::map<FormGlobalId, std::unique_ptr<FormStructure>> - form_structures) { + AsyncContext context) { SCOPED_UMA_HISTOGRAM_TIMER( "Autofill.Timing.OnLanguageDetermined.UpdateCache"); if (!self) return; - for (auto& [id, form_structure] : form_structures) + for (auto& [id, form_structure] : context.form_structures) self->form_structures_[id] = std::move(form_structure); + if (context.log_manager && self->log_manager_) + context.log_manager->Flush(*self->log_manager_); self->NotifyObservers(&Observer::OnAfterLanguageDetermined); }; - // Transfers the cached `form_structures_` to the worker task, which will - // eventually move them back into `form_structures_`. This means - // AutofillManager knows no forms for a brief period of time. + // Transfers ownership of the cached `form_structures_` to the worker task, + // which will eventually move them back into `form_structures_`. This means + // `AutofillManager::form_structures_` is empty for a brief period of time. + auto form_structures = std::exchange(form_structures_, {}); parsing_task_runner_->PostTaskAndReplyWithResult( - FROM_HERE, base::BindOnce(RunHeuristics, std::move(form_structures_)), + FROM_HERE, + base::BindOnce(RunHeuristics, + AsyncContext(std::move(form_structures), log_manager_)), base::BindOnce(UpdateCache, parsing_weak_ptr_factory_.GetWeakPtr())); - form_structures_.clear(); } void AutofillManager::OnTranslateDriverDestroyed( @@ -685,43 +698,54 @@ base::ranges::unique(form_structures, {}, &FormStructure::global_id), form_structures.end()); + struct AsyncContext { + AsyncContext(std::vector<std::unique_ptr<FormStructure>> form_structures, + LogManager* log_manager) + : form_structures(std::move(form_structures)), + log_manager(IsLoggingActive(log_manager) + ? LogManager::CreateBuffering() + : nullptr) {} + std::vector<std::unique_ptr<FormStructure>> form_structures; + std::unique_ptr<BufferingLogManager> log_manager; + }; + // To be run on a different task (must not access global or member // variables). - // TODO(crbug.com/1309848): We can't pass a UKM logger and a LogManager - // because they're member variables. To be fixed. - auto RunHeuristics = - [](std::vector<std::unique_ptr<FormStructure>> form_structures) { - SCOPED_UMA_HISTOGRAM_TIMER( - "Autofill.Timing.ParseFormsAsync.RunHeuristics"); - for (auto& form_structure : form_structures) { - form_structure->DetermineHeuristicTypes( - /*form_interactions_ukm_logger=*/nullptr, - /*log_manager=*/nullptr); - } - return form_structures; - }; + // TODO(crbug.com/1309848): We can't pass a UKM logger because it's a member + // variable. To be fixed. + auto RunHeuristics = [](AsyncContext context) { + SCOPED_UMA_HISTOGRAM_TIMER("Autofill.Timing.ParseFormsAsync.RunHeuristics"); + for (auto& form_structure : context.form_structures) { + form_structure->DetermineHeuristicTypes( + /*form_interactions_ukm_logger=*/nullptr, context.log_manager.get()); + } + return context; + }; // To be run on the main thread (accesses member variables). auto UpdateCache = [](base::WeakPtr<AutofillManager> self, base::OnceCallback<void(AutofillManager&, const std::vector<FormData>&)> callback, - const std::vector<FormData>& parsed_forms, - std::vector<std::unique_ptr<FormStructure>> form_structures) { + const std::vector<FormData>& parsed_forms, AsyncContext context) { SCOPED_UMA_HISTOGRAM_TIMER( "Autofill.Timing.ParseFormsAsync.UpdateCache"); if (!self) return; - for (auto& form_structure : form_structures) { + for (auto& form_structure : context.form_structures) { FormGlobalId id = form_structure->global_id(); self->form_structures_[id] = std::move(form_structure); } + if (context.log_manager && self->log_manager_) + context.log_manager->Flush(*self->log_manager_); self->NotifyObservers(&Observer::OnFormParsed); std::move(callback).Run(*self, parsed_forms); }; parsing_task_runner_->PostTaskAndReplyWithResult( - FROM_HERE, base::BindOnce(RunHeuristics, std::move(form_structures)), + FROM_HERE, + base::BindOnce(RunHeuristics, + AsyncContext(std::move(form_structures), log_manager_)), base::BindOnce(UpdateCache, parsing_weak_ptr_factory_.GetWeakPtr(), std::move(callback), parsed_forms)); } @@ -765,16 +789,26 @@ } form_structure->set_current_page_language(GetCurrentPageLanguage()); + struct AsyncContext { + AsyncContext(std::unique_ptr<FormStructure> form_structure, + LogManager* log_manager) + : form_structure(std::move(form_structure)), + log_manager(IsLoggingActive(log_manager) + ? LogManager::CreateBuffering() + : nullptr) {} + std::unique_ptr<FormStructure> form_structure; + std::unique_ptr<BufferingLogManager> log_manager; + }; + // To be run on a different task (must not access global or member // variables). - // TODO(crbug.com/1309848): We can't pass a UKM logger and a LogManager - // because they're member variables. To be fixed. - auto RunHeuristics = [](std::unique_ptr<FormStructure> form_structure) { + // TODO(crbug.com/1309848): We can't pass a UKM logger because it's a member + // variable. To be fixed. + auto RunHeuristics = [](AsyncContext context) { SCOPED_UMA_HISTOGRAM_TIMER("Autofill.Timing.ParseFormAsync.RunHeuristics"); - form_structure->DetermineHeuristicTypes( - /*form_interactions_ukm_logger=*/nullptr, - /*log_manager=*/nullptr); - return form_structure; + context.form_structure->DetermineHeuristicTypes( + /*form_interactions_ukm_logger=*/nullptr, context.log_manager.get()); + return context; }; // To be run on the main thread (accesses member variables). @@ -787,20 +821,23 @@ auto UpdateCache = [](base::WeakPtr<AutofillManager> self, base::OnceCallback<void(AutofillManager&, const FormData&)> callback, - const FormData& form_data, - std::unique_ptr<FormStructure> form_structure) { + const FormData& form_data, AsyncContext context) { SCOPED_UMA_HISTOGRAM_TIMER( "Autofill.Timing.ParseFormAsync.UpdateCache"); if (!self) return; - FormGlobalId id = form_structure->global_id(); - self->form_structures_[id] = std::move(form_structure); + FormGlobalId id = context.form_structure->global_id(); + self->form_structures_[id] = std::move(context.form_structure); + if (context.log_manager && self->log_manager_) + context.log_manager->Flush(*self->log_manager_); self->NotifyObservers(&Observer::OnFormParsed); std::move(callback).Run(*self, form_data); }; parsing_task_runner_->PostTaskAndReplyWithResult( - FROM_HERE, base::BindOnce(RunHeuristics, std::move(form_structure)), + FROM_HERE, + base::BindOnce(RunHeuristics, + AsyncContext(std::move(form_structure), log_manager_)), base::BindOnce(UpdateCache, parsing_weak_ptr_factory_.GetWeakPtr(), std::move(callback), form_data)); }
diff --git a/components/autofill/core/browser/autofill_test_utils.cc b/components/autofill/core/browser/autofill_test_utils.cc index 42991dc6..efea2774 100644 --- a/components/autofill/core/browser/autofill_test_utils.cc +++ b/components/autofill/core/browser/autofill_test_utils.cc
@@ -5,10 +5,12 @@ #include "components/autofill/core/browser/autofill_test_utils.h" #include <cstdint> +#include <iterator> #include <string> #include "base/guid.h" #include "base/rand_util.h" +#include "base/ranges/algorithm.h" #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" @@ -42,6 +44,8 @@ #include "ui/gfx/geometry/rect.h" using base::ASCIIToUTF16; +using FieldPrediction = ::autofill::AutofillQueryResponse::FormSuggestion:: + FieldSuggestion::FieldPrediction; namespace autofill { @@ -1047,38 +1051,56 @@ return all_signatures; } -void AddFieldSuggestionToForm( +FieldPrediction CreateFieldPrediction(ServerFieldType type, + FieldPrediction::Source source) { + FieldPrediction field_prediction; + field_prediction.set_type(type); + field_prediction.set_source(source); + if (source == FieldPrediction::SOURCE_OVERRIDE) + field_prediction.set_override(true); + return field_prediction; +} + +FieldPrediction CreateFieldPrediction(ServerFieldType type) { + if (type == NO_SERVER_DATA) + return CreateFieldPrediction(type, FieldPrediction::SOURCE_UNSPECIFIED); + return CreateFieldPrediction( + type, GroupTypeOfServerFieldType(type) == FieldTypeGroup::kPasswordField + ? FieldPrediction::SOURCE_PASSWORDS_DEFAULT + : FieldPrediction::SOURCE_AUTOFILL_DEFAULT); +} + +void AddFieldPredictionToForm( const FormFieldData& field_data, ServerFieldType field_type, AutofillQueryResponse_FormSuggestion* form_suggestion) { auto* field_suggestion = form_suggestion->add_field_suggestions(); field_suggestion->set_field_signature( CalculateFieldSignatureForField(field_data).value()); - field_suggestion->add_predictions()->set_type(field_type); -} - -void AddFieldPredictionsToForm( - const FormFieldData& field_data, - const std::vector<int>& field_types, - AutofillQueryResponse_FormSuggestion* form_suggestion) { - std::vector<ServerFieldType> types; - for (auto type : field_types) { - types.emplace_back(ToSafeServerFieldType(type, UNKNOWN_TYPE)); - } - AddFieldPredictionsToForm(field_data, types, form_suggestion); + *field_suggestion->add_predictions() = CreateFieldPrediction(field_type); } void AddFieldPredictionsToForm( const FormFieldData& field_data, const std::vector<ServerFieldType>& field_types, AutofillQueryResponse_FormSuggestion* form_suggestion) { + std::vector<FieldPrediction> field_predictions(field_types.size()); + base::ranges::transform(field_types, std::back_inserter(field_predictions), + static_cast<FieldPrediction (*)(ServerFieldType)>( + &CreateFieldPrediction)); + return AddFieldPredictionsToForm(field_data, field_predictions, + form_suggestion); +} + +void AddFieldPredictionsToForm( + const FormFieldData& field_data, + const std::vector<FieldPrediction>& field_predictions, + AutofillQueryResponse_FormSuggestion* form_suggestion) { auto* field_suggestion = form_suggestion->add_field_suggestions(); field_suggestion->set_field_signature( CalculateFieldSignatureForField(field_data).value()); - for (auto field_type : field_types) { - AutofillQueryResponse_FormSuggestion_FieldSuggestion_FieldPrediction* - prediction = field_suggestion->add_predictions(); - prediction->set_type(field_type); + for (const auto& prediction : field_predictions) { + *field_suggestion->add_predictions() = prediction; } }
diff --git a/components/autofill/core/browser/autofill_test_utils.h b/components/autofill/core/browser/autofill_test_utils.h index 22000c7d..14a4b58 100644 --- a/components/autofill/core/browser/autofill_test_utils.h +++ b/components/autofill/core/browser/autofill_test_utils.h
@@ -465,23 +465,34 @@ std::string NextYear(); std::string TenYearsFromNow(); -void AddFieldSuggestionToForm( +// Creates a `FieldPrediction` instance. +::autofill::AutofillQueryResponse::FormSuggestion::FieldSuggestion:: + FieldPrediction + CreateFieldPrediction(ServerFieldType type, + ::autofill::AutofillQueryResponse::FormSuggestion:: + FieldSuggestion::FieldPrediction::Source source); + +// Creates a `FieldPrediction` instance, with a plausible value for `source()`. +::autofill::AutofillQueryResponse::FormSuggestion::FieldSuggestion:: + FieldPrediction + CreateFieldPrediction(ServerFieldType type); + +void AddFieldPredictionToForm( const autofill::FormFieldData& field_data, ServerFieldType field_type, ::autofill::AutofillQueryResponse_FormSuggestion* form_suggestion); -// Adds |field_types| predictions of |field_data| to |form_suggestion| query -// response. Assumes int type can be cast to ServerFieldType. -void AddFieldPredictionsToForm( - const autofill::FormFieldData& field_data, - const std::vector<int>& field_types, - ::autofill::AutofillQueryResponse_FormSuggestion* form_suggestion); - void AddFieldPredictionsToForm( const autofill::FormFieldData& field_data, const std::vector<ServerFieldType>& field_types, ::autofill::AutofillQueryResponse_FormSuggestion* form_suggestion); +void AddFieldPredictionsToForm( + const autofill::FormFieldData& field_data, + const std::vector<::autofill::AutofillQueryResponse::FormSuggestion:: + FieldSuggestion::FieldPrediction>& field_predictions, + ::autofill::AutofillQueryResponse_FormSuggestion* form_suggestion); + } // namespace test } // namespace autofill
diff --git a/components/autofill/core/browser/browser_autofill_manager_unittest.cc b/components/autofill/core/browser/browser_autofill_manager_unittest.cc index a3e85119..659dec52 100644 --- a/components/autofill/core/browser/browser_autofill_manager_unittest.cc +++ b/components/autofill/core/browser/browser_autofill_manager_unittest.cc
@@ -5937,19 +5937,19 @@ AutofillQueryResponse::FormSuggestion* form_suggestion; // Set suggestions for form 1. form_suggestion = response.add_form_suggestions(); - autofill::test::AddFieldSuggestionToForm(form.fields[0], ADDRESS_HOME_CITY, + autofill::test::AddFieldPredictionToForm(form.fields[0], ADDRESS_HOME_CITY, form_suggestion); - autofill::test::AddFieldSuggestionToForm(form.fields[1], ADDRESS_HOME_STATE, + autofill::test::AddFieldPredictionToForm(form.fields[1], ADDRESS_HOME_STATE, form_suggestion); - autofill::test::AddFieldSuggestionToForm(form.fields[2], ADDRESS_HOME_ZIP, + autofill::test::AddFieldPredictionToForm(form.fields[2], ADDRESS_HOME_ZIP, form_suggestion); // Set suggestions for form 2. form_suggestion = response.add_form_suggestions(); - autofill::test::AddFieldSuggestionToForm(form2.fields[0], NAME_LAST, + autofill::test::AddFieldPredictionToForm(form2.fields[0], NAME_LAST, form_suggestion); - autofill::test::AddFieldSuggestionToForm(form2.fields[1], NAME_MIDDLE, + autofill::test::AddFieldPredictionToForm(form2.fields[1], NAME_MIDDLE, form_suggestion); - autofill::test::AddFieldSuggestionToForm(form2.fields[2], ADDRESS_HOME_ZIP, + autofill::test::AddFieldPredictionToForm(form2.fields[2], ADDRESS_HOME_ZIP, form_suggestion); std::string response_string; @@ -6066,15 +6066,15 @@ AutofillQueryResponse response; auto* form_suggestion = response.add_form_suggestions(); - autofill::test::AddFieldSuggestionToForm( + autofill::test::AddFieldPredictionToForm( form.fields[0], CREDIT_CARD_NAME_FIRST, form_suggestion); - autofill::test::AddFieldSuggestionToForm( + autofill::test::AddFieldPredictionToForm( form.fields[1], CREDIT_CARD_NAME_LAST, form_suggestion); - autofill::test::AddFieldSuggestionToForm(form.fields[2], CREDIT_CARD_NUMBER, + autofill::test::AddFieldPredictionToForm(form.fields[2], CREDIT_CARD_NUMBER, form_suggestion); - autofill::test::AddFieldSuggestionToForm( + autofill::test::AddFieldPredictionToForm( form.fields[3], CREDIT_CARD_EXP_MONTH, form_suggestion); - autofill::test::AddFieldSuggestionToForm( + autofill::test::AddFieldPredictionToForm( form.fields[4], CREDIT_CARD_EXP_4_DIGIT_YEAR, form_suggestion); std::string response_string; @@ -6586,10 +6586,9 @@ // Assign the specified predicted type for each field in the test case. FormStructure form_structure(form); for (size_t i = 0; i < test_fields.size(); ++i) { - AutofillQueryResponse::FormSuggestion::FieldSuggestion::FieldPrediction - prediction; - prediction.set_type(test_fields[i].predicted_type); - form_structure.field(i)->set_server_predictions({prediction}); + form_structure.field(i)->set_server_predictions( + {::autofill::test::CreateFieldPrediction( + test_fields[i].predicted_type)}); } BrowserAutofillManager::DeterminePossibleFieldTypesForUploadForTest(
diff --git a/components/autofill/core/browser/field_filler_unittest.cc b/components/autofill/core/browser/field_filler_unittest.cc index 6eb40d4a..2ac1a878 100644 --- a/components/autofill/core/browser/field_filler_unittest.cc +++ b/components/autofill/core/browser/field_filler_unittest.cc
@@ -153,8 +153,6 @@ TEST_F(AutofillFieldFillerTest, Type) { AutofillField field; - AutofillQueryResponse::FormSuggestion::FieldSuggestion::FieldPrediction - prediction; ASSERT_EQ(NO_SERVER_DATA, field.server_type()); ASSERT_EQ(UNKNOWN_TYPE, field.heuristic_type()); @@ -168,8 +166,8 @@ EXPECT_EQ(FieldTypeGroup::kName, field.Type().group()); // Set the server type and check it. - prediction.set_type(ADDRESS_HOME_LINE1); - field.set_server_predictions({prediction}); + field.set_server_predictions( + {::autofill::test::CreateFieldPrediction(ADDRESS_HOME_LINE1)}); EXPECT_EQ(ADDRESS_HOME_LINE1, field.Type().GetStorableType()); EXPECT_EQ(FieldTypeGroup::kAddressHome, field.Type().group()); @@ -179,14 +177,14 @@ EXPECT_EQ(FieldTypeGroup::kAddressHome, field.Type().group()); // Checks that setting server type resets overall type. - prediction.set_type(ADDRESS_HOME_LINE1); - field.set_server_predictions({prediction}); + field.set_server_predictions( + {::autofill::test::CreateFieldPrediction(ADDRESS_HOME_LINE1)}); EXPECT_EQ(ADDRESS_HOME_LINE1, field.Type().GetStorableType()); EXPECT_EQ(FieldTypeGroup::kAddressHome, field.Type().group()); // Remove the server type to make sure the heuristic type is preserved. - prediction.set_type(NO_SERVER_DATA); - field.set_server_predictions({prediction}); + field.set_server_predictions( + {::autofill::test::CreateFieldPrediction(NO_SERVER_DATA)}); EXPECT_EQ(NAME_FIRST, field.Type().GetStorableType()); EXPECT_EQ(FieldTypeGroup::kName, field.Type().group()); @@ -228,27 +226,25 @@ // unrecognized autocomplete attribute. TEST_F(AutofillFieldFillerTest, Type_CreditCardOverrideHtml_ServerPredicitons) { AutofillField field; - AutofillQueryResponse::FormSuggestion::FieldSuggestion::FieldPrediction - prediction; field.SetHtmlType(HtmlFieldType::kUnrecognized, HtmlFieldMode::kNone); // A credit card server prediction overrides the unrecognized type. - prediction.set_type(CREDIT_CARD_NUMBER); - field.set_server_predictions({prediction}); + field.set_server_predictions( + {::autofill::test::CreateFieldPrediction(CREDIT_CARD_NUMBER)}); EXPECT_EQ(CREDIT_CARD_NUMBER, field.Type().GetStorableType()); // A non credit card server prediction doesn't override the unrecognized // type. - prediction.set_type(NAME_FIRST); - field.set_server_predictions({prediction}); + field.set_server_predictions( + {::autofill::test::CreateFieldPrediction(NAME_FIRST)}); EXPECT_EQ(UNKNOWN_TYPE, field.Type().GetStorableType()); // A credit card server prediction doesn't override a known specified html // type. field.SetHtmlType(HtmlFieldType::kName, HtmlFieldMode::kNone); - prediction.set_type(CREDIT_CARD_NUMBER); - field.set_server_predictions({prediction}); + field.set_server_predictions( + {::autofill::test::CreateFieldPrediction(CREDIT_CARD_NUMBER)}); EXPECT_EQ(NAME_FULL, field.Type().GetStorableType()); } @@ -258,37 +254,35 @@ TEST_F(AutofillFieldFillerTest, Type_ServerPredictionOfCityAndNumber_OverrideHtml) { AutofillField field; - AutofillQueryResponse::FormSuggestion::FieldSuggestion::FieldPrediction - prediction; field.SetHtmlType(HtmlFieldType::kTel, HtmlFieldMode::kNone); - prediction.set_type(PHONE_HOME_CITY_AND_NUMBER); - field.set_server_predictions({prediction}); + field.set_server_predictions( + {::autofill::test::CreateFieldPrediction(PHONE_HOME_CITY_AND_NUMBER)}); EXPECT_EQ(PHONE_HOME_CITY_AND_NUMBER, field.Type().GetStorableType()); // Overrides to another number format. - prediction.set_type(PHONE_HOME_NUMBER); - field.set_server_predictions({prediction}); + field.set_server_predictions( + {::autofill::test::CreateFieldPrediction(PHONE_HOME_NUMBER)}); EXPECT_EQ(PHONE_HOME_NUMBER, field.Type().GetStorableType()); // Overrides autocomplete=tel-national too. field.SetHtmlType(HtmlFieldType::kTelNational, HtmlFieldMode::kNone); - prediction.set_type(PHONE_HOME_WHOLE_NUMBER); - field.set_server_predictions({prediction}); + field.set_server_predictions( + {::autofill::test::CreateFieldPrediction(PHONE_HOME_WHOLE_NUMBER)}); EXPECT_EQ(PHONE_HOME_WHOLE_NUMBER, field.Type().GetStorableType()); // If autocomplete=tel-national but server says it's not a phone field, // do not override. field.SetHtmlType(HtmlFieldType::kTelNational, HtmlFieldMode::kNone); - prediction.set_type(CREDIT_CARD_EXP_DATE_2_DIGIT_YEAR); - field.set_server_predictions({prediction}); + field.set_server_predictions({::autofill::test::CreateFieldPrediction( + CREDIT_CARD_EXP_DATE_2_DIGIT_YEAR)}); EXPECT_EQ(PHONE_HOME_CITY_AND_NUMBER, field.Type().GetStorableType()); // If html type not specified, we still use server prediction. field.SetHtmlType(HtmlFieldType::kUnspecified, HtmlFieldMode::kNone); - prediction.set_type(PHONE_HOME_CITY_AND_NUMBER); - field.set_server_predictions({prediction}); + field.set_server_predictions( + {::autofill::test::CreateFieldPrediction(PHONE_HOME_CITY_AND_NUMBER)}); EXPECT_EQ(PHONE_HOME_CITY_AND_NUMBER, field.Type().GetStorableType()); } @@ -334,8 +328,6 @@ TEST_F(AutofillFieldFillerTest, IsFieldFillable) { AutofillField field; - AutofillQueryResponse::FormSuggestion::FieldSuggestion::FieldPrediction - prediction; ASSERT_EQ(UNKNOWN_TYPE, field.Type().GetStorableType()); // Type is unknown. @@ -347,14 +339,14 @@ // Only server type is set. field.set_heuristic_type(GetActivePatternSource(), UNKNOWN_TYPE); - prediction.set_type(NAME_LAST); - field.set_server_predictions({prediction}); + field.set_server_predictions( + {::autofill::test::CreateFieldPrediction(NAME_LAST)}); EXPECT_TRUE(field.IsFieldFillable()); // Both types set. field.set_heuristic_type(GetActivePatternSource(), NAME_FIRST); - prediction.set_type(NAME_LAST); - field.set_server_predictions({prediction}); + field.set_server_predictions( + {::autofill::test::CreateFieldPrediction(NAME_LAST)}); EXPECT_TRUE(field.IsFieldFillable()); // Field has autocomplete="off" set. Since autofill was able to make a @@ -1377,11 +1369,9 @@ TEST_F(AutofillFieldFillerTest, FillStreetAddressTextField) { AutofillField field; - AutofillQueryResponse::FormSuggestion::FieldSuggestion::FieldPrediction - prediction; field.form_control_type = "text"; - prediction.set_type(ADDRESS_HOME_STREET_ADDRESS); - field.set_server_predictions({prediction}); + field.set_server_predictions( + {::autofill::test::CreateFieldPrediction(ADDRESS_HOME_STREET_ADDRESS)}); FieldFiller filler(/*app_locale=*/"en-US", /*address_normalizer=*/nullptr); std::u16string value = u"123 Fake St.\nApt. 42";
diff --git a/components/autofill/core/browser/form_structure_rationalizer_unittest.cc b/components/autofill/core/browser/form_structure_rationalizer_unittest.cc index 608827e..b2b7715 100644 --- a/components/autofill/core/browser/form_structure_rationalizer_unittest.cc +++ b/components/autofill/core/browser/form_structure_rationalizer_unittest.cc
@@ -94,7 +94,8 @@ auto* field_suggestion = form_suggestion->add_field_suggestions(); field_suggestion->set_field_signature( CalculateFieldSignatureForField(form.fields[i]).value()); - field_suggestion->add_predictions()->set_type(fields[i].field_type); + *field_suggestion->add_predictions() = + ::autofill::test::CreateFieldPrediction(fields[i].field_type); } std::string response_string = SerializeAndEncode(response);
diff --git a/components/autofill/core/browser/form_structure_unittest.cc b/components/autofill/core/browser/form_structure_unittest.cc index d3e39a3..5ed7dcb0 100644 --- a/components/autofill/core/browser/form_structure_unittest.cc +++ b/components/autofill/core/browser/form_structure_unittest.cc
@@ -41,11 +41,14 @@ using ::base::ASCIIToUTF16; using ::testing::AllOf; +using ::testing::AnyOf; using ::testing::Each; using ::testing::ElementsAre; using ::testing::IsEmpty; +using ::testing::Matcher; using ::testing::Not; using ::testing::Pointee; +using ::testing::Property; using ::testing::ResultOf; using ::testing::Truly; using ::testing::UnorderedElementsAre; @@ -53,9 +56,14 @@ namespace autofill { +using FieldPrediction = ::autofill::AutofillQueryResponse::FormSuggestion:: + FieldSuggestion::FieldPrediction; using autofill::features::kAutofillLabelAffixRemoval; using autofill::mojom::SubmissionIndicatorEvent; using autofill::mojom::SubmissionSource; +using autofill::test::AddFieldPredictionsToForm; +using autofill::test::AddFieldPredictionToForm; +using autofill::test::CreateFieldPrediction; namespace { @@ -70,29 +78,14 @@ return response_string; } -// Sets |field_type| suggestion for |field_data|'s signature. -void AddFieldSuggestionToForm( - ::autofill::AutofillQueryResponse_FormSuggestion* form_suggestion, - const autofill::FormFieldData& field_data, - ServerFieldType field_type) { - auto* field_suggestion = form_suggestion->add_field_suggestions(); - field_suggestion->set_field_signature( - CalculateFieldSignatureForField(field_data).value()); - field_suggestion->add_predictions()->set_type(field_type); -} - void AddFieldOverrideToForm( - ::autofill::AutofillQueryResponse_FormSuggestion* form_suggestion, autofill::FormFieldData field_data, - ServerFieldType field_type) { - AddFieldSuggestionToForm(form_suggestion, field_data, field_type); - - DCHECK_GT(form_suggestion->field_suggestions().size(), 0); - form_suggestion - ->mutable_field_suggestions(form_suggestion->field_suggestions().size() - - 1) - ->mutable_predictions(0) - ->set_override(true); + ServerFieldType field_type, + ::autofill::AutofillQueryResponse_FormSuggestion* form_suggestion) { + AddFieldPredictionsToForm( + field_data, + {CreateFieldPrediction(field_type, FieldPrediction::SOURCE_OVERRIDE)}, + form_suggestion); } // Matches any protobuf `actual` whose serialization is equal to the @@ -131,6 +124,10 @@ #endif }; +Matcher<FieldPrediction> EqualsPrediction(ServerFieldType type) { + return Property(&FieldPrediction::type, type); +} + } // namespace class FormStructureTestImpl : public test::FormStructureTest { @@ -5040,8 +5037,8 @@ // name. AutofillQueryResponse response; auto* form_suggestion = response.add_form_suggestions(); - AddFieldOverrideToForm(form_suggestion, form_data.fields[0], NAME_FIRST); - AddFieldSuggestionToForm(form_suggestion, form_data.fields[1], NAME_LAST); + AddFieldOverrideToForm(form_data.fields[0], NAME_FIRST, form_suggestion); + AddFieldPredictionToForm(form_data.fields[1], NAME_LAST, form_suggestion); std::string response_string = SerializeAndEncode(response); @@ -5153,10 +5150,10 @@ // Setup the query response. AutofillQueryResponse response; auto* form_suggestion = response.add_form_suggestions(); - AddFieldSuggestionToForm(form_suggestion, form_data.fields[0], NAME_FIRST); + AddFieldPredictionToForm(form_data.fields[0], NAME_FIRST, form_suggestion); // Simulate a NAME_LAST classification for the two last name fields. - AddFieldSuggestionToForm(form_suggestion, form_data.fields[1], NAME_LAST); - AddFieldSuggestionToForm(form_suggestion, form_data.fields[2], NAME_LAST); + AddFieldPredictionToForm(form_data.fields[1], NAME_LAST, form_suggestion); + AddFieldPredictionToForm(form_data.fields[2], NAME_LAST, form_suggestion); std::string response_string = SerializeAndEncode(response); @@ -5218,12 +5215,12 @@ // Setup the query response. AutofillQueryResponse response; auto* form_suggestion = response.add_form_suggestions(); - AddFieldSuggestionToForm(form_suggestion, form_data.fields[0], NAME_FULL); + AddFieldPredictionToForm(form_data.fields[0], NAME_FULL, form_suggestion); // Simulate ADDRESS_LINE classifications for the two last name fields. - AddFieldSuggestionToForm(form_suggestion, form_data.fields[1], - ADDRESS_HOME_LINE1); - AddFieldSuggestionToForm(form_suggestion, form_data.fields[2], - ADDRESS_HOME_LINE2); + AddFieldPredictionToForm(form_data.fields[1], ADDRESS_HOME_LINE1, + form_suggestion); + AddFieldPredictionToForm(form_data.fields[2], ADDRESS_HOME_LINE2, + form_suggestion); std::string response_string = SerializeAndEncode(response); @@ -5269,10 +5266,10 @@ // Setup the query response. AutofillQueryResponse response; auto* form_suggestion = response.add_form_suggestions(); - AddFieldSuggestionToForm(form_suggestion, form_data.fields[0], NAME_FIRST); - AddFieldSuggestionToForm(form_suggestion, form_data.fields[1], NAME_LAST); - AddFieldSuggestionToForm(form_suggestion, form_data.fields[2], - ADDRESS_HOME_LINE1); + AddFieldPredictionToForm(form_data.fields[0], NAME_FIRST, form_suggestion); + AddFieldPredictionToForm(form_data.fields[1], NAME_LAST, form_suggestion); + AddFieldPredictionToForm(form_data.fields[2], ADDRESS_HOME_LINE1, + form_suggestion); form_suggestion->add_field_suggestions()->add_predictions()->set_type( EMAIL_ADDRESS); form_suggestion->add_field_suggestions()->add_predictions()->set_type( @@ -5337,11 +5334,11 @@ // Setup the query response. AutofillQueryResponse response; auto* form_suggestion = response.add_form_suggestions(); - AddFieldSuggestionToForm(form_suggestion, form_data.fields[0], UNKNOWN_TYPE); - AddFieldSuggestionToForm(form_suggestion, form_data.fields[1], - NO_SERVER_DATA); - AddFieldSuggestionToForm(form_suggestion, form_data.fields[2], - ADDRESS_HOME_LINE1); + AddFieldPredictionToForm(form_data.fields[0], UNKNOWN_TYPE, form_suggestion); + AddFieldPredictionToForm(form_data.fields[1], NO_SERVER_DATA, + form_suggestion); + AddFieldPredictionToForm(form_data.fields[2], ADDRESS_HOME_LINE1, + form_suggestion); std::string response_string = SerializeAndEncode(response); @@ -5451,26 +5448,26 @@ test::GetEncodedSignatures(forms); { auto* form_suggestion = api_response.add_form_suggestions(); - AddFieldSuggestionToForm(form_suggestion, fields[0], expected_types[0]); - AddFieldSuggestionToForm(form_suggestion, fields[1], NO_SERVER_DATA); - AddFieldSuggestionToForm(form_suggestion, fields[2], NO_SERVER_DATA); - AddFieldSuggestionToForm(form_suggestion, fields[3], expected_types[3]); - AddFieldSuggestionToForm(form_suggestion, fields[4], expected_types[4]); + AddFieldPredictionToForm(fields[0], expected_types[0], form_suggestion); + AddFieldPredictionToForm(fields[1], NO_SERVER_DATA, form_suggestion); + AddFieldPredictionToForm(fields[2], NO_SERVER_DATA, form_suggestion); + AddFieldPredictionToForm(fields[3], expected_types[3], form_suggestion); + AddFieldPredictionToForm(fields[4], expected_types[4], form_suggestion); } // Response for the FormFieldData::host_form_signature 12345. encoded_signatures.push_back(FormSignature(12345)); { auto* form_suggestion = api_response.add_form_suggestions(); - AddFieldSuggestionToForm(form_suggestion, fields[0], NO_SERVER_DATA); - AddFieldSuggestionToForm(form_suggestion, fields[1], expected_types[1]); - AddFieldSuggestionToForm(form_suggestion, fields[2], expected_types[2]); + AddFieldPredictionToForm(fields[0], NO_SERVER_DATA, form_suggestion); + AddFieldPredictionToForm(fields[1], expected_types[1], form_suggestion); + AddFieldPredictionToForm(fields[2], expected_types[2], form_suggestion); } // Response for the FormFieldData::host_form_signature 67890. encoded_signatures.push_back(FormSignature(67890)); { auto* form_suggestion = api_response.add_form_suggestions(); - AddFieldSuggestionToForm(form_suggestion, fields[4], ADDRESS_HOME_CITY); - AddFieldSuggestionToForm(form_suggestion, fields[5], expected_types[5]); + AddFieldPredictionToForm(fields[4], ADDRESS_HOME_CITY, form_suggestion); + AddFieldPredictionToForm(fields[5], expected_types[5], form_suggestion); } // Serialize API response. @@ -5546,18 +5543,15 @@ AutofillQueryResponse api_response; // Make form 1 suggestions. auto* form_suggestion = api_response.add_form_suggestions(); - auto* field0 = form_suggestion->add_field_suggestions(); - field0->set_field_signature( - CalculateFieldSignatureForField(form.fields[0]).value()); - auto* field_prediction0 = field0->add_predictions(); - field_prediction0->set_type(NAME_FULL); - auto* field_prediction1 = field0->add_predictions(); - field_prediction1->set_type(PHONE_HOME_COUNTRY_CODE); - AddFieldSuggestionToForm(form_suggestion, form.fields[1], ADDRESS_HOME_LINE1); + AddFieldPredictionsToForm(form.fields[0], + {CreateFieldPrediction(NAME_FULL), + CreateFieldPrediction(PHONE_HOME_COUNTRY_CODE)}, + form_suggestion); + AddFieldPredictionToForm(form.fields[1], ADDRESS_HOME_LINE1, form_suggestion); // Make form 2 suggestions. form_suggestion = api_response.add_form_suggestions(); - AddFieldSuggestionToForm(form_suggestion, form2.fields[0], EMAIL_ADDRESS); - AddFieldSuggestionToForm(form_suggestion, form2.fields[1], NO_SERVER_DATA); + AddFieldPredictionToForm(form2.fields[0], EMAIL_ADDRESS, form_suggestion); + AddFieldPredictionToForm(form2.fields[1], NO_SERVER_DATA, form_suggestion); // Serialize API response. std::string response_string; std::string encoded_response_string; @@ -5572,21 +5566,23 @@ // the query. ASSERT_GE(forms[0]->field_count(), 2U); ASSERT_GE(forms[1]->field_count(), 2U); + EXPECT_EQ(NAME_FULL, forms[0]->field(0)->server_type()); - ASSERT_EQ(2U, forms[0]->field(0)->server_predictions().size()); - EXPECT_EQ(NAME_FULL, forms[0]->field(0)->server_predictions()[0].type()); - EXPECT_EQ(PHONE_HOME_COUNTRY_CODE, - forms[0]->field(0)->server_predictions()[1].type()); + EXPECT_THAT(forms[0]->field(0)->server_predictions(), + ElementsAre(EqualsPrediction(NAME_FULL), + EqualsPrediction(PHONE_HOME_COUNTRY_CODE))); + EXPECT_EQ(ADDRESS_HOME_LINE1, forms[0]->field(1)->server_type()); - ASSERT_EQ(1U, forms[0]->field(1)->server_predictions().size()); - EXPECT_EQ(ADDRESS_HOME_LINE1, - forms[0]->field(1)->server_predictions()[0].type()); + EXPECT_THAT(forms[0]->field(1)->server_predictions(), + ElementsAre(EqualsPrediction(ADDRESS_HOME_LINE1))); + EXPECT_EQ(EMAIL_ADDRESS, forms[1]->field(0)->server_type()); - ASSERT_EQ(1U, forms[1]->field(0)->server_predictions().size()); - EXPECT_EQ(EMAIL_ADDRESS, forms[1]->field(0)->server_predictions()[0].type()); + EXPECT_THAT(forms[1]->field(0)->server_predictions(), + ElementsAre(EqualsPrediction(EMAIL_ADDRESS))); + EXPECT_EQ(NO_SERVER_DATA, forms[1]->field(1)->server_type()); - ASSERT_EQ(1U, forms[1]->field(1)->server_predictions().size()); - EXPECT_EQ(0, forms[1]->field(1)->server_predictions()[0].type()); + EXPECT_THAT(forms[1]->field(1)->server_predictions(), + ElementsAre(EqualsPrediction(NO_SERVER_DATA))); } // Tests ParseApiQueryResponse when the payload cannot be parsed to an @@ -5605,10 +5601,8 @@ // Add form to the vector needed by the response parsing function. FormStructure form_structure(form); - AutofillQueryResponse::FormSuggestion::FieldSuggestion::FieldPrediction - prediction; - prediction.set_type(NAME_FULL); - form_structure.field(0)->set_server_predictions({prediction}); + form_structure.field(0)->set_server_predictions( + {CreateFieldPrediction(NAME_FULL)}); std::vector<FormStructure*> forms; forms.push_back(&form_structure); @@ -5638,10 +5632,8 @@ // Add form to the vector needed by the response parsing function. FormStructure form_structure(form); - AutofillQueryResponse::FormSuggestion::FieldSuggestion::FieldPrediction - prediction; - prediction.set_type(NAME_FULL); - form_structure.field(0)->set_server_predictions({prediction}); + form_structure.field(0)->set_server_predictions( + {CreateFieldPrediction(NAME_FULL)}); std::vector<FormStructure*> forms; forms.push_back(&form_structure); @@ -5654,7 +5646,7 @@ // is no issue when parsing the query response. In this test case there is an // issue with the encoding of the data, hence EMAIL_ADDRESS should not be // applied because of early exit of the parsing function. - AddFieldSuggestionToForm(form_suggestion, form.fields[0], EMAIL_ADDRESS); + AddFieldPredictionToForm(form.fields[0], EMAIL_ADDRESS, form_suggestion); // Serialize API response. std::string response_string; @@ -5689,9 +5681,9 @@ AutofillQueryResponse response; auto* form_suggestion = response.add_form_suggestions(); - AddFieldSuggestionToForm(form_suggestion, form.fields[0], EMAIL_ADDRESS); - AddFieldSuggestionToForm(form_suggestion, form.fields[1], - ACCOUNT_CREATION_PASSWORD); + AddFieldPredictionToForm(form.fields[0], EMAIL_ADDRESS, form_suggestion); + AddFieldPredictionToForm(form.fields[1], ACCOUNT_CREATION_PASSWORD, + form_suggestion); std::string response_string = SerializeAndEncode(response); FormStructure::ParseApiQueryResponse(response_string, forms, @@ -5751,10 +5743,10 @@ AutofillQueryResponse response; auto* form_suggestion = response.add_form_suggestions(); - AddFieldSuggestionToForm(form_suggestion, form.fields[0], NAME_FIRST); - AddFieldSuggestionToForm(form_suggestion, form.fields[1], NO_SERVER_DATA); - AddFieldSuggestionToForm(form_suggestion, form.fields[2], NO_SERVER_DATA); - AddFieldSuggestionToForm(form_suggestion, form.fields[3], NO_SERVER_DATA); + AddFieldPredictionToForm(form.fields[0], NAME_FIRST, form_suggestion); + AddFieldPredictionToForm(form.fields[1], NO_SERVER_DATA, form_suggestion); + AddFieldPredictionToForm(form.fields[2], NO_SERVER_DATA, form_suggestion); + AddFieldPredictionToForm(form.fields[3], NO_SERVER_DATA, form_suggestion); std::string response_string = SerializeAndEncode(response); @@ -5814,10 +5806,10 @@ AutofillQueryResponse response; auto* form_suggestion = response.add_form_suggestions(); - AddFieldSuggestionToForm(form_suggestion, form.fields[0], NO_SERVER_DATA); - AddFieldSuggestionToForm(form_suggestion, form.fields[1], NO_SERVER_DATA); - AddFieldSuggestionToForm(form_suggestion, form.fields[2], NO_SERVER_DATA); - AddFieldSuggestionToForm(form_suggestion, form.fields[3], NO_SERVER_DATA); + AddFieldPredictionToForm(form.fields[0], NO_SERVER_DATA, form_suggestion); + AddFieldPredictionToForm(form.fields[1], NO_SERVER_DATA, form_suggestion); + AddFieldPredictionToForm(form.fields[2], NO_SERVER_DATA, form_suggestion); + AddFieldPredictionToForm(form.fields[3], NO_SERVER_DATA, form_suggestion); std::string response_string = SerializeAndEncode(response); @@ -5881,12 +5873,12 @@ AutofillQueryResponse response; auto* form_suggestion = response.add_form_suggestions(); - AddFieldSuggestionToForm(form_suggestion, form.fields[0], - CREDIT_CARD_NAME_FULL); - AddFieldSuggestionToForm(form_suggestion, form.fields[1], CREDIT_CARD_NUMBER); - AddFieldSuggestionToForm(form_suggestion, form.fields[2], - CREDIT_CARD_EXP_DATE_4_DIGIT_YEAR); - AddFieldSuggestionToForm(form_suggestion, form.fields[3], NO_SERVER_DATA); + AddFieldPredictionToForm(form.fields[0], CREDIT_CARD_NAME_FULL, + form_suggestion); + AddFieldPredictionToForm(form.fields[1], CREDIT_CARD_NUMBER, form_suggestion); + AddFieldPredictionToForm(form.fields[2], CREDIT_CARD_EXP_DATE_4_DIGIT_YEAR, + form_suggestion); + AddFieldPredictionToForm(form.fields[3], NO_SERVER_DATA, form_suggestion); std::string response_string = SerializeAndEncode(response); @@ -5944,9 +5936,9 @@ // Setup the query response. AutofillQueryResponse response; auto* form_suggestion = response.add_form_suggestions(); - AddFieldSuggestionToForm(form_suggestion, form_data.fields[0], NAME_FIRST); - AddFieldSuggestionToForm(form_suggestion, form_data.fields[1], NAME_LAST); - AddFieldSuggestionToForm(form_suggestion, form_data.fields[2], EMAIL_ADDRESS); + AddFieldPredictionToForm(form_data.fields[0], NAME_FIRST, form_suggestion); + AddFieldPredictionToForm(form_data.fields[1], NAME_LAST, form_suggestion); + AddFieldPredictionToForm(form_data.fields[2], EMAIL_ADDRESS, form_suggestion); std::string response_string = SerializeAndEncode(response); @@ -5989,8 +5981,8 @@ // Setup the query response. AutofillQueryResponse response; auto* form_suggestion = response.add_form_suggestions(); - AddFieldSuggestionToForm(form_suggestion, form_data.fields[0], NAME_FIRST); - AddFieldSuggestionToForm(form_suggestion, form_data.fields[2], EMAIL_ADDRESS); + AddFieldPredictionToForm(form_data.fields[0], NAME_FIRST, form_suggestion); + AddFieldPredictionToForm(form_data.fields[2], EMAIL_ADDRESS, form_suggestion); std::string response_string = SerializeAndEncode(response);
diff --git a/components/autofill/core/browser/logging/log_manager.cc b/components/autofill/core/browser/logging/log_manager.cc index 1c0e107..86a6d1d01 100644 --- a/components/autofill/core/browser/logging/log_manager.cc +++ b/components/autofill/core/browser/logging/log_manager.cc
@@ -4,6 +4,8 @@ #include "components/autofill/core/browser/logging/log_manager.h" +#include <utility> + #include "base/memory/raw_ptr.h" #include "components/autofill/core/browser/logging/log_router.h" @@ -11,19 +13,20 @@ namespace { -class LogManagerImpl : public LogManager { +class RoutingLogManagerImpl : public RoutingLogManager { public: - LogManagerImpl(LogRouter* log_router, - base::RepeatingClosure notification_callback); + RoutingLogManagerImpl(LogRouter* log_router, + base::RepeatingClosure notification_callback); - LogManagerImpl(const LogManagerImpl&) = delete; - LogManagerImpl& operator=(const LogManagerImpl&) = delete; + RoutingLogManagerImpl(const RoutingLogManagerImpl&) = delete; + RoutingLogManagerImpl& operator=(const RoutingLogManagerImpl&) = delete; - ~LogManagerImpl() override; + ~RoutingLogManagerImpl() override; - // LogManager + // RoutingLogManager void OnLogRouterAvailabilityChanged(bool router_can_be_used) override; void SetSuspended(bool suspended) override; + // LogManager bool IsLoggingActive() const override; LogBufferSubmitter Log() override; void ProcessLog(base::Value::Dict node, @@ -42,18 +45,20 @@ base::RepeatingClosure notification_callback_; }; -LogManagerImpl::LogManagerImpl(LogRouter* log_router, - base::RepeatingClosure notification_callback) +RoutingLogManagerImpl::RoutingLogManagerImpl( + LogRouter* log_router, + base::RepeatingClosure notification_callback) : log_router_(log_router), can_use_log_router_(log_router_ && log_router_->RegisterManager(this)), notification_callback_(std::move(notification_callback)) {} -LogManagerImpl::~LogManagerImpl() { +RoutingLogManagerImpl::~RoutingLogManagerImpl() { if (log_router_) log_router_->UnregisterManager(this); } -void LogManagerImpl::OnLogRouterAvailabilityChanged(bool router_can_be_used) { +void RoutingLogManagerImpl::OnLogRouterAvailabilityChanged( + bool router_can_be_used) { DCHECK(log_router_); // |log_router_| should be calling this method. if (can_use_log_router_ == router_can_be_used) return; @@ -66,7 +71,7 @@ } } -void LogManagerImpl::SetSuspended(bool suspended) { +void RoutingLogManagerImpl::SetSuspended(bool suspended) { if (suspended == is_suspended_) return; is_suspended_ = suspended; @@ -77,27 +82,75 @@ } } -bool LogManagerImpl::IsLoggingActive() const { +bool RoutingLogManagerImpl::IsLoggingActive() const { return can_use_log_router_ && !is_suspended_; } -LogBufferSubmitter LogManagerImpl::Log() { +LogBufferSubmitter RoutingLogManagerImpl::Log() { return LogBufferSubmitter(this); } -void LogManagerImpl::ProcessLog(base::Value::Dict node, - base::PassKey<LogBufferSubmitter>) { +void RoutingLogManagerImpl::ProcessLog(base::Value::Dict node, + base::PassKey<LogBufferSubmitter>) { log_router_->ProcessLog(std::move(node)); } +class BufferingLogManagerImpl : public BufferingLogManager { + public: + BufferingLogManagerImpl() = default; + + BufferingLogManagerImpl(const BufferingLogManagerImpl&) = delete; + BufferingLogManagerImpl& operator=(const BufferingLogManagerImpl&) = delete; + + ~BufferingLogManagerImpl() override = default; + + // BufferingLogManager + void Flush(LogManager& destination) override; + // LogManager + bool IsLoggingActive() const override; + LogBufferSubmitter Log() override; + void ProcessLog(base::Value::Dict node, + base::PassKey<LogBufferSubmitter>) override; + + private: + std::vector<base::Value::Dict> nodes_; + absl::optional<base::PassKey<LogBufferSubmitter>> pass_key_; +}; + +void BufferingLogManagerImpl::Flush(LogManager& destination) { + auto nodes = std::exchange(nodes_, {}); + for (auto& node : nodes) + destination.ProcessLog(std::move(node), *pass_key_); +} + +bool BufferingLogManagerImpl::IsLoggingActive() const { + return true; +} + +LogBufferSubmitter BufferingLogManagerImpl::Log() { + return LogBufferSubmitter(this); +} + +void BufferingLogManagerImpl::ProcessLog( + base::Value::Dict node, + base::PassKey<LogBufferSubmitter> pass_key) { + nodes_.push_back(std::move(node)); + pass_key_ = pass_key; +} + } // namespace // static -std::unique_ptr<LogManager> LogManager::Create( +std::unique_ptr<RoutingLogManager> LogManager::Create( LogRouter* log_router, base::RepeatingClosure notification_callback) { - return std::make_unique<LogManagerImpl>(log_router, - std::move(notification_callback)); + return std::make_unique<RoutingLogManagerImpl>( + log_router, std::move(notification_callback)); +} + +// static +std::unique_ptr<BufferingLogManager> LogManager::CreateBuffering() { + return std::make_unique<BufferingLogManagerImpl>(); } } // namespace autofill
diff --git a/components/autofill/core/browser/logging/log_manager.h b/components/autofill/core/browser/logging/log_manager.h index 8e17ad8..c1642f1 100644 --- a/components/autofill/core/browser/logging/log_manager.h +++ b/components/autofill/core/browser/logging/log_manager.h
@@ -21,6 +21,8 @@ namespace autofill { class LogRouter; +class RoutingLogManager; +class BufferingLogManager; // This interface is used by the password management code to receive and display // logs about progress of actions like saving a password. @@ -29,12 +31,30 @@ // Returns the production code implementation of LogManager. If |log_router| // is null, the manager will do nothing. |notification_callback| will be // called every time the activity status of logging changes. - static std::unique_ptr<LogManager> Create( + static std::unique_ptr<RoutingLogManager> Create( LogRouter* log_router, base::RepeatingClosure notification_callback); + static std::unique_ptr<BufferingLogManager> CreateBuffering(); + virtual ~LogManager() = default; + // Returns true if logs recorded via LogTextMessage will be displayed, and + // false otherwise. + virtual bool IsLoggingActive() const = 0; + + // This is the preferred way to submitting log entries. + virtual LogBufferSubmitter Log() = 0; + + // Emits the log entry. + virtual void ProcessLog(base::Value::Dict node, + base::PassKey<LogBufferSubmitter>) = 0; +}; + +// This LogManager subclass can be connected to a LogRouter, which in turn +// passes logs to LogReceivers. +class RoutingLogManager : public LogManager { + public: // This method is called by a LogRouter, after the LogManager registers with // one. If |router_can_be_used| is true, logs can be sent to LogRouter after // the return from OnLogRouterAvailabilityChanged and will reach at least one @@ -45,17 +65,15 @@ // The owner of the LogManager can call this to start or end suspending the // logging, by setting |suspended| to true or false, respectively. virtual void SetSuspended(bool suspended) = 0; +}; - // Returns true if logs recorded will be displayed, and false otherwise. - virtual bool IsLoggingActive() const = 0; - - // This is the preferred way to submitting log entries. - virtual LogBufferSubmitter Log() = 0; - - // Emits the log entry. This is only supposed to be called by the RAII type - // LogBufferSubmitter when it submits its buffer on destruction. - virtual void ProcessLog(base::Value::Dict node, - base::PassKey<LogBufferSubmitter>) = 0; +// This LogManager subclass stores logs in a buffer, which can eventually be +// flushed to another LogManager. It facilitates logging across in sequences +// outside of the main thread in a thread-safe way. +class BufferingLogManager : public LogManager { + public: + // Passes the buffering log since the last Flush() to `destination`. + virtual void Flush(LogManager& destination) = 0; }; inline LogBuffer::IsActive IsLoggingActive(LogManager* log_manager) {
diff --git a/components/autofill/core/browser/logging/log_manager_unittest.cc b/components/autofill/core/browser/logging/log_manager_unittest.cc index e13c72b..1da1db5 100644 --- a/components/autofill/core/browser/logging/log_manager_unittest.cc +++ b/components/autofill/core/browser/logging/log_manager_unittest.cc
@@ -59,6 +59,7 @@ &router_, base::BindRepeating(&MockNotifiedObject::NotifyAboutLoggingActivity, base::Unretained(¬ified_object_))); + buffering_manager_ = LogManager::CreateBuffering(); } void TearDown() override { @@ -69,7 +70,8 @@ testing::StrictMock<MockLogReceiver> receiver_; LogRouter router_; testing::StrictMock<MockNotifiedObject> notified_object_; - std::unique_ptr<LogManager> manager_; + std::unique_ptr<RoutingLogManager> manager_; + std::unique_ptr<BufferingLogManager> buffering_manager_; }; TEST_F(LogManagerTest, LogTextMessageNoReceiver) { @@ -106,6 +108,33 @@ LOG_AF(*manager_) << kTestText; } +TEST_F(LogManagerTest, LogBufferingEntriesWhenFlushed) { + LOG_AF(*buffering_manager_) << kTestText; + LOG_AF(*buffering_manager_) << kTestText; + EXPECT_FALSE(manager_->IsLoggingActive()); + EXPECT_CALL(notified_object_, NotifyAboutLoggingActivity()); + router_.RegisterReceiver(&receiver_); + EXPECT_TRUE(manager_->IsLoggingActive()); + + // After flushing the buffering log manager, text should be passed. + EXPECT_CALL(receiver_, LogEntry(JsonHasText(kTestText))).Times(2); + buffering_manager_->Flush(*manager_); + + // Flushing a second time has no effect because the buffer is now empty. + EXPECT_CALL(receiver_, LogEntry(JsonHasText(kTestText))).Times(0); + buffering_manager_->Flush(*manager_); + + // After logging to the buffering log manager and flushing it again, text + // should be passed. + LOG_AF(*buffering_manager_) << kTestText; + LOG_AF(*buffering_manager_) << kTestText; + EXPECT_CALL(receiver_, LogEntry(JsonHasText(kTestText))).Times(2); + buffering_manager_->Flush(*manager_); + + EXPECT_CALL(notified_object_, NotifyAboutLoggingActivity()); + router_.UnregisterReceiver(&receiver_); +} + TEST_F(LogManagerTest, NullCallbackWillNotCrash) { manager_ = LogManager::Create(&router_, base::NullCallback()); router_.RegisterReceiver(&receiver_);
diff --git a/components/autofill/core/browser/logging/log_router.cc b/components/autofill/core/browser/logging/log_router.cc index 1f11210..d1d61e5b 100644 --- a/components/autofill/core/browser/logging/log_router.cc +++ b/components/autofill/core/browser/logging/log_router.cc
@@ -41,13 +41,13 @@ receiver.LogEntry(node); } -bool LogRouter::RegisterManager(LogManager* manager) { +bool LogRouter::RegisterManager(RoutingLogManager* manager) { DCHECK(manager); managers_.AddObserver(manager); return !receivers_.empty(); } -void LogRouter::UnregisterManager(LogManager* manager) { +void LogRouter::UnregisterManager(RoutingLogManager* manager) { DCHECK(managers_.HasObserver(manager)); managers_.RemoveObserver(manager); } @@ -55,7 +55,7 @@ void LogRouter::RegisterReceiver(LogReceiver* receiver) { DCHECK(receiver); if (receivers_.empty()) { - for (LogManager& manager : managers_) + for (RoutingLogManager& manager : managers_) manager.OnLogRouterAvailabilityChanged(true); } receivers_.AddObserver(receiver); @@ -65,7 +65,7 @@ DCHECK(receivers_.HasObserver(receiver)); receivers_.RemoveObserver(receiver); if (receivers_.empty()) { - for (LogManager& manager : managers_) + for (RoutingLogManager& manager : managers_) manager.OnLogRouterAvailabilityChanged(false); } }
diff --git a/components/autofill/core/browser/logging/log_router.h b/components/autofill/core/browser/logging/log_router.h index 9694bdf..0925dd0 100644 --- a/components/autofill/core/browser/logging/log_router.h +++ b/components/autofill/core/browser/logging/log_router.h
@@ -14,7 +14,7 @@ namespace autofill { -class LogManager; +class RoutingLogManager; class LogReceiver; // The router stands between LogManager and LogReceiver instances. Both managers @@ -45,9 +45,9 @@ // The managers must register to be notified about whether there are some // receivers or not. RegisterManager adds |manager| to the right observer list // and returns true iff there are some receivers registered. - bool RegisterManager(LogManager* manager); + bool RegisterManager(RoutingLogManager* manager); // Remove |manager| from the observers list. - void UnregisterManager(LogManager* manager); + void UnregisterManager(RoutingLogManager* manager); // The receivers must register to get updates with new logs in the future. void RegisterReceiver(LogReceiver* receiver); @@ -58,7 +58,7 @@ // Observer lists for managers and receivers. The |true| in the template // specialisation means that they will check that all observers were removed // on destruction. - base::ObserverList<LogManager, true>::Unchecked managers_; + base::ObserverList<RoutingLogManager, true>::Unchecked managers_; base::ObserverList<LogReceiver, true>::Unchecked receivers_; };
diff --git a/components/autofill/core/browser/logging/stub_log_manager.h b/components/autofill/core/browser/logging/stub_log_manager.h index ae8e9ff..003c202 100644 --- a/components/autofill/core/browser/logging/stub_log_manager.h +++ b/components/autofill/core/browser/logging/stub_log_manager.h
@@ -10,7 +10,7 @@ namespace autofill { // Use this in tests only, to provide a no-op implementation of LogManager. -class StubLogManager : public LogManager { +class StubLogManager : public RoutingLogManager { public: StubLogManager() = default;
diff --git a/components/autofill/core/browser/merchant_promo_code_manager_unittest.cc b/components/autofill/core/browser/merchant_promo_code_manager_unittest.cc index 8d75fbb..541c1f5 100644 --- a/components/autofill/core/browser/merchant_promo_code_manager_unittest.cc +++ b/components/autofill/core/browser/merchant_promo_code_manager_unittest.cc
@@ -25,9 +25,6 @@ namespace autofill { -using FieldPrediction = - AutofillQueryResponse::FormSuggestion::FieldSuggestion::FieldPrediction; - namespace { class MockSuggestionsHandler @@ -85,10 +82,8 @@ // Adds a promo code focused field to the suggestions context. void AddPromoCodeFocusedFieldToSuggestionsContext(SuggestionsContext* out) { - FieldPrediction merchant_promo_code_field_prediction; - merchant_promo_code_field_prediction.set_type(MERCHANT_PROMO_CODE); autofill_field_.set_server_predictions( - {merchant_promo_code_field_prediction}); + {::autofill::test::CreateFieldPrediction(MERCHANT_PROMO_CODE)}); out->focused_field = &autofill_field_; }
diff --git a/components/autofill/core/browser/metrics/autofill_metrics_unittest.cc b/components/autofill/core/browser/metrics/autofill_metrics_unittest.cc index 6afc999..fd2afd4 100644 --- a/components/autofill/core/browser/metrics/autofill_metrics_unittest.cc +++ b/components/autofill/core/browser/metrics/autofill_metrics_unittest.cc
@@ -85,6 +85,7 @@ #endif using ::autofill::metrics::kTestGuid; +using ::autofill::test::AddFieldPredictionToForm; using ::base::ASCIIToUTF16; using ::base::Bucket; using ::base::BucketsAre; @@ -1447,18 +1448,6 @@ false}}}); } -namespace { -void AddFieldSuggestionToForm( - AutofillQueryResponse_FormSuggestion* form_suggestion, - FormFieldData field_data, - ServerFieldType field_type) { - auto* field_suggestion = form_suggestion->add_field_suggestions(); - field_suggestion->set_field_signature( - CalculateFieldSignatureForField(field_data).value()); - field_suggestion->add_predictions()->set_type(field_type); -} -} // namespace - // Test that we log the address line fields whose server types are rationalized TEST_F(AutofillMetricsTest, LogRepeatedAddressTypeRationalized) { FormData form = CreateEmptyForm(); @@ -1494,11 +1483,11 @@ AutofillQueryResponse response; auto* form_suggestion = response.add_form_suggestions(); - AddFieldSuggestionToForm(form_suggestion, form.fields[0], NAME_FULL); - AddFieldSuggestionToForm(form_suggestion, form.fields[1], - ADDRESS_HOME_STREET_ADDRESS); - AddFieldSuggestionToForm(form_suggestion, form.fields[2], - ADDRESS_HOME_STREET_ADDRESS); + AddFieldPredictionToForm(form.fields[0], NAME_FULL, form_suggestion); + AddFieldPredictionToForm(form.fields[1], ADDRESS_HOME_STREET_ADDRESS, + form_suggestion); + AddFieldPredictionToForm(form.fields[2], ADDRESS_HOME_STREET_ADDRESS, + form_suggestion); std::string response_string = SerializeAndEncode(response); FormStructure::ParseApiQueryResponse( @@ -1601,13 +1590,13 @@ AutofillQueryResponse response; auto* form_suggestion = response.add_form_suggestions(); - AddFieldSuggestionToForm(form_suggestion, form.fields[0], - ADDRESS_HOME_COUNTRY); - AddFieldSuggestionToForm(form_suggestion, form.fields[1], NAME_FULL); - AddFieldSuggestionToForm(form_suggestion, form.fields[2], - ADDRESS_HOME_COUNTRY); - AddFieldSuggestionToForm(form_suggestion, form.fields[3], - ADDRESS_HOME_COUNTRY); + AddFieldPredictionToForm(form.fields[0], ADDRESS_HOME_COUNTRY, + form_suggestion); + AddFieldPredictionToForm(form.fields[1], NAME_FULL, form_suggestion); + AddFieldPredictionToForm(form.fields[2], ADDRESS_HOME_COUNTRY, + form_suggestion); + AddFieldPredictionToForm(form.fields[3], ADDRESS_HOME_COUNTRY, + form_suggestion); std::string response_string = SerializeAndEncode(response); FormStructure::ParseApiQueryResponse( @@ -2265,13 +2254,13 @@ AutofillQueryResponse response; auto* form_suggestion = response.add_form_suggestions(); // Server response will match with autocomplete. - AddFieldSuggestionToForm(form_suggestion, form.fields[0], NAME_LAST); + AddFieldPredictionToForm(form.fields[0], NAME_LAST, form_suggestion); // Server response will NOT match with autocomplete. - AddFieldSuggestionToForm(form_suggestion, form.fields[1], NAME_FIRST); + AddFieldPredictionToForm(form.fields[1], NAME_FIRST, form_suggestion); // Server response will have no data. - AddFieldSuggestionToForm(form_suggestion, form.fields[2], NO_SERVER_DATA); + AddFieldPredictionToForm(form.fields[2], NO_SERVER_DATA, form_suggestion); // Not logged. - AddFieldSuggestionToForm(form_suggestion, form.fields[3], NAME_MIDDLE); + AddFieldPredictionToForm(form.fields[3], NAME_MIDDLE, form_suggestion); std::string response_string = SerializeAndEncode(response); base::HistogramTester histogram_tester; @@ -8407,29 +8396,17 @@ std::vector<FormStructure*> forms_; }; -namespace { -void AddFieldSuggestionToForm( - AutofillQueryResponse_FormSuggestion* form_suggestion, - FieldSignature field_signature, - int field_type) { - auto* field_suggestion = form_suggestion->add_field_suggestions(); - field_suggestion->set_field_signature(field_signature.value()); - field_suggestion->add_predictions()->set_type(field_type); -} -} // namespace - TEST_F(AutofillMetricsParseQueryResponseTest, ServerHasData) { AutofillQueryResponse response; auto* form_suggestion = response.add_form_suggestions(); - AddFieldSuggestionToForm(form_suggestion, - forms_[0]->field(0)->GetFieldSignature(), 7); - AddFieldSuggestionToForm(form_suggestion, - forms_[0]->field(1)->GetFieldSignature(), 30); + AddFieldPredictionToForm(*forms_[0]->field(0), NAME_FULL, form_suggestion); + AddFieldPredictionToForm(*forms_[0]->field(1), ADDRESS_HOME_LINE1, + form_suggestion); form_suggestion = response.add_form_suggestions(); - AddFieldSuggestionToForm(form_suggestion, - forms_[1]->field(0)->GetFieldSignature(), 9); - AddFieldSuggestionToForm(form_suggestion, - forms_[1]->field(1)->GetFieldSignature(), 0); + AddFieldPredictionToForm(*forms_[1]->field(0), EMAIL_ADDRESS, + form_suggestion); + AddFieldPredictionToForm(*forms_[1]->field(1), NO_SERVER_DATA, + form_suggestion); std::string response_string = SerializeAndEncode(response); base::HistogramTester histogram_tester; @@ -8446,15 +8423,15 @@ TEST_F(AutofillMetricsParseQueryResponseTest, OneFormNoServerData) { AutofillQueryResponse response; auto* form_suggestion = response.add_form_suggestions(); - AddFieldSuggestionToForm(form_suggestion, - forms_[0]->field(0)->GetFieldSignature(), 0); - AddFieldSuggestionToForm(form_suggestion, - forms_[0]->field(1)->GetFieldSignature(), 0); + AddFieldPredictionToForm(*forms_[0]->field(0), NO_SERVER_DATA, + form_suggestion); + AddFieldPredictionToForm(*forms_[0]->field(1), NO_SERVER_DATA, + form_suggestion); form_suggestion = response.add_form_suggestions(); - AddFieldSuggestionToForm(form_suggestion, - forms_[1]->field(0)->GetFieldSignature(), 9); - AddFieldSuggestionToForm(form_suggestion, - forms_[1]->field(1)->GetFieldSignature(), 0); + AddFieldPredictionToForm(*forms_[1]->field(0), EMAIL_ADDRESS, + form_suggestion); + AddFieldPredictionToForm(*forms_[1]->field(1), NO_SERVER_DATA, + form_suggestion); std::string response_string = SerializeAndEncode(response); base::HistogramTester histogram_tester; FormStructure::ParseApiQueryResponse(response_string, forms_, @@ -8472,9 +8449,8 @@ for (int form_idx = 0; form_idx < 2; ++form_idx) { auto* form_suggestion = response.add_form_suggestions(); for (int field_idx = 0; field_idx < 2; ++field_idx) { - AddFieldSuggestionToForm( - form_suggestion, - forms_[form_idx]->field(field_idx)->GetFieldSignature(), 0); + AddFieldPredictionToForm(*forms_[form_idx]->field(field_idx), + NO_SERVER_DATA, form_suggestion); } } @@ -8493,15 +8469,15 @@ TEST_F(AutofillMetricsParseQueryResponseTest, PartialNoServerData) { AutofillQueryResponse response; auto* form_suggestion = response.add_form_suggestions(); - AddFieldSuggestionToForm(form_suggestion, - forms_[0]->field(0)->GetFieldSignature(), 0); - AddFieldSuggestionToForm(form_suggestion, - forms_[0]->field(1)->GetFieldSignature(), 10); + AddFieldPredictionToForm(*forms_[0]->field(0), NO_SERVER_DATA, + form_suggestion); + AddFieldPredictionToForm(*forms_[0]->field(1), PHONE_HOME_NUMBER, + form_suggestion); form_suggestion = response.add_form_suggestions(); - AddFieldSuggestionToForm(form_suggestion, - forms_[1]->field(0)->GetFieldSignature(), 0); - AddFieldSuggestionToForm(form_suggestion, - forms_[1]->field(1)->GetFieldSignature(), 11); + AddFieldPredictionToForm(*forms_[1]->field(0), NO_SERVER_DATA, + form_suggestion); + AddFieldPredictionToForm(*forms_[1]->field(1), PHONE_HOME_CITY_CODE, + form_suggestion); std::string response_string = SerializeAndEncode(response); base::HistogramTester histogram_tester;
diff --git a/components/autofill/core/browser/personal_data_manager.cc b/components/autofill/core/browser/personal_data_manager.cc index 8d54d9e..0b514e9 100644 --- a/components/autofill/core/browser/personal_data_manager.cc +++ b/components/autofill/core/browser/personal_data_manager.cc
@@ -1685,7 +1685,7 @@ AutofillProfileSaveStrikeDatabase* PersonalDataManager::GetProfileSaveStrikeDatabase() { return const_cast<AutofillProfileSaveStrikeDatabase*>( - base::as_const(*this).GetProfileSaveStrikeDatabase()); + std::as_const(*this).GetProfileSaveStrikeDatabase()); } const AutofillProfileSaveStrikeDatabase* @@ -1696,7 +1696,7 @@ AutofillProfileUpdateStrikeDatabase* PersonalDataManager::GetProfileUpdateStrikeDatabase() { return const_cast<AutofillProfileUpdateStrikeDatabase*>( - base::as_const(*this).GetProfileUpdateStrikeDatabase()); + std::as_const(*this).GetProfileUpdateStrikeDatabase()); } const AutofillProfileUpdateStrikeDatabase*
diff --git a/components/autofill/core/browser/test_autofill_client.cc b/components/autofill/core/browser/test_autofill_client.cc index 0e0b5e11..308f486 100644 --- a/components/autofill/core/browser/test_autofill_client.cc +++ b/components/autofill/core/browser/test_autofill_client.cc
@@ -4,6 +4,8 @@ #include "components/autofill/core/browser/test_autofill_client.h" +#include <utility> + #include "base/command_line.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" @@ -69,7 +71,7 @@ } PrefService* TestAutofillClient::GetPrefs() { - return const_cast<PrefService*>(base::as_const(*this).GetPrefs()); + return const_cast<PrefService*>(std::as_const(*this).GetPrefs()); } const PrefService* TestAutofillClient::GetPrefs() const {
diff --git a/components/autofill_assistant/browser/public/password_change/proto/actions.proto b/components/autofill_assistant/browser/public/password_change/proto/actions.proto index e833fb0..920e1cd 100644 --- a/components/autofill_assistant/browser/public/password_change/proto/actions.proto +++ b/components/autofill_assistant/browser/public/password_change/proto/actions.proto
@@ -34,6 +34,13 @@ PROGRESS_STEP_END = 4; } +enum FlowType { + FLOW_TYPE_UNSPECIFIED = 0; + + FLOW_TYPE_PASSWORD_CHANGE = 1; + FLOW_TYPE_PASSWORD_RESET = 2; +} + // Represents a choice in a prompt-type action. message Choice { // The text shown on the chip/button. @@ -116,12 +123,20 @@ optional ProgressStep progress_step = 4; } +// Sets the flow type. The flow type is used to determine the correct completion +// screen. +message SetFlowTypeSpecification { + // The type of the current flow. + optional FlowType flow_type = 1; +} + // A wrapper around all available `password_change` specifications. message GenericPasswordChangeSpecification { oneof specification { BasePromptSpecification base_prompt = 1; UseGeneratedPasswordPromptSpecification use_generated_password_prompt = 2; UpdateSidePanelSpecification update_side_panel = 3; + SetFlowTypeSpecification set_flow_type = 4; } }
diff --git a/components/browser_ui/site_settings/android/java/src/org/chromium/components/browser_ui/site_settings/GroupedWebsitesSettings.java b/components/browser_ui/site_settings/android/java/src/org/chromium/components/browser_ui/site_settings/GroupedWebsitesSettings.java index 8b21d4e1..5eb8d19 100644 --- a/components/browser_ui/site_settings/android/java/src/org/chromium/components/browser_ui/site_settings/GroupedWebsitesSettings.java +++ b/components/browser_ui/site_settings/android/java/src/org/chromium/components/browser_ui/site_settings/GroupedWebsitesSettings.java
@@ -114,7 +114,13 @@ getSiteSettingsDelegate().getManagedPreferenceDelegate()) { @Override public boolean isPreferenceControlledByPolicy(Preference preference) { - return getSiteSettingsDelegate().isFirstPartySetsDataAccessManaged(); + for (var site : mSiteGroup.getWebsites()) { + if (getSiteSettingsDelegate().isPartOfManagedFirstPartySet( + site.getAddress().getOrigin())) { + return true; + } + } + return false; } }); }
diff --git a/components/browser_ui/site_settings/android/java/src/org/chromium/components/browser_ui/site_settings/SingleWebsiteSettings.java b/components/browser_ui/site_settings/android/java/src/org/chromium/components/browser_ui/site_settings/SingleWebsiteSettings.java index 68006b6b..18e5ebc 100644 --- a/components/browser_ui/site_settings/android/java/src/org/chromium/components/browser_ui/site_settings/SingleWebsiteSettings.java +++ b/components/browser_ui/site_settings/android/java/src/org/chromium/components/browser_ui/site_settings/SingleWebsiteSettings.java
@@ -845,7 +845,8 @@ getSiteSettingsDelegate().getManagedPreferenceDelegate()) { @Override public boolean isPreferenceControlledByPolicy(Preference preference) { - return getSiteSettingsDelegate().isFirstPartySetsDataAccessManaged(); + return getSiteSettingsDelegate().isPartOfManagedFirstPartySet( + mSite.getAddress().getOrigin()); } }); }
diff --git a/components/commerce/core/commerce_feature_list.cc b/components/commerce/core/commerce_feature_list.cc index b899bba..7d99fee3 100644 --- a/components/commerce/core/commerce_feature_list.cc +++ b/components/commerce/core/commerce_feature_list.cc
@@ -125,7 +125,7 @@ // Params use for Discount Consent v2. BASE_FEATURE(kDiscountConsentV2, "DiscountConsentV2", - base::FEATURE_ENABLED_BY_DEFAULT); + base::FEATURE_DISABLED_BY_DEFAULT); BASE_FEATURE(kCommerceHintAndroid, "CommerceHintAndroid", @@ -140,7 +140,7 @@ "discount-consent-ntp-variation"; const base::FeatureParam<int> kNtpChromeCartModuleDiscountConsentNtpVariation{ &commerce::kDiscountConsentV2, - kNtpChromeCartModuleDiscountConsentNtpVariationParam, 4}; + kNtpChromeCartModuleDiscountConsentNtpVariationParam, 0}; const char kNtpChromeCartModuleDiscountConsentReshowTimeParam[] = "discount-consent-ntp-reshow-time"; const base::FeatureParam<base::TimeDelta> @@ -177,7 +177,7 @@ kNtpChromeCartModuleDiscountConsentNtpStepOneUseStaticContent{ &commerce::kDiscountConsentV2, kNtpChromeCartModuleDiscountConsentNtpStepOneUseStaticContentParam, - true}; + false}; const char kNtpChromeCartModuleDiscountConsentNtpStepOneStaticContentParam[] = "step-one-static-content"; const base::FeatureParam<std::string>
diff --git a/components/commerce_strings.grdp b/components/commerce_strings.grdp index 8039018..f4fac93 100644 --- a/components/commerce_strings.grdp +++ b/components/commerce_strings.grdp
@@ -3,7 +3,6 @@ <!-- Desktop only --> <if expr="not is_android and not is_ios"> <!-- Discount consent strings --> - <!-- TODO(crbug.com/1368330): Delete the following strings. --> <message name="IDS_DISCOUNT_CONTEXTUAL_CONSENT_TITLE" desc="The title shown on the consent bubble for getting discount."> Get discount on <ph name="MERCHANT_NAME">$1</ph> and more </message> @@ -25,18 +24,17 @@ <message name="IDS_DISCOUNT_CONTEXTUAL_CONSENT_ACCEPTED_CONFIRMATION_DONE" desc="The text shown on the consent confirmation bubble bubble. User can click this button to close the bubble."> Done </message> - <!-- Discount consent strings --> - <message name="IDS_NATIVE_NTP_CART_DISCOUNT_CONSENT_ACCEPT_BUTTON" desc="Text shown on the accept button of the consent dialog. By clicking this button, users has chosen to accept the consent to let Google find discounts for your carts."> + <!-- TODO(meiliang@): Use the final approved strings and remove the translateable tag. --> + <!-- These strings can skip translation because the feature is targeted en-us locale. Only the + en-us user can access the feature UI. --> + <message name="IDS_NATIVE_NTP_CART_DISCOUNT_CONSENT_ACCEPT_BUTTON" translateable="false" desc="Text shown on the accept button of the consent dialog. By clicking this button, users has chosen to accept the consent."> Yes, I'm in </message> - <message name="IDS_NATIVE_NTP_CART_DISCOUNT_CONSENT_TITLE" desc="The title shown on the native consent dialog for getting discount."> - Let Google help you find discounts for your carts + <message name="IDS_NATIVE_NTP_CART_DISCOUNT_CONSENT_TITLE" translateable="false" desc="The title shown on the native consent dialog for getting discount. Note: This is intentionally left blank. No translation is required."> + Get discounts on your carts & when you shop online </message> - <message name="IDS_NATIVE_NTP_CART_DISCOUNT_CONSENT_BODY" desc="The actual consent descrition that shows in the native consent dialog."> - Let Google use your carts to search for personalized discounts. When available, discounts will automatically show up on your carts. - </message> - <message name="IDS_NTP_CART_DISCOUNT_STEP_ONE_CONTENT" desc="Text shown in the consent card within the cart module. This is the first step of the discount consent flow."> - Let Google help you find discounts for your carts + <message name="IDS_NATIVE_NTP_CART_DISCOUNT_CONSENT_BODY" translateable="false" desc="The actual consent descrition that shows in the native consent dialog. Note: This is intentionally left blank. No translation is required."> + Let Google find personalized discounts on your carts and on online stores you visit. When available, discounts will automatically show up on your carts and on sites. </message> <!-- For Desktop Price Tracking -->
diff --git a/components/commerce_strings_grdp/IDS_NATIVE_NTP_CART_DISCOUNT_CONSENT_ACCEPT_BUTTON.png.sha1 b/components/commerce_strings_grdp/IDS_NATIVE_NTP_CART_DISCOUNT_CONSENT_ACCEPT_BUTTON.png.sha1 deleted file mode 100644 index aba059f..0000000 --- a/components/commerce_strings_grdp/IDS_NATIVE_NTP_CART_DISCOUNT_CONSENT_ACCEPT_BUTTON.png.sha1 +++ /dev/null
@@ -1 +0,0 @@ -fe8df36aafa46daddbbb72714f5e274853f52057 \ No newline at end of file
diff --git a/components/commerce_strings_grdp/IDS_NATIVE_NTP_CART_DISCOUNT_CONSENT_BODY.png.sha1 b/components/commerce_strings_grdp/IDS_NATIVE_NTP_CART_DISCOUNT_CONSENT_BODY.png.sha1 deleted file mode 100644 index 5f8b8a2..0000000 --- a/components/commerce_strings_grdp/IDS_NATIVE_NTP_CART_DISCOUNT_CONSENT_BODY.png.sha1 +++ /dev/null
@@ -1 +0,0 @@ -fe8df36aafa46daddbbb72714f5e274853f52057
diff --git a/components/commerce_strings_grdp/IDS_NATIVE_NTP_CART_DISCOUNT_CONSENT_TITLE.png.sha1 b/components/commerce_strings_grdp/IDS_NATIVE_NTP_CART_DISCOUNT_CONSENT_TITLE.png.sha1 deleted file mode 100644 index 5f8b8a2..0000000 --- a/components/commerce_strings_grdp/IDS_NATIVE_NTP_CART_DISCOUNT_CONSENT_TITLE.png.sha1 +++ /dev/null
@@ -1 +0,0 @@ -fe8df36aafa46daddbbb72714f5e274853f52057
diff --git a/components/commerce_strings_grdp/IDS_NTP_CART_DISCOUNT_STEP_ONE_CONTENT.png.sha1 b/components/commerce_strings_grdp/IDS_NTP_CART_DISCOUNT_STEP_ONE_CONTENT.png.sha1 deleted file mode 100644 index af69834..0000000 --- a/components/commerce_strings_grdp/IDS_NTP_CART_DISCOUNT_STEP_ONE_CONTENT.png.sha1 +++ /dev/null
@@ -1 +0,0 @@ -2b0a4f33c7dac6aeee0f6edc0315cb590df15dc3 \ No newline at end of file
diff --git a/components/device_signals/core/common/signals_constants.cc b/components/device_signals/core/common/signals_constants.cc index 562ccbf..7b58679 100644 --- a/components/device_signals/core/common/signals_constants.cc +++ b/components/device_signals/core/common/signals_constants.cc
@@ -61,10 +61,6 @@ // Name of the signal for getting information about the IMEI. const char kImei[] = "imei"; -// Name of the signal for getting information about the ip address on the -// device. -const char kIpAddress[] = "ipAddress"; - // MAC addresses of the device. const char kMacAddresses[] = "macAddresses";
diff --git a/components/device_signals/core/common/signals_constants.h b/components/device_signals/core/common/signals_constants.h index 878eca3..09b133ad 100644 --- a/components/device_signals/core/common/signals_constants.h +++ b/components/device_signals/core/common/signals_constants.h
@@ -25,7 +25,6 @@ extern const char kDeviceEnrollmentDomain[]; extern const char kOsFirewall[]; extern const char kImei[]; -extern const char kIpAddress[]; extern const char kMacAddresses[]; extern const char kMeid[]; extern const char kOs[];
diff --git a/components/exo/shell_surface.cc b/components/exo/shell_surface.cc index 9607fc6c..cf67fc6 100644 --- a/components/exo/shell_surface.cc +++ b/components/exo/shell_surface.cc
@@ -402,11 +402,6 @@ } } -void ShellSurface::SetUseImmersiveForFullscreen(bool value) { - ShellSurfaceBase::SetUseImmersiveForFullscreen(value); - Configure(); -} - //////////////////////////////////////////////////////////////////////////////// // aura::WindowObserver overrides:
diff --git a/components/exo/shell_surface.h b/components/exo/shell_surface.h index e89fa492..2aa0453 100644 --- a/components/exo/shell_surface.h +++ b/components/exo/shell_surface.h
@@ -114,7 +114,6 @@ void InitializeWindowState(ash::WindowState* window_state) override; absl::optional<gfx::Rect> GetWidgetBounds() const override; gfx::Point GetSurfaceOrigin() const override; - void SetUseImmersiveForFullscreen(bool value) override; // Overridden from aura::WindowObserver: void OnWindowBoundsChanged(aura::Window* window,
diff --git a/components/exo/shell_surface_unittest.cc b/components/exo/shell_surface_unittest.cc index c19e912..62150fb 100644 --- a/components/exo/shell_surface_unittest.cc +++ b/components/exo/shell_surface_unittest.cc
@@ -2701,25 +2701,4 @@ EXPECT_EQ(times_configured, 1); } -TEST_F(ShellSurfaceTest, SetImmersiveModeTriggersConfigure) { - int times_configured = 0; - auto test_callback = base::BindRepeating( - [](int* times_configured, const gfx::Rect&, - chromeos::WindowStateType new_type, bool, bool, - const gfx::Vector2d&) -> uint32_t { - ++(*times_configured); - return 0; - }, - ×_configured); - - std::unique_ptr<ShellSurface> shell_surface = - test::ShellSurfaceBuilder({1, 1}).BuildShellSurface(); - - shell_surface->set_configure_callback(test_callback); - - shell_surface->SetUseImmersiveForFullscreen(true); - - EXPECT_EQ(times_configured, 1); -} - } // namespace exo
diff --git a/components/exo/wayland/protocol/aura-shell.xml b/components/exo/wayland/protocol/aura-shell.xml index 93010a1d..5ab00a5 100644 --- a/components/exo/wayland/protocol/aura-shell.xml +++ b/components/exo/wayland/protocol/aura-shell.xml
@@ -24,7 +24,7 @@ DEALINGS IN THE SOFTWARE. </copyright> - <interface name="zaura_shell" version="43"> + <interface name="zaura_shell" version="42"> <description summary="aura_shell"> The global interface exposing aura shell capabilities is used to instantiate an interface extension for a wl_surface object. @@ -296,7 +296,7 @@ <enum name="fullscreen_mode"> <description summary="Specifies the behavior of the surface in fullscreen."> - [Deprecated] Possible windowing system behaviors if this surface were to go + Possible windowing system behaviors if this surface were to go fullscreen. </description> <entry @@ -312,7 +312,6 @@ <request name="set_fullscreen_mode" since="10"> <description summary="Sets the behavior of the surface in fullscreen."> - [Deprecated] Use the set_fullscreen_mode in the toplevel interface. Suggests how the windowing system should behave if this surface were to go fullscreen. Does not make the surface fullscreen. @@ -685,7 +684,7 @@ </request> </interface> - <interface name="zaura_toplevel" version="43"> + <interface name="zaura_toplevel" version="42"> <description summary="aura shell interface to the toplevel shell"> An interface to the toplevel shell, which allows the client to access shell specific functionality. @@ -922,7 +921,7 @@ <arg name="x" type="int"/> <arg name="y" type="int"/> <arg name="output" type="object" interface="wl_output" allow-null="true" - summary="output to contain the surface"/> + summary="output to contain the surface"/> </request> <request name="activate" since="42"> @@ -941,32 +940,6 @@ if it deems the client to be misbehaving. </description> </request> - - <!-- Version 43 additions --> - <enum name="fullscreen_mode"> - <description - summary="Specifies the behavior of the surface in fullscreen."> - Possible windowing system behaviors if this surface were to go - fullscreen. - </description> - <entry - name="plain" - value="0" - summary="user cannot access system UIs using mouse/touches"/> - <entry - name="immersive" - value="1" - summary="user can access system UIs such as the shelf and window frame - by pointing to, or swiping over, the screen edge"/> - </enum> - - <request name="set_fullscreen_mode" since="43"> - <description summary="Sets the behavior of the surface in fullscreen."> - Suggests how the windowing manager should behave if this surface were - to go fullscreen. Does not make the surface fullscreen. - </description> - <arg name="mode" type="uint" enum="fullscreen_mode"/> - </request> </interface> <interface name="zaura_popup" version="38">
diff --git a/components/exo/wayland/zaura_shell.cc b/components/exo/wayland/zaura_shell.cc index 410f5ed..5530233 100644 --- a/components/exo/wayland/zaura_shell.cc +++ b/components/exo/wayland/zaura_shell.cc
@@ -183,9 +183,9 @@ GetUserDataAs<AuraSurface>(resource)->DrawAttention(); } -void aura_surface_set_fullscreen_mode_deprecated(wl_client* client, - wl_resource* resource, - uint32_t mode) { +void aura_surface_set_fullscreen_mode(wl_client* client, + wl_resource* resource, + uint32_t mode) { GetUserDataAs<AuraSurface>(resource)->SetFullscreenMode(mode); } @@ -285,7 +285,7 @@ aura_surface_unset_occlusion_tracking, aura_surface_activate, aura_surface_draw_attention, - aura_surface_set_fullscreen_mode_deprecated, + aura_surface_set_fullscreen_mode, aura_surface_set_client_surface_str_id, aura_surface_set_server_start_resize, aura_surface_intent_to_snap, @@ -738,22 +738,6 @@ shell_surface_->RequestDeactivation(); } -bool IsImmersive(uint32_t mode) { - switch (mode) { - case ZAURA_TOPLEVEL_FULLSCREEN_MODE_PLAIN: - return false; - case ZAURA_TOPLEVEL_FULLSCREEN_MODE_IMMERSIVE: - return true; - default: - VLOG(2) << "Unknown immersive mode: " << mode; - return false; - } -} - -void AuraToplevel::SetFullscreenMode(uint32_t mode) { - shell_surface_->SetUseImmersiveForFullscreen(IsImmersive(mode)); -} - void AuraToplevel::SetClientUsesScreenCoordinates() { supports_window_bounds_ = true; shell_surface_->set_client_supports_window_bounds(true); @@ -1262,12 +1246,6 @@ GetUserDataAs<AuraToplevel>(resource)->Deactivate(); } -void aura_toplevel_set_fullscreen_mode(wl_client* client, - wl_resource* resource, - uint32_t mode) { - GetUserDataAs<AuraToplevel>(resource)->SetFullscreenMode(mode); -} - const struct zaura_toplevel_interface aura_toplevel_implementation = { aura_toplevel_set_orientation_lock, aura_toplevel_surface_submission_in_pixel_coordinates, @@ -1285,7 +1263,6 @@ aura_toplevel_set_origin, aura_toplevel_activate, aura_toplevel_deactivate, - aura_toplevel_set_fullscreen_mode, }; void aura_popup_surface_submission_in_pixel_coordinates(wl_client* client,
diff --git a/components/exo/wayland/zaura_shell.h b/components/exo/wayland/zaura_shell.h index 303993bf..a2e42f6e 100644 --- a/components/exo/wayland/zaura_shell.h +++ b/components/exo/wayland/zaura_shell.h
@@ -26,7 +26,7 @@ namespace wayland { class SerialTracker; -constexpr uint32_t kZAuraShellVersion = 43; +constexpr uint32_t kZAuraShellVersion = 42; // Adds bindings to the Aura Shell. Normally this implies Ash on ChromeOS // builds. On non-ChromeOS builds the protocol provides access to Aura windowing @@ -136,7 +136,6 @@ void SetZOrder(ui::ZOrderLevel z_order); void Activate(); void Deactivate(); - void SetFullscreenMode(uint32_t mode); ShellSurface* shell_surface_; SerialTracker* const serial_tracker_;
diff --git a/components/keyed_service/core/dependency_graph.cc b/components/keyed_service/core/dependency_graph.cc index 232295f..249ee94 100644 --- a/components/keyed_service/core/dependency_graph.cc +++ b/components/keyed_service/core/dependency_graph.cc
@@ -11,6 +11,7 @@ #include "base/containers/circular_deque.h" #include "base/containers/cxx20_erase.h" +#include "base/ranges/algorithm.h" #include "base/strings/string_piece.h" namespace { @@ -37,9 +38,9 @@ } // namespace -DependencyGraph::DependencyGraph() {} +DependencyGraph::DependencyGraph() = default; -DependencyGraph::~DependencyGraph() {} +DependencyGraph::~DependencyGraph() = default; void DependencyGraph::AddNode(DependencyNode* node) { all_nodes_.push_back(node); @@ -49,15 +50,9 @@ void DependencyGraph::RemoveNode(DependencyNode* node) { base::Erase(all_nodes_, node); - // Remove all dependency edges that contain this node. - auto it = edges_.begin(); - while (it != edges_.end()) { - auto temp = it; - ++it; - - if (temp->first == node || temp->second == node) - edges_.erase(temp); - } + base::EraseIf(edges_, [node](const auto& edge) { + return edge.first == node || edge.second == node; + }); construction_order_.clear(); } @@ -113,13 +108,8 @@ it++; edges.erase(temp); - bool has_incoming_edges = false; - for (auto jt = edges.begin(); jt != edges.end(); ++jt) { - if (jt->second == dest) { - has_incoming_edges = true; - break; - } - } + bool has_incoming_edges = base::ranges::any_of( + edges, [dest](const auto& edge) { return edge.second == dest; }); if (!has_incoming_edges) queue.push_back(dest);
diff --git a/components/omnibox/browser/location_bar_model.h b/components/omnibox/browser/location_bar_model.h index b1b185e..aa43596 100644 --- a/components/omnibox/browser/location_bar_model.h +++ b/components/omnibox/browser/location_bar_model.h
@@ -52,7 +52,8 @@ // UMA opted-in users. Examines the user's profile to determine if the // current page is the user's home page. virtual metrics::OmniboxEventProto::PageClassification GetPageClassification( - OmniboxFocusSource focus_source) = 0; + OmniboxFocusSource focus_source, + bool is_prefetch = false) = 0; // Returns the id of the icon to show to the left of the address, based on the // current URL. When search term replacement is active, this returns a search
diff --git a/components/omnibox/browser/location_bar_model_delegate.h b/components/omnibox/browser/location_bar_model_delegate.h index 2c86bcc3..9f68afd 100644 --- a/components/omnibox/browser/location_bar_model_delegate.h +++ b/components/omnibox/browser/location_bar_model_delegate.h
@@ -26,6 +26,8 @@ // Delegate which is used by LocationBarModel class. class LocationBarModelDelegate { public: + LocationBarModelDelegate() = default; + // Formats |url| using AutocompleteInput::FormattedStringWithEquivalentMeaning // providing an appropriate AutocompleteSchemeClassifier for the embedder. virtual std::u16string FormattedStringWithEquivalentMeaning(
diff --git a/components/omnibox/browser/location_bar_model_impl.cc b/components/omnibox/browser/location_bar_model_impl.cc index 1c14654..26b9068 100644 --- a/components/omnibox/browser/location_bar_model_impl.cc +++ b/components/omnibox/browser/location_bar_model_impl.cc
@@ -159,37 +159,47 @@ } OmniboxEventProto::PageClassification -LocationBarModelImpl::GetPageClassification(OmniboxFocusSource focus_source) { +LocationBarModelImpl::GetPageClassification(OmniboxFocusSource focus_source, + bool is_prefetch) { // We may be unable to fetch the current URL during startup or shutdown when // the omnibox exists but there is no attached page. GURL gurl; - if (!delegate_->GetURL(&gurl)) + if (!delegate_->GetURL(&gurl)) { return OmniboxEventProto::OTHER; - + } if (delegate_->IsNewTabPage()) { // Note that we treat OMNIBOX as the source if focus_source_ is INVALID, // i.e., if input isn't actually in progress. - return (focus_source == OmniboxFocusSource::FAKEBOX) + return is_prefetch ? OmniboxEventProto::NTP_ZPS_PREFETCH + : focus_source == OmniboxFocusSource::FAKEBOX ? OmniboxEventProto::INSTANT_NTP_WITH_FAKEBOX_AS_STARTING_FOCUS : OmniboxEventProto::INSTANT_NTP_WITH_OMNIBOX_AS_STARTING_FOCUS; } - if (!gurl.is_valid()) + if (!gurl.is_valid()) { return OmniboxEventProto::INVALID_SPEC; - if (delegate_->IsNewTabPageURL(gurl)) - return OmniboxEventProto::NTP; - if (gurl.spec() == url::kAboutBlankURL) + } + if (delegate_->IsNewTabPageURL(gurl)) { + return is_prefetch ? OmniboxEventProto::NTP_ZPS_PREFETCH + : OmniboxEventProto::NTP; + } + if (gurl.spec() == url::kAboutBlankURL) { return OmniboxEventProto::BLANK; - if (delegate_->IsHomePage(gurl)) + } + if (delegate_->IsHomePage(gurl)) { return OmniboxEventProto::HOME_PAGE; + } TemplateURLService* template_url_service = delegate_->GetTemplateURLService(); if (template_url_service && template_url_service->IsSearchResultsPageFromDefaultSearchProvider( gurl)) { - return OmniboxEventProto::SEARCH_RESULT_PAGE_NO_SEARCH_TERM_REPLACEMENT; + return is_prefetch ? OmniboxEventProto::SRP_ZPS_PREFETCH + : OmniboxEventProto:: + SEARCH_RESULT_PAGE_NO_SEARCH_TERM_REPLACEMENT; } - return OmniboxEventProto::OTHER; + return is_prefetch ? OmniboxEventProto::OTHER_ZPS_PREFETCH + : OmniboxEventProto::OTHER; } const gfx::VectorIcon& LocationBarModelImpl::GetVectorIcon() const {
diff --git a/components/omnibox/browser/location_bar_model_impl.h b/components/omnibox/browser/location_bar_model_impl.h index 08e5428..f8503c1b3 100644 --- a/components/omnibox/browser/location_bar_model_impl.h +++ b/components/omnibox/browser/location_bar_model_impl.h
@@ -39,7 +39,8 @@ security_state::SecurityLevel GetSecurityLevel() const override; net::CertStatus GetCertStatus() const override; metrics::OmniboxEventProto::PageClassification GetPageClassification( - OmniboxFocusSource focus_source) override; + OmniboxFocusSource focus_source, + bool is_prefetch = false) override; const gfx::VectorIcon& GetVectorIcon() const override; std::u16string GetSecureDisplayText() const override; std::u16string GetSecureAccessibilityText() const override;
diff --git a/components/omnibox/browser/location_bar_model_impl_unittest.cc b/components/omnibox/browser/location_bar_model_impl_unittest.cc index 577cf96a7..cf4ff71f 100644 --- a/components/omnibox/browser/location_bar_model_impl_unittest.cc +++ b/components/omnibox/browser/location_bar_model_impl_unittest.cc
@@ -13,6 +13,9 @@ #include "components/omnibox/browser/location_bar_model_delegate.h" #include "components/omnibox/browser/test_omnibox_client.h" #include "components/omnibox/common/omnibox_features.h" +#include "components/omnibox/common/omnibox_focus_state.h" +#include "components/search_engines/template_url_service.h" +#include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/gfx/color_palette.h" #include "ui/gfx/favicon_size.h" @@ -23,9 +26,15 @@ #include "components/vector_icons/vector_icons.h" // nogncheck #endif +using metrics::OmniboxEventProto; +using testing::_; +using testing::Invoke; +using testing::Return; +using testing::WithArg; + namespace { -class FakeLocationBarModelDelegate : public LocationBarModelDelegate { +class TestLocationBarModelDelegate : public LocationBarModelDelegate { public: void SetURL(const GURL& url) { url_ = url; } void SetShouldPreventElision(bool should_prevent_elision) { @@ -86,20 +95,28 @@ bool connection_info_initialized_ = true; }; +class MockLocationBarModelDelegate + : public testing::NiceMock<TestLocationBarModelDelegate> { + public: + ~MockLocationBarModelDelegate() override = default; + + // TestLocationBarModelDelegate: + MOCK_METHOD(bool, GetURL, (GURL * url), (override, const)); + MOCK_METHOD(bool, IsNewTabPage, (), (override, const)); + MOCK_METHOD(bool, IsNewTabPageURL, (const GURL& url), (override, const)); +}; + class LocationBarModelImplTest : public testing::Test { protected: - const GURL kValidSearchResultsPage = - GURL("https://www.google.com/search?q=foo+query"); - LocationBarModelImplTest() : model_(&delegate_, 1024) {} - FakeLocationBarModelDelegate* delegate() { return &delegate_; } + TestLocationBarModelDelegate* delegate() { return &delegate_; } LocationBarModelImpl* model() { return &model_; } private: base::test::TaskEnvironment task_environment_; - FakeLocationBarModelDelegate delegate_; + TestLocationBarModelDelegate delegate_; LocationBarModelImpl model_; }; @@ -200,4 +217,116 @@ #endif // BUILDFLAG(IS_IOS) +// Test that the expected page classification is returned. +TEST_F(LocationBarModelImplTest, GetPageClassification) { + MockLocationBarModelDelegate delegate; + LocationBarModelImpl model(&delegate, 0); + + // Simulate the page URL not being successfully retrieved. + EXPECT_CALL(delegate, GetURL(_)).WillRepeatedly(Return(false)); + + // Verify the page classification for prefetch and non-prefetch requests. + EXPECT_EQ(OmniboxEventProto::OTHER, + model.GetPageClassification(OmniboxFocusSource::OMNIBOX)); + EXPECT_EQ(OmniboxEventProto::OTHER, + model.GetPageClassification(OmniboxFocusSource::FAKEBOX)); + EXPECT_EQ(OmniboxEventProto::OTHER, + model.GetPageClassification(OmniboxFocusSource::OMNIBOX, + /*is_prefetch=*/true)); + EXPECT_EQ(OmniboxEventProto::OTHER, + model.GetPageClassification(OmniboxFocusSource::FAKEBOX, + /*is_prefetch=*/true)); + + // Simulate the page URL is being empty. + EXPECT_CALL(delegate, GetURL(_)).WillRepeatedly(Return(true)); + + // Verify the page classification for prefetch and non-prefetch requests. + EXPECT_EQ(OmniboxEventProto::INVALID_SPEC, + model.GetPageClassification(OmniboxFocusSource::OMNIBOX)); + EXPECT_EQ(OmniboxEventProto::INVALID_SPEC, + model.GetPageClassification(OmniboxFocusSource::FAKEBOX)); + EXPECT_EQ(OmniboxEventProto::INVALID_SPEC, + model.GetPageClassification(OmniboxFocusSource::OMNIBOX, + /*is_prefetch=*/true)); + EXPECT_EQ(OmniboxEventProto::INVALID_SPEC, + model.GetPageClassification(OmniboxFocusSource::FAKEBOX, + /*is_prefetch=*/true)); + + // Simulate the page being the 1P NTP. + EXPECT_CALL(delegate, GetURL(_)) + .WillRepeatedly(WithArg<0>(Invoke([](GURL* url) { + *url = GURL("https://foobar.com"); + return url->is_valid(); + }))); + EXPECT_CALL(delegate, IsNewTabPage()).WillRepeatedly(Return(true)); + + // Verify the page classification for prefetch and non-prefetch requests. + EXPECT_EQ(OmniboxEventProto::INSTANT_NTP_WITH_OMNIBOX_AS_STARTING_FOCUS, + model.GetPageClassification(OmniboxFocusSource::OMNIBOX)); + EXPECT_EQ(OmniboxEventProto::INSTANT_NTP_WITH_FAKEBOX_AS_STARTING_FOCUS, + model.GetPageClassification(OmniboxFocusSource::FAKEBOX)); + EXPECT_EQ(OmniboxEventProto::NTP_ZPS_PREFETCH, + model.GetPageClassification(OmniboxFocusSource::OMNIBOX, + /*is_prefetch=*/true)); + EXPECT_EQ(OmniboxEventProto::NTP_ZPS_PREFETCH, + model.GetPageClassification(OmniboxFocusSource::FAKEBOX, + /*is_prefetch=*/true)); + + // Simulate the page URL being chrome://newtab/. + EXPECT_CALL(delegate, IsNewTabPage()).WillRepeatedly(Return(false)); + EXPECT_CALL(delegate, IsNewTabPageURL(_)).WillRepeatedly(Return(true)); + + // Verify the page classification for prefetch and non-prefetch requests. + EXPECT_EQ(OmniboxEventProto::NTP, + model.GetPageClassification(OmniboxFocusSource::OMNIBOX)); + EXPECT_EQ(OmniboxEventProto::NTP, + model.GetPageClassification(OmniboxFocusSource::FAKEBOX)); + EXPECT_EQ(OmniboxEventProto::NTP_ZPS_PREFETCH, + model.GetPageClassification(OmniboxFocusSource::OMNIBOX, + /*is_prefetch=*/true)); + EXPECT_EQ(OmniboxEventProto::NTP_ZPS_PREFETCH, + model.GetPageClassification(OmniboxFocusSource::FAKEBOX, + /*is_prefetch=*/true)); + + // Simulate the page URL being successfully retrieved, and is the SRP. + EXPECT_CALL(delegate, GetURL(_)) + .WillRepeatedly(WithArg<0>(Invoke([&delegate](GURL* url) { + auto* turl_service = delegate.GetTemplateURLService(); + *url = turl_service->GenerateSearchURLForDefaultSearchProvider(u"foo"); + return url->is_valid(); + }))); + EXPECT_CALL(delegate, IsNewTabPageURL(_)).WillRepeatedly(Return(false)); + + // Verify the page classification for prefetch and non-prefetch requests. + EXPECT_EQ(OmniboxEventProto::SEARCH_RESULT_PAGE_NO_SEARCH_TERM_REPLACEMENT, + model.GetPageClassification(OmniboxFocusSource::OMNIBOX)); + EXPECT_EQ(OmniboxEventProto::SEARCH_RESULT_PAGE_NO_SEARCH_TERM_REPLACEMENT, + model.GetPageClassification(OmniboxFocusSource::FAKEBOX)); + EXPECT_EQ(OmniboxEventProto::SRP_ZPS_PREFETCH, + model.GetPageClassification(OmniboxFocusSource::OMNIBOX, + /*is_prefetch=*/true)); + EXPECT_EQ(OmniboxEventProto::SRP_ZPS_PREFETCH, + model.GetPageClassification(OmniboxFocusSource::FAKEBOX, + /*is_prefetch=*/true)); + + // Simulate the page URL being successfully retrieved, and is non-empty. + EXPECT_CALL(delegate, GetURL(_)) + .WillRepeatedly(WithArg<0>(Invoke([](GURL* url) { + *url = GURL("https://foobar.com"); + return url->is_valid(); + }))); + + // Verify the page classification for prefetch and non-prefetch requests. + EXPECT_EQ(OmniboxEventProto::OTHER, + model.GetPageClassification(OmniboxFocusSource::OMNIBOX)); + EXPECT_EQ(OmniboxEventProto::OTHER, + model.GetPageClassification(OmniboxFocusSource::FAKEBOX)); + EXPECT_EQ(OmniboxEventProto::OTHER_ZPS_PREFETCH, + model.GetPageClassification(OmniboxFocusSource::OMNIBOX, + /*is_prefetch=*/true)); + EXPECT_EQ(OmniboxEventProto::OTHER_ZPS_PREFETCH, + model.GetPageClassification(OmniboxFocusSource::FAKEBOX, + /*is_prefetch=*/true)); +} + } // namespace
diff --git a/components/omnibox/browser/omnibox_edit_model.cc b/components/omnibox/browser/omnibox_edit_model.cc index 9e9a070..e26da1f 100644 --- a/components/omnibox/browser/omnibox_edit_model.cc +++ b/components/omnibox/browser/omnibox_edit_model.cc
@@ -33,6 +33,7 @@ #include "components/omnibox/browser/autocomplete_classifier.h" #include "components/omnibox/browser/autocomplete_match_type.h" #include "components/omnibox/browser/autocomplete_provider.h" +#include "components/omnibox/browser/base_search_provider.h" #include "components/omnibox/browser/history_fuzzy_provider.h" #include "components/omnibox/browser/history_url_provider.h" #include "components/omnibox/browser/keyword_provider.h" @@ -655,6 +656,29 @@ omnibox_controller_->StartAutocomplete(input_); } +void OmniboxEditModel::StartPrefetch() { + auto page_classification = + controller()->GetLocationBarModel()->GetPageClassification( + OmniboxFocusSource::OMNIBOX, /*is_prefetch=*/true); + if (!OmniboxFieldTrial::IsZeroSuggestPrefetchingEnabledInContext( + page_classification)) { + return; + } + + const bool interaction_clobber_focus_type = + base::FeatureList::IsEnabled( + omnibox::kOmniboxOnClobberFocusTypeOnContent) && + !BaseSearchProvider::IsNTPPage(page_classification); + + AutocompleteInput input(u"", page_classification, + client()->GetSchemeClassifier()); + input.set_current_url(client()->GetURL()); + input.set_focus_type(interaction_clobber_focus_type + ? metrics::OmniboxFocusType::INTERACTION_CLOBBER + : metrics::OmniboxFocusType::INTERACTION_FOCUS); + autocomplete_controller()->StartPrefetch(input); +} + void OmniboxEditModel::StopAutocomplete() { autocomplete_controller()->Stop(true); }
diff --git a/components/omnibox/browser/omnibox_edit_model.h b/components/omnibox/browser/omnibox_edit_model.h index 97961db..5523c16 100644 --- a/components/omnibox/browser/omnibox_edit_model.h +++ b/components/omnibox/browser/omnibox_edit_model.h
@@ -194,6 +194,11 @@ void StartAutocomplete(bool has_selected_text, bool prevent_inline_autocomplete); + // Starts an autocomplete prefetch request so that zero-prefix providers can + // optionally start a prefetch request to warm up the their underlying + // service(s) and/or optionally cache their otherwise async response. + void StartPrefetch(); + // Closes the popup and cancels any pending asynchronous queries. void StopAutocomplete();
diff --git a/components/omnibox/browser/omnibox_field_trial.cc b/components/omnibox/browser/omnibox_field_trial.cc index a94048e..40fffbdc 100644 --- a/components/omnibox/browser/omnibox_field_trial.cc +++ b/components/omnibox/browser/omnibox_field_trial.cc
@@ -786,6 +786,22 @@ base::FeatureList::IsEnabled(omnibox::kZeroSuggestPrefetchingOnWeb); } +bool IsZeroSuggestPrefetchingEnabledInContext( + metrics::OmniboxEventProto::PageClassification page_classification) { + switch (page_classification) { + case metrics::OmniboxEventProto::NTP_ZPS_PREFETCH: + return base::FeatureList::IsEnabled(omnibox::kZeroSuggestPrefetching); + case metrics::OmniboxEventProto::SRP_ZPS_PREFETCH: + return base::FeatureList::IsEnabled( + omnibox::kZeroSuggestPrefetchingOnSRP); + case metrics::OmniboxEventProto::OTHER_ZPS_PREFETCH: + return base::FeatureList::IsEnabled( + omnibox::kZeroSuggestPrefetchingOnWeb); + default: + return false; + } +} + const base::FeatureParam<bool> kZeroSuggestIgnoreDuplicateVisits( &omnibox::kLocalHistorySuggestRevamp, "ZeroSuggestIgnoreDuplicateVisits",
diff --git a/components/omnibox/browser/omnibox_field_trial.h b/components/omnibox/browser/omnibox_field_trial.h index 5e9dfdb2..2fcfeb6 100644 --- a/components/omnibox/browser/omnibox_field_trial.h +++ b/components/omnibox/browser/omnibox_field_trial.h
@@ -523,6 +523,10 @@ // Returns true if any of the zero-suggest prefetching features are enabled. bool IsZeroSuggestPrefetchingEnabled(); +// Returns whether zero-suggest prefetching is enabled in the given context. +bool IsZeroSuggestPrefetchingEnabledInContext( + metrics::OmniboxEventProto::PageClassification page_classification); + // Whether duplicative visits should be ignored for local history zero-suggest. // A duplicative visit is a visit to the same search term in an interval smaller // than kAutocompleteDuplicateVisitIntervalThreshold.
diff --git a/components/omnibox/browser/omnibox_view.cc b/components/omnibox/browser/omnibox_view.cc index 1c10ad7..bdc88da 100644 --- a/components/omnibox/browser/omnibox_view.cc +++ b/components/omnibox/browser/omnibox_view.cc
@@ -261,11 +261,6 @@ model_->StopAutocomplete(); } -void OmniboxView::StartPrefetch(const AutocompleteInput& input) { - if (model_) - model_->autocomplete_controller()->StartPrefetch(input); -} - bool OmniboxView::IsImeShowingPopup() const { // Default to claiming that the IME is not showing a popup, since hiding the // omnibox dropdown is a bad user experience when we don't know for sure that
diff --git a/components/omnibox/browser/omnibox_view.h b/components/omnibox/browser/omnibox_view.h index 0c9d590..76d3ed3 100644 --- a/components/omnibox/browser/omnibox_view.h +++ b/components/omnibox/browser/omnibox_view.h
@@ -29,7 +29,6 @@ #include "ui/gfx/native_widget_types.h" #include "ui/gfx/range/range.h" -class AutocompleteInput; class GURL; class OmniboxEditController; class OmniboxViewMacTest; @@ -153,10 +152,6 @@ // defines a method with that name. virtual void CloseOmniboxPopup(); - // Starts an autocomplete prefetch query so those providers that benefit from - // it could perform a prefetch request and populate their caches. - virtual void StartPrefetch(const AutocompleteInput& input); - // Sets the focus to the omnibox. |is_user_initiated| is true when the user // explicitly focused the omnibox, and false when the omnibox was // automatically focused (like for browser startup or NTP load).
diff --git a/components/omnibox/browser/test_location_bar_model.cc b/components/omnibox/browser/test_location_bar_model.cc index 5a585ca..2e7185f 100644 --- a/components/omnibox/browser/test_location_bar_model.cc +++ b/components/omnibox/browser/test_location_bar_model.cc
@@ -47,7 +47,8 @@ } metrics::OmniboxEventProto::PageClassification -TestLocationBarModel::GetPageClassification(OmniboxFocusSource focus_source) { +TestLocationBarModel::GetPageClassification(OmniboxFocusSource focus_source, + bool is_prefetch) { return metrics::OmniboxEventProto::OTHER; } @@ -78,4 +79,4 @@ bool TestLocationBarModel::ShouldUseUpdatedConnectionSecurityIndicators() const { return false; -} \ No newline at end of file +}
diff --git a/components/omnibox/browser/test_location_bar_model.h b/components/omnibox/browser/test_location_bar_model.h index 861da61..508cf24 100644 --- a/components/omnibox/browser/test_location_bar_model.h +++ b/components/omnibox/browser/test_location_bar_model.h
@@ -32,7 +32,8 @@ security_state::SecurityLevel GetSecurityLevel() const override; net::CertStatus GetCertStatus() const override; metrics::OmniboxEventProto::PageClassification GetPageClassification( - OmniboxFocusSource focus_source) override; + OmniboxFocusSource focus_source, + bool is_prefetch = false) override; const gfx::VectorIcon& GetVectorIcon() const override; std::u16string GetSecureDisplayText() const override; std::u16string GetSecureAccessibilityText() const override;
diff --git a/components/omnibox/common/omnibox_features.cc b/components/omnibox/common/omnibox_features.cc index 3fada10..7ed7245a 100644 --- a/components/omnibox/common/omnibox_features.cc +++ b/components/omnibox/common/omnibox_features.cc
@@ -183,11 +183,13 @@ "OmniboxLocalZeroSuggestAgeThreshold", base::FEATURE_DISABLED_BY_DEFAULT); -// Used to enable sending INTERACTION_CLOBBER focus type for zero-prefix -// requests with an empty input on Web/SRP on Android platform. -BASE_FEATURE(kOmniboxOnClobberFocusTypeOnAndroid, - "OmniboxOnClobberFocusTypeOnAndroid", - base::FEATURE_DISABLED_BY_DEFAULT); +// Mainly used to enable sending INTERACTION_CLOBBER focus type for zero-prefix +// requests with an empty input on Web/SRP on Mobile. Enabled by default on +// Desktop because it is also used by Desktop in the cross-platform code in the +// OmniboxEditModel for triggering zero-suggest prefetching on Web/SRP. +BASE_FEATURE(kOmniboxOnClobberFocusTypeOnContent, + "OmniboxOnClobberFocusTypeOnContent", + enabled_by_default_desktop_only); // Enables on-focus zero-prefix suggestions on the NTP for signed-out users. BASE_FEATURE(kZeroSuggestOnNTPForSignedOutUsers,
diff --git a/components/omnibox/common/omnibox_features.h b/components/omnibox/common/omnibox_features.h index 884272c6..2be31a8 100644 --- a/components/omnibox/common/omnibox_features.h +++ b/components/omnibox/common/omnibox_features.h
@@ -49,7 +49,7 @@ BASE_DECLARE_FEATURE(kLocalHistorySuggestRevamp); BASE_DECLARE_FEATURE(kLocalHistoryZeroSuggestBeyondNTP); BASE_DECLARE_FEATURE(kOmniboxLocalZeroSuggestAgeThreshold); -BASE_DECLARE_FEATURE(kOmniboxOnClobberFocusTypeOnAndroid); +BASE_DECLARE_FEATURE(kOmniboxOnClobberFocusTypeOnContent); BASE_DECLARE_FEATURE(kZeroSuggestOnNTPForSignedOutUsers); BASE_DECLARE_FEATURE(kZeroSuggestPrefetching); BASE_DECLARE_FEATURE(kZeroSuggestPrefetchingOnSRP);
diff --git a/components/page_info/android/java/src/org/chromium/components/page_info/PageInfoCookiesController.java b/components/page_info/android/java/src/org/chromium/components/page_info/PageInfoCookiesController.java index 58ade37..9b8f6c9c 100644 --- a/components/page_info/android/java/src/org/chromium/components/page_info/PageInfoCookiesController.java +++ b/components/page_info/android/java/src/org/chromium/components/page_info/PageInfoCookiesController.java
@@ -7,6 +7,7 @@ import android.view.View; import android.view.ViewGroup; +import org.chromium.base.metrics.RecordHistogram; import org.chromium.components.browser_ui.site_settings.SingleWebsiteSettings; import org.chromium.components.browser_ui.site_settings.SiteDataCleaner; import org.chromium.components.browser_ui.site_settings.SiteSettingsCategory; @@ -105,10 +106,11 @@ if (mSubPage != null) { mSubPage.setStorageUsage(mWebsite.getTotalUsage()); } - if (mWebsite.getFPSCookieInfo() != null) { - mSubPage.maybeShowFPSInfo( - mWebsite.getFPSCookieInfo(), mWebsite.getAddress().getOrigin()); - } + + boolean isFPSInfoShown = mSubPage.maybeShowFPSInfo( + mWebsite.getFPSCookieInfo(), mWebsite.getAddress().getOrigin()); + RecordHistogram.recordBooleanHistogram( + "Security.PageInfo.Cookies.HasFPSInfo", isFPSInfoShown); } private void onCheckedChangedCallback(boolean state) {
diff --git a/components/page_info/android/java/src/org/chromium/components/page_info/PageInfoCookiesPreference.java b/components/page_info/android/java/src/org/chromium/components/page_info/PageInfoCookiesPreference.java index ad89ee26..fdf7b75 100644 --- a/components/page_info/android/java/src/org/chromium/components/page_info/PageInfoCookiesPreference.java +++ b/components/page_info/android/java/src/org/chromium/components/page_info/PageInfoCookiesPreference.java
@@ -163,9 +163,16 @@ updateCookieDeleteButton(); } - public void maybeShowFPSInfo(FPSCookieInfo fpsInfo, String currentOrigin) { + /** + * Returns a boolean indicating if the FPS info has been shown or not. + * + * @param fpsInfo First Party Sets info to show. + * @param currentOrigin PageInfo current origin. + * @return a boolean indicating if the FPS info has been shown or not. + */ + public boolean maybeShowFPSInfo(FPSCookieInfo fpsInfo, String currentOrigin) { if (fpsInfo == null) { - return; + return false; } assert getSiteSettingsDelegate().isPrivacySandboxFirstPartySetsUIFeatureEnabled() @@ -184,6 +191,8 @@ return getSiteSettingsDelegate().isPartOfManagedFirstPartySet(currentOrigin); } }); + + return true; } private void updateCookieDeleteButton() {
diff --git a/components/password_manager/core/browser/form_parsing/BUILD.gn b/components/password_manager/core/browser/form_parsing/BUILD.gn index 3a2ec64..30fc006e 100644 --- a/components/password_manager/core/browser/form_parsing/BUILD.gn +++ b/components/password_manager/core/browser/form_parsing/BUILD.gn
@@ -36,6 +36,7 @@ ":form_parsing", "//base/test:test_support", "//components/autofill/core/browser", + "//components/autofill/core/browser:test_support", "//components/autofill/core/common", "//components/password_manager/core/common", "//components/password_manager/core/common:features",
diff --git a/components/password_manager/core/browser/form_parsing/password_field_prediction_unittest.cc b/components/password_manager/core/browser/form_parsing/password_field_prediction_unittest.cc index a7770ad0..deca3087 100644 --- a/components/password_manager/core/browser/form_parsing/password_field_prediction_unittest.cc +++ b/components/password_manager/core/browser/form_parsing/password_field_prediction_unittest.cc
@@ -8,6 +8,7 @@ #include "base/strings/utf_string_conversions.h" #include "base/test/scoped_feature_list.h" +#include "components/autofill/core/browser/autofill_test_utils.h" #include "components/autofill/core/browser/form_structure.h" #include "components/autofill/core/common/form_data.h" #include "components/autofill/core/common/unique_ids.h" @@ -35,6 +36,7 @@ using FieldPrediction = autofill::AutofillQueryResponse::FormSuggestion:: FieldSuggestion::FieldPrediction; +using ::autofill::test::CreateFieldPrediction; namespace password_manager { @@ -85,14 +87,10 @@ AutofillField* field = form_structure.field(i); std::vector<FieldPrediction> predictions; - FieldPrediction prediction; - prediction.set_type(test_fields[i].input_type); - predictions.push_back(prediction); + predictions.push_back(CreateFieldPrediction(test_fields[i].input_type)); for (ServerFieldType type : test_fields[i].additional_types) { - FieldPrediction additional_prediction; - additional_prediction.set_type(type); - predictions.push_back(additional_prediction); + predictions.push_back(CreateFieldPrediction(type)); } field->set_server_predictions(predictions); field->set_may_use_prefilled_placeholder( @@ -164,9 +162,8 @@ // Set server predictions and create expected votes. for (size_t i = 0; i < test_form.size(); ++i) { AutofillField* field = form_structure.field(i); - FieldPrediction prediction; - prediction.set_type(test_form[i].input_type); - field->set_server_predictions({prediction}); + field->set_server_predictions( + {CreateFieldPrediction(test_form[i].input_type)}); } FormPredictions actual_predictions =
diff --git a/components/password_manager/core/browser/password_feature_manager_impl_unittest.cc b/components/password_manager/core/browser/password_feature_manager_impl_unittest.cc index c276cd6..d2483c86 100644 --- a/components/password_manager/core/browser/password_feature_manager_impl_unittest.cc +++ b/components/password_manager/core/browser/password_feature_manager_impl_unittest.cc
@@ -114,6 +114,36 @@ } TEST_F(PasswordFeatureManagerImplTest, + GenerationDisabledIfSyncPausedWithWebSignout) { + sync_service_.SetAccountInfo(account_); + sync_service_.SetHasSyncConsent(true); + sync_service_.SetDisableReasons({}); + sync_service_.SetPersistentAuthErrorWithWebSignout(); + + ASSERT_EQ(sync_service_.GetTransportState(), + syncer::SyncService::TransportState::PAUSED); + ASSERT_EQ(password_manager_util::GetPasswordSyncState(&sync_service_), + password_manager::SyncState::kNotSyncing); + + EXPECT_FALSE(password_feature_manager_.IsGenerationEnabled()); +} + +TEST_F(PasswordFeatureManagerImplTest, + GenerationEnabledDespiteSyncAuthErrorOtherThanWebSignout) { + sync_service_.SetAccountInfo(account_); + sync_service_.SetHasSyncConsent(true); + sync_service_.SetDisableReasons({}); + sync_service_.SetPersistentAuthErrorOtherThanWebSignout(); + + ASSERT_NE(sync_service_.GetTransportState(), + syncer::SyncService::TransportState::PAUSED); + ASSERT_EQ(password_manager_util::GetPasswordSyncState(&sync_service_), + password_manager::SyncState::kSyncingNormalEncryption); + + EXPECT_TRUE(password_feature_manager_.IsGenerationEnabled()); +} + +TEST_F(PasswordFeatureManagerImplTest, RequirementsForAutomatedPasswordChangeMetForSyncingUser) { sync_service_.SetAccountInfo(account_); sync_service_.SetHasSyncConsent(true); @@ -248,4 +278,4 @@ .feature_flag = true, .pref_value = true, })); -#endif // BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN) \ No newline at end of file +#endif // BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN)
diff --git a/components/password_manager/core/browser/password_manager_unittest.cc b/components/password_manager/core/browser/password_manager_unittest.cc index f6c2495..0b154ac 100644 --- a/components/password_manager/core/browser/password_manager_unittest.cc +++ b/components/password_manager/core/browser/password_manager_unittest.cc
@@ -20,6 +20,7 @@ #include "base/test/task_environment.h" #include "base/test/test_mock_time_task_runner.h" #include "build/build_config.h" +#include "components/autofill/core/browser/autofill_test_utils.h" #include "components/autofill/core/browser/form_structure.h" #include "components/autofill/core/browser/ui/suggestion.h" #include "components/autofill/core/common/form_data.h" @@ -74,6 +75,7 @@ using autofill::PasswordFormFillData; using autofill::ServerFieldType; using autofill::SINGLE_USERNAME; +using ::autofill::test::CreateFieldPrediction; using base::ASCIIToUTF16; using base::Feature; using base::TestMockTimeTaskRunner; @@ -91,9 +93,6 @@ using testing::SaveArg; using testing::WithArg; -using FieldPrediction = autofill::AutofillQueryResponse::FormSuggestion:: - FieldSuggestion::FieldPrediction; - namespace password_manager { namespace { @@ -3047,9 +3046,8 @@ // Server predictions says that this is a sign-in form. Since they have higher // priority than autocomplete attributes then the form should be filled. FormStructure form_structure(form.form_data); - FieldPrediction prediction; - prediction.set_type(autofill::PASSWORD); - form_structure.field(1)->set_server_predictions({prediction}); + form_structure.field(1)->set_server_predictions( + {CreateFieldPrediction(autofill::PASSWORD)}); #if !BUILDFLAG(IS_IOS) manager()->ProcessAutofillPredictions(&driver_, {&form_structure}); #else // On iOS predictions are propagated with nullptr driver. @@ -3082,14 +3080,13 @@ .WillRepeatedly(WithArg<1>(InvokeConsumer(store_.get(), form2))); FormStructure form_structure1(form1.form_data); - FieldPrediction prediction; - prediction.set_type(autofill::SINGLE_USERNAME); - form_structure1.field(0)->set_server_predictions({prediction}); + form_structure1.field(0)->set_server_predictions( + {CreateFieldPrediction(autofill::SINGLE_USERNAME)}); // Server predictions says that this is a sign-in form. Since they have higher // priority than autocomplete attributes then the form should be filled. FormStructure form_structure2(form2.form_data); - prediction.set_type(autofill::PASSWORD); - form_structure2.field(1)->set_server_predictions({prediction}); + form_structure2.field(1)->set_server_predictions( + {CreateFieldPrediction(autofill::PASSWORD)}); #if !BUILDFLAG(IS_IOS) manager()->ProcessAutofillPredictions(&driver_, @@ -3489,9 +3486,8 @@ // Set SINGLE_USERNAME predictions for the field. FormStructure form_structure(form_data); - FieldPrediction prediction; - prediction.set_type(autofill::SINGLE_USERNAME); - form_structure.field(0)->set_server_predictions({prediction}); + form_structure.field(0)->set_server_predictions( + {CreateFieldPrediction(SINGLE_USERNAME)}); #if !BUILDFLAG(IS_IOS) PasswordFormFillData fill_data; @@ -3542,9 +3538,8 @@ // Set ACCOUNT_CREATION_PASSWORD predictions for the field. FormStructure form_structure(form_data); - FieldPrediction prediction; - prediction.set_type(autofill::ACCOUNT_CREATION_PASSWORD); - form_structure.field(1)->set_server_predictions({prediction}); + form_structure.field(1)->set_server_predictions( + {CreateFieldPrediction(autofill::ACCOUNT_CREATION_PASSWORD)}); autofill::PasswordFormGenerationData form_generation_data; EXPECT_CALL(driver_, FormEligibleForGenerationFound(_)) @@ -3573,9 +3568,8 @@ // Setup a server prediction for the single username field. FormStructure form_structure(username_form.form_data); - FieldPrediction prediction; - prediction.set_type(SINGLE_USERNAME); - form_structure.field(0)->set_server_predictions({prediction}); + form_structure.field(0)->set_server_predictions( + {CreateFieldPrediction(SINGLE_USERNAME)}); manager()->ProcessAutofillPredictions(&driver_, {&form_structure}); // Simulate that a form which contains only 1 password field is added @@ -3674,9 +3668,8 @@ // Setup a server prediction for the single username field to // allow using possible username value for pending credentials. FormStructure form_structure(username_form.form_data); - FieldPrediction prediction; - prediction.set_type(SINGLE_USERNAME); - form_structure.field(0)->set_server_predictions({prediction}); + form_structure.field(0)->set_server_predictions( + {CreateFieldPrediction(SINGLE_USERNAME)}); manager()->ProcessAutofillPredictions(&driver_, {&form_structure}); // Simulate navigation to a single password form that cannot be a result of a @@ -3736,9 +3729,8 @@ non_password_form.name += u"1"; // for iOS. FormStructure form_structure(non_password_form); - FieldPrediction prediction; - prediction.set_type(server_type); - form_structure.field(0)->set_server_predictions({prediction}); + form_structure.field(0)->set_server_predictions( + {CreateFieldPrediction(server_type)}); bool should_be_filled = server_type == SINGLE_USERNAME || local_type == SINGLE_USERNAME; @@ -3941,11 +3933,10 @@ // Server predictions may arrive before the form is parsed by PasswordManager. FormStructure form_structure(form_data); - FieldPrediction prediction; - prediction.set_type(autofill::ACCOUNT_CREATION_PASSWORD); - form_structure.field(1)->set_server_predictions({prediction}); - prediction.set_type(autofill::CONFIRMATION_PASSWORD); - form_structure.field(2)->set_server_predictions({prediction}); + form_structure.field(1)->set_server_predictions( + {CreateFieldPrediction(autofill::ACCOUNT_CREATION_PASSWORD)}); + form_structure.field(2)->set_server_predictions( + {CreateFieldPrediction(autofill::CONFIRMATION_PASSWORD)}); manager()->ProcessAutofillPredictions(&driver_, {&form_structure}); autofill::PasswordFormGenerationData form_generation_data;
diff --git a/components/password_manager/core/browser/password_store_backend_migration_decorator.cc b/components/password_manager/core/browser/password_store_backend_migration_decorator.cc index 56171a8..dc396cd 100644 --- a/components/password_manager/core/browser/password_store_backend_migration_decorator.cc +++ b/components/password_manager/core/browser/password_store_backend_migration_decorator.cc
@@ -138,6 +138,11 @@ return; } + // TODO(crbug.com/1156584): The condition below could be simplified, as long + // as the handling of transient auth errors is unimportant, once the feature + // toggle syncer::kSyncPauseUponAnyPersistentAuthError is cleaned up. + // Alternatively IsPasswordSyncActive() could be removed entirely in favor of + // password_manager_util::GetPasswordSyncState(). if (sync_util::IsPasswordSyncActive(sync) && (sync->GetAuthError() == GoogleServiceAuthError(GoogleServiceAuthError::NONE))) {
diff --git a/components/permissions/features.cc b/components/permissions/features.cc index 7bed3f6..567974d 100644 --- a/components/permissions/features.cc +++ b/components/permissions/features.cc
@@ -148,7 +148,7 @@ kPermissionOnDeviceNotificationPredictionsHoldbackChance( &features::kPermissionOnDeviceNotificationPredictions, "holdback_chance", - 0.3); + 0.25); #if !BUILDFLAG(IS_ANDROID) // Specifies the `trigger_id` of the HaTS survey to trigger immediately after
diff --git a/components/reporting/DIR_METADATA b/components/reporting/DIR_METADATA index ec62bc6c4..9dfdc4de 100644 --- a/components/reporting/DIR_METADATA +++ b/components/reporting/DIR_METADATA
@@ -1 +1,10 @@ mixins: "//chromeos/ash/components/policy/COMMON_METADATA" + +monorail { + project: "chromium" + component: "Enterprise" +# Buganizer Component: Chrome OS Server Projects > Enterprise Management > Reporting +} + +team_email: "cros-reporting-team@google.com" +os: CHROME_OS
diff --git a/components/reporting/OWNERS b/components/reporting/OWNERS index 3b729b5..adaf75c 100644 --- a/components/reporting/OWNERS +++ b/components/reporting/OWNERS
@@ -6,4 +6,3 @@ scmoreno@google.com vshenvi@google.com xuhong@chromium.org -# Buganizer component: Chrome OS Server Projects > Enterprise Management > Reporting \ No newline at end of file
diff --git a/components/reporting/client/report_queue_impl.cc b/components/reporting/client/report_queue_impl.cc index a3ed597..42542303 100644 --- a/components/reporting/client/report_queue_impl.cc +++ b/components/reporting/client/report_queue_impl.cc
@@ -290,7 +290,7 @@ speculative_queue->AttachActualQueue( std::move(std::move(actual_queue_result))); }, - weak_ptr_factory_.GetWeakPtr())); + weak_ptr_factory_.GetMutableWeakPtr())); } void SpeculativeReportQueueImpl::AttachActualQueue(
diff --git a/components/reporting/health/health_module_delegate.cc b/components/reporting/health/health_module_delegate.cc index 0055fc4..9b5419f 100644 --- a/components/reporting/health/health_module_delegate.cc +++ b/components/reporting/health/health_module_delegate.cc
@@ -75,7 +75,7 @@ *data_in_memory_.add_history() = record; } -base::WeakPtr<HealthModuleDelegate> HealthModuleDelegate::GetWeakPtr() const { +base::WeakPtr<HealthModuleDelegate> HealthModuleDelegate::GetWeakPtr() { return weak_ptr_factory_.GetWeakPtr(); } } // namespace reporting
diff --git a/components/reporting/health/health_module_delegate.h b/components/reporting/health/health_module_delegate.h index 8907df2..688e39f 100644 --- a/components/reporting/health/health_module_delegate.h +++ b/components/reporting/health/health_module_delegate.h
@@ -42,7 +42,7 @@ bool IsInitialized() const; - base::WeakPtr<HealthModuleDelegate> GetWeakPtr() const; + base::WeakPtr<HealthModuleDelegate> GetWeakPtr(); private: // Local copy of the health data. This is read from storage on startup and
diff --git a/components/search_engines/default_search_policy_handler_unittest.cc b/components/search_engines/default_search_policy_handler_unittest.cc index 4c274335..772c469 100644 --- a/components/search_engines/default_search_policy_handler_unittest.cc +++ b/components/search_engines/default_search_policy_handler_unittest.cc
@@ -48,7 +48,7 @@ // method. void BuildDefaultSearchPolicy(PolicyMap* policy); - base::ListValue default_alternate_urls_; + base::Value::List default_alternate_urls_; }; const char DefaultSearchPolicyHandlerTest::kSearchURL[] = @@ -99,7 +99,7 @@ nullptr); policy->Set(key::kDefaultSearchProviderAlternateURLs, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD, - default_alternate_urls_.Clone(), nullptr); + base::Value(default_alternate_urls_.Clone()), nullptr); policy->Set(key::kDefaultSearchProviderImageURL, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD, base::Value(kImageURL), nullptr); @@ -194,52 +194,52 @@ UpdateProviderPolicy(policy); const base::Value* temp = nullptr; - const base::DictionaryValue* dictionary; - std::string value; - const base::ListValue* list_value; EXPECT_TRUE(store_->GetValue( DefaultSearchManager::kDefaultSearchProviderDataPrefName, &temp)); - temp->GetAsDictionary(&dictionary); + const base::Value::Dict* dictionary = temp->GetIfDict(); + ASSERT_TRUE(dictionary); - EXPECT_TRUE(dictionary->GetString(DefaultSearchManager::kURL, &value)); - EXPECT_EQ(kSearchURL, value); - EXPECT_TRUE(dictionary->GetString(DefaultSearchManager::kShortName, &value)); - EXPECT_EQ(kName, value); - EXPECT_TRUE(dictionary->GetString(DefaultSearchManager::kKeyword, &value)); - EXPECT_EQ(kKeyword, value); + const std::string* value = nullptr; + ASSERT_TRUE(value = dictionary->FindString(DefaultSearchManager::kURL)); + EXPECT_EQ(kSearchURL, *value); + ASSERT_TRUE(value = dictionary->FindString(DefaultSearchManager::kShortName)); + EXPECT_EQ(kName, *value); + ASSERT_TRUE(value = dictionary->FindString(DefaultSearchManager::kKeyword)); + EXPECT_EQ(kKeyword, *value); - EXPECT_TRUE( - dictionary->GetString(DefaultSearchManager::kSuggestionsURL, &value)); - EXPECT_EQ(kSuggestURL, value); - EXPECT_TRUE(dictionary->GetString(DefaultSearchManager::kFaviconURL, &value)); - EXPECT_EQ(kIconURL, value); + ASSERT_TRUE( + value = dictionary->FindString(DefaultSearchManager::kSuggestionsURL)); + EXPECT_EQ(kSuggestURL, *value); + EXPECT_TRUE(value = + dictionary->FindString(DefaultSearchManager::kFaviconURL)); + EXPECT_EQ(kIconURL, *value); - base::ListValue encodings; + base::Value::List encodings; encodings.Append("UTF-16"); encodings.Append("UTF-8"); - - EXPECT_TRUE( - dictionary->GetList(DefaultSearchManager::kInputEncodings, &list_value)); + const base::Value::List* list_value = nullptr; + ASSERT_TRUE(list_value = + dictionary->FindList(DefaultSearchManager::kInputEncodings)); EXPECT_EQ(encodings, *list_value); - EXPECT_TRUE( - dictionary->GetList(DefaultSearchManager::kAlternateURLs, &list_value)); + ASSERT_TRUE(list_value = + dictionary->FindList(DefaultSearchManager::kAlternateURLs)); EXPECT_EQ(default_alternate_urls_, *list_value); - EXPECT_TRUE(dictionary->GetString(DefaultSearchManager::kImageURL, &value)); - EXPECT_EQ(kImageURL, value); + ASSERT_TRUE(value = dictionary->FindString(DefaultSearchManager::kImageURL)); + EXPECT_EQ(kImageURL, *value); - EXPECT_TRUE( - dictionary->GetString(DefaultSearchManager::kImageURLPostParams, &value)); - EXPECT_EQ(kImageParams, value); + ASSERT_TRUE(value = dictionary->FindString( + DefaultSearchManager::kImageURLPostParams)); + EXPECT_EQ(kImageParams, *value); - EXPECT_TRUE(dictionary->GetString(DefaultSearchManager::kSearchURLPostParams, - &value)); - EXPECT_EQ(std::string(), value); + ASSERT_TRUE(value = dictionary->FindString( + DefaultSearchManager::kSearchURLPostParams)); + EXPECT_EQ(std::string(), *value); - EXPECT_TRUE(dictionary->GetString( - DefaultSearchManager::kSuggestionsURLPostParams, &value)); - EXPECT_EQ(std::string(), value); + EXPECT_TRUE(value = dictionary->FindString( + DefaultSearchManager::kSuggestionsURLPostParams)); + EXPECT_EQ(std::string(), *value); } // Checks that disabling default search is properly reflected the dictionary @@ -257,13 +257,13 @@ // Ignore any other search provider related policy in this case. EXPECT_FALSE(store_->GetValue(DefaultSearchManager::kURL, &temp)); - const base::DictionaryValue* dictionary; EXPECT_TRUE(store_->GetValue( DefaultSearchManager::kDefaultSearchProviderDataPrefName, &temp)); - temp->GetAsDictionary(&dictionary); + const base::Value::Dict* dictionary = temp->GetIfDict(); + ASSERT_TRUE(dictionary); absl::optional<bool> disabled = - dictionary->FindBoolKey(DefaultSearchManager::kDisabledByPolicy); - EXPECT_TRUE(disabled); + dictionary->FindBool(DefaultSearchManager::kDisabledByPolicy); + EXPECT_TRUE(disabled.has_value()); EXPECT_TRUE(disabled.value()); } @@ -294,44 +294,45 @@ UpdateProviderPolicy(policy); const base::Value* temp = nullptr; - const base::DictionaryValue* dictionary; - std::string value; - const base::ListValue* list_value; EXPECT_TRUE(store_->GetValue( DefaultSearchManager::kDefaultSearchProviderDataPrefName, &temp)); - temp->GetAsDictionary(&dictionary); + const base::Value::Dict* dictionary = temp->GetIfDict(); + ASSERT_TRUE(dictionary); // Name and keyword should be derived from host. - EXPECT_TRUE(dictionary->GetString(DefaultSearchManager::kURL, &value)); - EXPECT_EQ(kSearchURL, value); - EXPECT_TRUE(dictionary->GetString(DefaultSearchManager::kShortName, &value)); - EXPECT_EQ(kHostName, value); - EXPECT_TRUE(dictionary->GetString(DefaultSearchManager::kKeyword, &value)); - EXPECT_EQ(kHostName, value); + const std::string* value = nullptr; + ASSERT_TRUE(value = dictionary->FindString(DefaultSearchManager::kURL)); + EXPECT_EQ(kSearchURL, *value); + ASSERT_TRUE(value = dictionary->FindString(DefaultSearchManager::kShortName)); + EXPECT_EQ(kHostName, *value); + ASSERT_TRUE(value = dictionary->FindString(DefaultSearchManager::kKeyword)); + EXPECT_EQ(kHostName, *value); // Everything else should be set to the default value. - EXPECT_TRUE( - dictionary->GetString(DefaultSearchManager::kSuggestionsURL, &value)); - EXPECT_EQ(std::string(), value); - EXPECT_TRUE(dictionary->GetString(DefaultSearchManager::kFaviconURL, &value)); - EXPECT_EQ(std::string(), value); - EXPECT_TRUE( - dictionary->GetList(DefaultSearchManager::kInputEncodings, &list_value)); - EXPECT_EQ(base::ListValue(), *list_value); - EXPECT_TRUE( - dictionary->GetList(DefaultSearchManager::kAlternateURLs, &list_value)); - EXPECT_EQ(base::ListValue(), *list_value); - EXPECT_TRUE(dictionary->GetString(DefaultSearchManager::kImageURL, &value)); - EXPECT_EQ(std::string(), value); - EXPECT_TRUE( - dictionary->GetString(DefaultSearchManager::kImageURLPostParams, &value)); - EXPECT_EQ(std::string(), value); - EXPECT_TRUE(dictionary->GetString(DefaultSearchManager::kSearchURLPostParams, - &value)); - EXPECT_EQ(std::string(), value); - EXPECT_TRUE(dictionary->GetString( - DefaultSearchManager::kSuggestionsURLPostParams, &value)); - EXPECT_EQ(std::string(), value); + ASSERT_TRUE( + value = dictionary->FindString(DefaultSearchManager::kSuggestionsURL)); + EXPECT_EQ(std::string(), *value); + ASSERT_TRUE(value = + dictionary->FindString(DefaultSearchManager::kFaviconURL)); + EXPECT_EQ(std::string(), *value); + const base::Value::List* list_value = nullptr; + ASSERT_TRUE(list_value = + dictionary->FindList(DefaultSearchManager::kInputEncodings)); + EXPECT_EQ(base::Value::List(), *list_value); + ASSERT_TRUE(list_value = + dictionary->FindList(DefaultSearchManager::kAlternateURLs)); + EXPECT_EQ(base::Value::List(), *list_value); + ASSERT_TRUE(value = dictionary->FindString(DefaultSearchManager::kImageURL)); + EXPECT_EQ(std::string(), *value); + ASSERT_TRUE(value = dictionary->FindString( + DefaultSearchManager::kImageURLPostParams)); + EXPECT_EQ(std::string(), *value); + ASSERT_TRUE(value = dictionary->FindString( + DefaultSearchManager::kSearchURLPostParams)); + EXPECT_EQ(std::string(), *value); + ASSERT_TRUE(value = dictionary->FindString( + DefaultSearchManager::kSuggestionsURLPostParams)); + EXPECT_EQ(std::string(), *value); } // Checks that setting a file URL as the default search is reflected properly in @@ -347,19 +348,19 @@ UpdateProviderPolicy(policy); const base::Value* temp = nullptr; - const base::DictionaryValue* dictionary; - std::string value; EXPECT_TRUE(store_->GetValue( DefaultSearchManager::kDefaultSearchProviderDataPrefName, &temp)); - temp->GetAsDictionary(&dictionary); + const base::Value::Dict* dictionary = temp->GetIfDict(); + ASSERT_TRUE(dictionary); - EXPECT_TRUE(dictionary->GetString(DefaultSearchManager::kURL, &value)); - EXPECT_EQ(kFileSearchURL, value); - EXPECT_TRUE(dictionary->GetString(DefaultSearchManager::kShortName, &value)); - EXPECT_EQ("_", value); - EXPECT_TRUE(dictionary->GetString(DefaultSearchManager::kKeyword, &value)); - EXPECT_EQ("_", value); + const std::string* value = nullptr; + ASSERT_TRUE(value = dictionary->FindString(DefaultSearchManager::kURL)); + EXPECT_EQ(kFileSearchURL, *value); + ASSERT_TRUE(value = dictionary->FindString(DefaultSearchManager::kShortName)); + EXPECT_EQ("_", *value); + ASSERT_TRUE(value = dictionary->FindString(DefaultSearchManager::kKeyword)); + EXPECT_EQ("_", *value); } } // namespace policy
diff --git a/components/search_engines/template_url.cc b/components/search_engines/template_url.cc index fd5245d..6d847472 100644 --- a/components/search_engines/template_url.cc +++ b/components/search_engines/template_url.cc
@@ -1744,8 +1744,12 @@ const GURL& image_search_url) const { if (!IsSideImageSearchSupported()) return image_search_url; - return net::AppendOrReplaceQueryParameter( - image_search_url, side_image_search_param(), absl::nullopt); + std::string value; + if (!net::GetValueForKeyInQuery(image_search_url, side_image_search_param(), + &value)) + return image_search_url; + return net::AppendOrReplaceQueryParameter(image_search_url, + side_image_search_param(), ""); } void TemplateURL::CopyFrom(const TemplateURL& other) {
diff --git a/components/search_engines/template_url_unittest.cc b/components/search_engines/template_url_unittest.cc index f8f30d4..3fb2505 100644 --- a/components/search_engines/template_url_unittest.cc +++ b/components/search_engines/template_url_unittest.cc
@@ -2271,13 +2271,14 @@ // Removes the param if the provided URL has it. result = url.RemoveSideImageSearchParamFromURL( GURL("http://foo.com/?q=123&sideimagesearch=1")); - EXPECT_EQ("http://foo.com/?q=123", result.spec()); + EXPECT_EQ("http://foo.com/?q=123&sideimagesearch=", result.spec()); // Removes the first instance of the query param that exist in the URL. This // should not happen but just asserting for expected behavior. result = url.RemoveSideImageSearchParamFromURL( GURL("http://foo.com/?q=123&sideimagesearch=1&sideimagesearch=2")); - EXPECT_EQ("http://foo.com/?q=123&sideimagesearch=2", result.spec()); + EXPECT_EQ("http://foo.com/?q=123&sideimagesearch=&sideimagesearch=2", + result.spec()); } TEST_F(TemplateURLTest, ImageSearchBrandingLabel) {
diff --git a/components/services/app_service/public/cpp/preferred_app.cc b/components/services/app_service/public/cpp/preferred_app.cc index b08574a..83822fa 100644 --- a/components/services/app_service/public/cpp/preferred_app.cc +++ b/components/services/app_service/public/cpp/preferred_app.cc
@@ -172,36 +172,4 @@ return ret; } -apps::mojom::ReplacedAppPreferencesPtr -ConvertReplacedAppPreferencesToMojomReplacedAppPreferences( - const ReplacedAppPreferences& replace_preferences) { - auto replaced_app_preferences = apps::mojom::ReplacedAppPreferences::New(); - auto& replaced_preference_map = replaced_app_preferences->replaced_preference; - for (const auto& it : replace_preferences) { - for (const auto& filter : it.second) { - replaced_preference_map[it.first].push_back( - ConvertIntentFilterToMojomIntentFilter(filter)); - } - } - return replaced_app_preferences; -} - -ReplacedAppPreferences -ConvertMojomReplacedAppPreferencesToReplacedAppPreferences( - const apps::mojom::ReplacedAppPreferencesPtr& mojom_replace_preferences) { - ReplacedAppPreferences replaced_app_preferences; - if (!mojom_replace_preferences) { - return replaced_app_preferences; - } - auto& mojom_replaced_preference_map = - mojom_replace_preferences->replaced_preference; - for (const auto& it : mojom_replaced_preference_map) { - for (const auto& filter : it.second) { - replaced_app_preferences[it.first].push_back( - ConvertMojomIntentFilterToIntentFilter(filter)); - } - } - return replaced_app_preferences; -} - } // namespace apps
diff --git a/components/services/app_service/public/cpp/preferred_app.h b/components/services/app_service/public/cpp/preferred_app.h index b1a95b3..be62775 100644 --- a/components/services/app_service/public/cpp/preferred_app.h +++ b/components/services/app_service/public/cpp/preferred_app.h
@@ -77,14 +77,6 @@ std::vector<apps::mojom::PreferredAppPtr> ConvertPreferredAppsToMojomPreferredApps(const PreferredApps& preferred_apps); -apps::mojom::ReplacedAppPreferencesPtr -ConvertReplacedAppPreferencesToMojomReplacedAppPreferences( - const ReplacedAppPreferences& replace_preferences); - -ReplacedAppPreferences -ConvertMojomReplacedAppPreferencesToReplacedAppPreferences( - const apps::mojom::ReplacedAppPreferencesPtr& mojom_replace_preferences); - } // namespace apps #endif // COMPONENTS_SERVICES_APP_SERVICE_PUBLIC_CPP_PREFERRED_APP_H_
diff --git a/components/services/app_service/public/cpp/preferred_apps_converter_unittest.cc b/components/services/app_service/public/cpp/preferred_apps_converter_unittest.cc index e0ff1a8..8e103e8 100644 --- a/components/services/app_service/public/cpp/preferred_apps_converter_unittest.cc +++ b/components/services/app_service/public/cpp/preferred_apps_converter_unittest.cc
@@ -547,22 +547,3 @@ EXPECT_TRUE( IsEqual(old_preferred_apps_value, new_preferred_apps.GetReference())); } - -// TODO(crbug.com/1253250): Remove after migrating to non-mojo AppService. -TEST_F(PreferredAppsConverterTest, ReplacedAppPreferencesMojomConvert) { - std::string app_id("abcdefg"); - GURL filter_url = GURL("https://www.google.com/abc"); - - auto intent_filter = apps_util::MakeIntentFilterForUrlScope(filter_url); - - apps::ReplacedAppPreferences replaced_app_preferences; - replaced_app_preferences[app_id].push_back(std::move(intent_filter)); - - apps::ReplacedAppPreferences new_replaced_app_preferences = - apps::ConvertMojomReplacedAppPreferencesToReplacedAppPreferences( - apps::ConvertReplacedAppPreferencesToMojomReplacedAppPreferences( - replaced_app_preferences)); - ASSERT_EQ(1u, new_replaced_app_preferences.size()); - EXPECT_TRUE(apps::IsEqual(replaced_app_preferences[app_id], - new_replaced_app_preferences[app_id])); -}
diff --git a/components/services/app_service/public/mojom/types.mojom b/components/services/app_service/public/mojom/types.mojom index 524b879..7f1d92e3 100644 --- a/components/services/app_service/public/mojom/types.mojom +++ b/components/services/app_service/public/mojom/types.mojom
@@ -467,12 +467,6 @@ map<string, string>? extras; // Optional string extras. }; -// Represents a group of |app_ids| that is no longer preferred app of their -// corresponding |intent_filters|. -struct ReplacedAppPreferences { - map<string, array<IntentFilter>> replaced_preference; -}; - // Represents changes which have been made to the preferred apps list, both // adding new filters and removing existing filters. struct PreferredAppChanges {
diff --git a/components/sync/protocol/local_trusted_vault.proto b/components/sync/protocol/local_trusted_vault.proto index 75753b7..48c05e5 100644 --- a/components/sync/protocol/local_trusted_vault.proto +++ b/components/sync/protocol/local_trusted_vault.proto
@@ -19,12 +19,25 @@ optional bytes private_key_material = 1; // Indicates whether device is registered, i.e. whether its public key is - // successfully submitted to the server. + // successfully submitted to the server. If set to true, it is only + // trustworthy depending on whether re-registration completed successfully, + // reflected in `device_registered_version`. optional bool device_registered = 2; // Used to trigger another device registration attempt, even if device is // already registered. Not set if `device_registered` is false. optional int32 device_registered_version = 3; + + // If true, it indicates that a previous attempt to register or reregister + // the device failed, with a failure that suggests future attempts will fail + // too. This usually means additional keys are needed, which can be resolved + // via key retrieval. + // + // Note that true doesn't imply the device isn't registered. It may be that + // the failure corresponds to a re-registration attempt. In this case, besides + // key retrieval, it may be possible to resolve the error by attempting to + // download new keys. + optional bool last_registration_returned_local_data_obsolete = 4; } message LocalTrustedVaultDegradedRecoverabilityState { @@ -46,10 +59,12 @@ // The version corresponding to the last element in `vault_key`. optional int32 last_vault_key_version = 3; - // Indicates whether `vault_key` is stale, i.e. that the latest locally - // available key isn't the latest key in the vault. New keys need to be - // fetched through key retrieval procedure or by following key rotation. - optional bool keys_are_stale = 4; + // Indicates whether `vault_key` is marked as stale by upper layers, which + // suggests (but doesn't guarantee) that the server may contain additional + // (newer) keys. If the device is registered in the security domain, it means + // it may be worth downloading new keys (follow key rotation). Otherwise, new + // keys need to be fetched through key retrieval procedure. + optional bool keys_marked_as_stale_by_consumer = 4; // Device key and corresponding registration metadata. optional LocalDeviceRegistrationInfo local_device_registration_info = 5;
diff --git a/components/sync/trusted_vault/standalone_trusted_vault_backend.cc b/components/sync/trusted_vault/standalone_trusted_vault_backend.cc index 3dcd474..9d9ea0f5 100644 --- a/components/sync/trusted_vault/standalone_trusted_vault_backend.cc +++ b/components/sync/trusted_vault/standalone_trusted_vault_backend.cc
@@ -145,15 +145,16 @@ local_trusted_vault->set_data_version(1); } -// Version 1 may contain `keys_are_stale` accidentally set to true, upgrade to -// version 2 resets it to false. +// Version 1 may contain `keys_marked_as_stale_by_consumer` (before the field +// was renamed) accidentally set to true, upgrade to version 2 resets it to +// false. void UpgradeToVersion2(sync_pb::LocalTrustedVault* local_trusted_vault) { DCHECK(local_trusted_vault); DCHECK_EQ(local_trusted_vault->data_version(), 1); for (sync_pb::LocalTrustedVaultPerUser& per_user_vault : *local_trusted_vault->mutable_user()) { - per_user_vault.set_keys_are_stale(false); + per_user_vault.set_keys_marked_as_stale_by_consumer(false); } local_trusted_vault->set_data_version(2); } @@ -278,7 +279,7 @@ FindUserVault(account_info.gaia); if (per_user_vault && HasNonConstantKey(*per_user_vault) && - !per_user_vault->keys_are_stale()) { + !per_user_vault->keys_marked_as_stale_by_consumer()) { // There are locally available keys, which weren't marked as stale. Keys // download attempt is not needed. FulfillOngoingFetchKeys(/*status_for_uma=*/absl::nullopt); @@ -365,9 +366,14 @@ per_user_vault->set_gaia_id(gaia_id); } + // Having retrieved (or downloaded) new keys indicates that past failures may + // no longer be relevant. + per_user_vault->mutable_local_device_registration_info() + ->set_last_registration_returned_local_data_obsolete(false); + // Replace all keys. per_user_vault->set_last_vault_key_version(last_key_version); - per_user_vault->set_keys_are_stale(false); + per_user_vault->set_keys_marked_as_stale_by_consumer(false); per_user_vault->clear_vault_key(); for (const std::vector<uint8_t>& key : keys) { AssignBytesToProtoString( @@ -502,12 +508,12 @@ const CoreAccountInfo& account_info) { sync_pb::LocalTrustedVaultPerUser* per_user_vault = FindUserVault(account_info.gaia); - if (!per_user_vault || per_user_vault->keys_are_stale()) { + if (!per_user_vault || per_user_vault->keys_marked_as_stale_by_consumer()) { // No keys available for |account_info| or they are already marked as stale. return false; } - per_user_vault->set_keys_are_stale(true); + per_user_vault->set_keys_marked_as_stale_by_consumer(true); WriteToDisk(data_, file_path_); return true; } @@ -653,6 +659,16 @@ WriteToDisk(data_, file_path_); } +void StandaloneTrustedVaultBackend:: + SetLastRegistrationReturnedLocalDataObsoleteForTesting( + const std::string& gaia_id) { + sync_pb::LocalTrustedVaultPerUser* per_user_vault = FindUserVault(gaia_id); + DCHECK(per_user_vault); + per_user_vault->mutable_local_device_registration_info() + ->set_last_registration_returned_local_data_obsolete(true); + WriteToDisk(data_, file_path_); +} + void StandaloneTrustedVaultBackend::SetClockForTesting(base::Clock* clock) { clock_ = clock; } @@ -662,6 +678,10 @@ return pending_trusted_recovery_method_.has_value(); } +bool StandaloneTrustedVaultBackend::AreConnectionRequestsThrottledForTesting() { + return AreConnectionRequestsThrottled(); +} + absl::optional<TrustedVaultDeviceRegistrationStateForUMA> StandaloneTrustedVaultBackend::MaybeRegisterDevice() { // TODO(crbug.com/1102340): in case of transient failure this function is @@ -702,7 +722,8 @@ return TrustedVaultDeviceRegistrationStateForUMA::kAlreadyRegisteredV0; } - if (per_user_vault->keys_are_stale()) { + if (per_user_vault->local_device_registration_info() + .last_registration_returned_local_data_obsolete()) { // Client already knows that existing vault keys (or their absence) isn't // sufficient for device registration. Fresh keys should be obtained first. return TrustedVaultDeviceRegistrationStateForUMA::kLocalKeysAreStale; @@ -803,6 +824,13 @@ FindUserVault(primary_account_->gaia); DCHECK(per_user_vault); + // Registration is only attempted if the was no previous failure with + // |kLocalDataObsolete|. If this precondition wasn't guaranteed here, the + // field would need to be reset for some cases below such as `kSuccess` and + // `kAlreadyRegistered`. + DCHECK(!per_user_vault->local_device_registration_info() + .last_registration_returned_local_data_obsolete()); + switch (status) { case TrustedVaultRegistrationStatus::kSuccess: case TrustedVaultRegistrationStatus::kAlreadyRegistered: @@ -815,7 +843,8 @@ WriteToDisk(data_, file_path_); return; case TrustedVaultRegistrationStatus::kLocalDataObsolete: - per_user_vault->set_keys_are_stale(true); + per_user_vault->mutable_local_device_registration_info() + ->set_last_registration_returned_local_data_obsolete(true); WriteToDisk(data_, file_path_); return; case TrustedVaultRegistrationStatus::kAccessTokenFetchingFailure: @@ -906,7 +935,6 @@ case TrustedVaultDownloadKeysStatus::kMembershipNotFound: case TrustedVaultDownloadKeysStatus::kMembershipCorrupted: case TrustedVaultDownloadKeysStatus::kMembershipEmpty: - case TrustedVaultDownloadKeysStatus::kNoNewKeys: case TrustedVaultDownloadKeysStatus::kKeyProofsVerificationFailed: { // Unable to download new keys due to known protocol errors. The only way // to go out of these states is to receive new vault keys through external @@ -920,6 +948,13 @@ WriteToDisk(data_, file_path_); break; } + case TrustedVaultDownloadKeysStatus::kNoNewKeys: + // The registration itself exists, but there's no additional keys to + // download. This is bad because key download attempts are triggered for + // the case where local keys have been marked as stale, which means the + // user is likely in an unrecoverable state. + RecordFailedConnectionRequestForThrottling(); + break; case TrustedVaultDownloadKeysStatus::kAccessTokenFetchingFailure: // Request wasn't sent to the server, so there is no need for throttling. break;
diff --git a/components/sync/trusted_vault/standalone_trusted_vault_backend.h b/components/sync/trusted_vault/standalone_trusted_vault_backend.h index ae19e22..7ef6eba2 100644 --- a/components/sync/trusted_vault/standalone_trusted_vault_backend.h +++ b/components/sync/trusted_vault/standalone_trusted_vault_backend.h
@@ -129,11 +129,15 @@ void SetDeviceRegisteredVersionForTesting(const std::string& gaia_id, int version); + void SetLastRegistrationReturnedLocalDataObsoleteForTesting( + const std::string& gaia_id); void SetClockForTesting(base::Clock* clock); bool HasPendingTrustedRecoveryMethodForTesting() const; + bool AreConnectionRequestsThrottledForTesting(); + private: friend class base::RefCountedThreadSafe<StandaloneTrustedVaultBackend>;
diff --git a/components/sync/trusted_vault/standalone_trusted_vault_backend_unittest.cc b/components/sync/trusted_vault/standalone_trusted_vault_backend_unittest.cc index c669563..712b88e 100644 --- a/components/sync/trusted_vault/standalone_trusted_vault_backend_unittest.cc +++ b/components/sync/trusted_vault/standalone_trusted_vault_backend_unittest.cc
@@ -176,6 +176,7 @@ backend_ = base::MakeRefCounted<StandaloneTrustedVaultBackend>( file_path_, std::move(delegate), std::move(connection)); backend_->SetClockForTesting(&clock_); + backend_->ReadDataFromDisk(); // To avoid DCHECK failures in tests that exercise SetPrimaryAccount(), // return non-null for RegisterAuthenticationFactor(). This registration @@ -428,19 +429,19 @@ sync_pb::LocalTrustedVaultPerUser* user_data1 = initial_data.add_user(); sync_pb::LocalTrustedVaultPerUser* user_data2 = initial_data.add_user(); user_data1->set_gaia_id(account_info_1.gaia); - user_data1->set_keys_are_stale(true); + user_data1->set_keys_marked_as_stale_by_consumer(true); user_data2->set_gaia_id(account_info_2.gaia); - user_data2->set_keys_are_stale(true); + user_data2->set_keys_marked_as_stale_by_consumer(true); ASSERT_TRUE(WriteLocalTrustedVaultFile(initial_data, file_path())); - // Backend should reset |keys_are_stale| for both accounts and write new - // state. + // Backend should reset |keys_marked_as_stale_by_consumer| for both accounts + // and write new state. backend()->ReadDataFromDisk(); sync_pb::LocalTrustedVault new_data = ReadLocalTrustedVaultFile(file_path()); ASSERT_THAT(new_data.user_size(), Eq(2)); - EXPECT_FALSE(new_data.user(0).keys_are_stale()); - EXPECT_FALSE(new_data.user(1).keys_are_stale()); + EXPECT_FALSE(new_data.user(0).keys_marked_as_stale_by_consumer()); + EXPECT_FALSE(new_data.user(1).keys_marked_as_stale_by_consumer()); EXPECT_THAT(new_data.data_version(), Eq(2)); } @@ -678,9 +679,11 @@ EXPECT_TRUE(OSCrypt::DecryptString(ciphertext, &decrypted_content)); EXPECT_TRUE(proto.ParseFromString(decrypted_content)); ASSERT_THAT(proto.user_size(), Eq(1)); - // Ensure that keys are marked as stale, regression test for - // crbug.com/1358015. - EXPECT_TRUE(proto.user(0).keys_are_stale()); + // Ensure that the failure is remembered, so there are no retries. This is a + // regression test for crbug.com/1358015. + EXPECT_TRUE(proto.user(0) + .local_device_registration_info() + .last_registration_returned_local_data_obsolete()); // Additionally ensure that |local_device_registration_info| has correct // state. EXPECT_FALSE( @@ -688,6 +691,9 @@ EXPECT_TRUE(proto.user(0) .local_device_registration_info() .has_private_key_material()); + // Keys shouldn't be marked as stale: this is exclusively about upper layers + // invoking MarkLocalKeysAsStale(). + EXPECT_FALSE(proto.user(0).keys_marked_as_stale_by_consumer()); } TEST_F(StandaloneTrustedVaultBackendTest, @@ -792,7 +798,7 @@ } TEST_F(StandaloneTrustedVaultBackendTest, - ShouldNotRegisterDeviceIfLocalKeysAreStale) { + ShouldTryToRegisterDeviceEvenIfLocalKeysAreStale) { const CoreAccountInfo account_info = MakeAccountInfoWithGaiaId("user"); const std::vector<uint8_t> kVaultKey = {1, 2, 3}; const int kLastKeyVersion = 1; @@ -800,6 +806,36 @@ backend()->StoreKeys(account_info.gaia, {kVaultKey}, kLastKeyVersion); ASSERT_TRUE(backend()->MarkLocalKeysAsStale(account_info)); + EXPECT_CALL(*connection(), RegisterDeviceWithoutKeys).Times(0); + + EXPECT_CALL(*connection(), + RegisterAuthenticationFactor( + Eq(account_info), ElementsAre(kVaultKey), kLastKeyVersion, _, + AuthenticationFactorType::kPhysicalDevice, + /*authentication_factor_type_hint=*/Eq(absl::nullopt), _)); + + base::HistogramTester histogram_tester; + backend()->SetPrimaryAccount(account_info, + /*has_persistent_auth_error=*/false); + + histogram_tester.ExpectUniqueSample( + "Sync.TrustedVaultDeviceRegistrationState", + /*sample=*/ + TrustedVaultDeviceRegistrationStateForUMA:: + kAttemptingRegistrationWithNewKeyPair, + /*expected_bucket_count=*/1); +} + +TEST_F(StandaloneTrustedVaultBackendTest, + ShouldNotTryToRegisterDeviceIfPreviousAttemptFailed) { + const CoreAccountInfo account_info = MakeAccountInfoWithGaiaId("user"); + const std::vector<uint8_t> kVaultKey = {1, 2, 3}; + const int kLastKeyVersion = 1; + + backend()->StoreKeys(account_info.gaia, {kVaultKey}, kLastKeyVersion); + backend()->SetLastRegistrationReturnedLocalDataObsoleteForTesting( + account_info.gaia); + EXPECT_CALL(*connection(), RegisterAuthenticationFactor).Times(0); EXPECT_CALL(*connection(), RegisterDeviceWithoutKeys).Times(0); @@ -815,6 +851,38 @@ } TEST_F(StandaloneTrustedVaultBackendTest, + ShouldRegisterDeviceAlthoughPreviousAttemptFailedUponNewStoredKeys) { + const CoreAccountInfo account_info = MakeAccountInfoWithGaiaId("user"); + const std::vector<uint8_t> kInitialKeys = {1, 2, 3}; + const int kInitialKeysVersion = 5; + const std::vector<uint8_t> kNewKeys = {1, 2, 3, 4}; + const int kNewKeysVersion = 6; + + backend()->StoreKeys(account_info.gaia, {kInitialKeys}, kInitialKeysVersion); + backend()->SetLastRegistrationReturnedLocalDataObsoleteForTesting( + account_info.gaia); + + EXPECT_CALL(*connection(), RegisterAuthenticationFactor).Times(0); + EXPECT_CALL(*connection(), RegisterDeviceWithoutKeys).Times(0); + backend()->SetPrimaryAccount(account_info, + /*has_persistent_auth_error=*/false); + Mock::VerifyAndClearExpectations(connection()); + + ASSERT_FALSE(backend() + ->GetDeviceRegistrationInfoForTesting(account_info.gaia) + .device_registered()); + + // StoreKeys() should trigger a registration nevertheless. + EXPECT_CALL(*connection(), + RegisterAuthenticationFactor( + Eq(account_info), ElementsAre(kNewKeys), kNewKeysVersion, _, + AuthenticationFactorType::kPhysicalDevice, + /*authentication_factor_type_hint=*/Eq(absl::nullopt), _)); + + backend()->StoreKeys(account_info.gaia, {kNewKeys}, kNewKeysVersion); +} + +TEST_F(StandaloneTrustedVaultBackendTest, ShouldThrottleAndUnthrottleDeviceRegistration) { const CoreAccountInfo account_info = MakeAccountInfoWithGaiaId("user"); const std::vector<uint8_t> kVaultKey = {1, 2, 3}; @@ -850,7 +918,6 @@ base::HistogramTester histogram_tester; ResetBackend(); EXPECT_CALL(*connection(), RegisterAuthenticationFactor).Times(0); - backend()->ReadDataFromDisk(); backend()->SetPrimaryAccount(account_info, /*has_persistent_auth_error=*/false); histogram_tester.ExpectUniqueSample( @@ -865,7 +932,6 @@ ResetBackend(); EXPECT_CALL(*connection(), RegisterAuthenticationFactor); clock()->Advance(kTrustedVaultServiceThrottlingDuration.Get()); - backend()->ReadDataFromDisk(); backend()->SetPrimaryAccount(account_info, /*has_persistent_auth_error=*/false); histogram_tester2.ExpectUniqueSample( @@ -911,7 +977,6 @@ // throttled. ResetBackend(); EXPECT_CALL(*connection(), RegisterAuthenticationFactor); - backend()->ReadDataFromDisk(); backend()->SetPrimaryAccount(account_info, /*has_persistent_auth_error=*/false); } @@ -1170,6 +1235,7 @@ "Sync.TrustedVaultDownloadKeysStatus", /*sample=*/TrustedVaultDownloadKeysStatusForUMA::kOtherError, /*expected_bucket_count=*/1); + EXPECT_TRUE(backend()->AreConnectionRequestsThrottledForTesting()); download_keys_callback = TrustedVaultConnection::DownloadNewKeysCallback(); EXPECT_CALL(*connection(), DownloadNewKeys).Times(0); @@ -1180,12 +1246,63 @@ // Advance time to pass the throttling duration and trigger another attempt. clock()->Advance(kTrustedVaultServiceThrottlingDuration.Get()); + EXPECT_FALSE(backend()->AreConnectionRequestsThrottledForTesting()); EXPECT_CALL(*connection(), DownloadNewKeys); backend()->FetchKeys(account_info, /*callback=*/base::DoNothing()); EXPECT_FALSE(download_keys_callback.is_null()); } +TEST_F(StandaloneTrustedVaultBackendTest, + ShouldThrottleIfDownloadingReturnedNoNewKeys) { + const CoreAccountInfo account_info = MakeAccountInfoWithGaiaId("user"); + const std::vector<uint8_t> kInitialVaultKey = {1, 2, 3}; + const int kInitialLastKeyVersion = 1; + + std::vector<uint8_t> private_device_key_material = + StoreKeysAndMimicDeviceRegistration({kInitialVaultKey}, + kInitialLastKeyVersion, account_info); + EXPECT_TRUE(backend()->MarkLocalKeysAsStale(account_info)); + backend()->SetPrimaryAccount(account_info, + /*has_persistent_auth_error=*/false); + + TrustedVaultConnection::DownloadNewKeysCallback download_keys_callback; + ON_CALL(*connection(), DownloadNewKeys) + .WillByDefault( + [&](const CoreAccountInfo&, + const absl::optional<TrustedVaultKeyAndVersion>&, + std::unique_ptr<SecureBoxKeyPair> key_pair, + TrustedVaultConnection::DownloadNewKeysCallback callback) { + download_keys_callback = std::move(callback); + return std::make_unique<TrustedVaultConnection::Request>(); + }); + + EXPECT_CALL(*connection(), DownloadNewKeys); + + // FetchKeys() should trigger keys downloading. + backend()->FetchKeys(account_info, /*callback=*/base::DoNothing()); + ASSERT_FALSE(download_keys_callback.is_null()); + Mock::VerifyAndClearExpectations(connection()); + + // Mimic the server having no new keys. + base::HistogramTester histogram_tester; + std::move(download_keys_callback) + .Run(TrustedVaultDownloadKeysStatus::kNoNewKeys, + /*keys=*/std::vector<std::vector<uint8_t>>(), + /*last_key_version=*/0); + histogram_tester.ExpectUniqueSample( + "Sync.TrustedVaultDownloadKeysStatus", + /*sample=*/TrustedVaultDownloadKeysStatusForUMA::kNoNewKeys, + /*expected_bucket_count=*/1); + + EXPECT_TRUE(backend()->AreConnectionRequestsThrottledForTesting()); + + // Registration should remain intact. + EXPECT_TRUE(backend() + ->GetDeviceRegistrationInfoForTesting(account_info.gaia) + .device_registered()); +} + // Tests silent device registration (when no vault keys available yet). After // successful registration, the client should be able to download keys. TEST_F(StandaloneTrustedVaultBackendTest, @@ -1261,7 +1378,7 @@ const int kLastKeyVersion = 1; std::vector<uint8_t> private_device_key = StoreKeysAndMimicDeviceRegistration( - {kVaultKey}, kLastKeyVersion, account_info); + {GetConstantTrustedVaultKey(), kVaultKey}, kLastKeyVersion, account_info); // Mimic that device was registered before "redo registration" logic was // introduced. backend()->SetDeviceRegisteredVersionForTesting(account_info.gaia, @@ -1269,7 +1386,6 @@ // Mimic restart to be able to test histogram recording. ResetBackend(); - backend()->ReadDataFromDisk(); // Another device registration request should be issued upon setting the // primary account. @@ -1330,7 +1446,6 @@ { // Mimic the restart and verify that kAlreadyRegisteredV1 is recorded. ResetBackend(); - backend()->ReadDataFromDisk(); base::HistogramTester histogram_tester; backend()->SetPrimaryAccount(account_info, @@ -1378,7 +1493,6 @@ // Mimic restart to be able to test histogram recording. ResetBackend(); - backend()->ReadDataFromDisk(); // Another device registration request should be issued upon setting the // primary account and it should ignore presence of @@ -1434,7 +1548,6 @@ { // Mimic the restart and verify that kAlreadyRegisteredV1 is recorded. ResetBackend(); - backend()->ReadDataFromDisk(); base::HistogramTester histogram_tester; backend()->SetPrimaryAccount(account_info, @@ -1469,7 +1582,6 @@ // Mimic restart to be able to test histogram recording. ResetBackend(); - backend()->ReadDataFromDisk(); // No registration attempt should be made, since device is already registered // and "redo registration" logic is disabled. @@ -1508,7 +1620,6 @@ // Mimic restart to be able to test histogram recording. ResetBackend(); - backend()->ReadDataFromDisk(); // No registration attempt should be made, since device is already registered // with version 1. @@ -1740,7 +1851,6 @@ // Mimic a restart. The device should remain registered. ResetBackend(); - backend()->ReadDataFromDisk(); ASSERT_TRUE(backend() ->GetDeviceRegistrationInfoForTesting(account_info.gaia)
diff --git a/components/viz/common/features.cc b/components/viz/common/features.cc index 228cdb4..dbd3021 100644 --- a/components/viz/common/features.cc +++ b/components/viz/common/features.cc
@@ -220,6 +220,16 @@ "EagerSurfaceGarbageCollection", base::FEATURE_DISABLED_BY_DEFAULT); +// Only applies when a caller has requested a custom BeginFrame rate via the +// Throttle() API in frame_sink_manager.mojom. If enabled, parameters related +// to the BeginFrame rate are overridden in viz to reflect the throttled rate +// before being circulated in the system. The most notable are the interval and +// deadline in BeginFrameArgs. If disabled, these parameters reflect the default +// vsync rate (the behavior at the time this feature was created.) +BASE_FEATURE(kOverrideThrottledFrameRateParams, + "OverrideThrottledFrameRateParams", + base::FEATURE_DISABLED_BY_DEFAULT); + bool IsAdpfEnabled() { // TODO(crbug.com/1157620): Limit this to correct android version. return base::FeatureList::IsEnabled(kAdpf); @@ -385,4 +395,8 @@ return base::FeatureList::IsEnabled(kVideoDetectorIgnoreNonVideos); } +bool ShouldOverrideThrottledFrameRateParams() { + return base::FeatureList::IsEnabled(kOverrideThrottledFrameRateParams); +} + } // namespace features
diff --git a/components/viz/common/features.h b/components/viz/common/features.h index 689af05..5176e7b 100644 --- a/components/viz/common/features.h +++ b/components/viz/common/features.h
@@ -62,6 +62,7 @@ VIZ_COMMON_EXPORT BASE_DECLARE_FEATURE(kAllowUndamagedNonrootRenderPassToSkip); VIZ_COMMON_EXPORT BASE_DECLARE_FEATURE(kAggressiveFrameCulling); VIZ_COMMON_EXPORT BASE_DECLARE_FEATURE(kEagerSurfaceGarbageCollection); +VIZ_COMMON_EXPORT BASE_DECLARE_FEATURE(kOverrideThrottledFrameRateParams); VIZ_COMMON_EXPORT extern const char kDraw1Point12Ms[]; VIZ_COMMON_EXPORT extern const char kDraw2Points6Ms[]; @@ -100,6 +101,7 @@ VIZ_COMMON_EXPORT absl::optional<double> IsDynamicSchedulerEnabledForClients(); VIZ_COMMON_EXPORT int MaxOverlaysConsidered(); VIZ_COMMON_EXPORT bool ShouldVideoDetectorIgnoreNonVideoFrames(); +VIZ_COMMON_EXPORT bool ShouldOverrideThrottledFrameRateParams(); } // namespace features
diff --git a/components/viz/common/resources/resource_sizes.h b/components/viz/common/resources/resource_sizes.h index 6ca3bb8..12b3e82 100644 --- a/components/viz/common/resources/resource_sizes.h +++ b/components/viz/common/resources/resource_sizes.h
@@ -38,6 +38,12 @@ static bool MaybeSizeInBytes(const gfx::Size& size, ResourceFormat format, T* bytes); + // WARNING: The `format` must be single planar. + // TODO(hitawala): Add multiplanar format support. + template <typename T> + static bool MaybeSizeInBytes(const gfx::Size& size, + SharedImageFormat format, + T* bytes); // Dies with a CRASH() if the width can not be represented as a positive // number of bytes. @@ -47,7 +53,10 @@ // number of bytes. template <typename T> static T CheckedSizeInBytes(const gfx::Size& size, ResourceFormat format); - + // WARNING: The `format` must be single planar. + // TODO(hitawala): Add multiplanar format support. + template <typename T> + static T CheckedSizeInBytes(const gfx::Size& size, SharedImageFormat format); // Returns the width in bytes but may overflow or return 0. Only do this for // computing widths for sizes that have already been checked. template <typename T> @@ -56,6 +65,11 @@ // sizes that have already been checked. template <typename T> static T UncheckedSizeInBytes(const gfx::Size& size, ResourceFormat format); + // WARNING: The `format` must be single planar. + // TODO(hitawala): Add multiplanar format support. + template <typename T> + static T UncheckedSizeInBytes(const gfx::Size& size, + SharedImageFormat format); // Returns the width in bytes aligned but may overflow or return 0. Only do // this for computing widths for sizes that have already been checked. template <typename T> @@ -145,6 +159,13 @@ } template <typename T> +bool ResourceSizes::MaybeSizeInBytes(const gfx::Size& size, + SharedImageFormat format, + T* bytes) { + return MaybeSizeInBytes<T>(size, format.resource_format(), bytes); +} + +template <typename T> T ResourceSizes::CheckedWidthInBytes(int width, ResourceFormat format) { VerifyType<T>(); CHECK_GT(width, 0); @@ -164,6 +185,12 @@ } template <typename T> +T ResourceSizes::CheckedSizeInBytes(const gfx::Size& size, + SharedImageFormat format) { + return CheckedSizeInBytes<T>(size, format.resource_format()); +} + +template <typename T> T ResourceSizes::UncheckedWidthInBytes(int width, ResourceFormat format) { VerifyType<T>(); DCHECK_GT(width, 0); @@ -181,6 +208,12 @@ } template <typename T> +T ResourceSizes::UncheckedSizeInBytes(const gfx::Size& size, + SharedImageFormat format) { + return UncheckedSizeInBytes<T>(size, format.resource_format()); +} + +template <typename T> T ResourceSizes::UncheckedWidthInBytesAligned(int width, ResourceFormat format) { VerifyType<T>();
diff --git a/components/viz/service/display_embedder/skia_output_device_buffer_queue_unittest.cc b/components/viz/service/display_embedder/skia_output_device_buffer_queue_unittest.cc index 559f8f4..7e55967 100644 --- a/components/viz/service/display_embedder/skia_output_device_buffer_queue_unittest.cc +++ b/components/viz/service/display_embedder/skia_output_device_buffer_queue_unittest.cc
@@ -147,7 +147,7 @@ // gpu::SharedImageBackingFactory implementation. std::unique_ptr<gpu::SharedImageBacking> CreateSharedImage( const gpu::Mailbox& mailbox, - ResourceFormat format, + SharedImageFormat format, gpu::SurfaceHandle surface_handle, const gfx::Size& size, const gfx::ColorSpace& color_space, @@ -163,7 +163,7 @@ } std::unique_ptr<gpu::SharedImageBacking> CreateSharedImage( const gpu::Mailbox& mailbox, - ResourceFormat format, + SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, @@ -190,7 +190,7 @@ return nullptr; } bool IsSupported(uint32_t usage, - ResourceFormat format, + SharedImageFormat format, const gfx::Size& size, bool thread_safe, gfx::GpuMemoryBufferType gmb_type,
diff --git a/components/viz/service/frame_sinks/compositor_frame_sink_support.cc b/components/viz/service/frame_sinks/compositor_frame_sink_support.cc index f0cd7cd..7c13ec4 100644 --- a/components/viz/service/frame_sinks/compositor_frame_sink_support.cc +++ b/components/viz/service/frame_sinks/compositor_frame_sink_support.cc
@@ -20,6 +20,7 @@ #include "components/power_scheduler/power_mode.h" #include "components/power_scheduler/power_mode_arbiter.h" #include "components/power_scheduler/power_mode_voter.h" +#include "components/viz/common/features.h" #include "components/viz/common/frame_sinks/begin_frame_source.h" #include "components/viz/common/quads/compositor_frame.h" #include "components/viz/common/quads/compositor_render_pass.h" @@ -764,6 +765,14 @@ details.presentation_feedback = feedback; AdjustPresentationFeedback(&details.presentation_feedback, swap_timings.swap_start); + // Override with the throttled interval if one has been set. Otherwise, + // consumers will assume that the default vsync interval was the target and + // that the frames are presented too late when in fact, this is intentional. + if (begin_frame_interval_.is_positive() && + details.presentation_feedback.interval.is_positive() && + features::ShouldOverrideThrottledFrameRateParams()) { + details.presentation_feedback.interval = begin_frame_interval_; + } pending_received_frame_times_.erase(received_frame_timestamp); // We should only ever get one PresentationFeedback per frame_token. @@ -817,37 +826,50 @@ CheckPendingSurfaces(); + BeginFrameArgs adjusted_args = args; + if (begin_frame_interval_.is_positive() && + features::ShouldOverrideThrottledFrameRateParams()) { + adjusted_args.interval = begin_frame_interval_; + // Deadline is not necessarily frame_time + interval. For example, it may + // incorporate an estimate for the frame's draw/swap time, so it's + // desirable to preserve any offset from the next scheduled frame. + base::TimeDelta offset_from_next_scheduled_frame = + args.deadline - (args.frame_time + args.interval); + adjusted_args.deadline = args.frame_time + begin_frame_interval_ + + offset_from_next_scheduled_frame; + } + bool send_begin_frame_to_client = - client_ && ShouldSendBeginFrame(args.frame_time); + client_ && ShouldSendBeginFrame(adjusted_args.frame_time); if (send_begin_frame_to_client) { if (last_activated_surface_id_.is_valid()) - surface_manager_->SurfaceDamageExpected(last_activated_surface_id_, args); - last_begin_frame_args_ = args; + surface_manager_->SurfaceDamageExpected(last_activated_surface_id_, + adjusted_args); + last_begin_frame_args_ = adjusted_args; - BeginFrameArgs copy_args = args; // Force full frame if surface not yet activated to ensure surface creation. if (!last_activated_surface_id_.is_valid()) - copy_args.animate_only = false; + adjusted_args.animate_only = false; - copy_args.trace_id = ComputeTraceId(); + adjusted_args.trace_id = ComputeTraceId(); TRACE_EVENT_WITH_FLOW1("viz,benchmark", "Graphics.Pipeline", - TRACE_ID_GLOBAL(copy_args.trace_id), + TRACE_ID_GLOBAL(adjusted_args.trace_id), TRACE_EVENT_FLAG_FLOW_OUT, "step", "IssueBeginFrame"); - copy_args.frames_throttled_since_last = frames_throttled_since_last_; + adjusted_args.frames_throttled_since_last = frames_throttled_since_last_; frames_throttled_since_last_ = 0; - last_frame_time_ = args.frame_time; - client_->OnBeginFrame(copy_args, std::move(frame_timing_details_)); - begin_frame_tracker_.SentBeginFrame(args); - frame_sink_manager_->DidBeginFrame(frame_sink_id_, args); + last_frame_time_ = adjusted_args.frame_time; + client_->OnBeginFrame(adjusted_args, std::move(frame_timing_details_)); + begin_frame_tracker_.SentBeginFrame(adjusted_args); + frame_sink_manager_->DidBeginFrame(frame_sink_id_, adjusted_args); frame_timing_details_.clear(); UpdateNeedsBeginFramesInternal(); } // Notify surface animation manager of the latest time and advance a frame if // it needs a begin frame. - surface_animation_manager_.UpdateFrameTime(args.frame_time); + surface_animation_manager_.UpdateFrameTime(adjusted_args.frame_time); if (surface_animation_manager_.NeedsBeginFrame()) { surface_animation_manager_.NotifyFrameAdvanced(); @@ -856,7 +878,7 @@ if (surface_animation_manager_.NeedsBeginFrame()) { if (last_activated_surface_id_.is_valid()) { if (!send_begin_frame_to_client) - frame_sink_manager_->DidBeginFrame(frame_sink_id_, args); + frame_sink_manager_->DidBeginFrame(frame_sink_id_, adjusted_args); auto* surface = surface_manager_->GetSurfaceForId(last_activated_surface_id_); @@ -882,7 +904,7 @@ // `DidNotProduceFrame()`. if (!send_begin_frame_to_client && begin_frame_source_) { begin_frame_source_->DidFinishFrame(this); - frame_sink_manager_->DidFinishFrame(frame_sink_id_, args); + frame_sink_manager_->DidFinishFrame(frame_sink_id_, adjusted_args); } } } else {
diff --git a/components/viz/service/frame_sinks/compositor_frame_sink_support_unittest.cc b/components/viz/service/frame_sinks/compositor_frame_sink_support_unittest.cc index 9f3d94e8..e9d47065 100644 --- a/components/viz/service/frame_sinks/compositor_frame_sink_support_unittest.cc +++ b/components/viz/service/frame_sinks/compositor_frame_sink_support_unittest.cc
@@ -7,9 +7,11 @@ #include <utility> #include "base/bind.h" +#include "base/test/scoped_feature_list.h" #include "base/test/simple_test_tick_clock.h" #include "base/time/time.h" #include "build/build_config.h" +#include "components/viz/common/features.h" #include "components/viz/common/frame_sinks/copy_output_request.h" #include "components/viz/common/frame_sinks/copy_output_result.h" #include "components/viz/common/quads/compositor_frame.h" @@ -34,9 +36,12 @@ #include "third_party/khronos/GLES2/gl2.h" using testing::_; +using testing::Contains; using testing::Eq; using testing::Invoke; using testing::IsEmpty; +using testing::Key; +using testing::Ne; using testing::SizeIs; using testing::UnorderedElementsAre; @@ -95,12 +100,17 @@ class CompositorFrameSinkSupportTest : public testing::Test { public: - CompositorFrameSinkSupportTest() + explicit CompositorFrameSinkSupportTest( + bool override_throttled_frame_rate_params = false) : manager_(FrameSinkManagerImpl::InitParams(&shared_bitmap_manager_)), begin_frame_source_(0.f, false), local_surface_id_(3, kArbitraryToken), frame_sync_token_(GenTestSyncToken(4)), consumer_sync_token_(GenTestSyncToken(5)) { + if (override_throttled_frame_rate_params) { + scoped_feature_list_.InitAndEnableFeature( + features::kOverrideThrottledFrameRateParams); + } manager_.SetLocalClient(&frame_sink_manager_client_); now_src_ = std::make_unique<base::SimpleTestTickClock>(); manager_.surface_manager()->SetTickClockForTesting(now_src_.get()); @@ -240,6 +250,7 @@ } protected: + base::test::ScopedFeatureList scoped_feature_list_; std::unique_ptr<base::SimpleTestTickClock> now_src_; ServerSharedBitmapManager shared_bitmap_manager_; FrameSinkManagerImpl manager_; @@ -259,6 +270,14 @@ const gpu::SyncToken consumer_sync_token_; }; +class ThrottledBeginFrameCompositorFrameSinkSupportTest + : public CompositorFrameSinkSupportTest { + protected: + ThrottledBeginFrameCompositorFrameSinkSupportTest() + : CompositorFrameSinkSupportTest( + /*override_throttled_frame_rate_params=*/true) {} +}; + // Tests submitting a frame with resources followed by one with no resources // with no resource provider action in between. TEST_F(CompositorFrameSinkSupportTest, ResourceLifetimeSimple) { @@ -1553,7 +1572,7 @@ // Verifies that when CompositorFrameSinkSupport has its |begin_frame_interval_| // set, any BeginFrame would be sent only after this interval has passed from // the time when the last BeginFrame was sent. -TEST_F(CompositorFrameSinkSupportTest, BeginFrameInterval) { +TEST_F(ThrottledBeginFrameCompositorFrameSinkSupportTest, BeginFrameInterval) { FakeExternalBeginFrameSource begin_frame_source(0.f, false); testing::NiceMock<MockCompositorFrameSinkClient> mock_client; @@ -1582,9 +1601,14 @@ EXPECT_CALL(mock_client, OnBeginFrame(_, _)).Times(0); ++frames_throttled_since_last; } else { - args.frames_throttled_since_last = frames_throttled_since_last; + BeginFrameArgs expected_args(args); + expected_args.interval = throttled_interval; + expected_args.deadline = + frame_time + throttled_interval - + BeginFrameArgs::DefaultEstimatedDisplayDrawTime(interval); + expected_args.frames_throttled_since_last = frames_throttled_since_last; frames_throttled_since_last = 0; - EXPECT_CALL(mock_client, OnBeginFrame(args, _)).WillOnce([&]() { + EXPECT_CALL(mock_client, OnBeginFrame(expected_args, _)).WillOnce([&]() { support->SubmitCompositorFrame(local_surface_id_, MakeDefaultCompositorFrame()); GetSurfaceForId(id)->MarkAsDrawn(); @@ -1602,6 +1626,48 @@ support->SetNeedsBeginFrame(false); } +TEST_F(ThrottledBeginFrameCompositorFrameSinkSupportTest, + UsesThrottledIntervalInPresentationFeedback) { + static constexpr base::TimeDelta kThrottledFrameInterval = base::Hertz(5); + // Request BeginFrames. + support_->SetNeedsBeginFrame(true); + support_->ThrottleBeginFrame(kThrottledFrameInterval); + ASSERT_THAT(BeginFrameArgs::DefaultInterval(), Ne(kThrottledFrameInterval)); + + base::TimeTicks frame_time = base::TimeTicks::Now(); + + // Issue a BeginFrame. + BeginFrameArgs args = + CreateBeginFrameArgsForTesting(BEGINFRAME_FROM_HERE, 0, 1, frame_time); + begin_frame_source_.TestOnBeginFrame(args); + + // Client submits a compositor frame in response. + BeginFrameAck ack(args, true); + CompositorFrame frame = CompositorFrameBuilder() + .AddDefaultRenderPass() + .SetBeginFrameAck(ack) + .Build(); + auto token = frame.metadata.frame_token; + support_->SubmitCompositorFrame(local_surface_id_, std::move(frame)); + + // The presentation-feedback from the last submitted frame arrives. + SendPresentationFeedback(support_.get(), token); + + // Issue a new BeginFrame. The frame timing details with submitted + // presentation feedback should be received with the throttled interval. + frame_time += kThrottledFrameInterval; + args = CreateBeginFrameArgsForTesting(BEGINFRAME_FROM_HERE, 1, 2, frame_time); + begin_frame_source_.TestOnBeginFrame(args); + + ASSERT_THAT(fake_support_client_.all_frame_timing_details(), SizeIs(1)); + ASSERT_THAT(fake_support_client_.all_frame_timing_details(), + Contains(Key(token))); + EXPECT_THAT(fake_support_client_.all_frame_timing_details() + .at(token) + .presentation_feedback.interval, + Eq(kThrottledFrameInterval)); +} + TEST_F(CompositorFrameSinkSupportTest, ForceFullFrameToActivateSurface) { FakeExternalBeginFrameSource begin_frame_source(0.f, false); testing::NiceMock<MockCompositorFrameSinkClient> mock_client;
diff --git a/components/viz/test/fake_compositor_frame_sink_client.cc b/components/viz/test/fake_compositor_frame_sink_client.cc index 3e80d5d..fb9c36c 100644 --- a/components/viz/test/fake_compositor_frame_sink_client.cc +++ b/components/viz/test/fake_compositor_frame_sink_client.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 <utility> + #include "components/viz/test/fake_compositor_frame_sink_client.h" namespace viz { @@ -16,7 +18,11 @@ void FakeCompositorFrameSinkClient::OnBeginFrame( const BeginFrameArgs& args, - const FrameTimingDetailsMap& timing_details) {} + const FrameTimingDetailsMap& timing_details) { + for (const auto& [frame_token, timing] : timing_details) { + all_frame_timing_details_.insert_or_assign(frame_token, timing); + } +} void FakeCompositorFrameSinkClient::ReclaimResources( std::vector<ReturnedResource> resources) {
diff --git a/components/viz/test/fake_compositor_frame_sink_client.h b/components/viz/test/fake_compositor_frame_sink_client.h index 571857e0..86ca12e2 100644 --- a/components/viz/test/fake_compositor_frame_sink_client.h +++ b/components/viz/test/fake_compositor_frame_sink_client.h
@@ -42,12 +42,18 @@ return returned_resources_; } + const FrameTimingDetailsMap& all_frame_timing_details() const { + return all_frame_timing_details_; + } + private: void InsertResources(std::vector<ReturnedResource> resources); std::vector<ReturnedResource> returned_resources_; mojo::Receiver<mojom::CompositorFrameSinkClient> receiver_{this}; + + FrameTimingDetailsMap all_frame_timing_details_; }; } // namespace viz
diff --git a/components/web_package/web_bundle_parser.cc b/components/web_package/web_bundle_parser.cc index 5354e2d..01e87ef 100644 --- a/components/web_package/web_bundle_parser.cc +++ b/components/web_package/web_bundle_parser.cc
@@ -1142,15 +1142,12 @@ } void WebBundleParser::SharedBundleDataSource::AddObserver(Observer* observer) { - DCHECK(observers_.end() == observers_.find(observer)); - observers_.insert(observer); + observers_.AddObserver(observer); } void WebBundleParser::SharedBundleDataSource::RemoveObserver( Observer* observer) { - auto it = observers_.find(observer); - DCHECK(observers_.end() != it); - observers_.erase(it); + observers_.RemoveObserver(observer); } WebBundleParser::SharedBundleDataSource::~SharedBundleDataSource() = default; @@ -1159,8 +1156,8 @@ // |observer->OnDisconnect()| below may remove the last external reference to // |this|. scoped_refptr<SharedBundleDataSource> keep_alive(this); - for (auto* observer : observers_) - observer->OnDisconnect(); + for (Observer& observer : observers_) + observer.OnDisconnect(); } void WebBundleParser::SharedBundleDataSource::Read(
diff --git a/components/web_package/web_bundle_parser.h b/components/web_package/web_bundle_parser.h index 809cefe5..e090e308 100644 --- a/components/web_package/web_bundle_parser.h +++ b/components/web_package/web_bundle_parser.h
@@ -5,8 +5,8 @@ #ifndef COMPONENTS_WEB_PACKAGE_WEB_BUNDLE_PARSER_H_ #define COMPONENTS_WEB_PACKAGE_WEB_BUNDLE_PARSER_H_ -#include "base/containers/flat_set.h" #include "base/memory/ref_counted.h" +#include "base/observer_list.h" #include "components/web_package/mojom/web_bundle_parser.mojom.h" #include "mojo/public/cpp/bindings/receiver.h" #include "mojo/public/cpp/bindings/remote.h" @@ -28,14 +28,8 @@ class SharedBundleDataSource : public base::RefCounted<SharedBundleDataSource> { public: - class Observer { + class Observer : public base::CheckedObserver { public: - Observer() = default; - - Observer(const Observer&) = delete; - Observer& operator=(const Observer&) = delete; - - virtual ~Observer() = default; virtual void OnDisconnect() = 0; }; @@ -65,7 +59,7 @@ void OnDisconnect(); mojo::Remote<mojom::BundleDataSource> data_source_; - base::flat_set<Observer*> observers_; + base::ObserverList<Observer> observers_; }; private:
diff --git a/components/webapps/browser/banners/app_banner_manager.cc b/components/webapps/browser/banners/app_banner_manager.cc index adffbd4..1912e31 100644 --- a/components/webapps/browser/banners/app_banner_manager.cc +++ b/components/webapps/browser/banners/app_banner_manager.cc
@@ -334,7 +334,6 @@ case State::INACTIVE: case State::ACTIVE: case State::FETCHING_NATIVE_DATA: - case State::PENDING_WORKER: case State::PENDING_ENGAGEMENT: case State::SENDING_EVENT: case State::SENDING_EVENT_GOT_EARLY_PROMPT: @@ -368,15 +367,9 @@ InstallableParams params; params.valid_primary_icon = true; params.valid_manifest = true; - params.fetch_screenshots = true; - - return params; -} - -InstallableParams AppBannerManager::ParamsToPerformWorkerCheck() { - InstallableParams params; params.has_worker = true; params.wait_for_worker = true; + params.fetch_screenshots = true; return params; } @@ -403,11 +396,30 @@ return; UpdateState(State::ACTIVE); - if (data.valid_manifest) + if (data.worker_check_passed && data.valid_manifest) TrackDisplayEvent(DISPLAY_EVENT_WEB_APP_BANNER_REQUESTED); + bool no_matching_service_worker = + base::Contains(data.errors, NO_MATCHING_SERVICE_WORKER); + if (no_matching_service_worker) { + TrackDisplayEvent(DISPLAY_EVENT_LACKS_SERVICE_WORKER); + } + bool is_installable = data.NoBlockingErrors(); + // When |features::SkipInstallServiceWorkerCheck| is true, a service worker is + // still required to display the banner prompt. This would mean that while a + // banner may not appear, the site is still considered installable if it only + // failed service worker checks. + bool worker_errors_ignored_for_installs = false; + if (features::SkipInstallServiceWorkerCheck() && + data.HasErrorOnlyServiceWorkerErrors()) { + DCHECK(!is_installable || base::FeatureList::IsEnabled( + features::kCreateShortcutIgnoresManifest)); + worker_errors_ignored_for_installs = true; + is_installable = true; + } + if (!is_installable) { DCHECK(!data.errors.empty()); SetInstallableWebAppCheckResult(InstallableWebAppCheckResult::kNo); @@ -430,7 +442,27 @@ return; } - DCHECK(data.valid_manifest); + if (worker_errors_ignored_for_installs) { + DCHECK(data.HasErrorOnlyServiceWorkerErrors()); + + SetInstallableWebAppCheckResult( + InstallableWebAppCheckResult::kYes_ByUserRequest); + Stop(SERVICE_WORKER_NOT_REQUIRED); + return; + } + + if (no_matching_service_worker && + base::FeatureList::IsEnabled(features::kCreateShortcutIgnoresManifest)) { + SetInstallableWebAppCheckResult( + InstallableWebAppCheckResult::kYes_ByUserRequest); + Stop(NO_MATCHING_SERVICE_WORKER); + return; + } + + SetInstallableWebAppCheckResult( + InstallableWebAppCheckResult::kYes_Promotable); + + DCHECK(data.worker_check_passed && data.valid_manifest); DCHECK(!data.primary_icon_url.is_empty()); DCHECK(data.primary_icon); @@ -438,49 +470,16 @@ primary_icon_ = *data.primary_icon; has_maskable_primary_icon_ = data.has_maskable_primary_icon; screenshots_ = data.screenshots; - - if (features::SkipInstallServiceWorkerCheck() || - base::FeatureList::IsEnabled(features::kCreateShortcutIgnoresManifest)) { - SetInstallableWebAppCheckResult( - InstallableWebAppCheckResult::kYes_ByUserRequest); - } - - PerformServiceWorkerCheck(); -} - -void AppBannerManager::PerformServiceWorkerCheck() { - UpdateState(State::PENDING_WORKER); - manager_->GetData( - ParamsToPerformWorkerCheck(), - base::BindOnce(&AppBannerManager::OnDidPerformWorkerCheck, GetWeakPtr())); -} - -void AppBannerManager::OnDidPerformWorkerCheck(const InstallableData& data) { - if (!data.NoBlockingErrors()) { - TrackDisplayEvent(DISPLAY_EVENT_LACKS_SERVICE_WORKER); - Stop(data.FirstNoBlockingError()); + // If we triggered the installability check on page load, then it's possible + // we don't have enough engagement yet. If that's the case, return here but + // don't call Terminate(). We wait for OnEngagementEvent to tell us that we + // should trigger. + if (!HasSufficientEngagement()) { + UpdateState(State::PENDING_ENGAGEMENT); return; } - passed_worker_check_ = true; - - if (state_ == State::PENDING_WORKER) { - UpdateState(State::ACTIVE); - - SetInstallableWebAppCheckResult( - InstallableWebAppCheckResult::kYes_Promotable); - - // If we triggered the installability check on page load, then it's - // possible we don't have enough engagement yet. If that's the case, - // return here but don't call Terminate(). We wait for OnEngagementEvent - // to tell us that we should trigger. - if (!HasSufficientEngagement()) { - UpdateState(State::PENDING_ENGAGEMENT); - return; - } - - SendBannerPromptRequest(); - } + SendBannerPromptRequest(); } void AppBannerManager::RecordDidShowBanner() { @@ -521,9 +520,6 @@ BEFORE_INSTALL_EVENT_PROMPT_NOT_CALLED_AFTER_PREVENT_DEFAULT); } - if (state_ == State::PENDING_WORKER && !passed_worker_check_) - TrackDisplayEvent(DISPLAY_EVENT_LACKS_SERVICE_WORKER); - if (state_ == State::PENDING_ENGAGEMENT && !has_sufficient_engagement_) TrackDisplayEvent(DISPLAY_EVENT_NOT_VISITED_ENOUGH); @@ -534,9 +530,6 @@ switch (state_) { case State::PENDING_PROMPT: return RENDERER_CANCELLED; - case State::PENDING_WORKER: - return passed_worker_check_ ? NO_ERROR_DETECTED - : NO_MATCHING_SERVICE_WORKER; case State::PENDING_ENGAGEMENT: return has_sufficient_engagement_ ? NO_ERROR_DETECTED : INSUFFICIENT_ENGAGEMENT; @@ -735,7 +728,6 @@ return; case State::ACTIVE: case State::FETCHING_NATIVE_DATA: - case State::PENDING_WORKER: case State::PENDING_ENGAGEMENT: case State::SENDING_EVENT: case State::SENDING_EVENT_GOT_EARLY_PROMPT: @@ -808,7 +800,6 @@ case State::FETCHING_MANIFEST: case State::FETCHING_NATIVE_DATA: case State::PENDING_INSTALLABLE_CHECK: - case State::PENDING_WORKER: case State::SENDING_EVENT: case State::SENDING_EVENT_GOT_EARLY_PROMPT: return true;
diff --git a/components/webapps/browser/banners/app_banner_manager.h b/components/webapps/browser/banners/app_banner_manager.h index 9545716..00002ae 100644 --- a/components/webapps/browser/banners/app_banner_manager.h +++ b/components/webapps/browser/banners/app_banner_manager.h
@@ -83,9 +83,6 @@ // engagement to trigger the banner. PENDING_ENGAGEMENT, - // The pipeline is waiting for service worker install to trigger the banner. - PENDING_WORKER, - // The beforeinstallprompt event has been sent and the pipeline is waiting // for the response. SENDING_EVENT, @@ -276,10 +273,6 @@ // necessary for a web app banner. virtual InstallableParams ParamsToPerformInstallableWebAppCheck(); - // Returns an InstallableParams object that requests service worker check - // only. - virtual InstallableParams ParamsToPerformWorkerCheck(); - // Run at the conclusion of OnDidGetManifest. For web app banners, this calls // back to the InstallableManager to continue checking criteria. For native // app banners, this checks whether native apps are preferred in the manifest, @@ -293,15 +286,6 @@ // all other installable properties. virtual void OnDidPerformInstallableWebAppCheck(const InstallableData& data); - // Run at the conclusion of OnDidPerformInstallableWebAppCheck. This calls - // back to the InstallableManager to continue checking service worker criteria - // for web app banners. - virtual void PerformServiceWorkerCheck(); - - // Callback invoked by the InstallableManager once it has finished checking - // service worker. - virtual void OnDidPerformWorkerCheck(const InstallableData& data); - // Records that a banner was shown. void RecordDidShowBanner(); @@ -442,8 +426,6 @@ bool has_sufficient_engagement_ = false; bool load_finished_ = false; - bool passed_worker_check_ = false; - std::unique_ptr<StatusReporter> status_reporter_; bool install_animation_pending_ = false; InstallableWebAppCheckResult installable_web_app_check_result_ =
diff --git a/components/webapps/browser/installable/installable_data.cc b/components/webapps/browser/installable/installable_data.cc index 00ec9e7..2f0f745 100644 --- a/components/webapps/browser/installable/installable_data.cc +++ b/components/webapps/browser/installable/installable_data.cc
@@ -41,10 +41,6 @@ InstallableData::~InstallableData() = default; bool InstallableData::NoBlockingErrors() const { - return FirstNoBlockingError() == NO_ERROR_DETECTED; -} - -InstallableStatusCode InstallableData::FirstNoBlockingError() const { for (auto e : errors) { switch (e) { case WARN_NOT_OFFLINE_CAPABLE: @@ -56,12 +52,12 @@ continue; } #endif - [[fallthrough]]; + return false; default: - return e; + return false; } } - return NO_ERROR_DETECTED; + return true; } bool InstallableData::HasErrorOnlyServiceWorkerErrors() const {
diff --git a/components/webapps/browser/installable/installable_data.h b/components/webapps/browser/installable/installable_data.h index 6e6d2a2..31bdb3f 100644 --- a/components/webapps/browser/installable/installable_data.h +++ b/components/webapps/browser/installable/installable_data.h
@@ -52,10 +52,6 @@ // M93. bool NoBlockingErrors() const; - // Returns the first no blocking error if any one exist. Otherwise returns - // NO_ERROR_DETECTED. - InstallableStatusCode FirstNoBlockingError() const; - // Returns true if there is any |errors| and all errors are service worker // errors, i.e.|NO_MATCHING_SERVICE_WORKER| or |NOT_OFFLINE_CAPABLE|. bool HasErrorOnlyServiceWorkerErrors() const;
diff --git a/content/browser/back_forward_cache_browsertest.cc b/content/browser/back_forward_cache_browsertest.cc index 818547cf..881e4ab7 100644 --- a/content/browser/back_forward_cache_browsertest.cc +++ b/content/browser/back_forward_cache_browsertest.cc
@@ -1750,9 +1750,8 @@ } } -// TODO(https://crbug.com/1275493): Flaky on various builders. IN_PROC_BROWSER_TEST_F(BackForwardCacheBrowserTest, - DISABLED_SubframeTextInputStateUpdated) { + SubframeTextInputStateUpdated) { ASSERT_TRUE(embedded_test_server()->Start()); GURL url_1(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b(a))"));
diff --git a/content/browser/back_forward_cache_features_browsertest.cc b/content/browser/back_forward_cache_features_browsertest.cc index 8ebc382..632b760 100644 --- a/content/browser/back_forward_cache_features_browsertest.cc +++ b/content/browser/back_forward_cache_features_browsertest.cc
@@ -197,16 +197,8 @@ // Confirms that a page using a dedicated worker with WebTransport is not // cached. -// TODO(crbug.com/1299018): Flakes on Linux. -#if BUILDFLAG(IS_LINUX) -#define MAYBE_DoNotCacheWithDedicatedWorkerWithWebTransport \ - DISABLED_DoNotCacheWithDedicatedWorkerWithWebTransport -#else -#define MAYBE_DoNotCacheWithDedicatedWorkerWithWebTransport \ - DoNotCacheWithDedicatedWorkerWithWebTransport -#endif IN_PROC_BROWSER_TEST_P(BackForwardCacheWithDedicatedWorkerBrowserTest, - MAYBE_DoNotCacheWithDedicatedWorkerWithWebTransport) { + DoNotCacheWithDedicatedWorkerWithWebTransport) { CreateHttpsServer(); ASSERT_TRUE(https_server()->Start()); @@ -2051,17 +2043,23 @@ return controller_; } - void OnBannerPromptRequested(bool) {} + void OnBannerPromptRequested(base::OnceClosure closure, bool) { + std::move(closure).Run(); + } void SendBannerPromptRequest() { blink::mojom::AppBannerController* controller_ptr = controller_.get(); - base::OnceCallback<void(bool)> callback = base::BindOnce( - &MockAppBannerService::OnBannerPromptRequested, base::Unretained(this)); + base::RunLoop run_loop; + base::OnceClosure quit_closure = run_loop.QuitClosure(); + base::OnceCallback<void(bool)> callback = + base::BindOnce(&MockAppBannerService::OnBannerPromptRequested, + base::Unretained(this), std::move(quit_closure)); controller_ptr->BannerPromptRequest( receiver_.BindNewPipeAndPassRemote(), event_.BindNewPipeAndPassReceiver(), {"web"}, base::BindOnce(&MockAppBannerService::OnBannerPromptReply, base::Unretained(this), std::move(callback))); + run_loop.Run(); } void OnBannerPromptReply(base::OnceCallback<void(bool)> callback, @@ -2098,14 +2096,8 @@ bool ShouldEnabledAppBannerCaching() { return GetParam(); } }; -// Disabled on Mac due to flakes; see https://crbug.com/1276864#c8. -#if BUILDFLAG(IS_MAC) -#define MAYBE_TestAppBannerCaching DISABLED_TestAppBannerCaching -#else -#define MAYBE_TestAppBannerCaching TestAppBannerCaching -#endif IN_PROC_BROWSER_TEST_P(AppBannerBackForwardCacheBrowserTest, - MAYBE_TestAppBannerCaching) { + TestAppBannerCaching) { ASSERT_TRUE(embedded_test_server()->Start()); // 1) Navigate to A and request a PWA app banner. @@ -2116,16 +2108,15 @@ MockAppBannerService mock_app_banner_service; web_contents()->GetPrimaryMainFrame()->GetRemoteInterfaces()->GetInterface( mock_app_banner_service.controller().BindNewPipeAndPassReceiver()); - // Send the request to the renderer's frame. + // Send the request to the renderer's frame, wait until the request completes. mock_app_banner_service.SendBannerPromptRequest(); - RenderFrameDeletedObserver delete_observer_rfh(current_frame_host()); - // 2) Navigate away. Page A requested a PWA app banner, and thus not cached. + RenderFrameHostWrapper rfh_a(current_frame_host()); EXPECT_TRUE(NavigateToURL( shell(), embedded_test_server()->GetURL("b.com", "/title1.html"))); if (!ShouldEnabledAppBannerCaching()) { - ASSERT_TRUE(delete_observer_rfh.WaitUntilDeleted()); + ASSERT_TRUE(rfh_a.WaitUntilRenderFrameDeleted()); } // 3) Go back to A. @@ -2472,6 +2463,7 @@ // Disabled on Android, since we have problems starting up the websocket test // server in the host +// TODO(crbug.com/1372291): Re-enable the test after solving the WS server. #if BUILDFLAG(IS_ANDROID) #define MAYBE_WebSocketNotCached DISABLED_WebSocketNotCached #else
diff --git a/content/browser/file_system_access/file_system_access_directory_handle_impl.cc b/content/browser/file_system_access/file_system_access_directory_handle_impl.cc index a303633..59af491 100644 --- a/content/browser/file_system_access/file_system_access_directory_handle_impl.cc +++ b/content/browser/file_system_access/file_system_access_directory_handle_impl.cc
@@ -4,9 +4,8 @@ #include "content/browser/file_system_access/file_system_access_directory_handle_impl.h" +#include "base/guid.h" #include "base/i18n/file_util_icu.h" -#include "base/strings/escape.h" -#include "base/strings/strcat.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" @@ -576,6 +575,15 @@ basename); } +void FileSystemAccessDirectoryHandleImpl::GetUniqueId( + GetUniqueIdCallback callback) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + base::GUID id = manager()->GetUniqueId(*this); + DCHECK(id.is_valid()); + std::move(callback).Run(id.AsLowercaseString()); +} + base::WeakPtr<FileSystemAccessHandleBase> FileSystemAccessDirectoryHandleImpl::AsWeakPtr() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
diff --git a/content/browser/file_system_access/file_system_access_directory_handle_impl.h b/content/browser/file_system_access/file_system_access_directory_handle_impl.h index f41d859..e4e1251 100644 --- a/content/browser/file_system_access/file_system_access_directory_handle_impl.h +++ b/content/browser/file_system_access/file_system_access_directory_handle_impl.h
@@ -67,6 +67,7 @@ void Transfer( mojo::PendingReceiver<blink::mojom::FileSystemAccessTransferToken> token) override; + void GetUniqueId(GetUniqueIdCallback callback) override; // Calculates a FileSystemURL for a (direct) child of this directory with the // given basename. Returns an error when `basename` includes invalid input
diff --git a/content/browser/file_system_access/file_system_access_file_handle_impl.cc b/content/browser/file_system_access/file_system_access_file_handle_impl.cc index fdd742f..2601ea0 100644 --- a/content/browser/file_system_access/file_system_access_file_handle_impl.cc +++ b/content/browser/file_system_access/file_system_access_file_handle_impl.cc
@@ -645,6 +645,14 @@ auto_close)); } +void FileSystemAccessFileHandleImpl::GetUniqueId(GetUniqueIdCallback callback) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + auto id = manager()->GetUniqueId(*this); + DCHECK(id.is_valid()); + std::move(callback).Run(id.AsLowercaseString()); +} + base::WeakPtr<FileSystemAccessHandleBase> FileSystemAccessFileHandleImpl::AsWeakPtr() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
diff --git a/content/browser/file_system_access/file_system_access_file_handle_impl.h b/content/browser/file_system_access/file_system_access_file_handle_impl.h index 1d0d8dc..7d04c39 100644 --- a/content/browser/file_system_access/file_system_access_file_handle_impl.h +++ b/content/browser/file_system_access/file_system_access_file_handle_impl.h
@@ -64,6 +64,7 @@ void Transfer( mojo::PendingReceiver<blink::mojom::FileSystemAccessTransferToken> token) override; + void GetUniqueId(GetUniqueIdCallback callback) override; void set_max_swap_files_for_testing(int max) { max_swap_files_ = max; } storage::FileSystemURL get_swap_url_for_testing(
diff --git a/content/browser/file_system_access/file_system_access_file_writer_impl.h b/content/browser/file_system_access/file_system_access_file_writer_impl.h index 60217e79..2417dfd 100644 --- a/content/browser/file_system_access/file_system_access_file_writer_impl.h +++ b/content/browser/file_system_access/file_system_access_file_writer_impl.h
@@ -58,7 +58,7 @@ ~FileSystemAccessFileWriterImpl() override; const storage::FileSystemURL& swap_url() const { return swap_url_; } - const base::WeakPtr<FileSystemAccessFileWriterImpl> weak_ptr() const { + base::WeakPtr<FileSystemAccessFileWriterImpl> weak_ptr() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); return weak_factory_.GetWeakPtr(); }
diff --git a/content/browser/file_system_access/file_system_access_handle_base.cc b/content/browser/file_system_access/file_system_access_handle_base.cc index b6d405a..0fbf9fa 100644 --- a/content/browser/file_system_access/file_system_access_handle_base.cc +++ b/content/browser/file_system_access/file_system_access_handle_base.cc
@@ -12,7 +12,6 @@ #include "base/files/file_path.h" #include "base/strings/strcat.h" #include "base/strings/utf_string_conversions.h" -#include "base/threading/sequenced_task_runner_handle.h" #include "content/browser/file_system_access/file_system_access_directory_handle_impl.h" #include "content/browser/file_system_access/file_system_access_error.h" #include "content/browser/file_system_access/file_system_access_manager_impl.h" @@ -21,11 +20,9 @@ #include "content/browser/renderer_host/back_forward_cache_disable.h" #include "content/browser/web_contents/web_contents_impl.h" #include "content/public/browser/back_forward_cache.h" -#include "content/public/browser/browser_task_traits.h" #include "content/public/browser/web_contents.h" #include "content/public/common/content_client.h" #include "content/public/common/content_switches.h" -#include "net/base/filename_util.h" #include "storage/browser/file_system/file_system_operation.h" #include "storage/browser/file_system/file_system_url.h" #include "storage/common/file_system/file_system_types.h"
diff --git a/content/browser/file_system_access/file_system_access_manager_impl.cc b/content/browser/file_system_access/file_system_access_manager_impl.cc index d63a7c9c6..06b7788 100644 --- a/content/browser/file_system_access/file_system_access_manager_impl.cc +++ b/content/browser/file_system_access/file_system_access_manager_impl.cc
@@ -14,13 +14,10 @@ #include "base/files/file.h" #include "base/files/file_path.h" #include "base/files/file_util.h" +#include "base/guid.h" #include "base/notreached.h" #include "base/ranges/algorithm.h" -#include "base/strings/escape.h" -#include "base/strings/strcat.h" #include "base/strings/string_util.h" -#include "base/strings/utf_string_conversions.h" -#include "base/task/bind_post_task.h" #include "base/task/sequenced_task_runner.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" @@ -37,6 +34,7 @@ #include "content/browser/file_system_access/file_system_access_file_handle_impl.h" #include "content/browser/file_system_access/file_system_access_file_writer_impl.h" #include "content/browser/file_system_access/file_system_access_transfer_token_impl.h" +#include "content/browser/file_system_access/file_system_access_write_lock_manager.h" #include "content/browser/file_system_access/file_system_chooser.h" #include "content/browser/file_system_access/fixed_file_system_access_permission_grant.h" #include "content/public/browser/browser_task_traits.h" @@ -45,6 +43,7 @@ #include "content/public/browser/web_contents.h" #include "content/public/common/content_client.h" #include "content/public/common/content_switches.h" +#include "crypto/secure_hash.h" #include "mojo/public/cpp/bindings/callback_helpers.h" #include "net/base/filename_util.h" #include "services/network/public/cpp/is_potentially_trustworthy.h" @@ -54,7 +53,6 @@ #include "storage/browser/file_system/file_system_util.h" #include "storage/browser/quota/quota_manager_proxy.h" #include "storage/common/file_system/file_system_types.h" -#include "storage/common/file_system/file_system_util.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/blink/public/common/storage_key/storage_key.h" #include "third_party/blink/public/mojom/file_system_access/file_system_access_capacity_allocation_host.mojom.h" @@ -1524,6 +1522,42 @@ return SharedHandleState(std::move(read_grant), std::move(write_grant)); } +base::GUID FileSystemAccessManagerImpl::GetUniqueId( + const FileSystemAccessFileHandleImpl& file) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + // TODO(https://crbug.com/1342961): This is a temporary hack to put something + // that works behind a flag. Persist handle IDs such that they're stable + // across browsing sessions. + + auto it = file_ids_.find(file.url()); + if (it != file_ids_.end()) { + return it->second; + } + + // Generate and store a new guid for this file. + auto guid = base::GUID::GenerateRandomV4(); + file_ids_[file.url()] = guid; + return guid; +} + +base::GUID FileSystemAccessManagerImpl::GetUniqueId( + const FileSystemAccessDirectoryHandleImpl& directory) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + // TODO(https://crbug.com/1342961): This is a temporary hack to put something + // that works behind a flag. Persist handle IDs such that they're stable + // across browsing sessions. + + auto it = directory_ids_.find(directory.url()); + if (it != directory_ids_.end()) { + return it->second; + } + + // Generate and store a new guid for this directory. + auto guid = base::GUID::GenerateRandomV4(); + directory_ids_[directory.url()] = guid; + return guid; +} + void FileSystemAccessManagerImpl::CleanupAccessHandleCapacityAllocation( const storage::FileSystemURL& url, int64_t allocated_file_size,
diff --git a/content/browser/file_system_access/file_system_access_manager_impl.h b/content/browser/file_system_access/file_system_access_manager_impl.h index 3c83ffb..2805a9c 100644 --- a/content/browser/file_system_access/file_system_access_manager_impl.h +++ b/content/browser/file_system_access/file_system_access_manager_impl.h
@@ -9,6 +9,7 @@ #include "base/containers/flat_set.h" #include "base/containers/unique_ptr_adapters.h" #include "base/files/file_path.h" +#include "base/guid.h" #include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" #include "base/task/bind_post_task.h" @@ -17,15 +18,12 @@ #include "base/types/pass_key.h" #include "base/unguessable_token.h" #include "components/download/public/common/quarantine_connection.h" -#include "components/services/storage/public/cpp/buckets/bucket_info.h" -#include "components/services/storage/public/cpp/quota_error_or.h" #include "components/services/storage/public/mojom/file_system_access_context.mojom.h" #include "content/browser/blob_storage/chrome_blob_storage_context.h" #include "content/browser/file_system_access/file_system_access.pb.h" #include "content/browser/file_system_access/file_system_access_write_lock_manager.h" #include "content/browser/file_system_access/file_system_chooser.h" #include "content/common/content_export.h" -#include "content/public/browser/browser_thread.h" #include "content/public/browser/file_system_access_entry_factory.h" #include "content/public/browser/file_system_access_permission_context.h" #include "content/public/browser/file_system_access_permission_grant.h" @@ -54,12 +52,12 @@ } // namespace storage namespace content { -class FileSystemAccessFileHandleImpl; -class FileSystemAccessDirectoryHandleImpl; -class FileSystemAccessTransferTokenImpl; -class FileSystemAccessDataTransferTokenImpl; -class FileSystemAccessFileWriterImpl; class FileSystemAccessAccessHandleHostImpl; +class FileSystemAccessDataTransferTokenImpl; +class FileSystemAccessDirectoryHandleImpl; +class FileSystemAccessFileHandleImpl; +class FileSystemAccessFileWriterImpl; +class FileSystemAccessTransferTokenImpl; class StoragePartitionImpl; // This is the browser side implementation of the @@ -311,6 +309,10 @@ FileSystemAccessPermissionContext::HandleType handle_type, FileSystemAccessPermissionContext::UserAction user_action); + // Return a stable unique ID of the FileSystemHandle in GUID version 4 format. + base::GUID GetUniqueId(const FileSystemAccessFileHandleImpl& file); + base::GUID GetUniqueId(const FileSystemAccessDirectoryHandleImpl& directory); + // Creates a FileSystemURL which corresponds to a FilePath and Origin. storage::FileSystemURL CreateFileSystemURLFromPath( PathType path_type, @@ -574,6 +576,18 @@ std::unique_ptr<FileSystemAccessDataTransferTokenImpl>> data_transfer_tokens_ GUARDED_BY_CONTEXT(sequence_checker_); + // TODO(https://crbug.com/1342961): This is a temporary hack to put something + // that works behind a flag. Persist handle IDs such that they're stable + // across browsing sessions. + std::map<storage::FileSystemURL, + base::GUID, + storage::FileSystemURL::Comparator> + file_ids_ GUARDED_BY_CONTEXT(sequence_checker_); + std::map<storage::FileSystemURL, + base::GUID, + storage::FileSystemURL::Comparator> + directory_ids_ GUARDED_BY_CONTEXT(sequence_checker_); + absl::optional<FileSystemChooser::ResultEntry> auto_file_picker_result_for_test_ GUARDED_BY_CONTEXT(sequence_checker_);
diff --git a/content/browser/file_system_access/file_system_access_manager_impl_unittest.cc b/content/browser/file_system_access/file_system_access_manager_impl_unittest.cc index 856538b4..1e26d7b 100644 --- a/content/browser/file_system_access/file_system_access_manager_impl_unittest.cc +++ b/content/browser/file_system_access/file_system_access_manager_impl_unittest.cc
@@ -11,6 +11,7 @@ #include "base/callback_helpers.h" #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" +#include "base/guid.h" #include "base/memory/raw_ptr.h" #include "base/run_loop.h" #include "base/test/bind.h" @@ -18,6 +19,7 @@ #include "base/test/task_environment.h" #include "base/test/test_future.h" #include "base/threading/sequenced_task_runner_handle.h" +#include "base/unguessable_token.h" #include "components/services/storage/public/cpp/buckets/bucket_id.h" #include "components/services/storage/public/cpp/buckets/bucket_locator.h" #include "components/services/storage/public/cpp/buckets/constants.h" @@ -1565,4 +1567,44 @@ bad_message_observer.WaitForBadMessage()); } +TEST_F(FileSystemAccessManagerImplTest, GetUniqueId) { + const base::FilePath kTestPath(dir_.GetPath().AppendASCII("foo")); + auto default_bucket = CreateSandboxFileSystemAndGetDefaultBucket(); + + auto grant = base::MakeRefCounted<FixedFileSystemAccessPermissionGrant>( + FixedFileSystemAccessPermissionGrant::PermissionStatus::GRANTED, + kTestPath); + + auto test_url = file_system_context_->CreateCrackedFileSystemURL( + kTestStorageKey, storage::kFileSystemTypeTemporary, kTestPath); + test_url.SetBucket(default_bucket); + + FileSystemAccessFileHandleImpl file(manager_.get(), kBindingContext, test_url, + {ask_grant_, ask_grant_}); + auto file_id = manager_->GetUniqueId(file); + // Ensure a valid ID is provided. + EXPECT_TRUE(file_id.is_valid()); + + // Create a dir handle to the same path. The ID should be different than the + // ID for the file. + FileSystemAccessDirectoryHandleImpl dir(manager_.get(), kBindingContext, + test_url, {ask_grant_, ask_grant_}); + auto dir_id = manager_->GetUniqueId(dir); + EXPECT_TRUE(dir_id.is_valid()); + EXPECT_NE(file_id, dir_id); + + // Create a file handle to another path. The ID should be different from + // either of the other IDs. + auto other_url = file_system_context_->CreateCrackedFileSystemURL( + kTestStorageKey, storage::kFileSystemTypeTemporary, + kTestPath.AppendASCII("bar")); + other_url.SetBucket(default_bucket); + FileSystemAccessFileHandleImpl other_file( + manager_.get(), kBindingContext, other_url, {ask_grant_, ask_grant_}); + auto other_id = manager_->GetUniqueId(other_file); + EXPECT_TRUE(other_id.is_valid()); + EXPECT_NE(other_id, file_id); + EXPECT_NE(other_id, dir_id); +} + } // namespace content
diff --git a/content/browser/first_party_sets/database/first_party_sets_database.cc b/content/browser/first_party_sets/database/first_party_sets_database.cc index 824c8b7..5cee9039 100644 --- a/content/browser/first_party_sets/database/first_party_sets_database.cc +++ b/content/browser/first_party_sets/database/first_party_sets_database.cc
@@ -100,7 +100,7 @@ "CREATE TABLE IF NOT EXISTS policy_modifications(" "browser_context_id TEXT NOT NULL," "site TEXT NOT NULL," - "site_owner TEXT," // May be NULL if this row represents a deletion. + "primary_site TEXT," // May be NULL if this row represents a deletion. "PRIMARY KEY(browser_context_id,site)" ")WITHOUT ROWID"; if (!db.Execute(kPolicyModificationsSql)) @@ -307,7 +307,7 @@ DCHECK(!site.opaque()); static constexpr char kInsertSql[] = "INSERT INTO " - "policy_modifications(browser_context_id,site,site_owner)" + "policy_modifications(browser_context_id,site,primary_site)" "VALUES(?,?,?)"; sql::Statement insert_statement( db_->GetCachedStatement(SQL_FROM_HERE, kInsertSql)); @@ -505,7 +505,7 @@ results; static constexpr char kSelectSql[] = // clang-format off - "SELECT site,site_owner FROM policy_modifications " + "SELECT site,primary_site FROM policy_modifications " "WHERE browser_context_id=?"; // clang-format on sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSelectSql));
diff --git a/content/browser/first_party_sets/database/first_party_sets_database_unittest.cc b/content/browser/first_party_sets/database/first_party_sets_database_unittest.cc index 0d9a605..8c51bf52 100644 --- a/content/browser/first_party_sets/database/first_party_sets_database_unittest.cc +++ b/content/browser/first_party_sets/database/first_party_sets_database_unittest.cc
@@ -337,7 +337,7 @@ // ============ Verify persisting context config const char kSelectConfigSql[] = - "SELECT browser_context_id,site,site_owner FROM policy_modifications"; + "SELECT browser_context_id,site,primary_site FROM policy_modifications"; sql::Statement s_config(db.GetUniqueStatement(kSelectConfigSql)); EXPECT_TRUE(s_config.Step()); EXPECT_EQ(browser_context_id, s_config.ColumnString(0)); @@ -383,7 +383,7 @@ // Verify data in the policy_modifications table. const char kSelectConfigSql[] = - "SELECT browser_context_id,site,site_owner FROM policy_modifications"; + "SELECT browser_context_id,site,primary_site FROM policy_modifications"; sql::Statement s_config(db.GetUniqueStatement(kSelectConfigSql)); EXPECT_TRUE(s_config.Step()); EXPECT_EQ(browser_context_id, s_config.ColumnString(0)); @@ -465,7 +465,7 @@ // ============ Verify the new context config overwrote the pre-existing // data. const char kSelectConfigSql[] = - "SELECT browser_context_id,site,site_owner FROM policy_modifications " + "SELECT browser_context_id,site,primary_site FROM policy_modifications " "WHERE browser_context_id=?"; sql::Statement s_config(db.GetUniqueStatement(kSelectConfigSql)); s_config.BindString(0, browser_context_id);
diff --git a/content/browser/first_party_sets/first_party_sets_handler_impl.cc b/content/browser/first_party_sets/first_party_sets_handler_impl.cc index 8122aa6..5ba79be3 100644 --- a/content/browser/first_party_sets/first_party_sets_handler_impl.cc +++ b/content/browser/first_party_sets/first_party_sets_handler_impl.cc
@@ -10,15 +10,12 @@ #include "base/bind.h" #include "base/files/file.h" #include "base/logging.h" -#include "base/metrics/histogram_functions.h" #include "base/task/thread_pool.h" #include "base/types/optional_util.h" #include "base/values.h" #include "content/browser/first_party_sets/first_party_set_parser.h" #include "content/browser/first_party_sets/first_party_sets_loader.h" -#include "content/browser/first_party_sets/first_party_sets_site_data_remover.h" #include "content/browser/first_party_sets/local_set_declaration.h" -#include "content/public/browser/browser_context.h" #include "content/public/browser/content_browser_client.h" #include "content/public/browser/first_party_sets_handler.h" #include "content/public/common/content_client.h" @@ -33,30 +30,6 @@ constexpr base::FilePath::CharType kFirstPartySetsDatabase[] = FILE_PATH_LITERAL("first_party_sets.db"); -using ClearSiteDataOutcomeType = - FirstPartySetsHandlerImpl::ClearSiteDataOutcomeType; - -// `failed_data_types` is a bitmask used to indicate data types from -// BrowsingDataRemover::DataType enum that were failed to remove. -ClearSiteDataOutcomeType ComputeClearSiteDataOutcome( - uint64_t failed_data_types) { - ClearSiteDataOutcomeType outcome = ClearSiteDataOutcomeType::kSuccess; - if (failed_data_types & BrowsingDataRemover::DATA_TYPE_COOKIES) { - outcome = ClearSiteDataOutcomeType::kCookieFailed; - } - if (failed_data_types & BrowsingDataRemover::DATA_TYPE_DOM_STORAGE) { - outcome = outcome == ClearSiteDataOutcomeType::kCookieFailed - ? ClearSiteDataOutcomeType::kCookieAndStorageFailed - : ClearSiteDataOutcomeType::kStorageFailed; - } - return outcome; -} - -void RecordClearSiteDataOutcome(ClearSiteDataOutcomeType outcome) { - base::UmaHistogramEnumeration( - "FirstPartySets.Initialization.ClearSiteDataOutcomeType", outcome); -} - } // namespace // static @@ -307,81 +280,14 @@ DCHECK(!browser_context_id.empty()); DCHECK(enabled_); - if (db_helper_.is_null()) { - VLOG(1) << "Invalid First-Party Sets database. Failed to clear site data " - "for browser_context_id=" - << browser_context_id; - std::move(callback).Run(std::move(context_config)); - return; + if (!db_helper_.is_null()) { + // TODO(crbug.com/1219656): Call site state clearing. + // TODO(https://crbug.com/1219656): don't invoke `callback` until site state + // clearing is complete. + db_helper_.AsyncCall(&FirstPartySetsHandlerDatabaseHelper::PersistSets) + .WithArgs(browser_context_id, version_, global_sets_->Clone(), + context_config.Clone()); } - // Extract the callback into a variable and pass it into DB async call args, - // to prevent the case that `context_config` gets used after it's moved. This - // is because C++ does not have a defined evaluation order for function - // parameters. - base::OnceCallback<void(const std::vector<net::SchemefulSite>&)> - on_get_sites_to_clear = base::BindOnce( - &FirstPartySetsHandlerImpl::OnGetSitesToClear, - // base::Unretained(this) is safe here because this - // is a static singleton. - base::Unretained(this), browser_context_getter, browser_context_id, - context_config.Clone(), std::move(callback)); - - db_helper_ - .AsyncCall(&FirstPartySetsHandlerDatabaseHelper:: - UpdateAndGetSitesToClearForContext) - .WithArgs(browser_context_id, global_sets_->Clone(), - std::move(context_config)) - .Then(std::move(on_get_sites_to_clear)); -} - -void FirstPartySetsHandlerImpl::OnGetSitesToClear( - base::RepeatingCallback<BrowserContext*()> browser_context_getter, - const std::string& browser_context_id, - net::FirstPartySetsContextConfig context_config, - base::OnceCallback<void(net::FirstPartySetsContextConfig)> callback, - const std::vector<net::SchemefulSite>& sites_to_clear) const { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - BrowserContext* browser_context = browser_context_getter.Run(); - if (!browser_context) { - DVLOG(1) << "Invalid Browser Context. Failed to clear site data for " - "browser_context_id=" - << browser_context_id; - - std::move(callback).Run(std::move(context_config)); - return; - } - - FirstPartySetsSiteDataRemover::RemoveSiteData( - *browser_context->GetBrowsingDataRemover(), sites_to_clear, - base::BindOnce( - &FirstPartySetsHandlerImpl::DidClearSiteDataOnChangedSetsForContext, - // base::Unretained(this) is safe here because - // this is a static singleton. - base::Unretained(this), browser_context_id, std::move(context_config), - std::move(callback))); -} - -void FirstPartySetsHandlerImpl::DidClearSiteDataOnChangedSetsForContext( - const std::string& browser_context_id, - net::FirstPartySetsContextConfig context_config, - base::OnceCallback<void(net::FirstPartySetsContextConfig)> callback, - uint64_t failed_data_types) const { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(!db_helper_.is_null()); - - ClearSiteDataOutcomeType outcome = - ComputeClearSiteDataOutcome(failed_data_types); - RecordClearSiteDataOutcome(outcome); - if (outcome == ClearSiteDataOutcomeType::kSuccess) { - db_helper_ - .AsyncCall( - &FirstPartySetsHandlerDatabaseHelper::UpdateClearStatusForContext) - .WithArgs(browser_context_id); - } - db_helper_.AsyncCall(&FirstPartySetsHandlerDatabaseHelper::PersistSets) - .WithArgs(browser_context_id, version_, global_sets_->Clone(), - context_config.Clone()); std::move(callback).Run(std::move(context_config)); }
diff --git a/content/browser/first_party_sets/first_party_sets_handler_impl.h b/content/browser/first_party_sets/first_party_sets_handler_impl.h index db1fab84..20c0a7e 100644 --- a/content/browser/first_party_sets/first_party_sets_handler_impl.h +++ b/content/browser/first_party_sets/first_party_sets_handler_impl.h
@@ -41,28 +41,6 @@ // the current First-Party Sets data to disk. class CONTENT_EXPORT FirstPartySetsHandlerImpl : public FirstPartySetsHandler { public: - // The outcome types of clearing site data for data types covered in - // FirstPartySetsSiteDataRemover. We only clear - // `BrowsingDataRemover::DATA_TYPE_COOKIES` and - // `BrowsingDataRemover::DATA_TYPE_DOM_STORAGE` for now. Cache is "cleared" - // with a different approach. - // - // These values are persisted to logs. Entries should not be renumbered and - // numeric values should never be reused. - enum class ClearSiteDataOutcomeType { - kSuccess = 0, - // Failed to clear data type of `BrowsingDataRemover::DATA_TYPE_COOKIES`. - kCookieFailed = 1, - // Failed to clear data type of - // `BrowsingDataRemover::DATA_TYPE_DOM_STORAGE`. - kStorageFailed = 2, - // Failed to clear both `BrowsingDataRemover::DATA_TYPE_COOKIES` and - // `BrowsingDataRemover::DATA_TYPE_DOM_STORAGE` data types. - kCookieAndStorageFailed = 3, - - kMaxValue = kCookieAndStorageFailed, - }; - using SetsReadyOnceCallback = base::OnceCallback<void(net::GlobalFirstPartySets)>; @@ -109,6 +87,7 @@ const base::Value::Dict* policy, base::OnceCallback<void(net::FirstPartySetsContextConfig)> callback) override; + // TODO(shuuran@chromium.org): Implement the code to clear site state. void ClearSiteDataOnChangedSetsForContext( base::RepeatingCallback<BrowserContext*()> browser_context_getter, const std::string& browser_context_id, @@ -174,22 +153,6 @@ net::FirstPartySetsContextConfig GetContextConfigForPolicyInternal( const base::Value::Dict& policy) const; - void OnGetSitesToClear( - base::RepeatingCallback<BrowserContext*()> browser_context_getter, - const std::string& browser_context_id, - net::FirstPartySetsContextConfig context_config, - base::OnceCallback<void(net::FirstPartySetsContextConfig)> callback, - const std::vector<net::SchemefulSite>& sites_to_clear) const; - - // `failed_data_types` is a bitmask used to indicate data types from - // BrowsingDataRemover::DataType enum that were failed to remove. 0 indicates - // success. - void DidClearSiteDataOnChangedSetsForContext( - const std::string& browser_context_id, - net::FirstPartySetsContextConfig context_config, - base::OnceCallback<void(net::FirstPartySetsContextConfig)> callback, - uint64_t failed_data_types) const; - // Whether Init has been called already or not. bool initialized_ = false;
diff --git a/content/browser/first_party_sets/first_party_sets_handler_impl_unittest.cc b/content/browser/first_party_sets/first_party_sets_handler_impl_unittest.cc index ca6e01a3c..6d77cc5 100644 --- a/content/browser/first_party_sets/first_party_sets_handler_impl_unittest.cc +++ b/content/browser/first_party_sets/first_party_sets_handler_impl_unittest.cc
@@ -12,15 +12,12 @@ #include "base/files/scoped_temp_dir.h" #include "base/json/json_reader.h" #include "base/run_loop.h" -#include "base/test/metrics/histogram_tester.h" #include "base/test/task_environment.h" #include "base/test/test_future.h" #include "base/version.h" #include "content/browser/first_party_sets/first_party_set_parser.h" #include "content/browser/first_party_sets/local_set_declaration.h" #include "content/public/browser/first_party_sets_handler.h" -#include "content/public/test/browser_task_environment.h" -#include "content/public/test/test_browser_context.h" #include "net/base/schemeful_site.h" #include "net/first_party_sets/first_party_set_entry.h" #include "net/first_party_sets/first_party_sets_context_config.h" @@ -50,9 +47,6 @@ const char* kPrimaryField = "primary"; const char* kCctldsField = "ccTLDs"; -const char* kFirstPartySetsClearSiteDataOutcomeHistogram = - "FirstPartySets.Initialization.ClearSiteDataOutcomeType"; - BrowserContext* FakeBrowserContextGetter() { return nullptr; } @@ -188,12 +182,9 @@ FirstPartySetsHandlerImpl::GetInstance()->ResetForTesting(); } - BrowserContext* context() { return &context_; } - protected: base::ScopedTempDir scoped_dir_; - BrowserTaskEnvironment env_; - TestBrowserContext context_; + base::test::TaskEnvironment env_; }; class FirstPartySetsHandlerImplEnabledTest @@ -227,7 +218,6 @@ TEST_F(FirstPartySetsHandlerImplEnabledTest, ClearSiteDataOnChangedSetsForContext_Successful) { - base::HistogramTester histogram; net::SchemefulSite foo(GURL("https://foo.test")); net::SchemefulSite associated(GURL("https://associatedsite.test")); @@ -251,13 +241,11 @@ Pair(associated, net::FirstPartySetEntry( foo, net::SiteType::kAssociated, 0)))); - // Should not yet be recorded. - histogram.ExpectTotalCount(kFirstPartySetsClearSiteDataOutcomeHistogram, 0); base::RunLoop run_loop; FirstPartySetsHandlerImpl::GetInstance() ->ClearSiteDataOnChangedSetsForContext( - base::BindLambdaForTesting([&]() { return context(); }), - browser_context_id, net::FirstPartySetsContextConfig(), + base::BindRepeating(&FakeBrowserContextGetter), browser_context_id, + net::FirstPartySetsContextConfig(), base::BindLambdaForTesting( [&](net::FirstPartySetsContextConfig) { run_loop.Quit(); })); run_loop.Run(); @@ -271,15 +259,10 @@ Pair(associated, net::FirstPartySetEntry(foo, net::SiteType::kAssociated, absl::nullopt)))); - - histogram.ExpectUniqueSample( - kFirstPartySetsClearSiteDataOutcomeHistogram, - FirstPartySetsHandlerImpl::ClearSiteDataOutcomeType::kSuccess, 1); } TEST_F(FirstPartySetsHandlerImplEnabledTest, ClearSiteDataOnChangedSetsForContext_EmptyDBPath) { - base::HistogramTester histogram; net::SchemefulSite foo(GURL("https://foo.test")); net::SchemefulSite associated(GURL("https://associatedsite.test")); @@ -313,8 +296,6 @@ run_loop.Run(); EXPECT_EQ(GetPersistedGlobalSetsAndWait(browser_context_id), absl::nullopt); - // Should not be recorded. - histogram.ExpectTotalCount(kFirstPartySetsClearSiteDataOutcomeHistogram, 0); } TEST_F(FirstPartySetsHandlerImplEnabledTest, @@ -329,9 +310,8 @@ base::test::TestFuture<net::FirstPartySetsContextConfig> future; FirstPartySetsHandlerImpl::GetInstance() ->ClearSiteDataOnChangedSetsForContext( - base::BindLambdaForTesting([&]() { return context(); }), - browser_context_id, net::FirstPartySetsContextConfig(), - future.GetCallback()); + base::BindRepeating(&FakeBrowserContextGetter), browser_context_id, + net::FirstPartySetsContextConfig(), future.GetCallback()); FirstPartySetsHandlerImpl::GetInstance()->SetPublicFirstPartySets( base::Version("0.0.1"),
diff --git a/content/browser/preloading/prefetch/prefetch_canary_checker.cc b/content/browser/preloading/prefetch/prefetch_canary_checker.cc index 8c636f3..68b6743 100644 --- a/content/browser/preloading/prefetch/prefetch_canary_checker.cc +++ b/content/browser/preloading/prefetch/prefetch_canary_checker.cc
@@ -163,7 +163,7 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); } -base::WeakPtr<PrefetchCanaryChecker> PrefetchCanaryChecker::GetWeakPtr() const { +base::WeakPtr<PrefetchCanaryChecker> PrefetchCanaryChecker::GetWeakPtr() { return weak_factory_.GetWeakPtr(); }
diff --git a/content/browser/preloading/prefetch/prefetch_canary_checker.h b/content/browser/preloading/prefetch/prefetch_canary_checker.h index 13607a8..a06aa6d 100644 --- a/content/browser/preloading/prefetch/prefetch_canary_checker.h +++ b/content/browser/preloading/prefetch/prefetch_canary_checker.h
@@ -106,7 +106,7 @@ PrefetchCanaryChecker(const PrefetchCanaryChecker&) = delete; PrefetchCanaryChecker& operator=(const PrefetchCanaryChecker) = delete; - base::WeakPtr<PrefetchCanaryChecker> GetWeakPtr() const; + base::WeakPtr<PrefetchCanaryChecker> GetWeakPtr(); // Returns the successfulness of the last canary check, if there was one. If // the last status was not cached or was cached and needs to be revalidated,
diff --git a/content/browser/preloading/prefetch/prefetch_container.h b/content/browser/preloading/prefetch/prefetch_container.h index 9cb0fbf..521acb2 100644 --- a/content/browser/preloading/prefetch/prefetch_container.h +++ b/content/browser/preloading/prefetch/prefetch_container.h
@@ -69,7 +69,7 @@ const blink::mojom::Referrer& GetReferrer() const { return referrer_; } - base::WeakPtr<PrefetchContainer> GetWeakPtr() const { + base::WeakPtr<PrefetchContainer> GetWeakPtr() { return weak_method_factory_.GetWeakPtr(); }
diff --git a/content/browser/renderer_host/pending_beacon_browsertest.cc b/content/browser/renderer_host/pending_beacon_browsertest.cc index f880055a..79ebe8c 100644 --- a/content/browser/renderer_host/pending_beacon_browsertest.cc +++ b/content/browser/renderer_host/pending_beacon_browsertest.cc
@@ -13,6 +13,7 @@ #include "base/test/scoped_feature_list.h" #include "components/ukm/test_ukm_recorder.h" #include "content/browser/back_forward_cache_test_util.h" +#include "content/browser/renderer_host/pending_beacon_host.h" #include "content/browser/renderer_host/render_frame_host_impl.h" #include "content/browser/web_contents/web_contents_impl.h" #include "content/public/browser/browser_context.h" @@ -758,4 +759,49 @@ EXPECT_EQ(sent_beacon_count(), total_beacon); } +class PendingBeaconRendererProcessExitBrowserTest + : public PendingBeaconTimeoutBrowserTestBase { + protected: + const FeaturesType& GetEnabledFeatures() override { + static const FeaturesType enabled_features = { + {blink::features::kPendingBeaconAPI, {}}, + // Forces BFCache to work in low memory device so that a page won't be + // killed by normal page discard. + {features::kBackForwardCacheMemoryControls, + {{"memory_threshold_for_back_forward_cache_in_mb", "0"}}}}; + return enabled_features; + } +}; + +IN_PROC_BROWSER_TEST_F(PendingBeaconRendererProcessExitBrowserTest, + SendAllOnProcessCrash) { + const size_t total_beacon = 2; + RegisterBeaconRequestMonitor(total_beacon); + + // Creates a pending beacon that will only be sent on page discard or crash. + // Make beacon creations within a Promise to ensure they can all be created + // before executing next statement. + RunScriptInA(JsReplace(R"( + new Promise(resolve => { + new PendingGetBeacon($1); + new PendingPostBeacon($1); + resolve(); + }); + )", + kBeaconEndpoint)); + ASSERT_EQ(sent_beacon_count(), 0u); + ASSERT_TRUE( + PendingBeaconHost::GetForCurrentDocument(current_document().get())); + + // Make the renderer crash. + CrashTab(web_contents()); + // The RenderFrame is dead but the attached beacon host is still alive. + ASSERT_FALSE(current_document()->IsRenderFrameLive()); + ASSERT_TRUE( + PendingBeaconHost::GetForCurrentDocument(current_document().get())); + + WaitForAllBeaconsSent(total_beacon); + EXPECT_EQ(sent_beacon_count(), total_beacon); +} + } // namespace content
diff --git a/content/browser/renderer_host/pending_beacon_host.cc b/content/browser/renderer_host/pending_beacon_host.cc index 752b606..07e0c44 100644 --- a/content/browser/renderer_host/pending_beacon_host.cc +++ b/content/browser/renderer_host/pending_beacon_host.cc
@@ -11,10 +11,10 @@ #include "content/public/browser/permission_controller.h" #include "content/public/browser/permission_result.h" #include "content/public/browser/render_frame_host.h" +#include "content/public/browser/render_process_host.h" #include "services/network/public/cpp/cors/cors.h" #include "services/network/public/cpp/data_element.h" #include "services/network/public/cpp/resource_request.h" -#include "services/network/public/cpp/shared_url_loader_factory.h" #include "services/network/public/mojom/fetch_api.mojom.h" #include "third_party/blink/public/common/features.h" #include "third_party/blink/public/common/permissions/permission_utils.h" @@ -56,6 +56,8 @@ service_(service) { DCHECK(shared_url_factory_); DCHECK(service_); + + render_frame_host().GetProcess()->AddObserver(this); } void PendingBeaconHost::CreateBeacon( @@ -69,6 +71,11 @@ PendingBeaconHost::~PendingBeaconHost() { // The blink::Document is about to destroy. + if (IsInObserverList()) { + render_frame_host().GetProcess()->RemoveObserver(this); + } + CHECK(!IsInObserverList()); + // Checks if it has Background Sync granted before sending out the rest of // beacons. // https://github.com/WICG/unload-beacon#privacy @@ -136,6 +143,17 @@ // The renderer-side beacons should update their pending states by themselves. } +void PendingBeaconHost::RenderProcessExited( + RenderProcessHost*, + const ChildProcessTerminationInfo&) { + std::vector<std::unique_ptr<Beacon>> to_send; + to_send.swap(beacons_); + Send(to_send); +} +void PendingBeaconHost::RenderProcessHostDestroyed(RenderProcessHost*) { + render_frame_host().GetProcess()->RemoveObserver(this); +} + DOCUMENT_USER_DATA_KEY_IMPL(PendingBeaconHost); void Beacon::Deactivate() {
diff --git a/content/browser/renderer_host/pending_beacon_host.h b/content/browser/renderer_host/pending_beacon_host.h index 65898dda..928fa0e 100644 --- a/content/browser/renderer_host/pending_beacon_host.h +++ b/content/browser/renderer_host/pending_beacon_host.h
@@ -10,6 +10,7 @@ #include "base/memory/raw_ptr.h" #include "content/common/content_export.h" #include "content/public/browser/document_user_data.h" +#include "content/public/browser/render_process_host_observer.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/receiver.h" #include "services/network/public/cpp/shared_url_loader_factory.h" @@ -52,18 +53,23 @@ // according to individual PendingBeacon's backgroundTimeout property. // C. When the individual PendingBeacon's timer of timeout property expires. // -// 2. From browser. PendingBeaconHost can trigger the sending of beacons: +// 2. From browser. PendingBeaconHost can trigger the sending of beacons by +// itself: // A. When the associated document is discarded or deleted, PendingBeaconHost // sends out all queued beacons from its destructor. -// B. TODO(crbug.com/1293679): When the associated document's renderer -// process crashes, PendingBeaconHost sends out all queued beacon after -// being notified by RenderProcessHostDestroyed. +// B. When the associated document's renderer process crashes, +// RenderFrameHost becomes non-live and its DocumentUserData won't be +// cleared immediately, i.e. `DeleteForCurrentDocument()` and destructor +// won't be called, so queued beacons won't be sent there. +// Instead, PendingBeaconHost sends them out on being notified by +// `RenderProcessExited()`. // C. When the associated document enters `pagehide` state, i.e. the user has // navigated away from the document, PendingBeaconHost sends out all // queued beacons. class CONTENT_EXPORT PendingBeaconHost : public blink::mojom::PendingBeaconHost, - public DocumentUserData<PendingBeaconHost> { + public DocumentUserData<PendingBeaconHost>, + public RenderProcessHostObserver { public: ~PendingBeaconHost() override; PendingBeaconHost(const PendingBeaconHost&) = delete; @@ -95,6 +101,13 @@ // https://github.com/WICG/unload-beacon/issues/30 void SendAllOnNavigation(); + // `RenderProcessHostObserver` implementation. + // Sends out all queued beacons when renderer process crashes or exits. + // See `PendingBeaconHost` 2-B for more details. + void RenderProcessExited(RenderProcessHost*, + const ChildProcessTerminationInfo&) override; + void RenderProcessHostDestroyed(RenderProcessHost*) override; + private: friend class DocumentUserData<PendingBeaconHost>;
diff --git a/content/browser/renderer_host/pending_beacon_host_unittest.cc b/content/browser/renderer_host/pending_beacon_host_unittest.cc index 69ccf2cc..4468f0e 100644 --- a/content/browser/renderer_host/pending_beacon_host_unittest.cc +++ b/content/browser/renderer_host/pending_beacon_host_unittest.cc
@@ -12,6 +12,7 @@ #include "base/test/bind.h" #include "base/test/scoped_feature_list.h" #include "content/browser/renderer_host/pending_beacon_service.h" +#include "content/public/browser/child_process_termination_info.h" #include "content/public/browser/permission_result.h" #include "content/public/test/mock_permission_manager.h" #include "content/public/test/test_browser_context.h" @@ -295,6 +296,20 @@ ExpectTotalNetworkRequests(FROM_HERE, total); } +TEST_P(PendingBeaconHostTest, SendOnProcessExit) { + const std::string method = GetParam(); + const size_t total = 5; + + // Creates 5 beacons on the page. + auto beacons = CreateBeacons(total, method); + + // Simulates sending on process exits. + ChildProcessTerminationInfo termination_info; + host()->RenderProcessExited(main_rfh()->GetProcess(), termination_info); + + ExpectTotalNetworkRequests(FROM_HERE, total); +} + class BeaconTestBase : public PendingBeaconHostTestBase { protected: void TearDown() override {
diff --git a/content/browser/renderer_host/render_frame_host_impl.cc b/content/browser/renderer_host/render_frame_host_impl.cc index 1f49662..f6f3f8fc 100644 --- a/content/browser/renderer_host/render_frame_host_impl.cc +++ b/content/browser/renderer_host/render_frame_host_impl.cc
@@ -10109,7 +10109,7 @@ } RenderFrameHostImpl* RenderFrameHostImpl::GetMainFrame() { - return const_cast<RenderFrameHostImpl*>(base::as_const(*this).GetMainFrame()); + return const_cast<RenderFrameHostImpl*>(std::as_const(*this).GetMainFrame()); } const RenderFrameHostImpl* RenderFrameHostImpl::GetMainFrame() const {
diff --git a/content/browser/service_worker/service_worker_internals_ui_browsertest.cc b/content/browser/service_worker/service_worker_internals_ui_browsertest.cc index 8577e75b..6ea4ef2 100644 --- a/content/browser/service_worker/service_worker_internals_ui_browsertest.cc +++ b/content/browser/service_worker/service_worker_internals_ui_browsertest.cc
@@ -585,8 +585,8 @@ TearDownWindow(sw_internal_ui_window); } -// The test is flaky on Mac. crbug.com/1324856 -#if BUILDFLAG(IS_MAC) +// The test is flaky on Mac and Linux. crbug.com/1324856 +#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX) #define MAYBE_StopStartSWReflectedOnInternalUI \ DISABLED_StopStartSWReflectedOnInternalUI #else
diff --git a/content/child/browser_font_resource_trusted.cc b/content/child/browser_font_resource_trusted.cc index d0547085..725c65b 100644 --- a/content/child/browser_font_resource_trusted.cc +++ b/content/child/browser_font_resource_trusted.cc
@@ -25,6 +25,7 @@ #include "third_party/icu/source/common/unicode/ubidi.h" #include "third_party/skia/include/core/SkRect.h" #include "ui/gfx/geometry/rect_f.h" +#include "ui/gfx/ubidi_deleter.h" using ppapi::StringVar; using ppapi::thunk::EnterResourceNoLock; @@ -68,22 +69,19 @@ override_run_ = WebTextRun(blink::WebString::FromUTF16(text_), PP_ToBool(run.rtl), true); } else { - bidi_ = ubidi_open(); + bidi_ = std::unique_ptr<UBiDi, ui::gfx::UBiDiDeleter>(ubidi_open()); UErrorCode uerror = U_ZERO_ERROR; - ubidi_setPara(bidi_, text_.data(), text_.size(), run.rtl, nullptr, + ubidi_setPara(bidi_.get(), text_.data(), text_.size(), run.rtl, nullptr, &uerror); if (U_SUCCESS(uerror)) - num_runs_ = ubidi_countRuns(bidi_, &uerror); + num_runs_ = ubidi_countRuns(bidi_.get(), &uerror); } } TextRunCollection(const TextRunCollection&) = delete; TextRunCollection& operator=(const TextRunCollection&) = delete; - ~TextRunCollection() { - if (bidi_) - ubidi_close(bidi_); - } + ~TextRunCollection() = default; const std::u16string& text() const { return text_; } int num_runs() const { return num_runs_; } @@ -93,7 +91,8 @@ WebTextRun GetRunAt(int index, int32_t* run_start, int32_t* run_len) const { DCHECK(index < num_runs_); if (bidi_) { - bool run_rtl = !!ubidi_getVisualRun(bidi_, index, run_start, run_len); + bool run_rtl = + !!ubidi_getVisualRun(bidi_.get(), index, run_start, run_len); return WebTextRun(blink::WebString::FromUTF16( std::u16string(&text_[*run_start], *run_len)), run_rtl, true); @@ -108,7 +107,7 @@ private: // Will be null if we skipped autodetection. - raw_ptr<UBiDi, DanglingUntriaged> bidi_; + std::unique_ptr<UBiDi, ui::gfx::UBiDiDeleter> bidi_; // Text of all the runs. std::u16string text_;
diff --git a/content/renderer/render_frame_impl.cc b/content/renderer/render_frame_impl.cc index ab702e7..4b1aa44 100644 --- a/content/renderer/render_frame_impl.cc +++ b/content/renderer/render_frame_impl.cc
@@ -2609,8 +2609,7 @@ navigation_params->policy_container = ToWebPolicyContainer(std::move(policy_container)); - if (blink::IsIsolatedApplication() && frame_->IsOutermostMainFrame() && - permissions_policy) { + if (frame_->IsOutermostMainFrame() && permissions_policy) { navigation_params->permissions_policy_override = permissions_policy; }
diff --git a/content/test/data/first_party_sets/v0.init_too_old.sql b/content/test/data/first_party_sets/v0.init_too_old.sql index 30d3670..ea30e34c 100644 --- a/content/test/data/first_party_sets/v0.init_too_old.sql +++ b/content/test/data/first_party_sets/v0.init_too_old.sql
@@ -18,7 +18,7 @@ CREATE TABLE IF NOT EXISTS policy_modifications ( browser_context_id TEXT NOT NULL, site TEXT NOT NULL, - site_owner TEXT, -- May be NULL if this row represents a deletion. + primary_site TEXT, -- May be NULL if this row represents a deletion. PRIMARY KEY (browser_context_id, site) ) WITHOUT ROWID;
diff --git a/content/test/data/first_party_sets/v1.init_invalid_run_count.sql b/content/test/data/first_party_sets/v1.init_invalid_run_count.sql index 2c052b6..e02a64302 100644 --- a/content/test/data/first_party_sets/v1.init_invalid_run_count.sql +++ b/content/test/data/first_party_sets/v1.init_invalid_run_count.sql
@@ -18,7 +18,7 @@ CREATE TABLE IF NOT EXISTS policy_modifications ( browser_context_id TEXT NOT NULL, site TEXT NOT NULL, - site_owner TEXT, -- May be NULL if this row represents a deletion. + primary_site TEXT, -- May be NULL if this row represents a deletion. PRIMARY KEY (browser_context_id, site) ) WITHOUT ROWID;
diff --git a/content/test/data/first_party_sets/v1.init_too_new.sql b/content/test/data/first_party_sets/v1.init_too_new.sql index 8acc3aa..ee5f85d 100644 --- a/content/test/data/first_party_sets/v1.init_too_new.sql +++ b/content/test/data/first_party_sets/v1.init_too_new.sql
@@ -18,7 +18,7 @@ CREATE TABLE IF NOT EXISTS policy_modifications ( browser_context_id TEXT NOT NULL, site TEXT NOT NULL, - site_owner TEXT, -- May be NULL if this row represents a deletion. + primary_site TEXT, -- May be NULL if this row represents a deletion. PRIMARY KEY (browser_context_id, site) ) WITHOUT ROWID;
diff --git a/content/test/data/first_party_sets/v1.sql b/content/test/data/first_party_sets/v1.sql index bf40d87..f3ae912 100644 --- a/content/test/data/first_party_sets/v1.sql +++ b/content/test/data/first_party_sets/v1.sql
@@ -18,7 +18,7 @@ CREATE TABLE IF NOT EXISTS policy_modifications ( browser_context_id TEXT NOT NULL, site TEXT NOT NULL, - site_owner TEXT, -- May be NULL if this row represents a deletion. + primary_site TEXT, -- May be NULL if this row represents a deletion. PRIMARY KEY (browser_context_id, site) ) WITHOUT ROWID;
diff --git a/content/test/gpu/gpu_tests/test_expectations/pixel_expectations.txt b/content/test/gpu/gpu_tests/test_expectations/pixel_expectations.txt index 0ef845e..3db1cdc 100644 --- a/content/test/gpu/gpu_tests/test_expectations/pixel_expectations.txt +++ b/content/test/gpu/gpu_tests/test_expectations/pixel_expectations.txt
@@ -454,6 +454,11 @@ # Crash on Linux FYI Release (NVIDIA) using SkiaRenderer/Vulkan crbug.com/1353189 [ linux renderer-skia-vulkan nvidia-0x2184 ] Pixel_VideoStreamFromWebGLAlphaCanvas_TwoCopy_CpuReadback [ Failure ] +crbug.com/1372173 [ fuchsia ] Pixel_MediaRecorderFrom2DCanvas [ Failure ] +crbug.com/1372173 [ fuchsia ] Pixel_VideoStreamFrom2DAlphaCanvas_DisableReadbackFromTexture [ Failure ] +crbug.com/1372173 [ fuchsia ] Pixel_VideoStreamFrom2DCanvas [ Failure ] +crbug.com/1372173 [ fuchsia ] Pixel_VideoStreamFromWebGLCanvas [ Failure ] + ####################################################################### # Automated Entries After This Point - Do Not Manually Add Below Here # #######################################################################
diff --git a/docs/security/rule-of-2.md b/docs/security/rule-of-2.md index e4baf4d..6c01135 100644 --- a/docs/security/rule-of-2.md +++ b/docs/security/rule-of-2.md
@@ -83,6 +83,37 @@ JavaScript, Kotlin, and Swift. (Note that the safe subsets of these languages are safe by design, but of course implementation quality is a different story.) +#### Unsafe Code in Safe Languages + +Some memory-safe languages provide a backdoor to unsafety, such as the `unsafe` +keyword in Rust. This functions as a separate unsafe language subset inside the +memory-safe one. + +The presence of unsafe code does not negate the memory-safety properties of the +memory-safe language around it as a whole, but _how_ unsafe code is used is +critical. Poor use of an unsafe language subset is not meaningfully different +from any other unsafe implementation language. + +In order for a library with unsafe code to be safe for the purposes of the Rule +of 2, all unsafe usage must be able to be reviewed and verified by humans with +simple local reasoning. To achieve this, we expect all unsafe usage to be: +* Small: The minimal possible amount of code to perform the required task +* Encapsulated: All access to the unsafe code is through a safe API +* Documented: All preconditions of an unsafe block (e.g. a call to an unsafe + function) are spelled out in comments, along with explanations of how they are + satisfied. + +Because unsafe code reaches outside the normal expectations of a memory-safe +language, it must follow strict rules to avoid undefined behaviour and +memory-safety violations, and these are not always easy to verify. A careful +review by one or more experts in the unsafe language subset is required. + +It should be safe to use any code in a memory-safe language in a high-privilege +context. As such, the requirements on a memory-safe language implementation are +higher: All code in a memory-safe language must be capable of satisfying the +Rule of 2 in a high-privilege context (including any unsafe code) in order to be +used or admitted anywhere in the project. + ### High Privilege _High privilege_ is a relative term. The very highest-privilege programs are the @@ -249,11 +280,12 @@ Where possible, it's great to use a memory-safe language. Of the currently approved set of implementation languages in Chromium, the most likely candidates -are Java (on Android only) and JavaScript or WebAssembly (although we don't -currently use them in high-privilege processes like the browser). One can -imagine Swift on iOS or Kotlin on Android, too, although they are not currently +are Java (on Android only), Swift (on iOS only), and JavaScript or WebAssembly +(although we don't currently use them in high-privilege processes like the +browser). One can imagine Kotlin on Android, too, although it is not currently used in Chromium. (Some of us on Security Team aspire to get more of Chromium in -safer languages, and you may be able to [help with our experiments](rust-toolchain.md).) +safer languages, and you may be able to [help with our +experiments](rust-toolchain.md).) For an example of image processing, we have the pure-Java class [BaseGifImage](https://cs.chromium.org/chromium/src/third_party/gif_player/src/jp/tomorrowkey/android/gifplayer/BaseGifImage.java?rcl=27febd503d1bab047d73df26db83184fff8d6620&l=27). @@ -277,7 +309,6 @@ untrustworthy input strings. This does not automatically turn the matched text or captured groups into safe values. - ## Safe Types As discussed above in [Normalization](#normalization), there are some types that @@ -287,12 +318,12 @@ grammar or structure, and/or have been audited or fuzzed heavily. * `GURL` and `url::Origin` -* `SkBitmap` -* `SkPixmap` +* `SkBitmap` (in [N32 format](https://source.chromium.org/chromium/chromium/src/+/main:third_party/skia/include/core/SkColorType.h;l=54-58;drc=8d399817282e3c12ed54eb23ec42a5e418298ec6) only) +* `SkPixmap` (in [N32 format](https://source.chromium.org/chromium/chromium/src/+/main:third_party/skia/include/core/SkColorType.h;l=54-58;drc=8d399817282e3c12ed54eb23ec42a5e418298ec6) only) * Protocol buffers (see above; this is not a preferred option and should be avoided where possible) -There are also classes in //base that internally hold simple values that +There are also classes in `//base` that internally hold simple values that represent potentially complex data, such as: * `base::FilePath` @@ -312,4 +343,3 @@ default, though there is [ongoing work](https://bugs.chromium.org/p/chromium/issues/detail?id=841001) to change that default. -
diff --git a/extensions/browser/api/sockets_tcp_server/sockets_tcp_server_api.cc b/extensions/browser/api/sockets_tcp_server/sockets_tcp_server_api.cc index e948063..99821e2 100644 --- a/extensions/browser/api/sockets_tcp_server/sockets_tcp_server_api.cc +++ b/extensions/browser/api/sockets_tcp_server/sockets_tcp_server_api.cc
@@ -174,7 +174,7 @@ SocketPermissionRequest param( SocketPermissionRequest::TCP_LISTEN, params_->address, params_->port); - if (!SocketsManifestData::CheckRequest(extension(), param)) { + if (!CheckRequest(param)) { return RespondNow(Error(kPermissionError)); }
diff --git a/extensions/browser/api/sockets_udp/sockets_udp_api.cc b/extensions/browser/api/sockets_udp/sockets_udp_api.cc index 8d071cf..33558739 100644 --- a/extensions/browser/api/sockets_udp/sockets_udp_api.cc +++ b/extensions/browser/api/sockets_udp/sockets_udp_api.cc
@@ -199,7 +199,7 @@ content::SocketPermissionRequest param( SocketPermissionRequest::UDP_BIND, params_->address, params_->port); - if (!SocketsManifestData::CheckRequest(extension(), param)) { + if (!CheckRequest(param)) { return RespondNow(Error(kPermissionError)); } socket->Bind(params_->address, params_->port, @@ -259,7 +259,7 @@ content::SocketPermissionRequest param( SocketPermissionRequest::UDP_SEND_TO, params_->address, params_->port); - if (!SocketsManifestData::CheckRequest(extension(), param)) { + if (!CheckRequest(param)) { return RespondNow(Error(kPermissionError)); } @@ -389,7 +389,7 @@ SocketPermissionRequest::UDP_MULTICAST_MEMBERSHIP, kWildcardAddress, kWildcardPort); - if (!SocketsManifestData::CheckRequest(extension(), param)) { + if (!CheckRequest(param)) { return RespondNow(Error(kPermissionError)); } @@ -425,7 +425,7 @@ SocketPermissionRequest::UDP_MULTICAST_MEMBERSHIP, kWildcardAddress, kWildcardPort); - if (!SocketsManifestData::CheckRequest(extension(), param)) { + if (!CheckRequest(param)) { return RespondNow(Error(kPermissionError)); } socket->LeaveGroup( @@ -510,7 +510,7 @@ SocketPermissionRequest::UDP_MULTICAST_MEMBERSHIP, kWildcardAddress, kWildcardPort); - if (!SocketsManifestData::CheckRequest(extension(), param)) { + if (!CheckRequest(param)) { return RespondNow(Error(kPermissionError)); }
diff --git a/extensions/browser/extension_function_histogram_value.h b/extensions/browser/extension_function_histogram_value.h index 5083ca0c..9f3bfed 100644 --- a/extensions/browser/extension_function_histogram_value.h +++ b/extensions/browser/extension_function_histogram_value.h
@@ -1781,6 +1781,7 @@ WMDESKSPRIVATE_GETACTIVEDESK = 1718, WMDESKSPRIVATE_SWITCHDESK = 1719, OS_TELEMETRY_GETTPMINFO = 1720, + INPUTMETHODPRIVATE_NOTIFYINPUTMETHODREADYFORTESTING = 1721, // Last entry: Add new entries above, then run: // tools/metrics/histograms/update_extension_histograms.py ENUM_BOUNDARY
diff --git a/extensions/common/mojom/api_permission_id.mojom b/extensions/common/mojom/api_permission_id.mojom index 1eb96ac4..fdfaabed2 100644 --- a/extensions/common/mojom/api_permission_id.mojom +++ b/extensions/common/mojom/api_permission_id.mojom
@@ -268,6 +268,7 @@ kSidePanel = 241, kDownloadsUi = 242, kWebRequestAuthProvider = 243, + kChromeOSTelemetryNetworkInformation = 244, // Add new entries at the end of the enum and be sure to update the // "ExtensionPermission3" enum in tools/metrics/histograms/enums.xml
diff --git a/google_apis/gcm/base/socket_stream_unittest.cc b/google_apis/gcm/base/socket_stream_unittest.cc index ee53a99..93e4865 100644 --- a/google_apis/gcm/base/socket_stream_unittest.cc +++ b/google_apis/gcm/base/socket_stream_unittest.cc
@@ -237,8 +237,9 @@ const url::Origin kOrigin = url::Origin::Create(kDestination); mojo_socket_factory_remote_->CreateProxyResolvingSocket( kDestination, - net::NetworkIsolationKey(kOrigin /* top_frame_origin */, - kOrigin /* frame_origin */), + net::NetworkAnonymizationKey( + /* top_frame_site */ net::SchemefulSite(kOrigin), + /* frame_site */ net::SchemefulSite(kOrigin)), std::move(options), net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS), mojo_socket_remote_.BindNewPipeAndPassReceiver(),
diff --git a/google_apis/gcm/engine/connection_factory_impl.cc b/google_apis/gcm/engine/connection_factory_impl.cc index faf0d28..e5c9a6c 100644 --- a/google_apis/gcm/engine/connection_factory_impl.cc +++ b/google_apis/gcm/engine/connection_factory_impl.cc
@@ -360,13 +360,14 @@ network::mojom::ProxyResolvingSocketOptionsPtr options = network::mojom::ProxyResolvingSocketOptions::New(); options->use_tls = true; - // |current_endpoint| is always a Google URL, so this NetworkIsolationKey will - // be the same for all callers, and will allow pooling all connections to GCM - // in one socket connection, if an H2 or QUIC proxy is in use. - auto origin = url::Origin::Create(current_endpoint); - net::NetworkIsolationKey network_isolation_key(origin, origin); + // |current_endpoint| is always a Google URL, so this NetworkAnonymizationKey + // will be the same for all callers, and will allow pooling all connections to + // GCM in one socket connection, if an H2 or QUIC proxy is in use. + auto site = net::SchemefulSite(current_endpoint); + net::NetworkAnonymizationKey network_anonymization_key(site, site); socket_factory_->CreateProxyResolvingSocket( - current_endpoint, std::move(network_isolation_key), std::move(options), + current_endpoint, std::move(network_anonymization_key), + std::move(options), net::MutableNetworkTrafficAnnotationTag(traffic_annotation), socket_.BindNewPipeAndPassReceiver(), mojo::NullRemote() /* observer */, base::BindOnce(&ConnectionFactoryImpl::OnConnectDone,
diff --git a/google_apis/gcm/engine/connection_handler_impl_unittest.cc b/google_apis/gcm/engine/connection_handler_impl_unittest.cc index d5c8571c..182377f3 100644 --- a/google_apis/gcm/engine/connection_handler_impl_unittest.cc +++ b/google_apis/gcm/engine/connection_handler_impl_unittest.cc
@@ -27,7 +27,7 @@ #include "mojo/public/cpp/bindings/pending_remote.h" #include "mojo/public/cpp/bindings/remote.h" #include "net/base/ip_address.h" -#include "net/base/network_isolation_key.h" +#include "net/base/network_anonymization_key.h" #include "net/base/test_completion_callback.h" #include "net/log/net_log_source.h" #include "net/socket/socket_test_util.h" @@ -256,8 +256,9 @@ const url::Origin kOrigin = url::Origin::Create(kDestination); mojo_socket_factory_remote_->CreateProxyResolvingSocket( kDestination, - net::NetworkIsolationKey(kOrigin /* top_frame_origin */, - kOrigin /* frame_origin */), + net::NetworkAnonymizationKey( + /*top_frame_site=*/net::SchemefulSite(kOrigin), + /*frame_site=*/net::SchemefulSite(kOrigin)), std::move(options), net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS), mojo_socket_remote_.BindNewPipeAndPassReceiver(),
diff --git a/gpu/command_buffer/build_webgpu_cmd_buffer.py b/gpu/command_buffer/build_webgpu_cmd_buffer.py index fc673cd99..b5db950 100755 --- a/gpu/command_buffer/build_webgpu_cmd_buffer.py +++ b/gpu/command_buffer/build_webgpu_cmd_buffer.py
@@ -78,7 +78,7 @@ 'impl_func': False, 'internal': True, }, - 'SetExecutionContextToken': { + 'SetWebGPUExecutionContextToken': { 'impl_func': False, 'client_test': False, },
diff --git a/gpu/command_buffer/client/webgpu_cmd_helper_autogen.h b/gpu/command_buffer/client/webgpu_cmd_helper_autogen.h index 8a8e9ef4..7cd6811c00 100644 --- a/gpu/command_buffer/client/webgpu_cmd_helper_autogen.h +++ b/gpu/command_buffer/client/webgpu_cmd_helper_autogen.h
@@ -56,13 +56,13 @@ } } -void SetExecutionContextToken(uint32_t type, - uint32_t high_high, - uint32_t high_low, - uint32_t low_high, - uint32_t low_low) { - webgpu::cmds::SetExecutionContextToken* c = - GetCmdSpace<webgpu::cmds::SetExecutionContextToken>(); +void SetWebGPUExecutionContextToken(uint32_t type, + uint32_t high_high, + uint32_t high_low, + uint32_t low_high, + uint32_t low_low) { + webgpu::cmds::SetWebGPUExecutionContextToken* c = + GetCmdSpace<webgpu::cmds::SetWebGPUExecutionContextToken>(); if (c) { c->Init(type, high_high, high_low, low_high, low_low); }
diff --git a/gpu/command_buffer/client/webgpu_implementation.cc b/gpu/command_buffer/client/webgpu_implementation.cc index 0cbf2b15..70a9ca3 100644 --- a/gpu/command_buffer/client/webgpu_implementation.cc +++ b/gpu/command_buffer/client/webgpu_implementation.cc
@@ -452,14 +452,14 @@ #endif } -void WebGPUImplementation::SetExecutionContextToken(uint32_t type, - uint32_t high_high, - uint32_t high_low, - uint32_t low_high, - uint32_t low_low) { +void WebGPUImplementation::SetWebGPUExecutionContextToken(uint32_t type, + uint32_t high_high, + uint32_t high_low, + uint32_t low_high, + uint32_t low_low) { #if BUILDFLAG(USE_DAWN) - helper_->SetExecutionContextToken(type, high_high, high_low, low_high, - low_low); + helper_->SetWebGPUExecutionContextToken(type, high_high, high_low, low_high, + low_low); #endif }
diff --git a/gpu/command_buffer/client/webgpu_implementation_autogen.h b/gpu/command_buffer/client/webgpu_implementation_autogen.h index 574d8e2..2424dac 100644 --- a/gpu/command_buffer/client/webgpu_implementation_autogen.h +++ b/gpu/command_buffer/client/webgpu_implementation_autogen.h
@@ -28,10 +28,10 @@ GLuint texture_id, GLuint texture_generation) override; -void SetExecutionContextToken(uint32_t type, - uint32_t high_high, - uint32_t high_low, - uint32_t low_high, - uint32_t low_low) override; +void SetWebGPUExecutionContextToken(uint32_t type, + uint32_t high_high, + uint32_t high_low, + uint32_t low_high, + uint32_t low_low) override; #endif // GPU_COMMAND_BUFFER_CLIENT_WEBGPU_IMPLEMENTATION_AUTOGEN_H_
diff --git a/gpu/command_buffer/client/webgpu_interface.h b/gpu/command_buffer/client/webgpu_interface.h index 695b4e0..94cea0f 100644 --- a/gpu/command_buffer/client/webgpu_interface.h +++ b/gpu/command_buffer/client/webgpu_interface.h
@@ -90,11 +90,13 @@ WEBGPU_MAILBOX_NONE, mailbox); } - void SetExecutionContextToken(const blink::ExecutionContextToken& token) { + void SetWebGPUExecutionContextToken( + const blink::WebGPUExecutionContextToken& token) { uint64_t high = token.value().GetHighForSerialization(); uint64_t low = token.value().GetLowForSerialization(); - SetExecutionContextToken(token.variant_index(), high >> 32, - high & 0xFFFFFFFF, low >> 32, low & 0xFFFFFFFF); + SetWebGPUExecutionContextToken(token.variant_index(), high >> 32, + high & 0xFFFFFFFF, low >> 32, + low & 0xFFFFFFFF); } };
diff --git a/gpu/command_buffer/client/webgpu_interface_autogen.h b/gpu/command_buffer/client/webgpu_interface_autogen.h index 24f8664f..4f7ac16a 100644 --- a/gpu/command_buffer/client/webgpu_interface_autogen.h +++ b/gpu/command_buffer/client/webgpu_interface_autogen.h
@@ -26,9 +26,9 @@ GLuint device_generation, GLuint texture_id, GLuint texture_generation) = 0; -virtual void SetExecutionContextToken(uint32_t type, - uint32_t high_high, - uint32_t high_low, - uint32_t low_high, - uint32_t low_low) = 0; +virtual void SetWebGPUExecutionContextToken(uint32_t type, + uint32_t high_high, + uint32_t high_low, + uint32_t low_high, + uint32_t low_low) = 0; #endif // GPU_COMMAND_BUFFER_CLIENT_WEBGPU_INTERFACE_AUTOGEN_H_
diff --git a/gpu/command_buffer/client/webgpu_interface_stub_autogen.h b/gpu/command_buffer/client/webgpu_interface_stub_autogen.h index fe5b29be8..bb68495 100644 --- a/gpu/command_buffer/client/webgpu_interface_stub_autogen.h +++ b/gpu/command_buffer/client/webgpu_interface_stub_autogen.h
@@ -24,9 +24,9 @@ GLuint device_generation, GLuint texture_id, GLuint texture_generation) override; -void SetExecutionContextToken(uint32_t type, - uint32_t high_high, - uint32_t high_low, - uint32_t low_high, - uint32_t low_low) override; +void SetWebGPUExecutionContextToken(uint32_t type, + uint32_t high_high, + uint32_t high_low, + uint32_t low_high, + uint32_t low_low) override; #endif // GPU_COMMAND_BUFFER_CLIENT_WEBGPU_INTERFACE_STUB_AUTOGEN_H_
diff --git a/gpu/command_buffer/client/webgpu_interface_stub_impl_autogen.h b/gpu/command_buffer/client/webgpu_interface_stub_impl_autogen.h index 2c816aa..bb75daa6 100644 --- a/gpu/command_buffer/client/webgpu_interface_stub_impl_autogen.h +++ b/gpu/command_buffer/client/webgpu_interface_stub_impl_autogen.h
@@ -26,9 +26,10 @@ GLuint /* device_generation */, GLuint /* texture_id */, GLuint /* texture_generation */) {} -void WebGPUInterfaceStub::SetExecutionContextToken(uint32_t /* type */, - uint32_t /* high_high */, - uint32_t /* high_low */, - uint32_t /* low_high */, - uint32_t /* low_low */) {} +void WebGPUInterfaceStub::SetWebGPUExecutionContextToken( + uint32_t /* type */, + uint32_t /* high_high */, + uint32_t /* high_low */, + uint32_t /* low_high */, + uint32_t /* low_low */) {} #endif // GPU_COMMAND_BUFFER_CLIENT_WEBGPU_INTERFACE_STUB_IMPL_AUTOGEN_H_
diff --git a/gpu/command_buffer/common/webgpu_cmd_format_autogen.h b/gpu/command_buffer/common/webgpu_cmd_format_autogen.h index 149164c..ab4b022 100644 --- a/gpu/command_buffer/common/webgpu_cmd_format_autogen.h +++ b/gpu/command_buffer/common/webgpu_cmd_format_autogen.h
@@ -223,9 +223,9 @@ offsetof(DissociateMailboxForPresent, texture_generation) == 16, "offset of DissociateMailboxForPresent texture_generation should be 16"); -struct SetExecutionContextToken { - typedef SetExecutionContextToken ValueType; - static const CommandId kCmdId = kSetExecutionContextToken; +struct SetWebGPUExecutionContextToken { + typedef SetWebGPUExecutionContextToken ValueType; + static const CommandId kCmdId = kSetWebGPUExecutionContextToken; static const cmd::ArgFlags kArgFlags = cmd::kFixed; static const uint8_t cmd_flags = CMD_FLAG_SET_TRACE_LEVEL(3); @@ -267,19 +267,19 @@ uint32_t low_low; }; -static_assert(sizeof(SetExecutionContextToken) == 24, - "size of SetExecutionContextToken should be 24"); -static_assert(offsetof(SetExecutionContextToken, header) == 0, - "offset of SetExecutionContextToken header should be 0"); -static_assert(offsetof(SetExecutionContextToken, type) == 4, - "offset of SetExecutionContextToken type should be 4"); -static_assert(offsetof(SetExecutionContextToken, high_high) == 8, - "offset of SetExecutionContextToken high_high should be 8"); -static_assert(offsetof(SetExecutionContextToken, high_low) == 12, - "offset of SetExecutionContextToken high_low should be 12"); -static_assert(offsetof(SetExecutionContextToken, low_high) == 16, - "offset of SetExecutionContextToken low_high should be 16"); -static_assert(offsetof(SetExecutionContextToken, low_low) == 20, - "offset of SetExecutionContextToken low_low should be 20"); +static_assert(sizeof(SetWebGPUExecutionContextToken) == 24, + "size of SetWebGPUExecutionContextToken should be 24"); +static_assert(offsetof(SetWebGPUExecutionContextToken, header) == 0, + "offset of SetWebGPUExecutionContextToken header should be 0"); +static_assert(offsetof(SetWebGPUExecutionContextToken, type) == 4, + "offset of SetWebGPUExecutionContextToken type should be 4"); +static_assert(offsetof(SetWebGPUExecutionContextToken, high_high) == 8, + "offset of SetWebGPUExecutionContextToken high_high should be 8"); +static_assert(offsetof(SetWebGPUExecutionContextToken, high_low) == 12, + "offset of SetWebGPUExecutionContextToken high_low should be 12"); +static_assert(offsetof(SetWebGPUExecutionContextToken, low_high) == 16, + "offset of SetWebGPUExecutionContextToken low_high should be 16"); +static_assert(offsetof(SetWebGPUExecutionContextToken, low_low) == 20, + "offset of SetWebGPUExecutionContextToken low_low should be 20"); #endif // GPU_COMMAND_BUFFER_COMMON_WEBGPU_CMD_FORMAT_AUTOGEN_H_
diff --git a/gpu/command_buffer/common/webgpu_cmd_format_test_autogen.h b/gpu/command_buffer/common/webgpu_cmd_format_test_autogen.h index 533b850..3bb1874 100644 --- a/gpu/command_buffer/common/webgpu_cmd_format_test_autogen.h +++ b/gpu/command_buffer/common/webgpu_cmd_format_test_autogen.h
@@ -96,14 +96,14 @@ CheckBytesWrittenMatchesExpectedSize(next_cmd, sizeof(cmd)); } -TEST_F(WebGPUFormatTest, SetExecutionContextToken) { - cmds::SetExecutionContextToken& cmd = - *GetBufferAs<cmds::SetExecutionContextToken>(); +TEST_F(WebGPUFormatTest, SetWebGPUExecutionContextToken) { + cmds::SetWebGPUExecutionContextToken& cmd = + *GetBufferAs<cmds::SetWebGPUExecutionContextToken>(); void* next_cmd = cmd.Set(&cmd, static_cast<uint32_t>(11), static_cast<uint32_t>(12), static_cast<uint32_t>(13), static_cast<uint32_t>(14), static_cast<uint32_t>(15)); - EXPECT_EQ(static_cast<uint32_t>(cmds::SetExecutionContextToken::kCmdId), + EXPECT_EQ(static_cast<uint32_t>(cmds::SetWebGPUExecutionContextToken::kCmdId), cmd.header.command); EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u); EXPECT_EQ(static_cast<uint32_t>(11), cmd.type);
diff --git a/gpu/command_buffer/common/webgpu_cmd_ids_autogen.h b/gpu/command_buffer/common/webgpu_cmd_ids_autogen.h index ba17899d..1bb51f0 100644 --- a/gpu/command_buffer/common/webgpu_cmd_ids_autogen.h +++ b/gpu/command_buffer/common/webgpu_cmd_ids_autogen.h
@@ -11,12 +11,12 @@ #ifndef GPU_COMMAND_BUFFER_COMMON_WEBGPU_CMD_IDS_AUTOGEN_H_ #define GPU_COMMAND_BUFFER_COMMON_WEBGPU_CMD_IDS_AUTOGEN_H_ -#define WEBGPU_COMMAND_LIST(OP) \ - OP(DawnCommands) /* 256 */ \ - OP(AssociateMailboxImmediate) /* 257 */ \ - OP(DissociateMailbox) /* 258 */ \ - OP(DissociateMailboxForPresent) /* 259 */ \ - OP(SetExecutionContextToken) /* 260 */ +#define WEBGPU_COMMAND_LIST(OP) \ + OP(DawnCommands) /* 256 */ \ + OP(AssociateMailboxImmediate) /* 257 */ \ + OP(DissociateMailbox) /* 258 */ \ + OP(DissociateMailboxForPresent) /* 259 */ \ + OP(SetWebGPUExecutionContextToken) /* 260 */ enum CommandId { kOneBeforeStartPoint =
diff --git a/gpu/command_buffer/service/DEPS b/gpu/command_buffer/service/DEPS index 4c43e42d..92293950 100644 --- a/gpu/command_buffer/service/DEPS +++ b/gpu/command_buffer/service/DEPS
@@ -9,6 +9,7 @@ "+components/viz/common/gpu/metal_context_provider.h", "+components/viz/common/gpu/vulkan_context_provider.h", "+components/viz/common/resources/resource_format.h", + "+components/viz/common/resources/shared_image_format.h", "+components/viz/common/resources/resource_format_utils.h", "+components/viz/common/resources/resource_sizes.h", "+components/viz/common/resources/shared_image_format.h",
diff --git a/gpu/command_buffer/service/ahardwarebuffer_utils.cc b/gpu/command_buffer/service/ahardwarebuffer_utils.cc index b773d04..f964df7 100644 --- a/gpu/command_buffer/service/ahardwarebuffer_utils.cc +++ b/gpu/command_buffer/service/ahardwarebuffer_utils.cc
@@ -164,7 +164,7 @@ base::android::ScopedHardwareBufferHandle ahb_handle, SharedContextState* context_state, const gfx::Size& size, - const viz::ResourceFormat& format, + const viz::SharedImageFormat& format, uint32_t queue_family_index) { DCHECK(context_state); DCHECK(context_state->GrContextIsVulkan());
diff --git a/gpu/command_buffer/service/ahardwarebuffer_utils.h b/gpu/command_buffer/service/ahardwarebuffer_utils.h index 5d63e7d..7961d68 100644 --- a/gpu/command_buffer/service/ahardwarebuffer_utils.h +++ b/gpu/command_buffer/service/ahardwarebuffer_utils.h
@@ -8,7 +8,7 @@ #include <memory> #include "base/memory/scoped_refptr.h" -#include "components/viz/common/resources/resource_format.h" +#include "components/viz/common/resources/shared_image_format.h" #include "gpu/gpu_gles2_export.h" extern "C" typedef struct AHardwareBuffer AHardwareBuffer; @@ -76,7 +76,7 @@ base::android::ScopedHardwareBufferHandle ahb_handle, SharedContextState* context_state, const gfx::Size& size, - const viz::ResourceFormat& format, + const viz::SharedImageFormat& format, uint32_t queue_family_index); } // namespace gpu
diff --git a/gpu/command_buffer/service/gles2_cmd_decoder_passthrough_unittest_textures.cc b/gpu/command_buffer/service/gles2_cmd_decoder_passthrough_unittest_textures.cc index b020be5..a74f61fc 100644 --- a/gpu/command_buffer/service/gles2_cmd_decoder_passthrough_unittest_textures.cc +++ b/gpu/command_buffer/service/gles2_cmd_decoder_passthrough_unittest_textures.cc
@@ -13,9 +13,10 @@ namespace gpu { namespace gles2 { namespace { + std::unique_ptr<TestImageBacking> AllocateTextureAndCreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, @@ -37,9 +38,11 @@ TEST_F(GLES2DecoderPassthroughTest, CreateAndTexStorage2DSharedImageCHROMIUM) { MemoryTypeTracker memory_tracker(nullptr); Mailbox mailbox = Mailbox::GenerateForSharedImage(); + auto format = + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RGBA_8888); auto backing = AllocateTextureAndCreateSharedImage( - mailbox, viz::ResourceFormat::RGBA_8888, gfx::Size(10, 10), - gfx::ColorSpace(), kTopLeft_GrSurfaceOrigin, kPremul_SkAlphaType, 0); + mailbox, format, gfx::Size(10, 10), gfx::ColorSpace(), + kTopLeft_GrSurfaceOrigin, kPremul_SkAlphaType, 0); GLuint service_id = backing->service_id(); std::unique_ptr<SharedImageRepresentationFactoryRef> shared_image = GetSharedImageManager()->Register(std::move(backing), &memory_tracker); @@ -100,12 +103,13 @@ MemoryTypeTracker memory_tracker(nullptr); // Create a texture with kNewClientId. Mailbox mailbox = Mailbox::GenerateForSharedImage(); + auto format = + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RGBA_8888); std::unique_ptr<SharedImageRepresentationFactoryRef> shared_image = GetSharedImageManager()->Register( AllocateTextureAndCreateSharedImage( - mailbox, viz::ResourceFormat::RGBA_8888, gfx::Size(10, 10), - gfx::ColorSpace(), kTopLeft_GrSurfaceOrigin, kPremul_SkAlphaType, - 0), + mailbox, format, gfx::Size(10, 10), gfx::ColorSpace(), + kTopLeft_GrSurfaceOrigin, kPremul_SkAlphaType, 0), &memory_tracker); { @@ -136,12 +140,13 @@ shared_images; for (int i = 0; i < 40; i++) { Mailbox mailbox = Mailbox::GenerateForSharedImage(); + auto format = + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RGBA_8888); std::unique_ptr<SharedImageRepresentationFactoryRef> shared_image = GetSharedImageManager()->Register( AllocateTextureAndCreateSharedImage( - mailbox, viz::ResourceFormat::RGBA_8888, gfx::Size(10, 10), - gfx::ColorSpace(), kTopLeft_GrSurfaceOrigin, - kPremul_SkAlphaType, 0), + mailbox, format, gfx::Size(10, 10), gfx::ColorSpace(), + kTopLeft_GrSurfaceOrigin, kPremul_SkAlphaType, 0), &memory_tracker); shared_images.emplace_back(std::move(shared_image)); @@ -204,9 +209,11 @@ // Create a shared image. MemoryTypeTracker memory_tracker(nullptr); Mailbox mailbox = Mailbox::GenerateForSharedImage(); + auto format = + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RGBA_8888); auto shared_image_backing = AllocateTextureAndCreateSharedImage( - mailbox, viz::ResourceFormat::RGBA_8888, gfx::Size(10, 10), - gfx::ColorSpace(), kTopLeft_GrSurfaceOrigin, kPremul_SkAlphaType, 0); + mailbox, format, gfx::Size(10, 10), gfx::ColorSpace(), + kTopLeft_GrSurfaceOrigin, kPremul_SkAlphaType, 0); // Set the shared image to fail BeginAccess. shared_image_backing->set_can_access(false); std::unique_ptr<SharedImageRepresentationFactoryRef> shared_image = @@ -245,12 +252,13 @@ // Create an uncleared shared image. MemoryTypeTracker memory_tracker(nullptr); Mailbox mailbox = Mailbox::GenerateForSharedImage(); + auto format = + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RGBA_8888); std::unique_ptr<SharedImageRepresentationFactoryRef> shared_image = GetSharedImageManager()->Register( AllocateTextureAndCreateSharedImage( - mailbox, viz::ResourceFormat::RGBA_8888, gfx::Size(10, 10), - gfx::ColorSpace(), kTopLeft_GrSurfaceOrigin, kPremul_SkAlphaType, - 0), + mailbox, format, gfx::Size(10, 10), gfx::ColorSpace(), + kTopLeft_GrSurfaceOrigin, kPremul_SkAlphaType, 0), &memory_tracker); // Backing should be initially uncleared.
diff --git a/gpu/command_buffer/service/gles2_cmd_decoder_unittest_textures.cc b/gpu/command_buffer/service/gles2_cmd_decoder_unittest_textures.cc index 5086542..a5c3adf 100644 --- a/gpu/command_buffer/service/gles2_cmd_decoder_unittest_textures.cc +++ b/gpu/command_buffer/service/gles2_cmd_decoder_unittest_textures.cc
@@ -3075,12 +3075,14 @@ TEST_P(GLES2DecoderTest, CreateAndTexStorage2DSharedImageCHROMIUM) { MemoryTypeTracker memory_tracker(memory_tracker_.get()); Mailbox mailbox = Mailbox::GenerateForSharedImage(); + auto format = + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RGBA_8888); std::unique_ptr<SharedImageRepresentationFactoryRef> shared_image = GetSharedImageManager()->Register( std::make_unique<TestImageBacking>( - mailbox, viz::ResourceFormat::RGBA_8888, gfx::Size(10, 10), - gfx::ColorSpace(), kTopLeft_GrSurfaceOrigin, kPremul_SkAlphaType, - 0, 0, kNewServiceId), + mailbox, format, gfx::Size(10, 10), gfx::ColorSpace(), + kTopLeft_GrSurfaceOrigin, kPremul_SkAlphaType, 0, 0, + kNewServiceId), &memory_tracker); auto& cmd = *GetImmediateAs< @@ -3137,12 +3139,14 @@ // Try to create a mailbox with kNewClientId. MemoryTypeTracker memory_tracker(memory_tracker_.get()); Mailbox mailbox = Mailbox::GenerateForSharedImage(); + auto format = + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RGBA_8888); std::unique_ptr<SharedImageRepresentationFactoryRef> shared_image = GetSharedImageManager()->Register( std::make_unique<TestImageBacking>( - mailbox, viz::ResourceFormat::RGBA_8888, gfx::Size(10, 10), - gfx::ColorSpace(), kTopLeft_GrSurfaceOrigin, kPremul_SkAlphaType, - 0, 0, kNewServiceId), + mailbox, format, gfx::Size(10, 10), gfx::ColorSpace(), + kTopLeft_GrSurfaceOrigin, kPremul_SkAlphaType, 0, 0, + kNewServiceId), &memory_tracker); auto& cmd = *GetImmediateAs< @@ -3161,12 +3165,14 @@ TEST_P(GLES2DecoderTest, BeginEndSharedImageAccessCRHOMIUM) { MemoryTypeTracker memory_tracker(memory_tracker_.get()); Mailbox mailbox = Mailbox::GenerateForSharedImage(); + auto format = + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RGBA_8888); std::unique_ptr<SharedImageRepresentationFactoryRef> shared_image = GetSharedImageManager()->Register( std::make_unique<TestImageBacking>( - mailbox, viz::ResourceFormat::RGBA_8888, gfx::Size(10, 10), - gfx::ColorSpace(), kTopLeft_GrSurfaceOrigin, kPremul_SkAlphaType, - 0, 0, kNewServiceId), + mailbox, format, gfx::Size(10, 10), gfx::ColorSpace(), + kTopLeft_GrSurfaceOrigin, kPremul_SkAlphaType, 0, 0, + kNewServiceId), &memory_tracker); auto& cmd = *GetImmediateAs< @@ -3222,10 +3228,11 @@ // Create a shared image. MemoryTypeTracker memory_tracker(memory_tracker_.get()); Mailbox mailbox = Mailbox::GenerateForSharedImage(); + auto format = + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RGBA_8888); auto shared_image_backing = std::make_unique<TestImageBacking>( - mailbox, viz::ResourceFormat::RGBA_8888, gfx::Size(10, 10), - gfx::ColorSpace(), kTopLeft_GrSurfaceOrigin, kPremul_SkAlphaType, 0, 0, - kNewServiceId); + mailbox, format, gfx::Size(10, 10), gfx::ColorSpace(), + kTopLeft_GrSurfaceOrigin, kPremul_SkAlphaType, 0, 0, kNewServiceId); // Set the shared image to fail BeginAccess. shared_image_backing->set_can_access(false); std::unique_ptr<SharedImageRepresentationFactoryRef> shared_image =
diff --git a/gpu/command_buffer/service/shared_image/ahardwarebuffer_image_backing_factory.cc b/gpu/command_buffer/service/shared_image/ahardwarebuffer_image_backing_factory.cc index aa6d4a85..a6211d7 100644 --- a/gpu/command_buffer/service/shared_image/ahardwarebuffer_image_backing_factory.cc +++ b/gpu/command_buffer/service/shared_image/ahardwarebuffer_image_backing_factory.cc
@@ -127,7 +127,7 @@ public: AHardwareBufferImageBacking( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, @@ -248,7 +248,7 @@ AHardwareBufferImageBacking::AHardwareBufferImageBacking( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, @@ -542,12 +542,12 @@ bool AHardwareBufferImageBackingFactory::ValidateUsage( uint32_t usage, const gfx::Size& size, - viz::ResourceFormat format) const { - const FormatInfo& format_info = format_info_[format]; + viz::SharedImageFormat format) const { + const FormatInfo& format_info = GetFormatInfo(format); // Check if the format is supported by AHardwareBuffer. if (!format_info.ahb_supported) { - LOG(ERROR) << "viz::ResourceFormat " << format + LOG(ERROR) << "viz::ResourceFormat " << viz::ResourceFormatToString(format) << " not supported by AHardwareBuffer"; return false; } @@ -568,7 +568,7 @@ // Check if the GL texture can be created from AHB with this format. if (!format_info.gl_supported) { LOG(ERROR) - << "viz::ResourceFormat " << format + << "viz::ResourceFormat " << viz::ResourceFormatToString(format) << " can not be used to create a GL texture from AHardwareBuffer."; return false; } @@ -592,7 +592,7 @@ std::unique_ptr<SharedImageBacking> AHardwareBufferImageBackingFactory::MakeBacking( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, @@ -601,7 +601,7 @@ bool is_thread_safe, base::span<const uint8_t> pixel_data) { DCHECK(base::AndroidHardwareBufferCompat::IsSupportAvailable()); - DCHECK(format != viz::ETC1); + DCHECK(!viz::IsResourceFormatCompressed(format)); if (!ValidateUsage(usage, size, format)) { return nullptr; @@ -614,7 +614,7 @@ return nullptr; } - const FormatInfo& format_info = format_info_[format]; + const FormatInfo& format_info = GetFormatInfo(format); // Setup AHardwareBuffer. AHardwareBuffer* buffer = nullptr; @@ -699,7 +699,7 @@ std::unique_ptr<SharedImageBacking> AHardwareBufferImageBackingFactory::CreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, SurfaceHandle surface_handle, const gfx::Size& size, const gfx::ColorSpace& color_space, @@ -714,7 +714,7 @@ std::unique_ptr<SharedImageBacking> AHardwareBufferImageBackingFactory::CreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, @@ -732,7 +732,7 @@ bool AHardwareBufferImageBackingFactory::IsSupported( uint32_t usage, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, bool thread_safe, gfx::GpuMemoryBufferType gmb_type, @@ -756,11 +756,9 @@ } bool AHardwareBufferImageBackingFactory::IsFormatSupported( - viz::ResourceFormat format) { - DCHECK_GE(format, 0); - DCHECK_LE(format, viz::RESOURCE_FORMAT_MAX); - - return format_info_[format].ahb_supported; + viz::SharedImageFormat format) { + const FormatInfo& format_info = GetFormatInfo(format); + return format_info.ahb_supported; } AHardwareBufferImageBackingFactory::FormatInfo::FormatInfo() = default; @@ -789,22 +787,21 @@ return nullptr; } - auto resource_format = viz::GetResourceFormat(buffer_format); - - if (!ValidateUsage(usage, size, resource_format)) { + auto si_format = viz::SharedImageFormat::SinglePlane( + viz::GetResourceFormat(buffer_format)); + if (!ValidateUsage(usage, size, si_format)) { return nullptr; } size_t estimated_size; - if (!viz::ResourceSizes::MaybeSizeInBytes(size, resource_format, - &estimated_size)) { + if (!viz::ResourceSizes::MaybeSizeInBytes(size, si_format, &estimated_size)) { LOG(ERROR) << "Failed to calculate SharedImage size"; return nullptr; } auto backing = std::make_unique<AHardwareBufferImageBacking>( - mailbox, resource_format, size, color_space, surface_origin, alpha_type, - usage, std::move(handle.android_hardware_buffer), estimated_size, false, + mailbox, si_format, size, color_space, surface_origin, alpha_type, usage, + std::move(handle.android_hardware_buffer), estimated_size, false, base::ScopedFD(), dawn_procs_); backing->SetCleared();
diff --git a/gpu/command_buffer/service/shared_image/ahardwarebuffer_image_backing_factory.h b/gpu/command_buffer/service/shared_image/ahardwarebuffer_image_backing_factory.h index bd6f197..b1e70fc 100644 --- a/gpu/command_buffer/service/shared_image/ahardwarebuffer_image_backing_factory.h +++ b/gpu/command_buffer/service/shared_image/ahardwarebuffer_image_backing_factory.h
@@ -44,7 +44,7 @@ // SharedImageBackingFactory implementation. std::unique_ptr<SharedImageBacking> CreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, SurfaceHandle surface_handle, const gfx::Size& size, const gfx::ColorSpace& color_space, @@ -54,7 +54,7 @@ bool is_thread_safe) override; std::unique_ptr<SharedImageBacking> CreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, @@ -74,32 +74,15 @@ SkAlphaType alpha_type, uint32_t usage) override; bool IsSupported(uint32_t usage, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, bool thread_safe, gfx::GpuMemoryBufferType gmb_type, GrContextType gr_context_type, base::span<const uint8_t> pixel_data) override; - bool IsFormatSupported(viz::ResourceFormat format); + bool IsFormatSupported(viz::SharedImageFormat format); private: - bool ValidateUsage(uint32_t usage, - const gfx::Size& size, - viz::ResourceFormat format) const; - - bool CanImportGpuMemoryBuffer(gfx::GpuMemoryBufferType memory_buffer_type); - - std::unique_ptr<SharedImageBacking> MakeBacking( - const Mailbox& mailbox, - viz::ResourceFormat format, - const gfx::Size& size, - const gfx::ColorSpace& color_space, - GrSurfaceOrigin surface_origin, - SkAlphaType alpha_type, - uint32_t usage, - bool is_thread_safe, - base::span<const uint8_t> pixel_data); - struct FormatInfo { FormatInfo(); ~FormatInfo(); @@ -117,6 +100,28 @@ GLenum gl_type = 0; }; + bool ValidateUsage(uint32_t usage, + const gfx::Size& size, + viz::SharedImageFormat format) const; + + bool CanImportGpuMemoryBuffer(gfx::GpuMemoryBufferType memory_buffer_type); + + std::unique_ptr<SharedImageBacking> MakeBacking( + const Mailbox& mailbox, + viz::SharedImageFormat format, + const gfx::Size& size, + const gfx::ColorSpace& color_space, + GrSurfaceOrigin surface_origin, + SkAlphaType alpha_type, + uint32_t usage, + bool is_thread_safe, + base::span<const uint8_t> pixel_data); + + // WARNING: Format must be single plane. + const FormatInfo& GetFormatInfo(viz::SharedImageFormat format) const { + return format_info_[format.resource_format()]; + } + FormatInfo format_info_[viz::RESOURCE_FORMAT_MAX + 1]; // Used to limit the max size of AHardwareBuffer.
diff --git a/gpu/command_buffer/service/shared_image/ahardwarebuffer_image_backing_factory_unittest.cc b/gpu/command_buffer/service/shared_image/ahardwarebuffer_image_backing_factory_unittest.cc index adc44de8..242f75cb 100644 --- a/gpu/command_buffer/service/shared_image/ahardwarebuffer_image_backing_factory_unittest.cc +++ b/gpu/command_buffer/service/shared_image/ahardwarebuffer_image_backing_factory_unittest.cc
@@ -163,7 +163,8 @@ // Create a backing using mailbox. auto mailbox = Mailbox::GenerateForSharedImage(); - auto format = viz::ResourceFormat::RGBA_8888; + auto format = + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RGBA_8888); gfx::Size size(1, 1); auto color_space = gfx::ColorSpace::CreateSRGB(); GrSurfaceOrigin surface_origin = kTopLeft_GrSurfaceOrigin; @@ -223,7 +224,8 @@ return; auto mailbox = Mailbox::GenerateForSharedImage(); - auto format = viz::ResourceFormat::RGBA_8888; + auto format = + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RGBA_8888); gfx::Size size(4, 4); std::vector<uint8_t> initial_data(size.width() * size.height() * 4); @@ -261,7 +263,8 @@ return; auto mailbox = Mailbox::GenerateForSharedImage(); - auto format = viz::ResourceFormat::YUV_420_BIPLANAR; + auto format = viz::SharedImageFormat::SinglePlane( + viz::ResourceFormat::YUV_420_BIPLANAR); gfx::Size size(256, 256); auto color_space = gfx::ColorSpace::CreateSRGB(); GrSurfaceOrigin surface_origin = kTopLeft_GrSurfaceOrigin; @@ -280,7 +283,8 @@ return; auto mailbox = Mailbox::GenerateForSharedImage(); - auto format = viz::ResourceFormat::RGBA_8888; + auto format = + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RGBA_8888); gfx::Size size(0, 0); auto color_space = gfx::ColorSpace::CreateSRGB(); GrSurfaceOrigin surface_origin = kTopLeft_GrSurfaceOrigin; @@ -304,7 +308,8 @@ return; auto mailbox = Mailbox::GenerateForSharedImage(); - auto format = viz::ResourceFormat::RGBA_8888; + auto format = + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RGBA_8888); gfx::Size size(256, 256); auto color_space = gfx::ColorSpace::CreateSRGB(); GrSurfaceOrigin surface_origin = kTopLeft_GrSurfaceOrigin; @@ -494,7 +499,8 @@ SharedImageRepresentationFactory* shared_image_representation_factory) : size_(256, 256) { mailbox_ = Mailbox::GenerateForSharedImage(); - auto format = viz::ResourceFormat::RGBA_8888; + auto format = + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RGBA_8888); auto color_space = gfx::ColorSpace::CreateSRGB(); GrSurfaceOrigin surface_origin = kTopLeft_GrSurfaceOrigin; SkAlphaType alpha_type = kPremul_SkAlphaType;
diff --git a/gpu/command_buffer/service/shared_image/android_image_backing.cc b/gpu/command_buffer/service/shared_image/android_image_backing.cc index 7d4fd402..f3941b8 100644 --- a/gpu/command_buffer/service/shared_image/android_image_backing.cc +++ b/gpu/command_buffer/service/shared_image/android_image_backing.cc
@@ -11,7 +11,7 @@ namespace gpu { AndroidImageBacking::AndroidImageBacking(const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin,
diff --git a/gpu/command_buffer/service/shared_image/android_image_backing.h b/gpu/command_buffer/service/shared_image/android_image_backing.h index 928ad7b..f79f715 100644 --- a/gpu/command_buffer/service/shared_image/android_image_backing.h +++ b/gpu/command_buffer/service/shared_image/android_image_backing.h
@@ -14,7 +14,7 @@ class AndroidImageBacking : public ClearTrackingSharedImageBacking { public: AndroidImageBacking(const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin,
diff --git a/gpu/command_buffer/service/shared_image/android_video_image_backing.cc b/gpu/command_buffer/service/shared_image/android_video_image_backing.cc index ff74dd3..e49792c 100644 --- a/gpu/command_buffer/service/shared_image/android_video_image_backing.cc +++ b/gpu/command_buffer/service/shared_image/android_video_image_backing.cc
@@ -30,7 +30,7 @@ bool is_thread_safe) : AndroidImageBacking( mailbox, - viz::RGBA_8888, + viz::SharedImageFormat::SinglePlane(viz::RGBA_8888), size, color_space, surface_origin,
diff --git a/gpu/command_buffer/service/shared_image/angle_vulkan_image_backing.cc b/gpu/command_buffer/service/shared_image/angle_vulkan_image_backing.cc index 3cd6a05..a2239f1 100644 --- a/gpu/command_buffer/service/shared_image/angle_vulkan_image_backing.cc +++ b/gpu/command_buffer/service/shared_image/angle_vulkan_image_backing.cc
@@ -123,7 +123,7 @@ AngleVulkanImageBacking::AngleVulkanImageBacking( const raw_ptr<SharedContextState>& context_state, const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, @@ -187,7 +187,7 @@ if (usage() & kUsageNeedsColorAttachment) { vk_usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT; - if (format() == viz::ETC1) { + if (viz::IsResourceFormatCompressed(format())) { DLOG(ERROR) << "ETC1 format cannot be used as color attachment."; return false; }
diff --git a/gpu/command_buffer/service/shared_image/angle_vulkan_image_backing.h b/gpu/command_buffer/service/shared_image/angle_vulkan_image_backing.h index 771a82a1..e773aed 100644 --- a/gpu/command_buffer/service/shared_image/angle_vulkan_image_backing.h +++ b/gpu/command_buffer/service/shared_image/angle_vulkan_image_backing.h
@@ -27,7 +27,7 @@ public: AngleVulkanImageBacking(const raw_ptr<SharedContextState>& context_state, const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin,
diff --git a/gpu/command_buffer/service/shared_image/angle_vulkan_image_backing_factory.cc b/gpu/command_buffer/service/shared_image/angle_vulkan_image_backing_factory.cc index c6740c9b..7a4b59e 100644 --- a/gpu/command_buffer/service/shared_image/angle_vulkan_image_backing_factory.cc +++ b/gpu/command_buffer/service/shared_image/angle_vulkan_image_backing_factory.cc
@@ -31,7 +31,7 @@ std::unique_ptr<SharedImageBacking> AngleVulkanImageBackingFactory::CreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, SurfaceHandle surface_handle, const gfx::Size& size, const gfx::ColorSpace& color_space, @@ -52,7 +52,7 @@ std::unique_ptr<SharedImageBacking> AngleVulkanImageBackingFactory::CreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, @@ -113,7 +113,7 @@ bool AngleVulkanImageBackingFactory::IsSupported( uint32_t usage, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, bool thread_safe, gfx::GpuMemoryBufferType gmb_type, @@ -130,7 +130,7 @@ return false; } - return CanCreateSharedImage(size, pixel_data, format_info_[format], + return CanCreateSharedImage(size, pixel_data, GetFormatInfo(format), GL_TEXTURE_2D); }
diff --git a/gpu/command_buffer/service/shared_image/angle_vulkan_image_backing_factory.h b/gpu/command_buffer/service/shared_image/angle_vulkan_image_backing_factory.h index e18d00e6..b76c62c6 100644 --- a/gpu/command_buffer/service/shared_image/angle_vulkan_image_backing_factory.h +++ b/gpu/command_buffer/service/shared_image/angle_vulkan_image_backing_factory.h
@@ -21,7 +21,7 @@ // SharedImageBackingFactory implementation: std::unique_ptr<SharedImageBacking> CreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, SurfaceHandle surface_handle, const gfx::Size& size, const gfx::ColorSpace& color_space, @@ -31,7 +31,7 @@ bool is_thread_safe) override; std::unique_ptr<SharedImageBacking> CreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, @@ -51,7 +51,7 @@ SkAlphaType alpha_type, uint32_t usage) override; bool IsSupported(uint32_t usage, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, bool thread_safe, gfx::GpuMemoryBufferType gmb_type,
diff --git a/gpu/command_buffer/service/shared_image/compound_image_backing.cc b/gpu/command_buffer/service/shared_image/compound_image_backing.cc index 3697f56..6b605d1 100644 --- a/gpu/command_buffer/service/shared_image/compound_image_backing.cc +++ b/gpu/command_buffer/service/shared_image/compound_image_backing.cc
@@ -308,20 +308,22 @@ return nullptr; } + auto si_format = viz::SharedImageFormat::SinglePlane(plane_format); + auto shm_backing = std::make_unique<SharedMemoryImageBacking>( - mailbox, plane_format, plane_size, color_space, surface_origin, - alpha_type, SHARED_IMAGE_USAGE_CPU_WRITE, std::move(shm_wrapper)); + mailbox, si_format, plane_size, color_space, surface_origin, alpha_type, + SHARED_IMAGE_USAGE_CPU_WRITE, std::move(shm_wrapper)); shm_backing->SetNotRefCounted(); return std::make_unique<CompoundImageBacking>( - mailbox, plane_format, plane_size, color_space, surface_origin, - alpha_type, usage, surface_handle, allow_shm_overlays, - std::move(shm_backing), gpu_backing_factory->GetWeakPtr()); + mailbox, si_format, plane_size, color_space, surface_origin, alpha_type, + usage, surface_handle, allow_shm_overlays, std::move(shm_backing), + gpu_backing_factory->GetWeakPtr()); } CompoundImageBacking::CompoundImageBacking( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin,
diff --git a/gpu/command_buffer/service/shared_image/compound_image_backing.h b/gpu/command_buffer/service/shared_image/compound_image_backing.h index 3f8dedb..99c8cd9 100644 --- a/gpu/command_buffer/service/shared_image/compound_image_backing.h +++ b/gpu/command_buffer/service/shared_image/compound_image_backing.h
@@ -57,7 +57,7 @@ CompoundImageBacking( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin,
diff --git a/gpu/command_buffer/service/shared_image/compound_image_backing_unittest.cc b/gpu/command_buffer/service/shared_image/compound_image_backing_unittest.cc index e56fea6..b6298d5d 100644 --- a/gpu/command_buffer/service/shared_image/compound_image_backing_unittest.cc +++ b/gpu/command_buffer/service/shared_image/compound_image_backing_unittest.cc
@@ -29,7 +29,7 @@ // SharedImageBackingFactory implementation. std::unique_ptr<SharedImageBacking> CreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, SurfaceHandle surface_handle, const gfx::Size& size, const gfx::ColorSpace& color_space, @@ -46,7 +46,7 @@ } std::unique_ptr<SharedImageBacking> CreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, @@ -70,7 +70,7 @@ return nullptr; } bool IsSupported(uint32_t usage, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, bool thread_safe, gfx::GpuMemoryBufferType gmb_type,
diff --git a/gpu/command_buffer/service/shared_image/d3d_image_backing.cc b/gpu/command_buffer/service/shared_image/d3d_image_backing.cc index ecbeb12..172f3294 100644 --- a/gpu/command_buffer/service/shared_image/d3d_image_backing.cc +++ b/gpu/command_buffer/service/shared_image/d3d_image_backing.cc
@@ -63,25 +63,31 @@ } } -viz::ResourceFormat PlaneFormat(DXGI_FORMAT dxgi_format, size_t plane) { +viz::SharedImageFormat PlaneFormat(DXGI_FORMAT dxgi_format, size_t plane) { DCHECK_LT(plane, NumPlanes(dxgi_format)); + viz::ResourceFormat format; switch (dxgi_format) { // TODO(crbug.com/1011555): P010 formats are not fully supported by Skia. // Treat them the same as NV12 for the time being. case DXGI_FORMAT_NV12: case DXGI_FORMAT_P010: // Y plane is accessed as R8 and UV plane is accessed as RG88 in D3D. - return plane == 0 ? viz::RED_8 : viz::RG_88; + format = plane == 0 ? viz::RED_8 : viz::RG_88; + break; case DXGI_FORMAT_B8G8R8A8_UNORM: - return viz::BGRA_8888; + format = viz::BGRA_8888; + break; case DXGI_FORMAT_R10G10B10A2_UNORM: - return viz::RGBA_1010102; + format = viz::RGBA_1010102; + break; case DXGI_FORMAT_R16G16B16A16_FLOAT: - return viz::RGBA_F16; + format = viz::RGBA_F16; + break; default: NOTREACHED(); - return viz::BGRA_8888; + format = viz::BGRA_8888; } + return viz::SharedImageFormat::SinglePlane(format); } gfx::Size PlaneSize(DXGI_FORMAT dxgi_format, @@ -104,7 +110,7 @@ } scoped_refptr<gles2::TexturePassthrough> CreateGLTexture( - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, Microsoft::WRL::ComPtr<ID3D11Texture2D> d3d11_texture, @@ -163,7 +169,7 @@ size_t source_stride, uint8_t* dest_memory, size_t dest_stride, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size) { int row_bytes = size.width() * viz::BitsPerPixel(format) / 8; libyuv::CopyPlane(source_memory, source_stride, dest_memory, dest_stride, @@ -184,15 +190,16 @@ Microsoft::WRL::ComPtr<ID3D11Texture2D> d3d11_texture, Microsoft::WRL::ComPtr<IDXGISwapChain1> swap_chain, bool is_back_buffer) { - auto gl_texture = - CreateGLTexture(format, size, color_space, d3d11_texture, GL_TEXTURE_2D, - /*array_slice=*/0u, /*plane_index=*/0u, swap_chain); + auto si_format = viz::SharedImageFormat::SinglePlane(format); + auto gl_texture = CreateGLTexture( + si_format, size, color_space, d3d11_texture, GL_TEXTURE_2D, + /*array_slice=*/0u, /*plane_index=*/0u, swap_chain); if (!gl_texture) { LOG(ERROR) << "Failed to create GL texture"; return nullptr; } return base::WrapUnique(new D3DImageBacking( - mailbox, format, size, color_space, surface_origin, alpha_type, usage, + mailbox, si_format, size, color_space, surface_origin, alpha_type, usage, std::move(d3d11_texture), std::move(gl_texture), /*dxgi_shared_handle_state=*/nullptr, GL_TEXTURE_2D, /*array_slice=*/0u, /*plane_index=*/0u, std::move(swap_chain), is_back_buffer)); @@ -201,7 +208,7 @@ // static std::unique_ptr<D3DImageBacking> D3DImageBacking::Create( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, @@ -249,9 +256,10 @@ uint32_t usage, Microsoft::WRL::ComPtr<ID3D11Texture2D> d3d11_texture, scoped_refptr<gles2::TexturePassthrough> gl_texture) { - return base::WrapUnique(new D3DImageBacking( - mailbox, format, size, color_space, surface_origin, alpha_type, usage, - std::move(d3d11_texture), std::move(gl_texture))); + return base::WrapUnique( + new D3DImageBacking(mailbox, viz::SharedImageFormat::SinglePlane(format), + size, color_space, surface_origin, alpha_type, usage, + std::move(d3d11_texture), std::move(gl_texture))); } // static @@ -322,7 +330,7 @@ D3DImageBacking::D3DImageBacking( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, @@ -552,16 +560,17 @@ device); } #endif - const viz::ResourceFormat viz_resource_format = format(); - const WGPUTextureFormat wgpu_format = viz::ToWGPUFormat(viz_resource_format); + const viz::SharedImageFormat viz_si_format = format(); + const WGPUTextureFormat wgpu_format = viz::ToWGPUFormat(viz_si_format); if (wgpu_format == WGPUTextureFormat_Undefined) { - LOG(ERROR) << "Unsupported viz format found: " << viz_resource_format; + LOG(ERROR) << "Unsupported viz format found: " + << viz::ResourceFormatToString(viz_si_format); return nullptr; } const WGPUTextureUsageFlags usage = GetAllowedDawnUsages(wgpu_format); if (usage == WGPUTextureUsage_None) { LOG(ERROR) << "WGPUTextureUsage is unknown for viz format: " - << viz_resource_format; + << viz::ResourceFormatToString(viz_si_format); return nullptr; }
diff --git a/gpu/command_buffer/service/shared_image/d3d_image_backing.h b/gpu/command_buffer/service/shared_image/d3d_image_backing.h index c0e1d6b..1881d30 100644 --- a/gpu/command_buffer/service/shared_image/d3d_image_backing.h +++ b/gpu/command_buffer/service/shared_image/d3d_image_backing.h
@@ -48,7 +48,7 @@ // plane (Y/0 or UV/1) in NV12/P010 video textures. static std::unique_ptr<D3DImageBacking> Create( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, @@ -148,7 +148,7 @@ private: D3DImageBacking( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin,
diff --git a/gpu/command_buffer/service/shared_image/d3d_image_backing_factory.cc b/gpu/command_buffer/service/shared_image/d3d_image_backing_factory.cc index 9bb97763..6765702 100644 --- a/gpu/command_buffer/service/shared_image/d3d_image_backing_factory.cc +++ b/gpu/command_buffer/service/shared_image/d3d_image_backing_factory.cc
@@ -54,7 +54,8 @@ // Only RGBA formats supported by CreateSharedImage. absl::optional<DXGI_FORMAT> GetSupportedRGBAFormat( - viz::ResourceFormat viz_resource_format) { + viz::SharedImageFormat viz_si_format) { + auto viz_resource_format = viz_si_format.resource_format(); switch (viz_resource_format) { case viz::RGBA_F16: return DXGI_FORMAT_R16G16B16A16_FLOAT; @@ -308,7 +309,7 @@ std::unique_ptr<SharedImageBacking> D3DImageBackingFactory::CreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, SurfaceHandle surface_handle, const gfx::Size& size, const gfx::ColorSpace& color_space, @@ -331,6 +332,7 @@ // SHARED_IMAGE_USAGE_CPU_UPLOAD is set for shared memory GMBs. const bool is_shm_gmb = usage & SHARED_IMAGE_USAGE_CPU_UPLOAD; + const auto resource_format = format.resource_format(); D3D11_TEXTURE2D_DESC desc; desc.Width = size.width(); @@ -344,7 +346,7 @@ desc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET; // WebGPU can use RGBA_8888 and RGBA_16 for STORAGE_BINDING. if ((usage & gpu::SHARED_IMAGE_USAGE_WEBGPU) && - (format == viz::RGBA_8888 || format == viz::RGBA_F16)) { + (resource_format == viz::RGBA_8888 || resource_format == viz::RGBA_F16)) { desc.BindFlags |= D3D11_BIND_UNORDERED_ACCESS; } if (is_shm_gmb) { @@ -405,7 +407,7 @@ std::unique_ptr<SharedImageBacking> D3DImageBackingFactory::CreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, @@ -451,6 +453,7 @@ const gfx::Size plane_size = GetPlaneSize(plane, size); const viz::ResourceFormat plane_format = viz::GetResourceFormat(GetPlaneBufferFormat(plane, format)); + auto si_format = viz::SharedImageFormat::SinglePlane(plane_format); // TODO(sunnyps): Use GL_TEXTURE_2D for all cases since it's allowed by ANGLE. const GLenum texture_target = plane == gfx::BufferPlane::DEFAULT ? GL_TEXTURE_2D @@ -458,9 +461,9 @@ const size_t plane_index = plane == gfx::BufferPlane::UV ? 1 : 0; auto backing = D3DImageBacking::Create( - mailbox, plane_format, plane_size, color_space, surface_origin, - alpha_type, usage, std::move(d3d11_texture), - std::move(dxgi_shared_handle_state), texture_target, /*array_slice=*/0u, + mailbox, si_format, plane_size, color_space, surface_origin, alpha_type, + usage, std::move(d3d11_texture), std::move(dxgi_shared_handle_state), + texture_target, /*array_slice=*/0u, /*plane_index=*/plane_index); if (backing) backing->SetCleared(); @@ -487,7 +490,7 @@ } bool D3DImageBackingFactory::IsSupported(uint32_t usage, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, bool thread_safe, gfx::GpuMemoryBufferType gmb_type, @@ -505,7 +508,7 @@ if (usage & SHARED_IMAGE_USAGE_CPU_UPLOAD) { // Only allow single NV12 shared memory GMBs for now. This excludes // dual shared memory GMBs used by software video decoder. - if (format != viz::YUV_420_BIPLANAR) + if (format.resource_format() != viz::YUV_420_BIPLANAR) return false; } else { if (!GetSupportedRGBAFormat(format))
diff --git a/gpu/command_buffer/service/shared_image/d3d_image_backing_factory.h b/gpu/command_buffer/service/shared_image/d3d_image_backing_factory.h index 0cda07b..5b1c394 100644 --- a/gpu/command_buffer/service/shared_image/d3d_image_backing_factory.h +++ b/gpu/command_buffer/service/shared_image/d3d_image_backing_factory.h
@@ -74,7 +74,7 @@ std::unique_ptr<SharedImageBacking> CreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, SurfaceHandle surface_handle, const gfx::Size& size, const gfx::ColorSpace& color_space, @@ -84,7 +84,7 @@ bool is_thread_safe) override; std::unique_ptr<SharedImageBacking> CreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, @@ -105,7 +105,7 @@ uint32_t usage) override; bool IsSupported(uint32_t usage, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, bool thread_safe, gfx::GpuMemoryBufferType gmb_type,
diff --git a/gpu/command_buffer/service/shared_image/d3d_image_backing_factory_unittest.cc b/gpu/command_buffer/service/shared_image/d3d_image_backing_factory_unittest.cc index 6ffcf4e..ccb1660 100644 --- a/gpu/command_buffer/service/shared_image/d3d_image_backing_factory_unittest.cc +++ b/gpu/command_buffer/service/shared_image/d3d_image_backing_factory_unittest.cc
@@ -537,7 +537,8 @@ // Create a backing using mailbox. auto mailbox = Mailbox::GenerateForSharedImage(); - const auto format = viz::ResourceFormat::RGBA_8888; + const auto format = + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RGBA_8888); const gfx::Size size(1, 1); const auto color_space = gfx::ColorSpace::CreateSRGB(); const uint32_t usage = @@ -623,7 +624,8 @@ // Create a backing using mailbox. const auto mailbox = Mailbox::GenerateForSharedImage(); - const auto format = viz::ResourceFormat::RGBA_8888; + const auto format = + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RGBA_8888); const gfx::Size size(1, 1); const auto color_space = gfx::ColorSpace::CreateSRGB(); const gpu::SurfaceHandle surface_handle = gpu::kNullSurfaceHandle; @@ -694,7 +696,8 @@ // Create a backing using mailbox. auto mailbox = Mailbox::GenerateForSharedImage(); - const auto format = viz::ResourceFormat::RGBA_8888; + const auto format = + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RGBA_8888); const gfx::Size size(1, 1); const auto color_space = gfx::ColorSpace::CreateSRGB(); const uint32_t usage = SHARED_IMAGE_USAGE_GLES2 | @@ -821,7 +824,8 @@ // Create a backing using mailbox. auto mailbox = Mailbox::GenerateForSharedImage(); - const auto format = viz::ResourceFormat::RGBA_8888; + const auto format = + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RGBA_8888); const gfx::Size size(1, 1); const auto color_space = gfx::ColorSpace::CreateSRGB(); const uint32_t usage = SHARED_IMAGE_USAGE_GLES2 | @@ -919,7 +923,8 @@ // Create a mailbox. auto mailbox = Mailbox::GenerateForSharedImage(); - const auto format = viz::ResourceFormat::RGBA_8888; + const auto format = + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RGBA_8888); const gfx::Size size(1, 1); const auto color_space = gfx::ColorSpace::CreateSRGB(); const uint32_t usage = @@ -954,7 +959,9 @@ return; auto mailbox = Mailbox::GenerateForSharedImage(); - const auto format = gfx::BufferFormat::RGBA_8888; + const auto buffer_format = gfx::BufferFormat::RGBA_8888; + const auto format = viz::SharedImageFormat::SinglePlane( + viz::GetResourceFormat(buffer_format)); const gfx::Size size(1, 1); const auto plane = gfx::BufferPlane::DEFAULT; const auto color_space = gfx::ColorSpace::CreateSRGB(); @@ -965,8 +972,8 @@ const SkAlphaType alpha_type = kPremul_SkAlphaType; EXPECT_TRUE(shared_image_factory_->IsSupported( - usage, viz::GetResourceFormat(format), size, /*thread_safe=*/false, - gfx::DXGI_SHARED_HANDLE, GrContextType::kGL, /*pixel_data=*/{})); + usage, format, size, /*thread_safe=*/false, gfx::DXGI_SHARED_HANDLE, + GrContextType::kGL, /*pixel_data=*/{})); Microsoft::WRL::ComPtr<ID3D11Device> d3d11_device = shared_image_factory_->GetDeviceForTesting(); @@ -1007,11 +1014,11 @@ auto dup_handle = gpu_memory_buffer_handle.Clone(); auto backing = shared_image_factory_->CreateSharedImage( - mailbox, 0, std::move(gpu_memory_buffer_handle), format, plane, + mailbox, 0, std::move(gpu_memory_buffer_handle), buffer_format, plane, surface_handle, size, color_space, surface_origin, alpha_type, usage); ASSERT_NE(backing, nullptr); - EXPECT_EQ(backing->format(), viz::RGBA_8888); + EXPECT_EQ(backing->format(), format); EXPECT_EQ(backing->size(), size); EXPECT_EQ(backing->color_space(), color_space); EXPECT_EQ(backing->surface_origin(), surface_origin); @@ -1028,11 +1035,11 @@ // shared handle state and texture with the first backing. auto dup_mailbox = Mailbox::GenerateForSharedImage(); auto dup_backing = shared_image_factory_->CreateSharedImage( - dup_mailbox, 0, std::move(dup_handle), format, plane, surface_handle, - size, color_space, surface_origin, alpha_type, usage); + dup_mailbox, 0, std::move(dup_handle), buffer_format, plane, + surface_handle, size, color_space, surface_origin, alpha_type, usage); ASSERT_NE(dup_backing, nullptr); - EXPECT_EQ(dup_backing->format(), viz::RGBA_8888); + EXPECT_EQ(dup_backing->format(), format); EXPECT_EQ(dup_backing->size(), size); EXPECT_EQ(dup_backing->color_space(), color_space); EXPECT_EQ(dup_backing->surface_origin(), surface_origin); @@ -1095,7 +1102,8 @@ // Create a backing using mailbox. auto mailbox = Mailbox::GenerateForSharedImage(); - const auto format = viz::ResourceFormat::RGBA_8888; + const auto format = + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RGBA_8888); const gfx::Size size(1, 1); const auto color_space = gfx::ColorSpace::CreateSRGB(); const uint32_t usage = SHARED_IMAGE_USAGE_GLES2 | @@ -1226,7 +1234,8 @@ // Create a backing using mailbox. auto mailbox = Mailbox::GenerateForSharedImage(); - const auto format = viz::ResourceFormat::RGBA_8888; + const auto format = + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RGBA_8888); const gfx::Size size(1, 1); const auto color_space = gfx::ColorSpace::CreateSRGB(); const uint32_t usage = SHARED_IMAGE_USAGE_GLES2 | @@ -1419,7 +1428,8 @@ EXPECT_EQ(backing->mailbox(), mailboxes[i]); EXPECT_EQ(backing->size(), plane_sizes[i]); - EXPECT_EQ(backing->format(), plane_formats[i]); + EXPECT_EQ(backing->format(), + viz::SharedImageFormat::SinglePlane(plane_formats[i])); EXPECT_EQ(backing->color_space(), gfx::ColorSpace()); EXPECT_EQ(backing->surface_origin(), kTopLeft_GrSurfaceOrigin); EXPECT_EQ(backing->alpha_type(), kPremul_SkAlphaType); @@ -1732,7 +1742,8 @@ EXPECT_EQ(backing->mailbox(), mailboxes[i]); EXPECT_EQ(backing->size(), plane_sizes[i]); - EXPECT_EQ(backing->format(), plane_formats[i]); + EXPECT_EQ(backing->format(), + viz::SharedImageFormat::SinglePlane(plane_formats[i])); EXPECT_EQ(backing->color_space(), gfx::ColorSpace()); EXPECT_EQ(backing->surface_origin(), kTopLeft_GrSurfaceOrigin); EXPECT_EQ(backing->alpha_type(), kPremul_SkAlphaType);
diff --git a/gpu/command_buffer/service/shared_image/egl_image_backing.cc b/gpu/command_buffer/service/shared_image/egl_image_backing.cc index 2ecc731..868a27d 100644 --- a/gpu/command_buffer/service/shared_image/egl_image_backing.cc +++ b/gpu/command_buffer/service/shared_image/egl_image_backing.cc
@@ -177,14 +177,14 @@ EGLImageBacking::EGLImageBacking( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, SkAlphaType alpha_type, uint32_t usage, size_t estimated_size, - const GLCommonImageBackingFactory::FormatInfo format_info, + const GLCommonImageBackingFactory::FormatInfo& format_info, const GpuDriverBugWorkarounds& workarounds, bool use_passthrough, base::span<const uint8_t> pixel_data)
diff --git a/gpu/command_buffer/service/shared_image/egl_image_backing.h b/gpu/command_buffer/service/shared_image/egl_image_backing.h index 84c6d7e6..336e81d3 100644 --- a/gpu/command_buffer/service/shared_image/egl_image_backing.h +++ b/gpu/command_buffer/service/shared_image/egl_image_backing.h
@@ -37,14 +37,14 @@ class EGLImageBacking : public ClearTrackingSharedImageBacking { public: EGLImageBacking(const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, SkAlphaType alpha_type, uint32_t usage, size_t estimated_size, - const GLCommonImageBackingFactory::FormatInfo format_into, + const GLCommonImageBackingFactory::FormatInfo& format_into, const GpuDriverBugWorkarounds& workarounds, bool use_passthrough, base::span<const uint8_t> pixel_data);
diff --git a/gpu/command_buffer/service/shared_image/egl_image_backing_factory.cc b/gpu/command_buffer/service/shared_image/egl_image_backing_factory.cc index 64bf26d..4539d923 100644 --- a/gpu/command_buffer/service/shared_image/egl_image_backing_factory.cc +++ b/gpu/command_buffer/service/shared_image/egl_image_backing_factory.cc
@@ -38,7 +38,7 @@ std::unique_ptr<SharedImageBacking> EGLImageBackingFactory::CreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, SurfaceHandle surface_handle, const gfx::Size& size, const gfx::ColorSpace& color_space, @@ -52,7 +52,7 @@ std::unique_ptr<SharedImageBacking> EGLImageBackingFactory::CreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, @@ -80,7 +80,7 @@ } bool EGLImageBackingFactory::IsSupported(uint32_t usage, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, bool thread_safe, gfx::GpuMemoryBufferType gmb_type, @@ -109,13 +109,13 @@ return false; } - return CanCreateSharedImage(size, pixel_data, format_info_[format], + return CanCreateSharedImage(size, pixel_data, GetFormatInfo(format), GL_TEXTURE_2D); } std::unique_ptr<SharedImageBacking> EGLImageBackingFactory::MakeEglImageBacking( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, @@ -133,7 +133,7 @@ return std::make_unique<EGLImageBacking>( mailbox, format, size, color_space, surface_origin, alpha_type, usage, - estimated_size, format_info_[format], workarounds_, use_passthrough_, + estimated_size, GetFormatInfo(format), workarounds_, use_passthrough_, pixel_data); }
diff --git a/gpu/command_buffer/service/shared_image/egl_image_backing_factory.h b/gpu/command_buffer/service/shared_image/egl_image_backing_factory.h index 5e15bfd6..88b83f8 100644 --- a/gpu/command_buffer/service/shared_image/egl_image_backing_factory.h +++ b/gpu/command_buffer/service/shared_image/egl_image_backing_factory.h
@@ -40,7 +40,7 @@ // SharedImageBackingFactory implementation. std::unique_ptr<SharedImageBacking> CreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, SurfaceHandle surface_handle, const gfx::Size& size, const gfx::ColorSpace& color_space, @@ -50,7 +50,7 @@ bool is_thread_safe) override; std::unique_ptr<SharedImageBacking> CreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, @@ -70,7 +70,7 @@ SkAlphaType alpha_type, uint32_t usage) override; bool IsSupported(uint32_t usage, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, bool thread_safe, gfx::GpuMemoryBufferType gmb_type, @@ -80,7 +80,7 @@ private: std::unique_ptr<SharedImageBacking> MakeEglImageBacking( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin,
diff --git a/gpu/command_buffer/service/shared_image/egl_image_backing_factory_unittest.cc b/gpu/command_buffer/service/shared_image/egl_image_backing_factory_unittest.cc index b0c05fdd..81eb988 100644 --- a/gpu/command_buffer/service/shared_image/egl_image_backing_factory_unittest.cc +++ b/gpu/command_buffer/service/shared_image/egl_image_backing_factory_unittest.cc
@@ -74,7 +74,7 @@ } class EGLImageBackingFactoryThreadSafeTest - : public testing::TestWithParam<std::tuple<bool, viz::ResourceFormat>> { + : public testing::TestWithParam<std::tuple<bool, viz::SharedImageFormat>> { public: EGLImageBackingFactoryThreadSafeTest() : shared_image_manager_(std::make_unique<SharedImageManager>(true)) {} @@ -116,7 +116,7 @@ gles2::PassthroughCommandDecoderSupported(); } - viz::ResourceFormat get_format() { return std::get<1>(GetParam()); } + viz::SharedImageFormat get_format() { return std::get<1>(GetParam()); } protected: scoped_refptr<gl::GLSurface> surface_; @@ -139,7 +139,7 @@ public: CreateAndValidateSharedImageRepresentations( EGLImageBackingFactory* backing_factory, - viz::ResourceFormat format, + viz::SharedImageFormat format, bool is_thread_safe, gles2::MailboxManagerImpl* mailbox_manager, SharedImageManager* shared_image_manager, @@ -259,7 +259,7 @@ CreateAndValidateSharedImageRepresentations:: CreateAndValidateSharedImageRepresentations( EGLImageBackingFactory* backing_factory, - viz::ResourceFormat format, + viz::SharedImageFormat format, bool is_thread_safe, gles2::MailboxManagerImpl* mailbox_manager, SharedImageManager* shared_image_manager, @@ -302,8 +302,9 @@ context_state->feature_info()->feature_flags().chromium_image_ar30; const bool supports_ab30 = context_state->feature_info()->feature_flags().chromium_image_ab30; - if ((format == viz::ResourceFormat::BGRA_1010102 || - format == viz::ResourceFormat::RGBA_1010102) && + const auto resource_format = format.resource_format(); + if ((resource_format == viz::ResourceFormat::BGRA_1010102 || + resource_format == viz::ResourceFormat::RGBA_1010102) && !supports_ar30 && !supports_ab30) { EXPECT_FALSE(backing_); return; @@ -351,8 +352,8 @@ // support. It's possible Skia might support these formats even if the Chrome // feature flags are false. We just check here that the feature flags don't // allow Chrome to do something that Skia doesn't support. - if ((format != viz::ResourceFormat::BGRA_1010102 || supports_ar30) && - (format != viz::ResourceFormat::RGBA_1010102 || supports_ab30)) { + if ((resource_format != viz::ResourceFormat::BGRA_1010102 || supports_ar30) && + (resource_format != viz::ResourceFormat::RGBA_1010102 || supports_ab30)) { EXPECT_TRUE(scoped_write_access); if (!scoped_write_access) return; @@ -389,13 +390,14 @@ } // High bit depth rendering is not supported on Android. -const auto kResourceFormats = ::testing::Values(viz::ResourceFormat::RGBA_8888); +const auto kSharedImageFormats = ::testing::Values( + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RGBA_8888)); std::string TestParamToString( - const testing::TestParamInfo<std::tuple<bool, viz::ResourceFormat>>& + const testing::TestParamInfo<std::tuple<bool, viz::SharedImageFormat>>& param_info) { const bool allow_passthrough = std::get<0>(param_info.param); - const viz::ResourceFormat format = std::get<1>(param_info.param); + const viz::SharedImageFormat format = std::get<1>(param_info.param); return base::StringPrintf( "%s_%s", (allow_passthrough ? "AllowPassthrough" : "DisallowPassthrough"), gfx::BufferFormatToString(viz::BufferFormat(format))); @@ -404,7 +406,7 @@ INSTANTIATE_TEST_SUITE_P(Service, EGLImageBackingFactoryThreadSafeTest, ::testing::Combine(::testing::Bool(), - kResourceFormats), + kSharedImageFormats), TestParamToString); } // anonymous namespace
diff --git a/gpu/command_buffer/service/shared_image/external_vk_image_backing.cc b/gpu/command_buffer/service/shared_image/external_vk_image_backing.cc index 2600ed5..3db486b 100644 --- a/gpu/command_buffer/service/shared_image/external_vk_image_backing.cc +++ b/gpu/command_buffer/service/shared_image/external_vk_image_backing.cc
@@ -8,6 +8,7 @@ #include <vector> #include "build/build_config.h" +#include "components/viz/common/resources/resource_format_utils.h" #include "components/viz/common/resources/resource_sizes.h" #include "gpu/command_buffer/service/gl_utils.h" #include "gpu/command_buffer/service/shared_image/external_vk_image_gl_representation.h" @@ -53,7 +54,7 @@ namespace { -static const struct { +static const struct GLFormatInfo { GLenum gl_format; GLenum gl_type; GLuint bytes_per_pixel; @@ -83,6 +84,10 @@ static_assert(std::size(kFormatTable) == (viz::RESOURCE_FORMAT_MAX + 1), "kFormatTable does not handle all cases."); +GLFormatInfo GetGLFormatInfo(viz::SharedImageFormat format) { + return kFormatTable[format.resource_format()]; +} + class ScopedDedicatedMemoryObject { public: explicit ScopedDedicatedMemoryObject(gl::GLApi* api) : api_(api) { @@ -101,11 +106,11 @@ }; bool UseSeparateGLTexture(SharedContextState* context_state, - viz::ResourceFormat format) { + viz::SharedImageFormat format) { if (!context_state->support_vulkan_external_object()) return true; - if (format != viz::ResourceFormat::BGRA_8888) + if (format.resource_format() != viz::ResourceFormat::BGRA_8888) return false; auto* gl_context = context_state->real_context(); @@ -160,7 +165,7 @@ scoped_refptr<SharedContextState> context_state, VulkanCommandPool* command_pool, const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, @@ -183,7 +188,7 @@ if (usage & kUsageNeedsColorAttachment) { vk_usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT; - if (format == viz::ETC1) { + if (viz::IsResourceFormatCompressed(format)) { DLOG(ERROR) << "ETC1 format cannot be used as color attachment."; return nullptr; } @@ -258,6 +263,7 @@ auto* vulkan_implementation = context_state->vk_context_provider()->GetVulkanImplementation(); auto resource_format = viz::GetResourceFormat(buffer_format); + auto si_format = viz::SharedImageFormat::SinglePlane(resource_format); auto* device_queue = context_state->vk_context_provider()->GetDeviceQueue(); DCHECK(vulkan_implementation->CanImportGpuMemoryBuffer(device_queue, handle.type)); @@ -271,9 +277,9 @@ } bool use_separate_gl_texture = - UseSeparateGLTexture(context_state.get(), resource_format); + UseSeparateGLTexture(context_state.get(), si_format); auto backing = std::make_unique<ExternalVkImageBacking>( - base::PassKey<ExternalVkImageBacking>(), mailbox, resource_format, size, + base::PassKey<ExternalVkImageBacking>(), mailbox, si_format, size, color_space, surface_origin, alpha_type, usage, std::move(context_state), std::move(image), command_pool, use_separate_gl_texture); backing->SetCleared(); @@ -283,7 +289,7 @@ ExternalVkImageBacking::ExternalVkImageBacking( base::PassKey<ExternalVkImageBacking>, const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, @@ -646,10 +652,12 @@ api->glTexStorage2DEXTFn(GL_TEXTURE_2D, 1, internal_format, size().width(), size().height()); } else { - auto gl_format = kFormatTable[format()].gl_format; - auto gl_type = kFormatTable[format()].gl_type; + auto gl_format_info = GetGLFormatInfo(format()); + auto gl_format = gl_format_info.gl_format; + auto gl_type = gl_format_info.gl_type; if (gl_format == GL_ZERO || gl_type == GL_ZERO) - LOG(FATAL) << "Not support format: " << format(); + LOG(FATAL) << "Not support format: " + << viz::ResourceFormatToString(format()); api->glTexImage2DFn(GL_TEXTURE_2D, 0, gl_format, size().width(), size().height(), 0, gl_format, gl_type, nullptr); } @@ -1024,14 +1032,14 @@ const GLuint texture_service_id = texture_ ? texture_->service_id() : texture_passthrough_->service_id(); - DCHECK_GE(format(), 0); - DCHECK_LE(format(), viz::RESOURCE_FORMAT_MAX); - auto gl_format = kFormatTable[format()].gl_format; - auto gl_type = kFormatTable[format()].gl_type; - auto bytes_per_pixel = kFormatTable[format()].bytes_per_pixel; + auto gl_format_info = GetGLFormatInfo(format()); + auto gl_format = gl_format_info.gl_format; + auto gl_type = gl_format_info.gl_type; + auto bytes_per_pixel = gl_format_info.bytes_per_pixel; if (gl_format == GL_ZERO) { - NOTREACHED() << "Not supported resource format=" << format(); + NOTREACHED() << "Not supported resource format=" + << viz::ResourceFormatToString(format()); return; } @@ -1084,14 +1092,14 @@ const GLuint texture_service_id = texture_ ? texture_->service_id() : texture_passthrough_->service_id(); - DCHECK_GE(format(), 0); - DCHECK_LE(format(), viz::RESOURCE_FORMAT_MAX); - auto gl_format = kFormatTable[format()].gl_format; - auto gl_type = kFormatTable[format()].gl_type; - auto bytes_per_pixel = kFormatTable[format()].bytes_per_pixel; + auto gl_format_info = GetGLFormatInfo(format()); + auto gl_format = gl_format_info.gl_format; + auto gl_type = gl_format_info.gl_type; + auto bytes_per_pixel = gl_format_info.bytes_per_pixel; if (gl_format == GL_ZERO) { - NOTREACHED() << "Not supported resource format=" << format(); + NOTREACHED() << "Not supported resource format=" + << viz::ResourceFormatToString(format()); return; } @@ -1137,14 +1145,14 @@ const GLuint texture_service_id = texture_ ? texture_->service_id() : texture_passthrough_->service_id(); - DCHECK_GE(format(), 0); - DCHECK_LE(format(), viz::RESOURCE_FORMAT_MAX); - auto gl_format = kFormatTable[format()].gl_format; - auto gl_type = kFormatTable[format()].gl_type; - auto bytes_per_pixel = kFormatTable[format()].bytes_per_pixel; + auto gl_format_info = GetGLFormatInfo(format()); + auto gl_format = gl_format_info.gl_format; + auto gl_type = gl_format_info.gl_type; + auto bytes_per_pixel = gl_format_info.bytes_per_pixel; if (gl_format == GL_ZERO) { - NOTREACHED() << "Not supported resource format=" << format(); + NOTREACHED() << "Not supported resource format=" + << viz::ResourceFormatToString(format()); return; }
diff --git a/gpu/command_buffer/service/shared_image/external_vk_image_backing.h b/gpu/command_buffer/service/shared_image/external_vk_image_backing.h index cea11a8..7ab3065 100644 --- a/gpu/command_buffer/service/shared_image/external_vk_image_backing.h +++ b/gpu/command_buffer/service/shared_image/external_vk_image_backing.h
@@ -34,7 +34,7 @@ scoped_refptr<SharedContextState> context_state, VulkanCommandPool* command_pool, const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, @@ -58,7 +58,7 @@ ExternalVkImageBacking(base::PassKey<ExternalVkImageBacking>, const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin,
diff --git a/gpu/command_buffer/service/shared_image/external_vk_image_backing_factory.cc b/gpu/command_buffer/service/shared_image/external_vk_image_backing_factory.cc index c91de03..828085a 100644 --- a/gpu/command_buffer/service/shared_image/external_vk_image_backing_factory.cc +++ b/gpu/command_buffer/service/shared_image/external_vk_image_backing_factory.cc
@@ -97,7 +97,7 @@ std::unique_ptr<SharedImageBacking> ExternalVkImageBackingFactory::CreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, SurfaceHandle surface_handle, const gfx::Size& size, const gfx::ColorSpace& color_space, @@ -115,7 +115,7 @@ std::unique_ptr<SharedImageBacking> ExternalVkImageBackingFactory::CreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, @@ -160,7 +160,7 @@ bool ExternalVkImageBackingFactory::IsSupported( uint32_t usage, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, bool thread_safe, gfx::GpuMemoryBufferType gmb_type,
diff --git a/gpu/command_buffer/service/shared_image/external_vk_image_backing_factory.h b/gpu/command_buffer/service/shared_image/external_vk_image_backing_factory.h index f4b05bf..977a31d4 100644 --- a/gpu/command_buffer/service/shared_image/external_vk_image_backing_factory.h +++ b/gpu/command_buffer/service/shared_image/external_vk_image_backing_factory.h
@@ -36,7 +36,7 @@ // SharedImageBackingFactory implementation. std::unique_ptr<SharedImageBacking> CreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, SurfaceHandle surface_handle, const gfx::Size& size, const gfx::ColorSpace& color_space, @@ -46,7 +46,7 @@ bool is_thread_safe) override; std::unique_ptr<SharedImageBacking> CreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, @@ -66,7 +66,7 @@ SkAlphaType alpha_type, uint32_t usage) override; bool IsSupported(uint32_t usage, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, bool thread_safe, gfx::GpuMemoryBufferType gmb_type,
diff --git a/gpu/command_buffer/service/shared_image/external_vk_image_backing_factory_unittest.cc b/gpu/command_buffer/service/shared_image/external_vk_image_backing_factory_unittest.cc index 399d791..df4f183 100644 --- a/gpu/command_buffer/service/shared_image/external_vk_image_backing_factory_unittest.cc +++ b/gpu/command_buffer/service/shared_image/external_vk_image_backing_factory_unittest.cc
@@ -155,7 +155,8 @@ } // Create a backing using mailbox. auto mailbox = Mailbox::GenerateForSharedImage(); - const auto format = viz::ResourceFormat::RGBA_8888; + const auto format = + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RGBA_8888); const gfx::Size size(4, 4); const auto color_space = gfx::ColorSpace::CreateSRGB(); const uint32_t usage = @@ -279,7 +280,8 @@ } // Create a backing using mailbox. auto mailbox = Mailbox::GenerateForSharedImage(); - const auto format = viz::ResourceFormat::RGBA_8888; + const auto format = + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RGBA_8888); const gfx::Size size(4, 4); const auto color_space = gfx::ColorSpace::CreateSRGB(); const uint32_t usage =
diff --git a/gpu/command_buffer/service/shared_image/gl_common_image_backing_factory.h b/gpu/command_buffer/service/shared_image/gl_common_image_backing_factory.h index 89583f51..3a29c089 100644 --- a/gpu/command_buffer/service/shared_image/gl_common_image_backing_factory.h +++ b/gpu/command_buffer/service/shared_image/gl_common_image_backing_factory.h
@@ -67,6 +67,11 @@ gl::ProgressReporter* progress_reporter); ~GLCommonImageBackingFactory() override; + // WARNING: Format must be single plane. + const FormatInfo& GetFormatInfo(viz::SharedImageFormat format) { + return format_info_[format.resource_format()]; + } + bool CanCreateSharedImage(const gfx::Size& size, base::span<const uint8_t> pixel_data, const FormatInfo& format_info,
diff --git a/gpu/command_buffer/service/shared_image/gl_image_backing.cc b/gpu/command_buffer/service/shared_image/gl_image_backing.cc index 90687d0..57f3f9c 100644 --- a/gpu/command_buffer/service/shared_image/gl_image_backing.cc +++ b/gpu/command_buffer/service/shared_image/gl_image_backing.cc
@@ -308,8 +308,9 @@ InitializeGLTextureParams params; params.target = texture_target; + auto si_format = viz::SharedImageFormat::SinglePlane(format); auto shared_image = std::make_unique<GLImageBacking>( - std::move(image), mailbox, format, size, color_space, surface_origin, + std::move(image), mailbox, si_format, size, color_space, surface_origin, alpha_type, usage, params, true); shared_image->passthrough_texture_ = std::move(wrapped_gl_texture); @@ -322,7 +323,7 @@ GLImageBacking::GLImageBacking(scoped_refptr<gl::GLImage> image, const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, @@ -563,7 +564,7 @@ } else { GrBackendTexture backend_texture; GetGrBackendTexture(context_state->feature_info(), GetGLTarget(), size(), - GetGLServiceId(), format(), + GetGLServiceId(), format().resource_format(), context_state->gr_context()->threadSafeProxy(), &backend_texture); cached_promise_texture_ = SkPromiseImageTexture::Make(backend_texture);
diff --git a/gpu/command_buffer/service/shared_image/gl_image_backing.h b/gpu/command_buffer/service/shared_image/gl_image_backing.h index 9cd767b..9fb665a8 100644 --- a/gpu/command_buffer/service/shared_image/gl_image_backing.h +++ b/gpu/command_buffer/service/shared_image/gl_image_backing.h
@@ -183,7 +183,7 @@ GLImageBacking( scoped_refptr<gl::GLImage> image, const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin,
diff --git a/gpu/command_buffer/service/shared_image/gl_image_backing_factory.cc b/gpu/command_buffer/service/shared_image/gl_image_backing_factory.cc index fd7a1066..7dd9129 100644 --- a/gpu/command_buffer/service/shared_image/gl_image_backing_factory.cc +++ b/gpu/command_buffer/service/shared_image/gl_image_backing_factory.cc
@@ -93,7 +93,7 @@ std::unique_ptr<SharedImageBacking> GLImageBackingFactory::CreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, SurfaceHandle surface_handle, const gfx::Size& size, const gfx::ColorSpace& color_space, @@ -109,7 +109,7 @@ std::unique_ptr<SharedImageBacking> GLImageBackingFactory::CreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, @@ -201,8 +201,10 @@ params.is_cleared = true; params.framebuffer_attachment_angle = for_framebuffer_attachment && texture_usage_angle_; + + auto si_format = viz::SharedImageFormat::SinglePlane(plane_format); return std::make_unique<GLImageBacking>( - image, mailbox, plane_format, plane_size, color_space, surface_origin, + image, mailbox, si_format, plane_size, color_space, surface_origin, alpha_type, usage, params, use_passthrough_); } @@ -223,7 +225,7 @@ } bool GLImageBackingFactory::IsSupported(uint32_t usage, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, bool thread_safe, gfx::GpuMemoryBufferType gmb_type, @@ -283,7 +285,7 @@ std::unique_ptr<SharedImageBacking> GLImageBackingFactory::CreateSharedImageInternal( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, SurfaceHandle surface_handle, const gfx::Size& size, const gfx::ColorSpace& color_space, @@ -291,8 +293,8 @@ SkAlphaType alpha_type, uint32_t usage, base::span<const uint8_t> pixel_data) { - const FormatInfo& format_info = format_info_[format]; - const BufferFormatInfo& buffer_format_info = buffer_format_info_[format]; + const FormatInfo& format_info = GetFormatInfo(format); + const BufferFormatInfo& buffer_format_info = GetBufferFormatInfo(format); GLenum target = buffer_format_info.target_for_scanout; if (!buffer_format_info.allow_scanout) {
diff --git a/gpu/command_buffer/service/shared_image/gl_image_backing_factory.h b/gpu/command_buffer/service/shared_image/gl_image_backing_factory.h index 157226ef..5ded78c 100644 --- a/gpu/command_buffer/service/shared_image/gl_image_backing_factory.h +++ b/gpu/command_buffer/service/shared_image/gl_image_backing_factory.h
@@ -47,7 +47,7 @@ // SharedImageBackingFactory implementation. std::unique_ptr<SharedImageBacking> CreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, SurfaceHandle surface_handle, const gfx::Size& size, const gfx::ColorSpace& color_space, @@ -57,7 +57,7 @@ bool is_thread_safe) override; std::unique_ptr<SharedImageBacking> CreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, @@ -77,7 +77,7 @@ SkAlphaType alpha_type, uint32_t usage) override; bool IsSupported(uint32_t usage, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, bool thread_safe, gfx::GpuMemoryBufferType gmb_type, @@ -85,25 +85,6 @@ base::span<const uint8_t> pixel_data) override; private: - scoped_refptr<gl::GLImage> MakeGLImage(int client_id, - gfx::GpuMemoryBufferHandle handle, - gfx::BufferFormat format, - const gfx::ColorSpace& color_space, - gfx::BufferPlane plane, - SurfaceHandle surface_handle, - const gfx::Size& size); - - std::unique_ptr<SharedImageBacking> CreateSharedImageInternal( - const Mailbox& mailbox, - viz::ResourceFormat format, - SurfaceHandle surface_handle, - const gfx::Size& size, - const gfx::ColorSpace& color_space, - GrSurfaceOrigin surface_origin, - SkAlphaType alpha_type, - uint32_t usage, - base::span<const uint8_t> pixel_data); - struct BufferFormatInfo { // Whether to allow SHARED_IMAGE_USAGE_SCANOUT. bool allow_scanout = false; @@ -115,6 +96,30 @@ gfx::BufferFormat buffer_format = gfx::BufferFormat::RGBA_8888; }; + scoped_refptr<gl::GLImage> MakeGLImage(int client_id, + gfx::GpuMemoryBufferHandle handle, + gfx::BufferFormat format, + const gfx::ColorSpace& color_space, + gfx::BufferPlane plane, + SurfaceHandle surface_handle, + const gfx::Size& size); + + std::unique_ptr<SharedImageBacking> CreateSharedImageInternal( + const Mailbox& mailbox, + viz::SharedImageFormat format, + SurfaceHandle surface_handle, + const gfx::Size& size, + const gfx::ColorSpace& color_space, + GrSurfaceOrigin surface_origin, + SkAlphaType alpha_type, + uint32_t usage, + base::span<const uint8_t> pixel_data); + + // WARNING: Format must be single plane. + const BufferFormatInfo& GetBufferFormatInfo(viz::SharedImageFormat format) { + return buffer_format_info_[format.resource_format()]; + } + // Factory used to generate GLImages for SCANOUT backings. const raw_ptr<ImageFactory> image_factory_ = nullptr;
diff --git a/gpu/command_buffer/service/shared_image/gl_image_backing_factory_unittest.cc b/gpu/command_buffer/service/shared_image/gl_image_backing_factory_unittest.cc index 5767bd3b..ea1d4e5 100644 --- a/gpu/command_buffer/service/shared_image/gl_image_backing_factory_unittest.cc +++ b/gpu/command_buffer/service/shared_image/gl_image_backing_factory_unittest.cc
@@ -83,7 +83,7 @@ }; class GLImageBackingFactoryTestBase - : public testing::TestWithParam<std::tuple<bool, viz::ResourceFormat>> { + : public testing::TestWithParam<std::tuple<bool, viz::SharedImageFormat>> { public: explicit GLImageBackingFactoryTestBase(bool is_thread_safe) : shared_image_manager_( @@ -122,15 +122,16 @@ } bool can_create_scanout_or_gmb_shared_image( - viz::ResourceFormat format) const { - if (format == viz::ResourceFormat::BGRA_1010102) + viz::SharedImageFormat format) const { + auto resource_format = format.resource_format(); + if (resource_format == viz::ResourceFormat::BGRA_1010102) return supports_ar30_; - else if (format == viz::ResourceFormat::RGBA_1010102) + else if (resource_format == viz::ResourceFormat::RGBA_1010102) return supports_ab30_; return true; } - viz::ResourceFormat get_format() { return std::get<1>(GetParam()); } + viz::SharedImageFormat get_format() { return std::get<1>(GetParam()); } protected: ::testing::NiceMock<MockProgressReporter> progress_reporter_; @@ -269,10 +270,11 @@ // Create a R-8 image texture, and check that the internal_format is that // of the image (GL_RGBA for TextureImageFactory). This only matters for // the validating decoder. + auto red_format = + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RED_8); backing = backing_factory_->CreateSharedImage( - mailbox, viz::ResourceFormat::RED_8, gpu::kNullSurfaceHandle, size, - color_space, surface_origin, alpha_type, usage, - false /* is_thread_safe */); + mailbox, red_format, gpu::kNullSurfaceHandle, size, color_space, + surface_origin, alpha_type, usage, false /* is_thread_safe */); EXPECT_TRUE(backing); shared_image = shared_image_manager_->Register(std::move(backing), memory_type_tracker_.get()); @@ -294,9 +296,10 @@ TEST_P(GLImageBackingFactoryTest, InitialData) { // TODO(andrescj): these loop over the formats can be replaced by test // parameters. - for (auto format : + for (auto resource_format : {viz::ResourceFormat::RGBA_8888, viz::ResourceFormat::BGRA_1010102, viz::ResourceFormat::RGBA_1010102}) { + auto format = viz::SharedImageFormat::SinglePlane(resource_format); const bool should_succeed = can_create_scanout_or_gmb_shared_image(format); if (should_succeed) EXPECT_CALL(progress_reporter_, ReportProgress).Times(AtLeast(1)); @@ -431,7 +434,8 @@ TEST_P(GLImageBackingFactoryTest, InvalidFormat) { auto mailbox = Mailbox::GenerateForSharedImage(); - auto format = viz::ResourceFormat::YUV_420_BIPLANAR; + auto format = viz::SharedImageFormat::SinglePlane( + viz::ResourceFormat::YUV_420_BIPLANAR); gfx::Size size(256, 256); auto color_space = gfx::ColorSpace::CreateSRGB(); GrSurfaceOrigin surface_origin = kTopLeft_GrSurfaceOrigin; @@ -510,7 +514,8 @@ const gles2::Validators* validators = feature_info->validators(); for (int i = 0; i <= viz::RESOURCE_FORMAT_MAX; ++i) { - auto format = static_cast<viz::ResourceFormat>(i); + auto format = viz::SharedImageFormat::SinglePlane( + static_cast<viz::ResourceFormat>(i)); if (!viz::GLSupportsFormat(format) || viz::IsResourceFormatCompressed(format)) continue; @@ -702,20 +707,21 @@ } #if !BUILDFLAG(IS_ANDROID) -const auto kResourceFormats = - ::testing::Values(viz::ResourceFormat::RGBA_8888, - viz::ResourceFormat::BGRA_1010102, - viz::ResourceFormat::RGBA_1010102); +const auto kSharedImageFormats = ::testing::Values( + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RGBA_8888), + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::BGRA_1010102), + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RGBA_1010102)); #else // High bit depth rendering is not supported on Android. -const auto kResourceFormats = ::testing::Values(viz::ResourceFormat::RGBA_8888); +const auto kSharedImageFormats = ::testing::Values( + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RGBA_8888)); #endif std::string TestParamToString( - const testing::TestParamInfo<std::tuple<bool, viz::ResourceFormat>>& + const testing::TestParamInfo<std::tuple<bool, viz::SharedImageFormat>>& param_info) { const bool allow_passthrough = std::get<0>(param_info.param); - const viz::ResourceFormat format = std::get<1>(param_info.param); + const viz::SharedImageFormat format = std::get<1>(param_info.param); return base::StringPrintf( "%s_%s", (allow_passthrough ? "AllowPassthrough" : "DisallowPassthrough"), gfx::BufferFormatToString(viz::BufferFormat(format))); @@ -724,12 +730,12 @@ INSTANTIATE_TEST_SUITE_P(Service, GLImageBackingFactoryTest, ::testing::Combine(::testing::Bool(), - kResourceFormats), + kSharedImageFormats), TestParamToString); INSTANTIATE_TEST_SUITE_P(Service, GLImageBackingFactoryWithGMBTest, ::testing::Combine(::testing::Bool(), - kResourceFormats), + kSharedImageFormats), TestParamToString); } // anonymous namespace
diff --git a/gpu/command_buffer/service/shared_image/gl_texture_image_backing.cc b/gpu/command_buffer/service/shared_image/gl_texture_image_backing.cc index bacf5a2e..ef7e56f 100644 --- a/gpu/command_buffer/service/shared_image/gl_texture_image_backing.cc +++ b/gpu/command_buffer/service/shared_image/gl_texture_image_backing.cc
@@ -69,7 +69,7 @@ using InitializeGLTextureParams = GLTextureImageBackingHelper::InitializeGLTextureParams; -int BytesPerPixel(viz::ResourceFormat format) { +int BytesPerPixel(viz::SharedImageFormat format) { int bits = viz::BitsPerPixel(format); DCHECK_GE(bits, 8); return bits / 8; @@ -91,8 +91,9 @@ // GLTextureImageBacking bool GLTextureImageBacking::SupportsPixelUploadWithFormat( - viz::ResourceFormat format) { - switch (format) { + viz::SharedImageFormat format) { + auto resource_format = format.resource_format(); + switch (resource_format) { case viz::ResourceFormat::RGBA_8888: case viz::ResourceFormat::RGBA_4444: case viz::ResourceFormat::BGRA_8888: @@ -120,7 +121,7 @@ } GLTextureImageBacking::GLTextureImageBacking(const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, @@ -224,13 +225,14 @@ GLuint gl_unpack_row_length = 0; std::vector<uint8_t> repacked_data; - if (format() == viz::BGRX_8888 || format() == viz::RGBX_8888) { + auto resource_format = format().resource_format(); + if (resource_format == viz::BGRX_8888 || resource_format == viz::RGBX_8888) { DCHECK_EQ(gl_format, static_cast<GLenum>(GL_RGB)); // BGRX and RGBX data is uploaded as GL_RGB. Repack from 4 to 3 bytes per // pixel. repacked_data = - RepackPixelDataAsRgb(size(), pixmap, format() == viz::BGRX_8888); + RepackPixelDataAsRgb(size(), pixmap, resource_format == viz::BGRX_8888); } else if (pixmap_stride > expected_stride) { if (SupportsUnpackSubimage()) { // Use GL_UNPACK_ROW_LENGTH to skip data past end of each row on upload. @@ -311,7 +313,7 @@ if (!cached_promise_texture_) { GrBackendTexture backend_texture; GetGrBackendTexture(context_state->feature_info(), GetGLTarget(), size(), - GetGLServiceId(), format(), + GetGLServiceId(), format().resource_format(), context_state->gr_context()->threadSafeProxy(), &backend_texture); cached_promise_texture_ = SkPromiseImageTexture::Make(backend_texture);
diff --git a/gpu/command_buffer/service/shared_image/gl_texture_image_backing.h b/gpu/command_buffer/service/shared_image/gl_texture_image_backing.h index fe379859..60513c01 100644 --- a/gpu/command_buffer/service/shared_image/gl_texture_image_backing.h +++ b/gpu/command_buffer/service/shared_image/gl_texture_image_backing.h
@@ -18,10 +18,10 @@ // backed by a GLImage. class GLTextureImageBacking : public ClearTrackingSharedImageBacking { public: - static bool SupportsPixelUploadWithFormat(viz::ResourceFormat format); + static bool SupportsPixelUploadWithFormat(viz::SharedImageFormat format); GLTextureImageBacking(const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin,
diff --git a/gpu/command_buffer/service/shared_image/gl_texture_image_backing_factory.cc b/gpu/command_buffer/service/shared_image/gl_texture_image_backing_factory.cc index 37d479b7..9fbcb87 100644 --- a/gpu/command_buffer/service/shared_image/gl_texture_image_backing_factory.cc +++ b/gpu/command_buffer/service/shared_image/gl_texture_image_backing_factory.cc
@@ -47,7 +47,7 @@ std::unique_ptr<SharedImageBacking> GLTextureImageBackingFactory::CreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, SurfaceHandle surface_handle, const gfx::Size& size, const gfx::ColorSpace& color_space, @@ -64,7 +64,7 @@ std::unique_ptr<SharedImageBacking> GLTextureImageBackingFactory::CreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, @@ -99,7 +99,7 @@ GLenum target, GLuint service_id, bool is_cleared, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, uint32_t usage) { auto result = std::make_unique<GLTextureImageBacking>( @@ -117,7 +117,7 @@ bool GLTextureImageBackingFactory::IsSupported( uint32_t usage, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, bool thread_safe, gfx::GpuMemoryBufferType gmb_type, @@ -173,14 +173,14 @@ #endif } - return CanCreateSharedImage(size, pixel_data, format_info_[format], + return CanCreateSharedImage(size, pixel_data, GetFormatInfo(format), GL_TEXTURE_2D); } std::unique_ptr<SharedImageBacking> GLTextureImageBackingFactory::CreateSharedImageInternal( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, SurfaceHandle surface_handle, const gfx::Size& size, const gfx::ColorSpace& color_space, @@ -188,7 +188,7 @@ SkAlphaType alpha_type, uint32_t usage, base::span<const uint8_t> pixel_data) { - const FormatInfo& format_info = format_info_[format]; + const FormatInfo& format_info = GetFormatInfo(format); GLenum target = GL_TEXTURE_2D; const bool for_framebuffer_attachment =
diff --git a/gpu/command_buffer/service/shared_image/gl_texture_image_backing_factory.h b/gpu/command_buffer/service/shared_image/gl_texture_image_backing_factory.h index 15d9ca8..00c43ab 100644 --- a/gpu/command_buffer/service/shared_image/gl_texture_image_backing_factory.h +++ b/gpu/command_buffer/service/shared_image/gl_texture_image_backing_factory.h
@@ -44,7 +44,7 @@ // SharedImageBackingFactory implementation. std::unique_ptr<SharedImageBacking> CreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, SurfaceHandle surface_handle, const gfx::Size& size, const gfx::ColorSpace& color_space, @@ -54,7 +54,7 @@ bool is_thread_safe) override; std::unique_ptr<SharedImageBacking> CreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, @@ -74,7 +74,7 @@ SkAlphaType alpha_type, uint32_t usage) override; bool IsSupported(uint32_t usage, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, bool thread_safe, gfx::GpuMemoryBufferType gmb_type, @@ -86,14 +86,14 @@ GLenum target, GLuint service_id, bool is_cleared, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, uint32_t usage); private: std::unique_ptr<SharedImageBacking> CreateSharedImageInternal( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, SurfaceHandle surface_handle, const gfx::Size& size, const gfx::ColorSpace& color_space,
diff --git a/gpu/command_buffer/service/shared_image/gl_texture_image_backing_factory_unittest.cc b/gpu/command_buffer/service/shared_image/gl_texture_image_backing_factory_unittest.cc index 8716bad..b05f309 100644 --- a/gpu/command_buffer/service/shared_image/gl_texture_image_backing_factory_unittest.cc +++ b/gpu/command_buffer/service/shared_image/gl_texture_image_backing_factory_unittest.cc
@@ -119,14 +119,15 @@ gles2::PassthroughCommandDecoderSupported(); } - bool IsFormatSupport(viz::ResourceFormat format) const { - if (format == viz::ResourceFormat::RED_8 || - format == viz::ResourceFormat::RG_88) { + bool IsFormatSupport(viz::SharedImageFormat format) const { + auto resource_format = format.resource_format(); + if (resource_format == viz::ResourceFormat::RED_8 || + resource_format == viz::ResourceFormat::RG_88) { return supports_r_rg_; - } else if (format == viz::ResourceFormat::BGRA_1010102 || - format == viz::ResourceFormat::RGBA_1010102) { + } else if (resource_format == viz::ResourceFormat::BGRA_1010102 || + resource_format == viz::ResourceFormat::RGBA_1010102) { return supports_ar30_ || supports_ab30_; - } else if (format == viz::ResourceFormat::ETC1) { + } else if (resource_format == viz::ResourceFormat::ETC1) { return supports_etc1_; } return true; @@ -160,23 +161,24 @@ } }; -// ResourceFormat parameterized tests. +// SharedImageFormat parameterized tests. class GLTextureImageBackingFactoryWithFormatTest : public GLTextureImageBackingFactoryTest, - public testing::WithParamInterface<viz::ResourceFormat> { + public testing::WithParamInterface<viz::SharedImageFormat> { public: - viz::ResourceFormat get_format() { return GetParam(); } + viz::SharedImageFormat get_format() { return GetParam(); } }; -// ResourceFormat parameterized tests for initial data upload. Only a subset +// SharedImageFormat parameterized tests for initial data upload. Only a subset // of formats support upload. using GLTextureImageBackingFactoryInitialDataTest = GLTextureImageBackingFactoryWithFormatTest; -// ResourceFormat parameterized tests with a factory that supports pixel upload. +// SharedImageFormat parameterized tests with a factory that supports pixel +// upload. class GLTextureImageBackingFactoryWithUploadTest : public GLTextureImageBackingFactoryTestBase, - public testing::WithParamInterface<viz::ResourceFormat> { + public testing::WithParamInterface<viz::SharedImageFormat> { public: GLTextureImageBackingFactoryWithUploadTest() : GLTextureImageBackingFactoryTestBase(false) {} @@ -184,11 +186,12 @@ GpuDriverBugWorkarounds workarounds; SetUpBase(workarounds, /*for_cpu_upload_usage=*/true); } - viz::ResourceFormat get_format() { return GetParam(); } + viz::SharedImageFormat get_format() { return GetParam(); } }; TEST_F(GLTextureImageBackingFactoryTest, InvalidFormat) { - auto format = viz::ResourceFormat::YUV_420_BIPLANAR; + auto format = viz::SharedImageFormat::SinglePlane( + viz::ResourceFormat::YUV_420_BIPLANAR); gfx::Size size(256, 256); uint32_t usage = SHARED_IMAGE_USAGE_GLES2; bool supported = @@ -200,7 +203,8 @@ // Ensures that GLTextureImageBacking registers it's estimated size // with memory tracker. TEST_F(GLTextureImageBackingFactoryTest, EstimatedSize) { - auto format = viz::ResourceFormat::RGBA_8888; + auto format = + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RGBA_8888); auto mailbox = Mailbox::GenerateForSharedImage(); gfx::Size size(256, 256); auto color_space = gfx::ColorSpace::CreateSRGB(); @@ -241,7 +245,8 @@ const gles2::Validators* validators = feature_info->validators(); for (int i = 0; i <= viz::RESOURCE_FORMAT_MAX; ++i) { - auto format = static_cast<viz::ResourceFormat>(i); + auto format = viz::SharedImageFormat::SinglePlane( + static_cast<viz::ResourceFormat>(i)); if (!viz::GLSupportsFormat(format) || viz::IsResourceFormatCompressed(format)) continue; @@ -298,7 +303,7 @@ GTEST_SKIP(); } - viz::ResourceFormat format = get_format(); + viz::SharedImageFormat format = get_format(); if (!IsFormatSupport(format)) { GTEST_SKIP(); } @@ -378,8 +383,11 @@ // support. It's possible Skia might support these formats even if the Chrome // feature flags are false. We just check here that the feature flags don't // allow Chrome to do something that Skia doesn't support. - if ((format != viz::ResourceFormat::BGRA_1010102 || supports_ar30_) && - (format != viz::ResourceFormat::RGBA_1010102 || supports_ab30_)) { + auto resource_format = format.resource_format(); + if ((resource_format != viz::ResourceFormat::BGRA_1010102 || + supports_ar30_) && + (resource_format != viz::ResourceFormat::RGBA_1010102 || + supports_ab30_)) { ASSERT_TRUE(scoped_write_access); auto* surface = scoped_write_access->surface(); ASSERT_TRUE(surface); @@ -408,7 +416,7 @@ } TEST_P(GLTextureImageBackingFactoryWithFormatTest, InvalidSize) { - viz::ResourceFormat format = get_format(); + viz::SharedImageFormat format = get_format(); if (!IsFormatSupport(format)) { GTEST_SKIP(); } @@ -428,7 +436,7 @@ } TEST_P(GLTextureImageBackingFactoryInitialDataTest, InitialData) { - viz::ResourceFormat format = get_format(); + viz::SharedImageFormat format = get_format(); if (!IsFormatSupport(format)) { GTEST_SKIP(); } @@ -487,7 +495,7 @@ } TEST_P(GLTextureImageBackingFactoryInitialDataTest, InitialDataWrongSize) { - viz::ResourceFormat format = get_format(); + viz::SharedImageFormat format = get_format(); if (!IsFormatSupport(format)) { GTEST_SKIP(); } @@ -498,18 +506,20 @@ viz::ResourceSizes::CheckedSizeInBytes<size_t>(size, format); std::vector<uint8_t> initial_data_small(required_size / 2); std::vector<uint8_t> initial_data_large(required_size * 2); - bool supported = backing_factory_->IsSupported( - usage, format, size, /*thread_safe=*/false, gfx::EMPTY_BUFFER, - GrContextType::kGL, initial_data_small); + bool supported = + backing_factory_->IsSupported(usage, format, size, + /*thread_safe=*/false, gfx::EMPTY_BUFFER, + GrContextType::kGL, initial_data_small); EXPECT_FALSE(supported); - supported = backing_factory_->IsSupported( - usage, format, size, /*thread_safe=*/false, gfx::EMPTY_BUFFER, - GrContextType::kGL, initial_data_large); + supported = + backing_factory_->IsSupported(usage, format, size, + /*thread_safe=*/false, gfx::EMPTY_BUFFER, + GrContextType::kGL, initial_data_large); EXPECT_FALSE(supported); } TEST_P(GLTextureImageBackingFactoryWithUploadTest, UploadFromMemory) { - viz::ResourceFormat format = get_format(); + viz::SharedImageFormat format = get_format(); if (!IsFormatSupport(format)) { GTEST_SKIP(); } @@ -556,42 +566,44 @@ EXPECT_TRUE(backing->UploadFromMemory(larger_bitmap.pixmap())); } -const auto kResourceFormats = - ::testing::Values(viz::ResourceFormat::RGBA_8888, - viz::ResourceFormat::BGRA_8888, - viz::ResourceFormat::RGBA_4444, - viz::ResourceFormat::RED_8, - viz::ResourceFormat::RG_88, - viz::ResourceFormat::BGRA_1010102, - viz::ResourceFormat::RGBA_1010102, - viz::ResourceFormat::RGBX_8888, - viz::ResourceFormat::BGRX_8888); +const auto kSharedImageFormats = ::testing::Values( + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RGBA_8888), + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::BGRA_8888), + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RGBA_4444), + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RED_8), + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RG_88), + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::BGRA_1010102), + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RGBA_1010102), + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RGBX_8888), + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::BGRX_8888)); std::string TestParamToString( - const testing::TestParamInfo<viz::ResourceFormat>& param_info) { + const testing::TestParamInfo<viz::SharedImageFormat>& param_info) { return viz::ResourceFormatToString(param_info.param); } -INSTANTIATE_TEST_SUITE_P(, - GLTextureImageBackingFactoryInitialDataTest, - ::testing::Values(viz::ResourceFormat::ETC1, - viz::ResourceFormat::RGBA_8888, - viz::ResourceFormat::BGRA_8888, - viz::ResourceFormat::RGBA_4444, - viz::ResourceFormat::RED_8, - viz::ResourceFormat::RG_88, - viz::ResourceFormat::BGRA_1010102, - viz::ResourceFormat::RGBA_1010102), - TestParamToString); +INSTANTIATE_TEST_SUITE_P( + , + GLTextureImageBackingFactoryInitialDataTest, + ::testing::Values( + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::ETC1), + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RGBA_8888), + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::BGRA_8888), + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RGBA_4444), + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RED_8), + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RG_88), + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::BGRA_1010102), + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RGBA_1010102)), + TestParamToString); INSTANTIATE_TEST_SUITE_P(, GLTextureImageBackingFactoryWithFormatTest, - kResourceFormats, + kSharedImageFormats, TestParamToString); INSTANTIATE_TEST_SUITE_P(, GLTextureImageBackingFactoryWithUploadTest, - kResourceFormats, + kSharedImageFormats, TestParamToString); } // anonymous namespace
diff --git a/gpu/command_buffer/service/shared_image/gl_texture_image_backing_helper.cc b/gpu/command_buffer/service/shared_image/gl_texture_image_backing_helper.cc index b82dff4c..e6879ff 100644 --- a/gpu/command_buffer/service/shared_image/gl_texture_image_backing_helper.cc +++ b/gpu/command_buffer/service/shared_image/gl_texture_image_backing_helper.cc
@@ -103,11 +103,9 @@ } Mailbox dst_mailbox = Mailbox::GenerateForSharedImage(); - viz::SharedImageFormat si_format = - viz::SharedImageFormat::SinglePlane(backing->format()); bool success = factory->CreateSharedImage( - dst_mailbox, si_format, backing->size(), backing->color_space(), + dst_mailbox, backing->format(), backing->size(), backing->color_space(), kTopLeft_GrSurfaceOrigin, kPremul_SkAlphaType, gpu::kNullSurfaceHandle, backing->usage() | SHARED_IMAGE_USAGE_WEBGPU); if (!success) {
diff --git a/gpu/command_buffer/service/shared_image/iosurface_image_backing_factory.mm b/gpu/command_buffer/service/shared_image/iosurface_image_backing_factory.mm index 8976e83..d9d3179 100644 --- a/gpu/command_buffer/service/shared_image/iosurface_image_backing_factory.mm +++ b/gpu/command_buffer/service/shared_image/iosurface_image_backing_factory.mm
@@ -40,7 +40,7 @@ id<MTLDevice> mtl_device, IOSurfaceRef io_surface, const gfx::Size& size, - viz::ResourceFormat format) { + viz::SharedImageFormat format) { TRACE_EVENT0("gpu", "IOSurfaceImageBackingFactory::CreateMetalTexture"); base::scoped_nsprotocol<id<MTLTexture>> mtl_texture; MTLPixelFormat mtl_pixel_format = @@ -218,7 +218,7 @@ #if BUILDFLAG(USE_DAWN) // See comments in IOSurfaceImageBackingFactory::CreateSharedImage // regarding RGBA versus BGRA. - viz::ResourceFormat actual_format = backing->format(); + viz::ResourceFormat actual_format = (backing->format()).resource_format(); if (actual_format == viz::RGBA_8888) actual_format = viz::BGRA_8888;
diff --git a/gpu/command_buffer/service/shared_image/iosurface_image_backing_factory_unittest.cc b/gpu/command_buffer/service/shared_image/iosurface_image_backing_factory_unittest.cc index e78a1ab..74f7fcf 100644 --- a/gpu/command_buffer/service/shared_image/iosurface_image_backing_factory_unittest.cc +++ b/gpu/command_buffer/service/shared_image/iosurface_image_backing_factory_unittest.cc
@@ -150,7 +150,8 @@ } Mailbox mailbox = Mailbox::GenerateForSharedImage(); - viz::ResourceFormat format = viz::ResourceFormat::RGBA_8888; + viz::SharedImageFormat format = + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RGBA_8888); gfx::Size size(256, 256); gfx::ColorSpace color_space = gfx::ColorSpace::CreateSRGB(); GrSurfaceOrigin surface_origin = kTopLeft_GrSurfaceOrigin; @@ -234,7 +235,8 @@ // Create a backing using mailbox. auto mailbox = Mailbox::GenerateForSharedImage(); - auto format = viz::ResourceFormat::RGBA_8888; + auto format = + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RGBA_8888); gfx::Size size(1, 1); auto color_space = gfx::ColorSpace::CreateSRGB(); GrSurfaceOrigin surface_origin = kTopLeft_GrSurfaceOrigin; @@ -315,7 +317,8 @@ // Create a backing using mailbox. auto mailbox = Mailbox::GenerateForSharedImage(); - auto format = viz::ResourceFormat::RGBA_8888; + auto format = + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RGBA_8888); gfx::Size size(1, 1); auto color_space = gfx::ColorSpace::CreateSRGB(); GrSurfaceOrigin surface_origin = kTopLeft_GrSurfaceOrigin; @@ -389,7 +392,8 @@ // Create a backing using mailbox. auto mailbox = Mailbox::GenerateForSharedImage(); - const auto format = viz::ResourceFormat::RGBA_8888; + const auto format = + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RGBA_8888); const gfx::Size size(1, 1); const auto color_space = gfx::ColorSpace::CreateSRGB(); GrSurfaceOrigin surface_origin = kTopLeft_GrSurfaceOrigin; @@ -513,7 +517,8 @@ TEST_F(IOSurfaceImageBackingFactoryTest, UnclearDawn_SkiaFails) { // Create a backing using mailbox. auto mailbox = Mailbox::GenerateForSharedImage(); - const auto format = viz::ResourceFormat::RGBA_8888; + const auto format = + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RGBA_8888); const gfx::Size size(1, 1); const auto color_space = gfx::ColorSpace::CreateSRGB(); GrSurfaceOrigin surface_origin = kTopLeft_GrSurfaceOrigin; @@ -608,7 +613,8 @@ TEST_F(IOSurfaceImageBackingFactoryTest, SkiaAccessFirstFails) { // Create a mailbox. auto mailbox = Mailbox::GenerateForSharedImage(); - const auto format = viz::ResourceFormat::RGBA_8888; + const auto format = + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RGBA_8888); const gfx::Size size(1, 1); const auto color_space = gfx::ColorSpace::CreateSRGB(); GrSurfaceOrigin surface_origin = kTopLeft_GrSurfaceOrigin;
diff --git a/gpu/command_buffer/service/shared_image/ozone_image_backing.cc b/gpu/command_buffer/service/shared_image/ozone_image_backing.cc index 6d9b9a3..902081d 100644 --- a/gpu/command_buffer/service/shared_image/ozone_image_backing.cc +++ b/gpu/command_buffer/service/shared_image/ozone_image_backing.cc
@@ -240,7 +240,7 @@ OzoneImageBacking::OzoneImageBacking( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, gfx::BufferPlane plane, const gfx::Size& size, const gfx::ColorSpace& color_space,
diff --git a/gpu/command_buffer/service/shared_image/ozone_image_backing.h b/gpu/command_buffer/service/shared_image/ozone_image_backing.h index fe452d6..0007b9a3 100644 --- a/gpu/command_buffer/service/shared_image/ozone_image_backing.h +++ b/gpu/command_buffer/service/shared_image/ozone_image_backing.h
@@ -39,7 +39,7 @@ public: OzoneImageBacking( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, gfx::BufferPlane plane, const gfx::Size& size, const gfx::ColorSpace& color_space,
diff --git a/gpu/command_buffer/service/shared_image/ozone_image_backing_factory.cc b/gpu/command_buffer/service/shared_image/ozone_image_backing_factory.cc index 16fc445..69657437 100644 --- a/gpu/command_buffer/service/shared_image/ozone_image_backing_factory.cc +++ b/gpu/command_buffer/service/shared_image/ozone_image_backing_factory.cc
@@ -63,7 +63,7 @@ std::unique_ptr<OzoneImageBacking> OzoneImageBackingFactory::CreateSharedImageInternal( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, SurfaceHandle surface_handle, const gfx::Size& size, const gfx::ColorSpace& color_space, @@ -100,7 +100,7 @@ std::unique_ptr<SharedImageBacking> OzoneImageBackingFactory::CreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, SurfaceHandle surface_handle, const gfx::Size& size, const gfx::ColorSpace& color_space, @@ -116,7 +116,7 @@ std::unique_ptr<SharedImageBacking> OzoneImageBackingFactory::CreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, @@ -170,9 +170,10 @@ const viz::ResourceFormat plane_format = viz::GetResourceFormat(GetPlaneBufferFormat(plane, buffer_format)); auto backing = std::make_unique<OzoneImageBacking>( - mailbox, plane_format, plane, plane_size, color_space, surface_origin, - alpha_type, usage, shared_context_state_.get(), std::move(pixmap), - dawn_procs_, workarounds_, use_passthrough_); + mailbox, viz::SharedImageFormat::SinglePlane(plane_format), plane, + plane_size, color_space, surface_origin, alpha_type, usage, + shared_context_state_.get(), std::move(pixmap), dawn_procs_, workarounds_, + use_passthrough_); backing->SetCleared(); return backing; @@ -180,7 +181,7 @@ bool OzoneImageBackingFactory::IsSupported( uint32_t usage, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, bool thread_safe, gfx::GpuMemoryBufferType gmb_type,
diff --git a/gpu/command_buffer/service/shared_image/ozone_image_backing_factory.h b/gpu/command_buffer/service/shared_image/ozone_image_backing_factory.h index 032579f..0caa9b4 100644 --- a/gpu/command_buffer/service/shared_image/ozone_image_backing_factory.h +++ b/gpu/command_buffer/service/shared_image/ozone_image_backing_factory.h
@@ -33,7 +33,7 @@ // SharedImageBackingFactory implementation std::unique_ptr<SharedImageBacking> CreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, SurfaceHandle surface_handle, const gfx::Size& size, const gfx::ColorSpace& color_space, @@ -44,7 +44,7 @@ std::unique_ptr<SharedImageBacking> CreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, @@ -66,7 +66,7 @@ uint32_t usage) override; bool IsSupported(uint32_t usage, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, bool thread_safe, gfx::GpuMemoryBufferType gmb_type, @@ -84,7 +84,7 @@ std::unique_ptr<OzoneImageBacking> CreateSharedImageInternal( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, SurfaceHandle surface_handle, const gfx::Size& size, const gfx::ColorSpace& color_space,
diff --git a/gpu/command_buffer/service/shared_image/raw_draw_image_backing.cc b/gpu/command_buffer/service/shared_image/raw_draw_image_backing.cc index e985fa2e..1d59787 100644 --- a/gpu/command_buffer/service/shared_image/raw_draw_image_backing.cc +++ b/gpu/command_buffer/service/shared_image/raw_draw_image_backing.cc
@@ -93,7 +93,7 @@ }; RawDrawImageBacking::RawDrawImageBacking(const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin,
diff --git a/gpu/command_buffer/service/shared_image/raw_draw_image_backing.h b/gpu/command_buffer/service/shared_image/raw_draw_image_backing.h index eb66d01..61b1c1a2 100644 --- a/gpu/command_buffer/service/shared_image/raw_draw_image_backing.h +++ b/gpu/command_buffer/service/shared_image/raw_draw_image_backing.h
@@ -24,7 +24,7 @@ class RawDrawImageBacking : public ClearTrackingSharedImageBacking { public: RawDrawImageBacking(const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin,
diff --git a/gpu/command_buffer/service/shared_image/raw_draw_image_backing_factory.cc b/gpu/command_buffer/service/shared_image/raw_draw_image_backing_factory.cc index 29a6776..87b7f55 100644 --- a/gpu/command_buffer/service/shared_image/raw_draw_image_backing_factory.cc +++ b/gpu/command_buffer/service/shared_image/raw_draw_image_backing_factory.cc
@@ -17,7 +17,7 @@ std::unique_ptr<SharedImageBacking> RawDrawImageBackingFactory::CreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, SurfaceHandle surface_handle, const gfx::Size& size, const gfx::ColorSpace& color_space, @@ -34,7 +34,7 @@ std::unique_ptr<SharedImageBacking> RawDrawImageBackingFactory::CreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, @@ -76,7 +76,7 @@ bool RawDrawImageBackingFactory::IsSupported( uint32_t usage, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, bool thread_safe, gfx::GpuMemoryBufferType gmb_type,
diff --git a/gpu/command_buffer/service/shared_image/raw_draw_image_backing_factory.h b/gpu/command_buffer/service/shared_image/raw_draw_image_backing_factory.h index feacbff..2eeaa8a 100644 --- a/gpu/command_buffer/service/shared_image/raw_draw_image_backing_factory.h +++ b/gpu/command_buffer/service/shared_image/raw_draw_image_backing_factory.h
@@ -19,7 +19,7 @@ // SharedImageBackingFactory implementation: std::unique_ptr<SharedImageBacking> CreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, SurfaceHandle surface_handle, const gfx::Size& size, const gfx::ColorSpace& color_space, @@ -29,7 +29,7 @@ bool is_thread_safe) override; std::unique_ptr<SharedImageBacking> CreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, @@ -49,7 +49,7 @@ SkAlphaType alpha_type, uint32_t usage) override; bool IsSupported(uint32_t usage, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, bool thread_safe, gfx::GpuMemoryBufferType gmb_type,
diff --git a/gpu/command_buffer/service/shared_image/shared_image_backing.cc b/gpu/command_buffer/service/shared_image/shared_image_backing.cc index 5f7d2ad..f6b737f 100644 --- a/gpu/command_buffer/service/shared_image/shared_image_backing.cc +++ b/gpu/command_buffer/service/shared_image/shared_image_backing.cc
@@ -59,7 +59,7 @@ } // namespace SharedImageBacking::SharedImageBacking(const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, @@ -92,7 +92,7 @@ SkImageInfo SharedImageBacking::AsSkImageInfo() const { return SkImageInfo::Make(size_.width(), size_.height(), viz::ResourceFormatToClosestSkColorType( - /*gpu_compositing=*/true, format_), + /*gpu_compositing=*/true, format()), alpha_type_, color_space_.ToSkColorSpace()); } @@ -307,7 +307,7 @@ ClearTrackingSharedImageBacking::ClearTrackingSharedImageBacking( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin,
diff --git a/gpu/command_buffer/service/shared_image/shared_image_backing.h b/gpu/command_buffer/service/shared_image/shared_image_backing.h index 14bdbab..5a8d466 100644 --- a/gpu/command_buffer/service/shared_image/shared_image_backing.h +++ b/gpu/command_buffer/service/shared_image/shared_image_backing.h
@@ -17,6 +17,7 @@ #include "base/trace_event/memory_allocator_dump_guid.h" #include "build/build_config.h" #include "components/viz/common/resources/resource_format.h" +#include "components/viz/common/resources/shared_image_format.h" #include "gpu/command_buffer/common/mailbox.h" #include "gpu/gpu_gles2_export.h" #include "third_party/abseil-cpp/absl/types/optional.h" @@ -80,7 +81,7 @@ class GPU_GLES2_EXPORT SharedImageBacking { public: SharedImageBacking(const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, @@ -91,7 +92,7 @@ virtual ~SharedImageBacking(); - viz::ResourceFormat format() const { return format_; } + viz::SharedImageFormat format() const { return format_; } const gfx::Size& size() const { return size_; } const gfx::ColorSpace& color_space() const { return color_space_; } GrSurfaceOrigin surface_origin() const { return surface_origin_; } @@ -283,7 +284,7 @@ }; const Mailbox mailbox_; - const viz::ResourceFormat format_; + const viz::SharedImageFormat format_; const gfx::Size size_; const gfx::ColorSpace color_space_; const GrSurfaceOrigin surface_origin_; @@ -317,7 +318,7 @@ : public SharedImageBacking { public: ClearTrackingSharedImageBacking(const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin,
diff --git a/gpu/command_buffer/service/shared_image/shared_image_backing_factory.h b/gpu/command_buffer/service/shared_image/shared_image_backing_factory.h index 9d31d0c4..b64bbe58 100644 --- a/gpu/command_buffer/service/shared_image/shared_image_backing_factory.h +++ b/gpu/command_buffer/service/shared_image/shared_image_backing_factory.h
@@ -8,7 +8,7 @@ #include <memory> #include "base/memory/weak_ptr.h" -#include "components/viz/common/resources/resource_format.h" +#include "components/viz/common/resources/shared_image_format.h" #include "gpu/config/gpu_preferences.h" #include "gpu/gpu_gles2_export.h" #include "gpu/ipc/common/surface_handle.h" @@ -33,7 +33,7 @@ virtual std::unique_ptr<SharedImageBacking> CreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, SurfaceHandle surface_handle, const gfx::Size& size, const gfx::ColorSpace& color_space, @@ -43,7 +43,7 @@ bool is_thread_safe) = 0; virtual std::unique_ptr<SharedImageBacking> CreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, @@ -65,7 +65,7 @@ // Returns true if the factory is supported virtual bool IsSupported(uint32_t usage, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, bool thread_safe, gfx::GpuMemoryBufferType gmb_type,
diff --git a/gpu/command_buffer/service/shared_image/shared_image_factory.cc b/gpu/command_buffer/service/shared_image/shared_image_factory.cc index d0f4b96..760031d 100644 --- a/gpu/command_buffer/service/shared_image/shared_image_factory.cc +++ b/gpu/command_buffer/service/shared_image/shared_image_factory.cc
@@ -286,15 +286,14 @@ } bool SharedImageFactory::CreateSharedImage(const Mailbox& mailbox, - viz::SharedImageFormat si_format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, SkAlphaType alpha_type, gpu::SurfaceHandle surface_handle, uint32_t usage) { - DCHECK(si_format.is_single_plane()); - auto format = si_format.resource_format(); + DCHECK(format.is_single_plane()); auto* factory = GetFactoryByUsage(usage, format, size, /*pixel_data=*/{}, gfx::EMPTY_BUFFER); if (!factory) @@ -311,15 +310,14 @@ } bool SharedImageFactory::CreateSharedImage(const Mailbox& mailbox, - viz::SharedImageFormat si_format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, SkAlphaType alpha_type, uint32_t usage, base::span<const uint8_t> data) { - DCHECK(si_format.is_single_plane()); - auto format = si_format.resource_format(); + DCHECK(format.is_single_plane()); SharedImageBackingFactory* factory = nullptr; if (backing_factory_for_testing_) { factory = backing_factory_for_testing_; @@ -354,11 +352,12 @@ GrSurfaceOrigin surface_origin, SkAlphaType alpha_type, uint32_t usage) { - auto resource_format = viz::GetResourceFormat(format); + auto si_format = + viz::SharedImageFormat::SinglePlane(viz::GetResourceFormat(format)); gfx::GpuMemoryBufferType gmb_type = handle.type; bool use_compound = false; - auto* factory = GetFactoryByUsage(usage, resource_format, size, + auto* factory = GetFactoryByUsage(usage, si_format, size, /*pixel_data=*/{}, gmb_type); if (!factory && gmb_type == gfx::SHARED_MEMORY_BUFFER) { @@ -366,7 +365,7 @@ // another GPU backing type to satisfy requirements. use_compound = true; factory = GetFactoryByUsage(usage | SHARED_IMAGE_USAGE_CPU_UPLOAD, - resource_format, size, + si_format, size, /*pixel_data=*/{}, gfx::EMPTY_BUFFER); } @@ -558,7 +557,7 @@ SharedImageBackingFactory* SharedImageFactory::GetFactoryByUsage( uint32_t usage, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, base::span<const uint8_t> pixel_data, gfx::GpuMemoryBufferType gmb_type) { @@ -574,7 +573,8 @@ } LOG(ERROR) << "Could not find SharedImageBackingFactory with params: usage: " - << CreateLabelForSharedImageUsage(usage) << ", format: " << format + << CreateLabelForSharedImageUsage(usage) + << ", format: " << viz::ResourceFormatToString(format) << ", share_between_threads: " << share_between_threads << ", gmb_type: " << GmbTypeToString(gmb_type); return nullptr;
diff --git a/gpu/command_buffer/service/shared_image/shared_image_factory.h b/gpu/command_buffer/service/shared_image/shared_image_factory.h index 830a4faa..b7b941be 100644 --- a/gpu/command_buffer/service/shared_image/shared_image_factory.h +++ b/gpu/command_buffer/service/shared_image/shared_image_factory.h
@@ -130,7 +130,7 @@ SharedImageBackingFactory* GetFactoryByUsage( uint32_t usage, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, base::span<const uint8_t> pixel_data, gfx::GpuMemoryBufferType gmb_type);
diff --git a/gpu/command_buffer/service/shared_image/shared_image_manager_unittest.cc b/gpu/command_buffer/service/shared_image/shared_image_manager_unittest.cc index a5dca8eb..cb02023 100644 --- a/gpu/command_buffer/service/shared_image/shared_image_manager_unittest.cc +++ b/gpu/command_buffer/service/shared_image/shared_image_manager_unittest.cc
@@ -22,7 +22,8 @@ std::unique_ptr<TestImageBacking> CreateImageBacking(size_t size_in_bytes) { auto mailbox = Mailbox::GenerateForSharedImage(); - auto format = viz::ResourceFormat::RGBA_8888; + auto format = + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RGBA_8888); gfx::Size size(256, 256); auto color_space = gfx::ColorSpace::CreateSRGB(); auto surface_origin = kTopLeft_GrSurfaceOrigin; @@ -40,7 +41,8 @@ auto tracker = std::make_unique<MemoryTypeTracker>(nullptr); auto mailbox = Mailbox::GenerateForSharedImage(); - auto format = viz::ResourceFormat::RGBA_8888; + auto format = + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RGBA_8888); gfx::Size size(256, 256); auto color_space = gfx::ColorSpace::CreateSRGB(); auto surface_origin = kTopLeft_GrSurfaceOrigin; @@ -112,7 +114,8 @@ auto tracker = std::make_unique<MemoryTypeTracker>(nullptr); auto mailbox = Mailbox::GenerateForSharedImage(); - auto format = viz::ResourceFormat::RGBA_8888; + auto format = + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RGBA_8888); gfx::Size size(256, 256); auto color_space = gfx::ColorSpace::CreateSRGB(); auto surface_origin = kTopLeft_GrSurfaceOrigin; @@ -144,7 +147,8 @@ auto tracker2 = std::make_unique<MemoryTypeTracker>(nullptr); auto mailbox = Mailbox::GenerateForSharedImage(); - auto format = viz::ResourceFormat::RGBA_8888; + auto format = + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RGBA_8888); gfx::Size size(256, 256); auto color_space = gfx::ColorSpace::CreateSRGB(); auto surface_origin = kTopLeft_GrSurfaceOrigin; @@ -214,7 +218,8 @@ &memory_tracker2, memory_tracker2.task_runner()); auto mailbox = Mailbox::GenerateForSharedImage(); - auto format = viz::ResourceFormat::RGBA_8888; + auto format = + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RGBA_8888); gfx::Size size(256, 256); auto color_space = gfx::ColorSpace::CreateSRGB(); auto surface_origin = kTopLeft_GrSurfaceOrigin;
diff --git a/gpu/command_buffer/service/shared_image/shared_image_representation.h b/gpu/command_buffer/service/shared_image/shared_image_representation.h index ef146e3..bdc5ae6 100644 --- a/gpu/command_buffer/service/shared_image/shared_image_representation.h +++ b/gpu/command_buffer/service/shared_image/shared_image_representation.h
@@ -81,7 +81,7 @@ MemoryTypeTracker* tracker); virtual ~SharedImageRepresentation(); - viz::ResourceFormat format() const { return backing_->format(); } + viz::SharedImageFormat format() const { return backing_->format(); } const gfx::Size& size() const { return backing_->size(); } const gfx::ColorSpace& color_space() const { return backing_->color_space(); } GrSurfaceOrigin surface_origin() const { return backing_->surface_origin(); }
diff --git a/gpu/command_buffer/service/shared_image/shared_image_representation_unittest.cc b/gpu/command_buffer/service/shared_image/shared_image_representation_unittest.cc index 6aeec55..ea128d21 100644 --- a/gpu/command_buffer/service/shared_image/shared_image_representation_unittest.cc +++ b/gpu/command_buffer/service/shared_image/shared_image_representation_unittest.cc
@@ -23,7 +23,8 @@ void SetUp() override { tracker_ = std::make_unique<MemoryTypeTracker>(nullptr); mailbox_ = Mailbox::GenerateForSharedImage(); - auto format = viz::ResourceFormat::RGBA_8888; + auto format = + viz::SharedImageFormat::SinglePlane(viz::ResourceFormat::RGBA_8888); gfx::Size size(256, 256); auto color_space = gfx::ColorSpace::CreateSRGB(); auto surface_origin = kTopLeft_GrSurfaceOrigin;
diff --git a/gpu/command_buffer/service/shared_image/shared_memory_image_backing.cc b/gpu/command_buffer/service/shared_image/shared_memory_image_backing.cc index 2929a543..a61edd4 100644 --- a/gpu/command_buffer/service/shared_image/shared_memory_image_backing.cc +++ b/gpu/command_buffer/service/shared_image/shared_memory_image_backing.cc
@@ -30,6 +30,7 @@ namespace gpu { namespace { + class MemoryImageRepresentationImpl : public MemoryImageRepresentation { public: MemoryImageRepresentationImpl(SharedImageManager* manager, @@ -186,7 +187,7 @@ SharedMemoryImageBacking::SharedMemoryImageBacking( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin,
diff --git a/gpu/command_buffer/service/shared_image/shared_memory_image_backing.h b/gpu/command_buffer/service/shared_image/shared_memory_image_backing.h index 272b1af..e26e357 100644 --- a/gpu/command_buffer/service/shared_image/shared_memory_image_backing.h +++ b/gpu/command_buffer/service/shared_image/shared_memory_image_backing.h
@@ -22,7 +22,7 @@ class SharedMemoryImageBacking : public SharedImageBacking { public: SharedMemoryImageBacking(const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin,
diff --git a/gpu/command_buffer/service/shared_image/shared_memory_image_backing_factory.cc b/gpu/command_buffer/service/shared_image/shared_memory_image_backing_factory.cc index ae6fa80..cbe4f3c 100644 --- a/gpu/command_buffer/service/shared_image/shared_memory_image_backing_factory.cc +++ b/gpu/command_buffer/service/shared_image/shared_memory_image_backing_factory.cc
@@ -21,7 +21,7 @@ std::unique_ptr<SharedImageBacking> SharedMemoryImageBackingFactory::CreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, SurfaceHandle surface_handle, const gfx::Size& size, const gfx::ColorSpace& color_space, @@ -36,7 +36,7 @@ std::unique_ptr<SharedImageBacking> SharedMemoryImageBackingFactory::CreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, @@ -68,14 +68,14 @@ } auto backing = std::make_unique<SharedMemoryImageBacking>( - mailbox, format, size, color_space, surface_origin, alpha_type, usage, - std::move(shm_wrapper)); + mailbox, viz::SharedImageFormat::SinglePlane(format), size, color_space, + surface_origin, alpha_type, usage, std::move(shm_wrapper)); return backing; } bool SharedMemoryImageBackingFactory::IsSupported( uint32_t usage, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, bool thread_safe, gfx::GpuMemoryBufferType gmb_type,
diff --git a/gpu/command_buffer/service/shared_image/shared_memory_image_backing_factory.h b/gpu/command_buffer/service/shared_image/shared_memory_image_backing_factory.h index fba6936..f846f67 100644 --- a/gpu/command_buffer/service/shared_image/shared_memory_image_backing_factory.h +++ b/gpu/command_buffer/service/shared_image/shared_memory_image_backing_factory.h
@@ -22,7 +22,7 @@ // SharedImageBackingFactory implementation std::unique_ptr<SharedImageBacking> CreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, SurfaceHandle surface_handle, const gfx::Size& size, const gfx::ColorSpace& color_space, @@ -33,7 +33,7 @@ std::unique_ptr<SharedImageBacking> CreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, @@ -55,7 +55,7 @@ uint32_t usage) override; bool IsSupported(uint32_t usage, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, bool thread_safe, gfx::GpuMemoryBufferType gmb_type,
diff --git a/gpu/command_buffer/service/shared_image/skia_gl_image_representation.cc b/gpu/command_buffer/service/shared_image/skia_gl_image_representation.cc index 522f1b0..e0ab8c4 100644 --- a/gpu/command_buffer/service/shared_image/skia_gl_image_representation.cc +++ b/gpu/command_buffer/service/shared_image/skia_gl_image_representation.cc
@@ -43,7 +43,8 @@ if (!GetGrBackendTexture( context_state->feature_info(), gl_representation->GetTextureBase()->target(), backing->size(), - gl_representation->GetTextureBase()->service_id(), backing->format(), + gl_representation->GetTextureBase()->service_id(), + (backing->format()).resource_format(), context_state->gr_context()->threadSafeProxy(), &backend_texture)) { return nullptr; }
diff --git a/gpu/command_buffer/service/shared_image/test_image_backing.cc b/gpu/command_buffer/service/shared_image/test_image_backing.cc index b4fcbe99..a4694b9 100644 --- a/gpu/command_buffer/service/shared_image/test_image_backing.cc +++ b/gpu/command_buffer/service/shared_image/test_image_backing.cc
@@ -154,7 +154,7 @@ } // namespace TestImageBacking::TestImageBacking(const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, @@ -188,7 +188,7 @@ } TestImageBacking::TestImageBacking(const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin,
diff --git a/gpu/command_buffer/service/shared_image/test_image_backing.h b/gpu/command_buffer/service/shared_image/test_image_backing.h index cbfde9b..7f856de 100644 --- a/gpu/command_buffer/service/shared_image/test_image_backing.h +++ b/gpu/command_buffer/service/shared_image/test_image_backing.h
@@ -16,7 +16,7 @@ public: // Constructor which uses a dummy GL texture ID for the backing. TestImageBacking(const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, @@ -25,7 +25,7 @@ size_t estimated_size); // Constructor which uses a provided GL texture ID for the backing. TestImageBacking(const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin,
diff --git a/gpu/command_buffer/service/shared_image/wrapped_sk_image_backing_factory.cc b/gpu/command_buffer/service/shared_image/wrapped_sk_image_backing_factory.cc index 9feb0cbd..f5b7bd67 100644 --- a/gpu/command_buffer/service/shared_image/wrapped_sk_image_backing_factory.cc +++ b/gpu/command_buffer/service/shared_image/wrapped_sk_image_backing_factory.cc
@@ -56,7 +56,7 @@ public: WrappedSkImage(base::PassKey<WrappedSkImageBackingFactory>, const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, @@ -233,7 +233,7 @@ return false; context_state_->set_need_context_state_reset(true); - DCHECK_NE(format(), viz::ResourceFormat::ETC1); + DCHECK(!viz::IsResourceFormatCompressed(format())); auto mipmap = usage() & SHARED_IMAGE_USAGE_MIPMAP ? GrMipMapped::kYes : GrMipMapped::kNo; const std::string label = "WrappedSkImageBackingFactory_Initialize" + @@ -281,7 +281,7 @@ return false; context_state_->set_need_context_state_reset(true); - if (format() == viz::ResourceFormat::ETC1) { + if (viz::IsResourceFormatCompressed(format())) { backend_texture_ = context_state_->gr_context()->createCompressedBackendTexture( size().width(), size().height(), SkImage::kETC1_CompressionType, @@ -419,7 +419,7 @@ std::unique_ptr<SharedImageBacking> WrappedSkImageBackingFactory::CreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, SurfaceHandle surface_handle, const gfx::Size& size, const gfx::ColorSpace& color_space, @@ -452,7 +452,7 @@ std::unique_ptr<SharedImageBacking> WrappedSkImageBackingFactory::CreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, @@ -502,7 +502,7 @@ bool WrappedSkImageBackingFactory::IsSupported( uint32_t usage, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, bool thread_safe, gfx::GpuMemoryBufferType gmb_type, @@ -524,7 +524,7 @@ // Currently, WrappedSkImage does not support LUMINANCE_8 format and this // format is used for single channel planes. See https://crbug.com/1252502 for // more details. - if (format == viz::LUMINANCE_8) { + if (format.resource_format() == viz::LUMINANCE_8) { return false; }
diff --git a/gpu/command_buffer/service/shared_image/wrapped_sk_image_backing_factory.h b/gpu/command_buffer/service/shared_image/wrapped_sk_image_backing_factory.h index 16822cc..852087b 100644 --- a/gpu/command_buffer/service/shared_image/wrapped_sk_image_backing_factory.h +++ b/gpu/command_buffer/service/shared_image/wrapped_sk_image_backing_factory.h
@@ -33,7 +33,7 @@ // SharedImageBackingFactory implementation: std::unique_ptr<SharedImageBacking> CreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, SurfaceHandle surface_handle, const gfx::Size& size, const gfx::ColorSpace& color_space, @@ -43,7 +43,7 @@ bool is_thread_safe) override; std::unique_ptr<SharedImageBacking> CreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, @@ -63,7 +63,7 @@ SkAlphaType alpha_type, uint32_t usage) override; bool IsSupported(uint32_t usage, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, bool thread_safe, gfx::GpuMemoryBufferType gmb_type,
diff --git a/gpu/command_buffer/service/webgpu_decoder_impl.cc b/gpu/command_buffer/service/webgpu_decoder_impl.cc index 17cd651..1ad2bde 100644 --- a/gpu/command_buffer/service/webgpu_decoder_impl.cc +++ b/gpu/command_buffer/service/webgpu_decoder_impl.cc
@@ -431,7 +431,7 @@ std::vector<std::string> force_enabled_toggles_; std::vector<std::string> force_disabled_toggles_; bool allow_unsafe_apis_; - blink::ExecutionContextToken execution_context_token_; + blink::WebGPUExecutionContextToken execution_context_token_; std::unique_ptr<dawn::wire::WireServer> wire_server_; std::unique_ptr<DawnServiceSerializer> wire_serializer_; @@ -473,7 +473,7 @@ const DawnProcTable& procs, WGPUDevice device, WGPUTextureUsage usage) { - viz::ResourceFormat format = representation->format(); + viz::ResourceFormat format = (representation->format()).resource_format(); // Include list of formats this is tested to work with. // See gpu/command_buffer/tests/webgpu_mailbox_unittest.cc switch (format) { @@ -573,7 +573,7 @@ DCHECK(texture_); } - bool ComputeStagingBufferParams(viz::ResourceFormat format, + bool ComputeStagingBufferParams(viz::SharedImageFormat format, const gfx::Size& size, uint32_t* bytes_per_row, size_t* buffer_size) const { @@ -1832,33 +1832,26 @@ return error::kNoError; } -error::Error WebGPUDecoderImpl::HandleSetExecutionContextToken( +error::Error WebGPUDecoderImpl::HandleSetWebGPUExecutionContextToken( uint32_t immediate_data_size, const volatile void* cmd_data) { - const volatile webgpu::cmds::SetExecutionContextToken& c = - *static_cast<const volatile webgpu::cmds::SetExecutionContextToken*>( - cmd_data); + const volatile webgpu::cmds::SetWebGPUExecutionContextToken& c = *static_cast< + const volatile webgpu::cmds::SetWebGPUExecutionContextToken*>(cmd_data); uint32_t type(c.type); uint64_t high = uint64_t(c.high_high) << 32 | uint64_t(c.high_low); uint64_t low = uint64_t(c.low_high) << 32 | uint64_t(c.low_low); base::UnguessableToken token = base::UnguessableToken::Deserialize(high, low); switch (type) { - // TODO(dawn:549) LocalFrameToken is a temp solution for initial testing. - // It will not be used in the final product because it can produce - // known races. The use of LocalFrameToken should only be enabled through - // --enable-unsafe-webgpu for now for testing. Once DocumentToken is ready, - // this should be migrated before enabling by default. - case blink::ExecutionContextToken::Base::template TypeIndex< - blink::LocalFrameToken>::kValue: { - DCHECK(enable_unsafe_webgpu_); + case blink::WebGPUExecutionContextToken::Base::template TypeIndex< + blink::DocumentToken>::kValue: { execution_context_token_ = - blink::ExecutionContextToken(blink::LocalFrameToken(token)); + blink::WebGPUExecutionContextToken(blink::DocumentToken(token)); break; } - case blink::ExecutionContextToken::Base::template TypeIndex< + case blink::WebGPUExecutionContextToken::Base::template TypeIndex< blink::DedicatedWorkerToken>::kValue: { - execution_context_token_ = - blink::ExecutionContextToken(blink::DedicatedWorkerToken(token)); + execution_context_token_ = blink::WebGPUExecutionContextToken( + blink::DedicatedWorkerToken(token)); break; } default:
diff --git a/gpu/command_buffer/webgpu_cmd_buffer_functions.txt b/gpu/command_buffer/webgpu_cmd_buffer_functions.txt index 11c30f0c..a0d0351 100644 --- a/gpu/command_buffer/webgpu_cmd_buffer_functions.txt +++ b/gpu/command_buffer/webgpu_cmd_buffer_functions.txt
@@ -11,7 +11,6 @@ GL_APICALL void GL_APIENTRY wgDissociateMailbox (GLuint texture_id, GLuint texture_generation); GL_APICALL void GL_APIENTRY wgDissociateMailboxForPresent (GLuint device_id, GLuint device_generation, GLuint texture_id, GLuint texture_generation); -// The ExecutionContext tokens are represented by two 64 bit uints, but the -// the generator currently only supports 32 bit members so we break the token -// into 4 parts. -GL_APICALL void GL_APIENTRY wgSetExecutionContextToken (uint32_t type, uint32_t high_high, uint32_t high_low, uint32_t low_high, uint32_t low_low); +// The WebGPUExecutionContextTokens are represented by two 64 bit uints, but the +// generator only supports 32 bit members so we break the token into 4 parts. +GL_APICALL void GL_APIENTRY wgSetWebGPUExecutionContextToken (uint32_t type, uint32_t high_high, uint32_t high_low, uint32_t low_high, uint32_t low_low);
diff --git a/gpu/ipc/service/dcomp_texture_win.cc b/gpu/ipc/service/dcomp_texture_win.cc index 6a53866..03294573 100644 --- a/gpu/ipc/service/dcomp_texture_win.cc +++ b/gpu/ipc/service/dcomp_texture_win.cc
@@ -67,15 +67,16 @@ DCOMPTextureBacking(scoped_refptr<gl::DCOMPSurfaceProxy> dcomp_surface_proxy, const Mailbox& mailbox, const gfx::Size& size) - : ClearTrackingSharedImageBacking(mailbox, - viz::BGRA_8888, - size, - gfx::ColorSpace::CreateSRGB(), - kTopLeft_GrSurfaceOrigin, - kPremul_SkAlphaType, - gpu::SHARED_IMAGE_USAGE_SCANOUT, - /*estimated_size=*/0, - /*is_thread_safe=*/false), + : ClearTrackingSharedImageBacking( + mailbox, + viz::SharedImageFormat::SinglePlane(viz::BGRA_8888), + size, + gfx::ColorSpace::CreateSRGB(), + kTopLeft_GrSurfaceOrigin, + kPremul_SkAlphaType, + gpu::SHARED_IMAGE_USAGE_SCANOUT, + /*estimated_size=*/0, + /*is_thread_safe=*/false), dcomp_surface_proxy_(std::move(dcomp_surface_proxy)) { SetCleared(); }
diff --git a/gpu/ipc/service/image_decode_accelerator_stub_unittest.cc b/gpu/ipc/service/image_decode_accelerator_stub_unittest.cc index e5e6cee..9388cf2 100644 --- a/gpu/ipc/service/image_decode_accelerator_stub_unittest.cc +++ b/gpu/ipc/service/image_decode_accelerator_stub_unittest.cc
@@ -141,7 +141,7 @@ // SharedImageBackingFactory implementation. std::unique_ptr<SharedImageBacking> CreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, SurfaceHandle surface_handle, const gfx::Size& size, const gfx::ColorSpace& color_space, @@ -154,7 +154,7 @@ } std::unique_ptr<SharedImageBacking> CreateSharedImage( const Mailbox& mailbox, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, @@ -177,8 +177,9 @@ SkAlphaType alpha_type, uint32_t usage) override { auto test_image_backing = std::make_unique<TestImageBacking>( - mailbox, viz::GetResourceFormat(format), size, color_space, - surface_origin, alpha_type, usage, 0); + mailbox, + viz::SharedImageFormat::SinglePlane(viz::GetResourceFormat(format)), + size, color_space, surface_origin, alpha_type, usage, 0); // If the backing is not cleared, SkiaImageRepresentation errors out // when trying to create the scoped read access. @@ -187,7 +188,7 @@ return std::move(test_image_backing); } bool IsSupported(uint32_t usage, - viz::ResourceFormat format, + viz::SharedImageFormat format, const gfx::Size& size, bool thread_safe, gfx::GpuMemoryBufferType gmb_type,
diff --git "a/infra/config/generated/builders/ci/Cast Android \050dbg\051/properties.json" "b/infra/config/generated/builders/ci/Cast Android \050dbg\051/properties.json" index deedadd..ca5297c3 100644 --- "a/infra/config/generated/builders/ci/Cast Android \050dbg\051/properties.json" +++ "b/infra/config/generated/builders/ci/Cast Android \050dbg\051/properties.json"
@@ -47,10 +47,6 @@ { "builder": "android-x64-cast", "group": "tryserver.chromium.android" - }, - { - "builder": "cast_shell_android", - "group": "tryserver.chromium.android" } ] }
diff --git a/infra/config/generated/builders/ci/Cast Audio Linux/properties.json b/infra/config/generated/builders/ci/Cast Audio Linux/properties.json index 689b367..b2d5ac4f 100644 --- a/infra/config/generated/builders/ci/Cast Audio Linux/properties.json +++ b/infra/config/generated/builders/ci/Cast Audio Linux/properties.json
@@ -40,10 +40,6 @@ ], "mirroring_builder_group_and_names": [ { - "builder": "cast_shell_audio_linux", - "group": "tryserver.chromium.linux" - }, - { "builder": "linux-x64-castos-audio", "group": "tryserver.chromium.linux" }
diff --git a/infra/config/generated/builders/ci/Cast Linux ARM64/properties.json b/infra/config/generated/builders/ci/Cast Linux ARM64/properties.json index 000e7ff..7b38e18 100644 --- a/infra/config/generated/builders/ci/Cast Linux ARM64/properties.json +++ b/infra/config/generated/builders/ci/Cast Linux ARM64/properties.json
@@ -42,10 +42,6 @@ ], "mirroring_builder_group_and_names": [ { - "builder": "cast_shell_linux_arm64", - "group": "tryserver.chromium.linux" - }, - { "builder": "linux-arm64-castos", "group": "tryserver.chromium.linux" }
diff --git a/infra/config/generated/builders/ci/Cast Linux Debug/properties.json b/infra/config/generated/builders/ci/Cast Linux Debug/properties.json index 6e62b72c..9a8e79a 100644 --- a/infra/config/generated/builders/ci/Cast Linux Debug/properties.json +++ b/infra/config/generated/builders/ci/Cast Linux Debug/properties.json
@@ -40,10 +40,6 @@ ], "mirroring_builder_group_and_names": [ { - "builder": "cast_shell_linux_dbg", - "group": "tryserver.chromium.linux" - }, - { "builder": "linux-x64-castos-dbg", "group": "tryserver.chromium.linux" }
diff --git a/infra/config/generated/builders/ci/Cast Linux/properties.json b/infra/config/generated/builders/ci/Cast Linux/properties.json index 3ef8926a..67a2a68 100644 --- a/infra/config/generated/builders/ci/Cast Linux/properties.json +++ b/infra/config/generated/builders/ci/Cast Linux/properties.json
@@ -40,10 +40,6 @@ ], "mirroring_builder_group_and_names": [ { - "builder": "cast_shell_linux", - "group": "tryserver.chromium.linux" - }, - { "builder": "linux-x64-castos", "group": "tryserver.chromium.linux" }
diff --git a/infra/config/generated/builders/reclient/Mac Builder reclient test untrusted/properties.json b/infra/config/generated/builders/reclient/Mac Builder reclient test untrusted/properties.json index a7ec6871..5f0d9c0 100644 --- a/infra/config/generated/builders/reclient/Mac Builder reclient test untrusted/properties.json +++ b/infra/config/generated/builders/reclient/Mac Builder reclient test untrusted/properties.json
@@ -45,6 +45,9 @@ } }, "$build/reclient": { + "bootstrap_env": { + "RBE_ip_timeout": "-1s" + }, "instance": "rbe-chromium-untrusted-test", "metrics_project": "chromium-reclient-metrics" },
diff --git a/infra/config/generated/builders/reclient/Mac Builder reclient test/properties.json b/infra/config/generated/builders/reclient/Mac Builder reclient test/properties.json index 5f60cef..5be9b4b 100644 --- a/infra/config/generated/builders/reclient/Mac Builder reclient test/properties.json +++ b/infra/config/generated/builders/reclient/Mac Builder reclient test/properties.json
@@ -45,6 +45,9 @@ } }, "$build/reclient": { + "bootstrap_env": { + "RBE_ip_timeout": "-1s" + }, "instance": "rbe-chromium-trusted-test", "metrics_project": "chromium-reclient-metrics" },
diff --git a/infra/config/generated/builders/try/cast_shell_android/properties.json b/infra/config/generated/builders/try/cast_shell_android/properties.json deleted file mode 100644 index 89a424c..0000000 --- a/infra/config/generated/builders/try/cast_shell_android/properties.json +++ /dev/null
@@ -1,63 +0,0 @@ -{ - "$build/chromium_tests_builder_config": { - "builder_config": { - "builder_db": { - "entries": [ - { - "builder_id": { - "bucket": "ci", - "builder": "Cast Android (dbg)", - "project": "chromium" - }, - "builder_spec": { - "build_gs_bucket": "chromium-android-archive", - "builder_group": "chromium.android", - "execution_mode": "COMPILE_AND_TEST", - "legacy_android_config": { - "config": "cast_builder" - }, - "legacy_chromium_config": { - "apply_configs": [ - "mb" - ], - "build_config": "Debug", - "config": "android", - "target_bits": 32, - "target_platform": "android" - }, - "legacy_gclient_config": { - "apply_configs": [ - "android", - "enable_reclient" - ], - "config": "chromium" - } - } - } - ] - }, - "builder_ids": [ - { - "bucket": "ci", - "builder": "Cast Android (dbg)", - "project": "chromium" - } - ] - } - }, - "$build/goma": { - "enable_ats": true, - "rpc_extra_params": "?prod", - "server_host": "goma.chromium.org", - "use_luci_auth": true - }, - "$recipe_engine/resultdb/test_presentation": { - "column_keys": [], - "grouping_keys": [ - "status", - "v.test_suite" - ] - }, - "builder_group": "tryserver.chromium.android", - "recipe": "chromium_trybot" -} \ No newline at end of file
diff --git a/infra/config/generated/builders/try/cast_shell_audio_linux/properties.json b/infra/config/generated/builders/try/cast_shell_audio_linux/properties.json deleted file mode 100644 index 9814604d..0000000 --- a/infra/config/generated/builders/try/cast_shell_audio_linux/properties.json +++ /dev/null
@@ -1,62 +0,0 @@ -{ - "$build/chromium_tests_builder_config": { - "builder_config": { - "builder_db": { - "entries": [ - { - "builder_id": { - "bucket": "ci", - "builder": "Cast Audio Linux", - "project": "chromium" - }, - "builder_spec": { - "build_gs_bucket": "chromium-linux-archive", - "builder_group": "chromium.linux", - "execution_mode": "COMPILE_AND_TEST", - "legacy_chromium_config": { - "apply_configs": [ - "mb" - ], - "build_config": "Release", - "config": "chromium_clang", - "target_bits": 64 - }, - "legacy_gclient_config": { - "apply_configs": [ - "enable_reclient" - ], - "config": "chromium" - } - } - } - ] - }, - "builder_ids": [ - { - "bucket": "ci", - "builder": "Cast Audio Linux", - "project": "chromium" - } - ] - } - }, - "$build/goma": { - "enable_ats": true, - "rpc_extra_params": "?prod", - "server_host": "goma.chromium.org", - "use_luci_auth": true - }, - "$build/reclient": { - "instance": "rbe-chromium-untrusted", - "metrics_project": "chromium-reclient-metrics" - }, - "$recipe_engine/resultdb/test_presentation": { - "column_keys": [], - "grouping_keys": [ - "status", - "v.test_suite" - ] - }, - "builder_group": "tryserver.chromium.linux", - "recipe": "chromium_trybot" -} \ No newline at end of file
diff --git a/infra/config/generated/builders/try/cast_shell_linux/properties.json b/infra/config/generated/builders/try/cast_shell_linux/properties.json deleted file mode 100644 index 3ae211c..0000000 --- a/infra/config/generated/builders/try/cast_shell_linux/properties.json +++ /dev/null
@@ -1,62 +0,0 @@ -{ - "$build/chromium_tests_builder_config": { - "builder_config": { - "builder_db": { - "entries": [ - { - "builder_id": { - "bucket": "ci", - "builder": "Cast Linux", - "project": "chromium" - }, - "builder_spec": { - "build_gs_bucket": "chromium-linux-archive", - "builder_group": "chromium.linux", - "execution_mode": "COMPILE_AND_TEST", - "legacy_chromium_config": { - "apply_configs": [ - "mb" - ], - "build_config": "Release", - "config": "chromium_clang", - "target_bits": 64 - }, - "legacy_gclient_config": { - "apply_configs": [ - "enable_reclient" - ], - "config": "chromium" - } - } - } - ] - }, - "builder_ids": [ - { - "bucket": "ci", - "builder": "Cast Linux", - "project": "chromium" - } - ] - } - }, - "$build/goma": { - "enable_ats": true, - "rpc_extra_params": "?prod", - "server_host": "goma.chromium.org", - "use_luci_auth": true - }, - "$build/reclient": { - "instance": "rbe-chromium-untrusted", - "metrics_project": "chromium-reclient-metrics" - }, - "$recipe_engine/resultdb/test_presentation": { - "column_keys": [], - "grouping_keys": [ - "status", - "v.test_suite" - ] - }, - "builder_group": "tryserver.chromium.linux", - "recipe": "chromium_trybot" -} \ No newline at end of file
diff --git a/infra/config/generated/builders/try/cast_shell_linux_arm64/properties.json b/infra/config/generated/builders/try/cast_shell_linux_arm64/properties.json deleted file mode 100644 index 690bfb48..0000000 --- a/infra/config/generated/builders/try/cast_shell_linux_arm64/properties.json +++ /dev/null
@@ -1,64 +0,0 @@ -{ - "$build/chromium_tests_builder_config": { - "builder_config": { - "builder_db": { - "entries": [ - { - "builder_id": { - "bucket": "ci", - "builder": "Cast Linux ARM64", - "project": "chromium" - }, - "builder_spec": { - "build_gs_bucket": "chromium-linux-archive", - "builder_group": "chromium.linux", - "execution_mode": "COMPILE_AND_TEST", - "legacy_chromium_config": { - "apply_configs": [ - "mb" - ], - "build_config": "Release", - "config": "chromium_clang", - "target_arch": "arm", - "target_bits": 64 - }, - "legacy_gclient_config": { - "apply_configs": [ - "arm64", - "enable_reclient" - ], - "config": "chromium" - } - } - } - ] - }, - "builder_ids": [ - { - "bucket": "ci", - "builder": "Cast Linux ARM64", - "project": "chromium" - } - ] - } - }, - "$build/goma": { - "enable_ats": true, - "rpc_extra_params": "?prod", - "server_host": "goma.chromium.org", - "use_luci_auth": true - }, - "$build/reclient": { - "instance": "rbe-chromium-untrusted", - "metrics_project": "chromium-reclient-metrics" - }, - "$recipe_engine/resultdb/test_presentation": { - "column_keys": [], - "grouping_keys": [ - "status", - "v.test_suite" - ] - }, - "builder_group": "tryserver.chromium.linux", - "recipe": "chromium_trybot" -} \ No newline at end of file
diff --git a/infra/config/generated/builders/try/cast_shell_linux_dbg/properties.json b/infra/config/generated/builders/try/cast_shell_linux_dbg/properties.json deleted file mode 100644 index 35131b73..0000000 --- a/infra/config/generated/builders/try/cast_shell_linux_dbg/properties.json +++ /dev/null
@@ -1,62 +0,0 @@ -{ - "$build/chromium_tests_builder_config": { - "builder_config": { - "builder_db": { - "entries": [ - { - "builder_id": { - "bucket": "ci", - "builder": "Cast Linux Debug", - "project": "chromium" - }, - "builder_spec": { - "build_gs_bucket": "chromium-linux-archive", - "builder_group": "chromium.linux", - "execution_mode": "COMPILE_AND_TEST", - "legacy_chromium_config": { - "apply_configs": [ - "mb" - ], - "build_config": "Debug", - "config": "chromium_clang", - "target_bits": 64 - }, - "legacy_gclient_config": { - "apply_configs": [ - "enable_reclient" - ], - "config": "chromium" - } - } - } - ] - }, - "builder_ids": [ - { - "bucket": "ci", - "builder": "Cast Linux Debug", - "project": "chromium" - } - ] - } - }, - "$build/goma": { - "enable_ats": true, - "rpc_extra_params": "?prod", - "server_host": "goma.chromium.org", - "use_luci_auth": true - }, - "$build/reclient": { - "instance": "rbe-chromium-untrusted", - "metrics_project": "chromium-reclient-metrics" - }, - "$recipe_engine/resultdb/test_presentation": { - "column_keys": [], - "grouping_keys": [ - "status", - "v.test_suite" - ] - }, - "builder_group": "tryserver.chromium.linux", - "recipe": "chromium_trybot" -} \ No newline at end of file
diff --git a/infra/config/generated/luci/commit-queue.cfg b/infra/config/generated/luci/commit-queue.cfg index 6039d83..3f89c45 100644 --- a/infra/config/generated/luci/commit-queue.cfg +++ b/infra/config/generated/luci/commit-queue.cfg
@@ -1237,26 +1237,6 @@ } } builders { - name: "chromium/try/cast_shell_android" - includable_only: true - } - builders { - name: "chromium/try/cast_shell_audio_linux" - includable_only: true - } - builders { - name: "chromium/try/cast_shell_linux" - includable_only: true - } - builders { - name: "chromium/try/cast_shell_linux_arm64" - includable_only: true - } - builders { - name: "chromium/try/cast_shell_linux_dbg" - includable_only: true - } - builders { name: "chromium/try/chromeos-amd64-generic-cfi-thin-lto-rel" includable_only: true }
diff --git a/infra/config/generated/luci/cr-buildbucket.cfg b/infra/config/generated/luci/cr-buildbucket.cfg index 38945f3..a95e144 100644 --- a/infra/config/generated/luci/cr-buildbucket.cfg +++ b/infra/config/generated/luci/cr-buildbucket.cfg
@@ -62701,534 +62701,6 @@ description_html: "checks that builder configs in properties files match the recipe-side configs" } builders { - name: "cast_shell_android" - swarming_host: "chromium-swarm.appspot.com" - dimensions: "builder:cast_shell_android" - dimensions: "cores:8" - dimensions: "cpu:x86-64" - dimensions: "os:Ubuntu-18.04" - dimensions: "pool:luci.chromium.try" - exe { - cipd_package: "infra/chromium/bootstrapper/${platform}" - cipd_version: "latest" - cmd: "bootstrapper" - } - properties: - '{' - ' "$bootstrap/exe": {' - ' "exe": {' - ' "cipd_package": "infra/recipe_bundles/chromium.googlesource.com/chromium/tools/build",' - ' "cipd_version": "refs/heads/main",' - ' "cmd": [' - ' "luciexe"' - ' ]' - ' }' - ' },' - ' "$bootstrap/properties": {' - ' "properties_file": "infra/config/generated/builders/try/cast_shell_android/properties.json",' - ' "top_level_project": {' - ' "ref": "refs/heads/main",' - ' "repo": {' - ' "host": "chromium.googlesource.com",' - ' "project": "chromium/src"' - ' }' - ' }' - ' },' - ' "builder_group": "tryserver.chromium.android",' - ' "led_builder_is_bootstrapped": true,' - ' "recipe": "chromium_trybot"' - '}' - execution_timeout_secs: 14400 - expiration_secs: 7200 - grace_period { - seconds: 120 - } - caches { - name: "win_toolchain" - path: "win_toolchain" - } - build_numbers: YES - service_account: "chromium-try-builder@chops-service-accounts.iam.gserviceaccount.com" - task_template_canary_percentage { - value: 5 - } - experiments { - key: "chromium_swarming.expose_merge_script_failures" - value: 20 - } - experiments { - key: "enable_weetbix_queries" - value: 100 - } - experiments { - key: "luci.recipes.use_python3" - value: 100 - } - experiments { - key: "weetbix.enable_weetbix_exonerations" - value: 100 - } - experiments { - key: "weetbix.retry_weak_exonerations" - value: 100 - } - resultdb { - enable: true - bq_exports { - project: "chrome-luci-data" - dataset: "chromium" - table: "try_test_results" - test_results {} - } - bq_exports { - project: "chrome-luci-data" - dataset: "chromium" - table: "gpu_try_test_results" - test_results { - predicate { - test_id_regexp: "ninja://chrome/test:telemetry_gpu_integration_test[^/]*/.+" - } - } - } - bq_exports { - project: "chrome-luci-data" - dataset: "chromium" - table: "blink_web_tests_try_test_results" - test_results { - predicate { - test_id_regexp: "(ninja://[^/]*blink_web_tests/.+)|(ninja://[^/]*blink_wpt_tests/.+)" - } - } - } - history_options { - use_invocation_timestamp: true - } - } - } - builders { - name: "cast_shell_audio_linux" - swarming_host: "chromium-swarm.appspot.com" - dimensions: "builderless:1" - dimensions: "cores:8" - dimensions: "cpu:x86-64" - dimensions: "os:Ubuntu-18.04" - dimensions: "pool:luci.chromium.try" - dimensions: "ssd:0" - exe { - cipd_package: "infra/chromium/bootstrapper/${platform}" - cipd_version: "latest" - cmd: "bootstrapper" - } - properties: - '{' - ' "$bootstrap/exe": {' - ' "exe": {' - ' "cipd_package": "infra/recipe_bundles/chromium.googlesource.com/chromium/tools/build",' - ' "cipd_version": "refs/heads/main",' - ' "cmd": [' - ' "luciexe"' - ' ]' - ' }' - ' },' - ' "$bootstrap/properties": {' - ' "properties_file": "infra/config/generated/builders/try/cast_shell_audio_linux/properties.json",' - ' "top_level_project": {' - ' "ref": "refs/heads/main",' - ' "repo": {' - ' "host": "chromium.googlesource.com",' - ' "project": "chromium/src"' - ' }' - ' }' - ' },' - ' "builder_group": "tryserver.chromium.linux",' - ' "led_builder_is_bootstrapped": true,' - ' "recipe": "chromium_trybot"' - '}' - execution_timeout_secs: 14400 - expiration_secs: 7200 - grace_period { - seconds: 120 - } - caches { - name: "win_toolchain" - path: "win_toolchain" - } - build_numbers: YES - service_account: "chromium-try-builder@chops-service-accounts.iam.gserviceaccount.com" - task_template_canary_percentage { - value: 5 - } - experiments { - key: "chromium_swarming.expose_merge_script_failures" - value: 20 - } - experiments { - key: "enable_weetbix_queries" - value: 100 - } - experiments { - key: "luci.recipes.use_python3" - value: 100 - } - experiments { - key: "weetbix.enable_weetbix_exonerations" - value: 100 - } - experiments { - key: "weetbix.retry_weak_exonerations" - value: 100 - } - resultdb { - enable: true - bq_exports { - project: "chrome-luci-data" - dataset: "chromium" - table: "try_test_results" - test_results {} - } - bq_exports { - project: "chrome-luci-data" - dataset: "chromium" - table: "gpu_try_test_results" - test_results { - predicate { - test_id_regexp: "ninja://chrome/test:telemetry_gpu_integration_test[^/]*/.+" - } - } - } - bq_exports { - project: "chrome-luci-data" - dataset: "chromium" - table: "blink_web_tests_try_test_results" - test_results { - predicate { - test_id_regexp: "(ninja://[^/]*blink_web_tests/.+)|(ninja://[^/]*blink_wpt_tests/.+)" - } - } - } - history_options { - use_invocation_timestamp: true - } - } - } - builders { - name: "cast_shell_linux" - swarming_host: "chromium-swarm.appspot.com" - dimensions: "builder:cast_shell_linux" - dimensions: "cores:8" - dimensions: "cpu:x86-64" - dimensions: "os:Ubuntu-18.04" - dimensions: "pool:luci.chromium.try" - exe { - cipd_package: "infra/chromium/bootstrapper/${platform}" - cipd_version: "latest" - cmd: "bootstrapper" - } - properties: - '{' - ' "$bootstrap/exe": {' - ' "exe": {' - ' "cipd_package": "infra/recipe_bundles/chromium.googlesource.com/chromium/tools/build",' - ' "cipd_version": "refs/heads/main",' - ' "cmd": [' - ' "luciexe"' - ' ]' - ' }' - ' },' - ' "$bootstrap/properties": {' - ' "properties_file": "infra/config/generated/builders/try/cast_shell_linux/properties.json",' - ' "top_level_project": {' - ' "ref": "refs/heads/main",' - ' "repo": {' - ' "host": "chromium.googlesource.com",' - ' "project": "chromium/src"' - ' }' - ' }' - ' },' - ' "builder_group": "tryserver.chromium.linux",' - ' "led_builder_is_bootstrapped": true,' - ' "recipe": "chromium_trybot"' - '}' - execution_timeout_secs: 14400 - expiration_secs: 7200 - grace_period { - seconds: 120 - } - caches { - name: "win_toolchain" - path: "win_toolchain" - } - build_numbers: YES - service_account: "chromium-try-builder@chops-service-accounts.iam.gserviceaccount.com" - task_template_canary_percentage { - value: 5 - } - experiments { - key: "chromium_swarming.expose_merge_script_failures" - value: 20 - } - experiments { - key: "enable_weetbix_queries" - value: 100 - } - experiments { - key: "luci.recipes.use_python3" - value: 100 - } - experiments { - key: "weetbix.enable_weetbix_exonerations" - value: 100 - } - experiments { - key: "weetbix.retry_weak_exonerations" - value: 100 - } - resultdb { - enable: true - bq_exports { - project: "chrome-luci-data" - dataset: "chromium" - table: "try_test_results" - test_results {} - } - bq_exports { - project: "chrome-luci-data" - dataset: "chromium" - table: "gpu_try_test_results" - test_results { - predicate { - test_id_regexp: "ninja://chrome/test:telemetry_gpu_integration_test[^/]*/.+" - } - } - } - bq_exports { - project: "chrome-luci-data" - dataset: "chromium" - table: "blink_web_tests_try_test_results" - test_results { - predicate { - test_id_regexp: "(ninja://[^/]*blink_web_tests/.+)|(ninja://[^/]*blink_wpt_tests/.+)" - } - } - } - history_options { - use_invocation_timestamp: true - } - } - } - builders { - name: "cast_shell_linux_arm64" - swarming_host: "chromium-swarm.appspot.com" - dimensions: "builderless:1" - dimensions: "cores:8" - dimensions: "cpu:x86-64" - dimensions: "os:Ubuntu-18.04" - dimensions: "pool:luci.chromium.try" - dimensions: "ssd:0" - exe { - cipd_package: "infra/chromium/bootstrapper/${platform}" - cipd_version: "latest" - cmd: "bootstrapper" - } - properties: - '{' - ' "$bootstrap/exe": {' - ' "exe": {' - ' "cipd_package": "infra/recipe_bundles/chromium.googlesource.com/chromium/tools/build",' - ' "cipd_version": "refs/heads/main",' - ' "cmd": [' - ' "luciexe"' - ' ]' - ' }' - ' },' - ' "$bootstrap/properties": {' - ' "properties_file": "infra/config/generated/builders/try/cast_shell_linux_arm64/properties.json",' - ' "top_level_project": {' - ' "ref": "refs/heads/main",' - ' "repo": {' - ' "host": "chromium.googlesource.com",' - ' "project": "chromium/src"' - ' }' - ' }' - ' },' - ' "builder_group": "tryserver.chromium.linux",' - ' "led_builder_is_bootstrapped": true,' - ' "recipe": "chromium_trybot"' - '}' - execution_timeout_secs: 14400 - expiration_secs: 7200 - grace_period { - seconds: 120 - } - caches { - name: "win_toolchain" - path: "win_toolchain" - } - build_numbers: YES - service_account: "chromium-try-builder@chops-service-accounts.iam.gserviceaccount.com" - task_template_canary_percentage { - value: 5 - } - experiments { - key: "chromium_swarming.expose_merge_script_failures" - value: 20 - } - experiments { - key: "enable_weetbix_queries" - value: 100 - } - experiments { - key: "luci.recipes.use_python3" - value: 100 - } - experiments { - key: "weetbix.enable_weetbix_exonerations" - value: 100 - } - experiments { - key: "weetbix.retry_weak_exonerations" - value: 100 - } - resultdb { - enable: true - bq_exports { - project: "chrome-luci-data" - dataset: "chromium" - table: "try_test_results" - test_results {} - } - bq_exports { - project: "chrome-luci-data" - dataset: "chromium" - table: "gpu_try_test_results" - test_results { - predicate { - test_id_regexp: "ninja://chrome/test:telemetry_gpu_integration_test[^/]*/.+" - } - } - } - bq_exports { - project: "chrome-luci-data" - dataset: "chromium" - table: "blink_web_tests_try_test_results" - test_results { - predicate { - test_id_regexp: "(ninja://[^/]*blink_web_tests/.+)|(ninja://[^/]*blink_wpt_tests/.+)" - } - } - } - history_options { - use_invocation_timestamp: true - } - } - } - builders { - name: "cast_shell_linux_dbg" - swarming_host: "chromium-swarm.appspot.com" - dimensions: "builderless:1" - dimensions: "cores:8" - dimensions: "cpu:x86-64" - dimensions: "os:Ubuntu-18.04" - dimensions: "pool:luci.chromium.try" - dimensions: "ssd:0" - exe { - cipd_package: "infra/chromium/bootstrapper/${platform}" - cipd_version: "latest" - cmd: "bootstrapper" - } - properties: - '{' - ' "$bootstrap/exe": {' - ' "exe": {' - ' "cipd_package": "infra/recipe_bundles/chromium.googlesource.com/chromium/tools/build",' - ' "cipd_version": "refs/heads/main",' - ' "cmd": [' - ' "luciexe"' - ' ]' - ' }' - ' },' - ' "$bootstrap/properties": {' - ' "properties_file": "infra/config/generated/builders/try/cast_shell_linux_dbg/properties.json",' - ' "top_level_project": {' - ' "ref": "refs/heads/main",' - ' "repo": {' - ' "host": "chromium.googlesource.com",' - ' "project": "chromium/src"' - ' }' - ' }' - ' },' - ' "builder_group": "tryserver.chromium.linux",' - ' "led_builder_is_bootstrapped": true,' - ' "recipe": "chromium_trybot"' - '}' - execution_timeout_secs: 14400 - expiration_secs: 7200 - grace_period { - seconds: 120 - } - caches { - name: "win_toolchain" - path: "win_toolchain" - } - build_numbers: YES - service_account: "chromium-try-builder@chops-service-accounts.iam.gserviceaccount.com" - task_template_canary_percentage { - value: 5 - } - experiments { - key: "chromium_swarming.expose_merge_script_failures" - value: 20 - } - experiments { - key: "enable_weetbix_queries" - value: 100 - } - experiments { - key: "luci.recipes.use_python3" - value: 100 - } - experiments { - key: "weetbix.enable_weetbix_exonerations" - value: 100 - } - experiments { - key: "weetbix.retry_weak_exonerations" - value: 100 - } - resultdb { - enable: true - bq_exports { - project: "chrome-luci-data" - dataset: "chromium" - table: "try_test_results" - test_results {} - } - bq_exports { - project: "chrome-luci-data" - dataset: "chromium" - table: "gpu_try_test_results" - test_results { - predicate { - test_id_regexp: "ninja://chrome/test:telemetry_gpu_integration_test[^/]*/.+" - } - } - } - bq_exports { - project: "chrome-luci-data" - dataset: "chromium" - table: "blink_web_tests_try_test_results" - test_results { - predicate { - test_id_regexp: "(ninja://[^/]*blink_web_tests/.+)|(ninja://[^/]*blink_wpt_tests/.+)" - } - } - } - history_options { - use_invocation_timestamp: true - } - } - } - builders { name: "chromeos-amd64-generic-cfi-thin-lto-rel" swarming_host: "chromium-swarm.appspot.com" dimensions: "builderless:1"
diff --git a/infra/config/generated/luci/luci-milo.cfg b/infra/config/generated/luci/luci-milo.cfg index 061f0ca..ebdeae23 100644 --- a/infra/config/generated/luci/luci-milo.cfg +++ b/infra/config/generated/luci/luci-milo.cfg
@@ -2672,18 +2672,6 @@ name: "buildbucket/luci.chromium.try/builder-config-verifier" } builders { - name: "buildbucket/luci.chromium.try/cast_shell_android" - } - builders { - name: "buildbucket/luci.chromium.try/cast_shell_linux" - } - builders { - name: "buildbucket/luci.chromium.try/cast_shell_linux_arm64" - } - builders { - name: "buildbucket/luci.chromium.try/cast_shell_linux_dbg" - } - builders { name: "buildbucket/luci.chromium.try/chromeos-amd64-generic-dbg" } builders { @@ -16365,21 +16353,6 @@ name: "buildbucket/luci.chromium.try/builder-config-verifier" } builders { - name: "buildbucket/luci.chromium.try/cast_shell_android" - } - builders { - name: "buildbucket/luci.chromium.try/cast_shell_audio_linux" - } - builders { - name: "buildbucket/luci.chromium.try/cast_shell_linux" - } - builders { - name: "buildbucket/luci.chromium.try/cast_shell_linux_arm64" - } - builders { - name: "buildbucket/luci.chromium.try/cast_shell_linux_dbg" - } - builders { name: "buildbucket/luci.chromium.try/chromeos-amd64-generic-cfi-thin-lto-rel" } builders { @@ -17537,9 +17510,6 @@ name: "buildbucket/luci.chromium.try/android_unswarmed_pixel_aosp" } builders { - name: "buildbucket/luci.chromium.try/cast_shell_android" - } - builders { name: "buildbucket/luci.chromium.try/gpu-fyi-try-android-l-nexus-5-32" } builders { @@ -17831,18 +17801,6 @@ id: "tryserver.chromium.linux" name: "tryserver.chromium.linux" builders { - name: "buildbucket/luci.chromium.try/cast_shell_audio_linux" - } - builders { - name: "buildbucket/luci.chromium.try/cast_shell_linux" - } - builders { - name: "buildbucket/luci.chromium.try/cast_shell_linux_arm64" - } - builders { - name: "buildbucket/luci.chromium.try/cast_shell_linux_dbg" - } - builders { name: "buildbucket/luci.chromium.try/gpu-fyi-try-lacros-amd-rel" } builders {
diff --git a/infra/config/generated/luci/project.cfg b/infra/config/generated/luci/project.cfg index c23bdfa..13c2cd0b 100644 --- a/infra/config/generated/luci/project.cfg +++ b/infra/config/generated/luci/project.cfg
@@ -7,7 +7,7 @@ name: "chromium" access: "group:all" lucicfg { - version: "1.32.1" + version: "1.33.2" package_dir: "../.." config_dir: "generated/luci" entry_point: "main.star"
diff --git a/infra/config/subprojects/chromium/try/tryserver.chromium.android.star b/infra/config/subprojects/chromium/try/tryserver.chromium.android.star index 8e78732..898e6a7 100644 --- a/infra/config/subprojects/chromium/try/tryserver.chromium.android.star +++ b/infra/config/subprojects/chromium/try/tryserver.chromium.android.star
@@ -694,16 +694,6 @@ ) try_.builder( - name = "cast_shell_android", - branch_selector = branches.STANDARD_MILESTONE, - mirrors = [ - "ci/Cast Android (dbg)", - ], - builderless = not settings.is_main, - main_list_view = "try", -) - -try_.builder( name = "linux_android_dbg_ng", )
diff --git a/infra/config/subprojects/chromium/try/tryserver.chromium.linux.star b/infra/config/subprojects/chromium/try/tryserver.chromium.linux.star index abec98ae3..d923f42 100644 --- a/infra/config/subprojects/chromium/try/tryserver.chromium.linux.star +++ b/infra/config/subprojects/chromium/try/tryserver.chromium.linux.star
@@ -35,42 +35,6 @@ ) try_.builder( - name = "cast_shell_audio_linux", - mirrors = [ - "ci/Cast Audio Linux", - ], -) - -try_.builder( - name = "cast_shell_linux", - branch_selector = branches.STANDARD_MILESTONE, - mirrors = [ - "ci/Cast Linux", - ], - builderless = not settings.is_main, - main_list_view = "try", -) - -try_.builder( - name = "cast_shell_linux_dbg", - branch_selector = branches.STANDARD_MILESTONE, - mirrors = [ - "ci/Cast Linux Debug", - ], - main_list_view = "try", -) - -try_.builder( - name = "cast_shell_linux_arm64", - branch_selector = branches.MAIN, - mirrors = [ - "ci/Cast Linux ARM64", - ], - main_list_view = "try", - os = os.LINUX_BIONIC, -) - -try_.builder( name = "layout_test_leak_detection", mirrors = [ "ci/WebKit Linux Leak",
diff --git a/infra/config/subprojects/reclient/reclient.star b/infra/config/subprojects/reclient/reclient.star index 74a1410..25bf0a6 100644 --- a/infra/config/subprojects/reclient/reclient.star +++ b/infra/config/subprojects/reclient/reclient.star
@@ -188,6 +188,9 @@ builderless = True, cores = None, priority = 35, + reclient_bootstrap_env = { + "RBE_ip_timeout": "-1s", + }, ) fyi_reclient_staging_builder(
diff --git a/ios/chrome/app/BUILD.gn b/ios/chrome/app/BUILD.gn index c9f13f7..d4fda56 100644 --- a/ios/chrome/app/BUILD.gn +++ b/ios/chrome/app/BUILD.gn
@@ -443,6 +443,7 @@ "//ios/chrome/browser/ui/download", "//ios/chrome/browser/ui/first_run", "//ios/chrome/browser/ui/first_run:utils", + "//ios/chrome/browser/ui/keyboard:features", "//ios/chrome/browser/ui/main", "//ios/chrome/browser/ui/main:scene", "//ios/chrome/browser/ui/main:scene_state_header",
diff --git a/ios/chrome/app/main_application_delegate.h b/ios/chrome/app/main_application_delegate.h index d079abd..b284635 100644 --- a/ios/chrome/app/main_application_delegate.h +++ b/ios/chrome/app/main_application_delegate.h
@@ -10,7 +10,7 @@ @class AppState; // The main delegate of the application. -@interface MainApplicationDelegate : NSObject<UIApplicationDelegate> +@interface MainApplicationDelegate : UIResponder <UIApplicationDelegate> // Handles the application stage changes. @property(nonatomic, strong) AppState* appState;
diff --git a/ios/chrome/app/main_application_delegate.mm b/ios/chrome/app/main_application_delegate.mm index 4ab79d0..ee828d2 100644 --- a/ios/chrome/app/main_application_delegate.mm +++ b/ios/chrome/app/main_application_delegate.mm
@@ -27,6 +27,7 @@ #import "ios/chrome/browser/download/background_service/background_download_service_factory.h" #import "ios/chrome/browser/push_notification/push_notification_delegate.h" #import "ios/chrome/browser/push_notification/push_notification_util.h" +#import "ios/chrome/browser/ui/keyboard/features.h" #import "ios/chrome/browser/ui/main/scene_controller.h" #import "ios/chrome/browser/ui/main/scene_delegate.h" #import "ios/chrome/browser/ui/main/scene_state.h" @@ -372,6 +373,16 @@ } } +#pragma mark - UIResponder methods + +- (void)buildMenuWithBuilder:(id<UIMenuBuilder>)builder { + [super buildMenuWithBuilder:builder]; + + if (IsKeyboardShortcutsMenuEnabled()) { + // TODO(crbug.com/1371848): Build the menu. + } +} + #pragma mark - Testing methods + (AppState*)sharedAppState {
diff --git a/ios/chrome/browser/flags/BUILD.gn b/ios/chrome/browser/flags/BUILD.gn index 3ccf600..f62a35f 100644 --- a/ios/chrome/browser/flags/BUILD.gn +++ b/ios/chrome/browser/flags/BUILD.gn
@@ -73,6 +73,7 @@ "//ios/chrome/browser/ui/first_run:field_trial", "//ios/chrome/browser/ui/first_run:field_trial_constants", "//ios/chrome/browser/ui/fullscreen:feature_flags", + "//ios/chrome/browser/ui/keyboard:features", "//ios/chrome/browser/ui/ntp:feature_flags", "//ios/chrome/browser/ui/omnibox:features", "//ios/chrome/browser/ui/open_in:features",
diff --git a/ios/chrome/browser/flags/about_flags.mm b/ios/chrome/browser/flags/about_flags.mm index 7b0f8f4..de7d78cf 100644 --- a/ios/chrome/browser/flags/about_flags.mm +++ b/ios/chrome/browser/flags/about_flags.mm
@@ -84,6 +84,7 @@ #import "ios/chrome/browser/ui/first_run/field_trial_constants.h" #import "ios/chrome/browser/ui/first_run/trending_queries_field_trial.h" #import "ios/chrome/browser/ui/fullscreen/fullscreen_features.h" +#import "ios/chrome/browser/ui/keyboard/features.h" #import "ios/chrome/browser/ui/ntp/new_tab_page_feature.h" #import "ios/chrome/browser/ui/omnibox/omnibox_ui_features.h" #import "ios/chrome/browser/ui/open_in/features.h" @@ -1244,6 +1245,9 @@ flag_descriptions::kAppStoreRatingIgnoreEligibilityCheckTestDescription, flags_ui::kOsIos, FEATURE_VALUE_TYPE(kAppStoreRatingIgnoreEligibilityCheckTest)}, + {"keyboard-shortcuts-menu", flag_descriptions::kKeyboardShortcutsMenuName, + flag_descriptions::kKeyboardShortcutsMenuDescription, flags_ui::kOsIos, + FEATURE_VALUE_TYPE(kKeyboardShortcutsMenu)}, }; bool SkipConditionalFeatureEntry(const flags_ui::FeatureEntry& entry) {
diff --git a/ios/chrome/browser/flags/ios_chrome_flag_descriptions.cc b/ios/chrome/browser/flags/ios_chrome_flag_descriptions.cc index e0d18b76..e2e6045a 100644 --- a/ios/chrome/browser/flags/ios_chrome_flag_descriptions.cc +++ b/ios/chrome/browser/flags/ios_chrome_flag_descriptions.cc
@@ -443,6 +443,10 @@ "Enables improvements to text fragments UI, including a menu for removing " "or resharing a highlight."; +const char kKeyboardShortcutsMenuName[] = "Keyboard Shortcuts Menu"; +const char kKeyboardShortcutsMenuDescription[] = + "Enables the new keyboard shortcuts menu."; + const char kLockBottomToolbarName[] = "Lock bottom toolbar"; const char kLockBottomToolbarDescription[] = "When enabled, the bottom toolbar will not get collapsed when scrolling "
diff --git a/ios/chrome/browser/flags/ios_chrome_flag_descriptions.h b/ios/chrome/browser/flags/ios_chrome_flag_descriptions.h index 53b39e37..425ca325 100644 --- a/ios/chrome/browser/flags/ios_chrome_flag_descriptions.h +++ b/ios/chrome/browser/flags/ios_chrome_flag_descriptions.h
@@ -398,6 +398,10 @@ extern const char kIOSSharedHighlightingV2Name[]; extern const char kIOSSharedHighlightingV2Description[]; +// Title and description for the flag to enable Keyboard Shortcuts Refresh. +extern const char kKeyboardShortcutsMenuName[]; +extern const char kKeyboardShortcutsMenuDescription[]; + // Title and description for the flag to lock the bottom toolbar into place. extern const char kLockBottomToolbarName[]; extern const char kLockBottomToolbarDescription[];
diff --git a/ios/chrome/browser/ui/autofill/chrome_autofill_client_ios.mm b/ios/chrome/browser/ui/autofill/chrome_autofill_client_ios.mm index fc7c527e..00eadb7 100644 --- a/ios/chrome/browser/ui/autofill/chrome_autofill_client_ios.mm +++ b/ios/chrome/browser/ui/autofill/chrome_autofill_client_ios.mm
@@ -150,7 +150,7 @@ } PrefService* ChromeAutofillClientIOS::GetPrefs() { - return const_cast<PrefService*>(base::as_const(*this).GetPrefs()); + return const_cast<PrefService*>(std::as_const(*this).GetPrefs()); } const PrefService* ChromeAutofillClientIOS::GetPrefs() const {
diff --git a/ios/chrome/browser/ui/content_suggestions/ntp_home_egtest.mm b/ios/chrome/browser/ui/content_suggestions/ntp_home_egtest.mm index 9ad7c04..9106f7d 100644 --- a/ios/chrome/browser/ui/content_suggestions/ntp_home_egtest.mm +++ b/ios/chrome/browser/ui/content_suggestions/ntp_home_egtest.mm
@@ -874,8 +874,7 @@ // Test to ensure that feed can be enabled/disabled and that feed header changes // accordingly. -// TODO(crbug.com/1194106): Failing on official ios canary. -- (void)DISABLED_testToggleFeedEnabled { +- (void)testToggleFeedEnabled { // Ensure that label is visible with correct text for enabled feed, and that // the NTP is scrollable. [self checkFeedLabelForFeedVisible:YES];
diff --git a/ios/chrome/browser/ui/infobars/translate_infobar_egtest.mm b/ios/chrome/browser/ui/infobars/translate_infobar_egtest.mm index 78a5755..819c70d 100644 --- a/ios/chrome/browser/ui/infobars/translate_infobar_egtest.mm +++ b/ios/chrome/browser/ui/infobars/translate_infobar_egtest.mm
@@ -900,8 +900,7 @@ // Tests that the "Never Translate this site" option dismisses the infobar and // updates the prefs accordingly. -// TODO(crbug.com/1352108): Re-enable -- (void)DISABLED_testInfobarNeverTranslateSite { +- (void)testInfobarNeverTranslateSite { // Start the HTTP server. std::unique_ptr<web::DataResponseProvider> provider(new TestResponseProvider); web::test::SetUpHttpServer(std::move(provider));
diff --git a/ios/chrome/browser/ui/keyboard/BUILD.gn b/ios/chrome/browser/ui/keyboard/BUILD.gn index cb4b15e..fe7b376 100644 --- a/ios/chrome/browser/ui/keyboard/BUILD.gn +++ b/ios/chrome/browser/ui/keyboard/BUILD.gn
@@ -14,6 +14,15 @@ ] } +source_set("features") { + configs += [ "//build/config/compiler:enable_arc" ] + sources = [ + "features.h", + "features.mm", + ] + deps = [ "//base" ] +} + source_set("unit_tests") { configs += [ "//build/config/compiler:enable_arc" ] testonly = true
diff --git a/ios/chrome/browser/ui/keyboard/features.h b/ios/chrome/browser/ui/keyboard/features.h new file mode 100644 index 0000000..fe51433e --- /dev/null +++ b/ios/chrome/browser/ui/keyboard/features.h
@@ -0,0 +1,16 @@ +// 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 IOS_CHROME_BROWSER_UI_KEYBOARD_FEATURES_H_ +#define IOS_CHROME_BROWSER_UI_KEYBOARD_FEATURES_H_ + +#import "base/feature_list.h" + +// Feature flag to enable the Keyboard Shortcuts Menu feature. +BASE_DECLARE_FEATURE(kKeyboardShortcutsMenu); + +// Returns true if the Keyboard Shortcuts Menu feature is enabled. +bool IsKeyboardShortcutsMenuEnabled(); + +#endif // IOS_CHROME_BROWSER_UI_KEYBOARD_FEATURES_H_
diff --git a/ios/chrome/browser/ui/keyboard/features.mm b/ios/chrome/browser/ui/keyboard/features.mm new file mode 100644 index 0000000..7733575 --- /dev/null +++ b/ios/chrome/browser/ui/keyboard/features.mm
@@ -0,0 +1,17 @@ +// 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/chrome/browser/ui/keyboard/features.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +BASE_FEATURE(kKeyboardShortcutsMenu, + "KeyboardShortcutsMenu", + base::FEATURE_DISABLED_BY_DEFAULT); + +bool IsKeyboardShortcutsMenuEnabled() { + return base::FeatureList::IsEnabled(kKeyboardShortcutsMenu); +}
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 71aa479..777497d 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 @@ -490be485010d289ecf1600b0232ffcfda4e1d268 \ No newline at end of file +072d76ea235b4525e9d722cf7163fdd7bcdd71b8 \ 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 66090d7..957be1c1 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 @@ -26a44587d98ea4be26e85531f0b3d6c599f483a8 \ No newline at end of file +04038a55a02f067f00452e84c9efff63e26c6e3f \ 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 0fe311c9..f624219 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 @@ -c77764ea47ba841ff5246a80e90445d87d41c20c \ No newline at end of file +26a9a573cc7de73d94c4725c7fa0916bce80ec84 \ 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 c4029e8..d521883 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 @@ -2614068616371cb82253c4c9ba9312d1d5b68f34 \ No newline at end of file +f70638735b9e2c44a566db433c895fb786d7586e \ 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 9ca1414..61b1644 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 @@ -407dafe4db3134a6750ea087c38aa0bccfd666a1 \ No newline at end of file +655a9fe4a13b9ad51e12bf0b4da13d2a8a971bcb \ 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 15766587..8de7e8e6 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 @@ -10c24e38298e82748ea0dbb6edbc85506751e29e \ No newline at end of file +953d5ae8706d287b6ac0042df2f55474ac9dbfa6 \ 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 dfe59fc..51934e1 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 @@ -a815f1425df18850b2b157979ddc233dece9ea24 \ No newline at end of file +e19891419e30221830b63142220aea6679de3bbc \ 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 93cc89b..58eb43c 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 @@ -3830e882cbc9d1b95664fa33908c20caf5829ea8 \ No newline at end of file +4be852c3b0d009a8e9ddd4e5af59e6020a2c762b \ No newline at end of file
diff --git a/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.ios.zip.sha1 b/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.ios.zip.sha1 index 5ba44f69..f502fb2e 100644 --- a/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.ios.zip.sha1 +++ b/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.ios.zip.sha1
@@ -1 +1 @@ -e23b8267277d58a57c91db874ad8d55e0d8435ee \ No newline at end of file +a393c4c1105b5f9944273cba650096a0cdc447f2 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.iossimulator.zip.sha1 b/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.iossimulator.zip.sha1 index 908c53f..f66ceebb 100644 --- a/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.iossimulator.zip.sha1 +++ b/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.iossimulator.zip.sha1
@@ -1 +1 @@ -a0e07f8715e49ed4fea16613da9cc39f8bfb3c9d \ No newline at end of file +f7d2006a625187702b37c847dc0c71c28ee2700e \ 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 ac609700..99c2254 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 @@ -3f8d750ab682d5afe4a547dd351529a7ce07c817 \ No newline at end of file +1be78f3a9b3a993be29034eb90b3c5d6d4744b0e \ 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 11b3f91..0fe399e8a 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 @@ -5acefaf67b3758e17eedef97323768ab7ad9c8f1 \ No newline at end of file +033996c4ff9c6b605522ac37725d76c76539fbe9 \ 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 506b2ee..92c6118 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 @@ -1b10818dd6e4105bddc7bb13ff63edb63ecc5e76 \ No newline at end of file +a797ef05385929d54c6e22ee0cf11645695893cc \ 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 ca36b44..182ef03 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 @@ -f279d7ae0018ccf934e10b33c3bf4453eed82fe3 \ No newline at end of file +c58967935392871fab656ef6cf2d2f8740deb3fa \ No newline at end of file
diff --git a/ios/web/js_messaging/java_script_feature.mm b/ios/web/js_messaging/java_script_feature.mm index d872374..a228106b 100644 --- a/ios/web/js_messaging/java_script_feature.mm +++ b/ios/web/js_messaging/java_script_feature.mm
@@ -160,7 +160,7 @@ } return base::BindRepeating(&JavaScriptFeature::ScriptMessageReceived, - weak_factory_.GetWeakPtr()); + weak_factory_.GetMutableWeakPtr()); } void JavaScriptFeature::ScriptMessageReceived(WebState* web_state,
diff --git a/ios/web_view/internal/autofill/web_view_autofill_client_ios.mm b/ios/web_view/internal/autofill/web_view_autofill_client_ios.mm index 9942ee3..002f13f2 100644 --- a/ios/web_view/internal/autofill/web_view_autofill_client_ios.mm +++ b/ios/web_view/internal/autofill/web_view_autofill_client_ios.mm
@@ -116,7 +116,7 @@ } PrefService* WebViewAutofillClientIOS::GetPrefs() { - return const_cast<PrefService*>(base::as_const(*this).GetPrefs()); + return const_cast<PrefService*>(std::as_const(*this).GetPrefs()); } const PrefService* WebViewAutofillClientIOS::GetPrefs() const {
diff --git a/media/formats/hls/source_string.h b/media/formats/hls/source_string.h index 5cb6b80..f3c1de8 100644 --- a/media/formats/hls/source_string.h +++ b/media/formats/hls/source_string.h
@@ -120,26 +120,6 @@ ResolutionState resolution_state_; }; -// `SourceLineIterator` may not create resolved source strings -template <> -ResolvedSourceString ResolvedSourceString::Create( - base::PassKey<SourceLineIterator>, - size_t line, - base::StringPiece str) = delete; - -// `VariableDictionary` may not create unresolved source strings -template <> -SourceString SourceString::Create(base::PassKey<VariableDictionary>, - size_t line, - size_t column, - base::StringPiece str, - SourceStringState resolution_state) = delete; - -// Resolved source strings may not skip variable substitution -template <> -ResolvedSourceString ResolvedSourceString::SkipVariableSubstitution() const = - delete; - // Exposes a line-based iteration API over the source text of an HLS manifest. struct MEDIA_EXPORT SourceLineIterator { explicit SourceLineIterator(base::StringPiece source);
diff --git a/media/gpu/mac/vt_video_decode_accelerator_mac.cc b/media/gpu/mac/vt_video_decode_accelerator_mac.cc index fd9133b..b3b3a4a4 100644 --- a/media/gpu/mac/vt_video_decode_accelerator_mac.cc +++ b/media/gpu/mac/vt_video_decode_accelerator_mac.cc
@@ -2229,9 +2229,10 @@ } auto shared_image = std::make_unique<gpu::GLImageBacking>( - gl_image, mailbox, viz_resource_format, plane_size, color_space, - kTopLeft_GrSurfaceOrigin, kOpaque_SkAlphaType, shared_image_usage, - gl_params, gl_client_.is_passthrough); + gl_image, mailbox, + viz::SharedImageFormat::SinglePlane(viz_resource_format), plane_size, + color_space, kTopLeft_GrSurfaceOrigin, kOpaque_SkAlphaType, + shared_image_usage, gl_params, gl_client_.is_passthrough); const bool success = shared_image_stub->factory()->RegisterBacking( std::move(shared_image));
diff --git a/media/gpu/v4l2/v4l2_video_decoder_delegate_av1.cc b/media/gpu/v4l2/v4l2_video_decoder_delegate_av1.cc index dce3e40..fc619a98 100644 --- a/media/gpu/v4l2/v4l2_video_decoder_delegate_av1.cc +++ b/media/gpu/v4l2/v4l2_video_decoder_delegate_av1.cc
@@ -572,8 +572,8 @@ frame_header.buffer_removal_time); v4l2_frame_params.refresh_frame_flags = frame_header.refresh_frame_flags; - // TODO(b/248602457): enable code for |reference_frame_index| after - // frame_number() is implemented for |ref_frames|. + // TODO(b/248602457): Enable code for |order_hints| setup + // after |ref_order_hint| maintenance is implemented. // These params looks duplicated with |ref_frame_idx|, but they are required // and used when |frame_refs_short_signaling| is set according to the AV1 @@ -583,8 +583,13 @@ v4l2_frame_params.gold_frame_idx = frame_header.reference_frame_index[libgav1::kReferenceFrameGolden]; - // TODO(b/248602457): enable code for |reference_frame_index| after - // frame_number() is implemented for |ref_frames|. + for (size_t i = 0; i < libgav1::kNumReferenceFrameTypes; ++i) { + const auto* v4l2_ref_pic = + static_cast<const V4L2AV1Picture*>(ref_frames[i].get()); + + v4l2_frame_params.reference_frame_ts[i] = + v4l2_ref_pic->dec_surface()->GetReferenceID(); + } static_assert(std::size(decltype(v4l2_frame_params.ref_frame_idx){}) == libgav1::kNumInterReferenceFrameTypes,
diff --git a/mojo/public/tools/bindings/mojom_bindings_generator.py b/mojo/public/tools/bindings/mojom_bindings_generator.py index d1a5c7e..5a5cace 100755 --- a/mojo/public/tools/bindings/mojom_bindings_generator.py +++ b/mojo/public/tools/bindings/mojom_bindings_generator.py
@@ -414,6 +414,10 @@ if __name__ == "__main__": with crbug_1001171.DumpStateOnLookupError(): + ret = main() # Exit without running GC, which can save multiple seconds due to the large - # number of object created. - os._exit(main()) + # number of object created. But flush is necessary as os._exit doesn't do + # that. + sys.stdout.flush() + sys.stderr.flush() + os._exit(ret)
diff --git a/mojo/public/tools/mojom/mojom_parser.py b/mojo/public/tools/mojom/mojom_parser.py index 06918e7..00543b5b 100755 --- a/mojo/public/tools/mojom/mojom_parser.py +++ b/mojo/public/tools/mojom/mojom_parser.py
@@ -495,5 +495,8 @@ if __name__ == '__main__': Run(sys.argv[1:]) # Exit without running GC, which can save multiple seconds due to the large - # number of object created. + # number of object created. But flush is necessary as os._exit doesn't do + # that. + sys.stdout.flush() + sys.stderr.flush() os._exit(0)
diff --git a/net/base/features.cc b/net/base/features.cc index 9bea5282..1dc8c29 100644 --- a/net/base/features.cc +++ b/net/base/features.cc
@@ -390,4 +390,8 @@ "CaseInsensitiveCookiePrefix", base::FEATURE_ENABLED_BY_DEFAULT); +BASE_FEATURE(kEnableWebsocketsOverHttp3, + "EnableWebsocketsOverHttp3", + base::FEATURE_DISABLED_BY_DEFAULT); + } // namespace net::features
diff --git a/net/base/features.h b/net/base/features.h index d754a2a..223318a 100644 --- a/net/base/features.h +++ b/net/base/features.h
@@ -477,6 +477,8 @@ NET_EXPORT BASE_DECLARE_FEATURE(kCaseInsensitiveCookiePrefix); +NET_EXPORT BASE_DECLARE_FEATURE(kEnableWebsocketsOverHttp3); + } // namespace net::features #endif // NET_BASE_FEATURES_H_
diff --git a/net/base/isolation_info_unittest.cc b/net/base/isolation_info_unittest.cc index 5cf5c4d..2b5b8a2 100644 --- a/net/base/isolation_info_unittest.cc +++ b/net/base/isolation_info_unittest.cc
@@ -68,8 +68,8 @@ IsolationInfoEnabledFeatureFlagsTestingParam> { public: IsolationInfoTest() { - std::vector<base::Feature> enabled_features = {}; - std::vector<base::Feature> disabled_features = {}; + std::vector<base::test::FeatureRef> enabled_features = {}; + std::vector<base::test::FeatureRef> disabled_features = {}; if (IsDoubleKeyIsolationInfoEnabled()) { enabled_features.push_back(
diff --git a/net/base/network_anonymization_key_unittest.cc b/net/base/network_anonymization_key_unittest.cc index 838ef56..c97937f 100644 --- a/net/base/network_anonymization_key_unittest.cc +++ b/net/base/network_anonymization_key_unittest.cc
@@ -51,8 +51,8 @@ public testing::WithParamInterface<EnabledFeatureFlagsTestingParam> { public: void SetUp() override { - std::vector<base::Feature> enabled_features = {}; - std::vector<base::Feature> disabled_features = {}; + std::vector<base::test::FeatureRef> enabled_features = {}; + std::vector<base::test::FeatureRef> disabled_features = {}; if (IsDoubleKeyNetworkIsolationKeyEnabled()) { enabled_features.push_back( @@ -679,4 +679,4 @@ &expected_failure_nak)); } -} // namespace net \ No newline at end of file +} // namespace net
diff --git a/net/base/url_util.cc b/net/base/url_util.cc index d2a28b0..7255bb01 100644 --- a/net/base/url_util.cc +++ b/net/base/url_util.cc
@@ -20,7 +20,6 @@ #include "base/strings/utf_string_conversions.h" #include "net/base/ip_address.h" #include "net/base/registry_controlled_domains/registry_controlled_domain.h" -#include "third_party/abseil-cpp/absl/types/optional.h" #include "url/gurl.h" #include "url/scheme_host_port.h" #include "url/url_canon.h" @@ -78,14 +77,10 @@ GURL AppendOrReplaceQueryParameter(const GURL& url, const std::string& name, - absl::optional<base::StringPiece> value) { + const std::string& value) { bool replaced = false; std::string param_name = base::EscapeQueryParamValue(name, true); - bool should_keep_param = value.has_value(); - - std::string param_value; - if (should_keep_param) - param_value = base::EscapeQueryParamValue(value.value(), true); + std::string param_value = base::EscapeQueryParamValue(value, true); const std::string input = url.query(); url::Component cursor(0, input.size()); @@ -99,11 +94,7 @@ // Check |replaced| as only the first pair should be replaced. if (!replaced && key == param_name) { replaced = true; - if (!should_keep_param) - continue; - key_value_pair = (param_name + "=" + param_value); - } else { key_value_pair.assign(input, key_range.begin, value_range.end() - key_range.begin); @@ -113,7 +104,7 @@ output += key_value_pair; } - if (!replaced && should_keep_param) { + if (!replaced) { if (!output.empty()) output += "&";
diff --git a/net/base/url_util.h b/net/base/url_util.h index bc1f761..4148aeb 100644 --- a/net/base/url_util.h +++ b/net/base/url_util.h
@@ -14,7 +14,6 @@ #include "base/strings/string_piece.h" #include "net/base/net_export.h" -#include "third_party/abseil-cpp/absl/types/optional.h" #include "url/third_party/mozilla/url_parse.h" class GURL; @@ -41,10 +40,9 @@ const std::string& value); // Returns a new GURL by appending or replacing the given query parameter name -// and the value. If `name` appears more than once, only the first name-value +// and the value. If |name| appears more than once, only the first name-value // pair is replaced. Unsafe characters in the name and the value are escaped // like %XX%XX. The original query component is preserved if it's present. -// Using `absl::nullopt` for `value` will remove the `name` parameter. // // Examples: // @@ -54,13 +52,9 @@ // AppendOrReplaceQueryParameter( // GURL("http://example.com?x=y&name=old"), "name", "new").spec() // => "http://example.com?x=y&name=new" -// AppendOrReplaceQueryParameter( -// GURL("http://example.com?x=y&name=old"), "name", absl::nullopt).spec() -// => "http://example.com?x=y&" -NET_EXPORT GURL -AppendOrReplaceQueryParameter(const GURL& url, - const std::string& name, - absl::optional<base::StringPiece> value); +NET_EXPORT GURL AppendOrReplaceQueryParameter(const GURL& url, + const std::string& name, + const std::string& value); // Iterates over the key-value pairs in the query portion of |url|. // NOTE: QueryIterator stores reference to |url| and creates base::StringPiece
diff --git a/net/base/url_util_unittest.cc b/net/base/url_util_unittest.cc index 3c5ee04..ea5d7eed 100644 --- a/net/base/url_util_unittest.cc +++ b/net/base/url_util_unittest.cc
@@ -9,7 +9,6 @@ #include "base/format_macros.h" #include "base/strings/utf_string_conversions.h" #include "testing/gtest/include/gtest/gtest.h" -#include "third_party/abseil-cpp/absl/types/optional.h" #include "url/gurl.h" #include "url/scheme_host_port.h" #include "url/url_util.h" @@ -81,7 +80,7 @@ GURL("http://example.com/path?name=old&existing=one&name=old"), "name", "new").spec()); - // Preserve the content of the original params regardless of our failure to + // Preserve the content of the original params regarless of our failure to // interpret them correctly. EXPECT_EQ("http://example.com/path?bar&name=new&left=&" "=right&=&&name=again", @@ -89,78 +88,6 @@ GURL("http://example.com/path?bar&name=old&left=&" "=right&=&&name=again"), "name", "new").spec()); - - // ----- Removing the key using nullopt value ----- - - // Removes the name-value pair from the URL preserving other query parameters. - EXPECT_EQ("http://example.com/path?abc=xyz", - AppendOrReplaceQueryParameter( - GURL("http://example.com/path?name=value&abc=xyz"), "name", - absl::nullopt) - .spec()); - - // Removes the name-value pair from the URL. - EXPECT_EQ("http://example.com/path?", - AppendOrReplaceQueryParameter( - GURL("http://example.com/path?existing=one"), "existing", - absl::nullopt) - .spec()); - - // Removes the first name-value pair. - EXPECT_EQ("http://example.com/path?c=d&e=f", - AppendOrReplaceQueryParameter( - GURL("http://example.com/path?a=b&c=d&e=f"), "a", absl::nullopt) - .spec()); - - // Removes a name-value pair in between two query params. - EXPECT_EQ( - "http://example.com/path?existing=one&hello=world", - AppendOrReplaceQueryParameter( - GURL("http://example.com/path?existing=one&replace=sure&hello=world"), - "replace", absl::nullopt) - .spec()); - - // Removes the last name-value pair. - EXPECT_EQ("http://example.com/path?existing=one", - AppendOrReplaceQueryParameter( - GURL("http://example.com/path?existing=one&replace=sure"), - "replace", absl::nullopt) - .spec()); - - // Removing a name-value pair with unsafe characters included. The - // unsafe characters should be escaped. - EXPECT_EQ("http://example.com/path?existing=one&hello=world", - AppendOrReplaceQueryParameter( - GURL("http://example.com/" - "path?existing=one&na+me=v.alue%3D&hello=world"), - "na me", absl::nullopt) - .spec()); - - // Does nothing if the provided query param key does not exist. - EXPECT_EQ("http://example.com/path?existing=one&name=old", - AppendOrReplaceQueryParameter( - GURL("http://example.com/path?existing=one&name=old"), "old", - absl::nullopt) - .spec()); - - // Remove the value of first parameter with this name only. - EXPECT_EQ( - "http://example.com/path?existing=one&name=old", - AppendOrReplaceQueryParameter( - GURL("http://example.com/path?name=something&existing=one&name=old"), - "name", absl::nullopt) - .spec()); - - // Preserve the content of the original params regardless of our failure to - // interpret them correctly. - EXPECT_EQ( - "http://example.com/path?bar&left=&" - "=right&=&&name=again", - AppendOrReplaceQueryParameter( - GURL("http://example.com/path?bar&name=old&left=&" - "=right&=&&name=again"), - "name", absl::nullopt) - .spec()); } TEST(UrlUtilTest, GetValueForKeyInQuery) {
diff --git a/net/cert/internal/trust_store_chrome_unittest.cc b/net/cert/internal/trust_store_chrome_unittest.cc index 14a14e0..ad58476 100644 --- a/net/cert/internal/trust_store_chrome_unittest.cc +++ b/net/cert/internal/trust_store_chrome_unittest.cc
@@ -48,9 +48,11 @@ EXPECT_EQ(CertificateTrustType::TRUSTED_ANCHOR, trust.type); } - // Other certificates should not be included. + // Other certificates should not be included. Which test cert used here isn't + // important as long as it isn't one of the certificates in the + // chrome_root_store/test_store.certs. scoped_refptr<X509Certificate> other_cert = - ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem"); + ImportCertFromFile(GetTestCertsDirectory(), "root_ca_cert.pem"); ASSERT_TRUE(other_cert); scoped_refptr<ParsedCertificate> other_parsed = ToParsedCertificate(*other_cert);
diff --git a/net/cookies/cookie_partition_key_unittest.cc b/net/cookies/cookie_partition_key_unittest.cc index f2657a4..02712c6 100644 --- a/net/cookies/cookie_partition_key_unittest.cc +++ b/net/cookies/cookie_partition_key_unittest.cc
@@ -188,8 +188,8 @@ SCOPED_TRACE(test_case.desc); base::test::ScopedFeatureList feature_list; - std::vector<base::Feature> enabled_features; - std::vector<base::Feature> disabled_features; + std::vector<base::test::FeatureRef> enabled_features; + std::vector<base::test::FeatureRef> disabled_features; if (PartitionedCookiesEnabled()) { enabled_features.push_back(features::kPartitionedCookies); } else {
diff --git a/net/http/bidirectional_stream.cc b/net/http/bidirectional_stream.cc index 80caf3858..26bfa94c 100644 --- a/net/http/bidirectional_stream.cc +++ b/net/http/bidirectional_stream.cc
@@ -259,7 +259,7 @@ load_timing_info_.receive_headers_end = base::TimeTicks::Now(); read_end_time_ = load_timing_info_.receive_headers_end; session_->http_stream_factory()->ProcessAlternativeServices( - session_, net::NetworkIsolationKey(), response_info.headers.get(), + session_, net::NetworkAnonymizationKey(), response_info.headers.get(), url::SchemeHostPort(request_info_->url)); delegate_->OnHeadersReceived(response_headers); }
diff --git a/net/http/broken_alternative_services.cc b/net/http/broken_alternative_services.cc index 9b62fb4f..f2021ec 100644 --- a/net/http/broken_alternative_services.cc +++ b/net/http/broken_alternative_services.cc
@@ -59,19 +59,19 @@ BrokenAlternativeService::BrokenAlternativeService( const AlternativeService& alternative_service, - const NetworkIsolationKey& network_isolation_key, - bool use_network_isolation_key) + const NetworkAnonymizationKey& network_anonymization_key, + bool use_network_anonymization_key) : alternative_service(alternative_service), - network_isolation_key(use_network_isolation_key ? network_isolation_key - : NetworkIsolationKey()) { -} + network_anonymization_key(use_network_anonymization_key + ? network_anonymization_key + : NetworkAnonymizationKey()) {} BrokenAlternativeService::~BrokenAlternativeService() = default; bool BrokenAlternativeService::operator<( const BrokenAlternativeService& other) const { - return std::tie(alternative_service, network_isolation_key) < - std::tie(other.alternative_service, other.network_isolation_key); + return std::tie(alternative_service, network_anonymization_key) < + std::tie(other.alternative_service, other.network_anonymization_key); } BrokenAlternativeServices::BrokenAlternativeServices( @@ -378,7 +378,7 @@ } delegate_->OnExpireBrokenAlternativeService( - it->first.alternative_service, it->first.network_isolation_key); + it->first.alternative_service, it->first.network_anonymization_key); broken_alternative_service_map_.erase(it->first); broken_alternative_service_list_.erase(it);
diff --git a/net/http/broken_alternative_services.h b/net/http/broken_alternative_services.h index f4e8128..a706067 100644 --- a/net/http/broken_alternative_services.h +++ b/net/http/broken_alternative_services.h
@@ -13,7 +13,7 @@ #include "base/memory/weak_ptr.h" #include "base/time/time.h" #include "base/timer/timer.h" -#include "net/base/network_isolation_key.h" +#include "net/base/network_anonymization_key.h" #include "net/http/alternative_service.h" namespace base { @@ -25,11 +25,12 @@ // Contains information about a broken alternative service, and the context in // which it's known to be broken. struct NET_EXPORT_PRIVATE BrokenAlternativeService { - // If |use_network_isolation_key| is false, |network_isolation_key| is - // ignored, and an empty NetworkIsolationKey is used instead. - BrokenAlternativeService(const AlternativeService& alternative_service, - const NetworkIsolationKey& network_isolation_key, - bool use_network_isolation_key); + // If |use_network_anonymization_key| is false, |network_anonymization_key| is + // ignored, and an empty NetworkAnonymizationKey is used instead. + BrokenAlternativeService( + const AlternativeService& alternative_service, + const NetworkAnonymizationKey& network_anonymization_key, + bool use_network_anonymization_key); ~BrokenAlternativeService(); @@ -38,8 +39,8 @@ AlternativeService alternative_service; // The context in which the alternative service is known to be broken in. Used - // to avoid cross-NetworkIsolationKey communication. - NetworkIsolationKey network_isolation_key; + // to avoid cross-NetworkAnonymizationKey communication. + NetworkAnonymizationKey network_anonymization_key; }; // Stores broken alternative services and when their brokenness expires. @@ -73,7 +74,7 @@ // Called when a broken alternative service's expiration time is reached. virtual void OnExpireBrokenAlternativeService( const AlternativeService& expired_alternative_service, - const NetworkIsolationKey& network_isolation_key) = 0; + const NetworkAnonymizationKey& network_anonymization_key) = 0; virtual ~Delegate() = default; }; @@ -111,8 +112,8 @@ // Marks |broken_alternative_service| as recently broken. Being recently // broken will cause WasAlternativeServiceRecentlyBroken(alternative_service, - // network_isolation_key) to return true until Confirm(alternative_service, - // network_isolation_key) is called. + // network_anonymization_key) to return true until + // Confirm(alternative_service, network_anonymization_key) is called. void MarkRecentlyBroken( const BrokenAlternativeService& broken_alternative_service);
diff --git a/net/http/broken_alternative_services_unittest.cc b/net/http/broken_alternative_services_unittest.cc index 8608ca80..745d75f 100644 --- a/net/http/broken_alternative_services_unittest.cc +++ b/net/http/broken_alternative_services_unittest.cc
@@ -11,7 +11,7 @@ #include "base/test/test_mock_time_task_runner.h" #include "base/time/tick_clock.h" #include "base/time/time.h" -#include "net/base/network_isolation_key.h" +#include "net/base/network_anonymization_key.h" #include "net/base/schemeful_site.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" @@ -34,17 +34,17 @@ broken_services_(50, this, broken_services_clock_) { SchemefulSite site1(GURL("http://foo.test")); SchemefulSite site2(GURL("http://bar.test")); - network_isolation_key1_ = NetworkIsolationKey(site1, site1); - network_isolation_key2_ = NetworkIsolationKey(site2, site2); + network_anonymization_key1_ = NetworkAnonymizationKey(site1, site1); + network_anonymization_key2_ = NetworkAnonymizationKey(site2, site2); } // BrokenAlternativeServices::Delegate implementation void OnExpireBrokenAlternativeService( const AlternativeService& expired_alternative_service, - const NetworkIsolationKey& network_isolation_key) override { + const NetworkAnonymizationKey& network_anonymization_key) override { expired_alt_svcs_.emplace_back(expired_alternative_service, - network_isolation_key, - true /* use_network_isolation_key */); + network_anonymization_key, + true /* use_network_anonymization_key */); } void TestExponentialBackoff(base::TimeDelta initial_delay, @@ -61,20 +61,20 @@ std::vector<BrokenAlternativeService> expired_alt_svcs_; - NetworkIsolationKey network_isolation_key1_; - NetworkIsolationKey network_isolation_key2_; + NetworkAnonymizationKey network_anonymization_key1_; + NetworkAnonymizationKey network_anonymization_key2_; }; TEST_F(BrokenAlternativeServicesTest, MarkBroken) { const BrokenAlternativeService alternative_service1( - AlternativeService(kProtoHTTP2, "foo", 443), network_isolation_key1_, - true /* use_network_isolation_key */); + AlternativeService(kProtoHTTP2, "foo", 443), network_anonymization_key1_, + true /* use_network_anonymization_key */); const BrokenAlternativeService alternative_service2( - AlternativeService(kProtoHTTP2, "foo", 1234), network_isolation_key1_, - true /* use_network_isolation_key */); + AlternativeService(kProtoHTTP2, "foo", 1234), network_anonymization_key1_, + true /* use_network_anonymization_key */); const BrokenAlternativeService alternative_service3( - AlternativeService(kProtoHTTP2, "foo", 443), network_isolation_key2_, - true /* use_network_isolation_key */); + AlternativeService(kProtoHTTP2, "foo", 443), network_anonymization_key2_, + true /* use_network_anonymization_key */); EXPECT_FALSE(broken_services_.IsBroken(alternative_service1)); EXPECT_FALSE(broken_services_.IsBroken(alternative_service2)); @@ -121,14 +121,14 @@ TEST_F(BrokenAlternativeServicesTest, MarkBrokenUntilDefaultNetworkChanges) { const BrokenAlternativeService alternative_service1( - AlternativeService(kProtoHTTP2, "foo", 443), network_isolation_key1_, - true /* use_network_isolation_key */); + AlternativeService(kProtoHTTP2, "foo", 443), network_anonymization_key1_, + true /* use_network_anonymization_key */); const BrokenAlternativeService alternative_service2( - AlternativeService(kProtoHTTP2, "foo", 1234), network_isolation_key1_, - true /* use_network_isolation_key */); + AlternativeService(kProtoHTTP2, "foo", 1234), network_anonymization_key1_, + true /* use_network_anonymization_key */); const BrokenAlternativeService alternative_service3( - AlternativeService(kProtoHTTP2, "foo", 443), network_isolation_key2_, - true /* use_network_isolation_key */); + AlternativeService(kProtoHTTP2, "foo", 443), network_anonymization_key2_, + true /* use_network_anonymization_key */); EXPECT_FALSE(broken_services_.IsBroken(alternative_service1)); EXPECT_FALSE(broken_services_.WasRecentlyBroken(alternative_service1)); EXPECT_FALSE(broken_services_.IsBroken(alternative_service2)); @@ -189,11 +189,11 @@ TEST_F(BrokenAlternativeServicesTest, MarkRecentlyBroken) { const BrokenAlternativeService alternative_service1( - AlternativeService(kProtoHTTP2, "foo", 443), network_isolation_key1_, - true /* use_network_isolation_key */); + AlternativeService(kProtoHTTP2, "foo", 443), network_anonymization_key1_, + true /* use_network_anonymization_key */); const BrokenAlternativeService alternative_service2( - AlternativeService(kProtoHTTP2, "foo", 443), network_isolation_key2_, - true /* use_network_isolation_key */); + AlternativeService(kProtoHTTP2, "foo", 443), network_anonymization_key2_, + true /* use_network_anonymization_key */); EXPECT_FALSE(broken_services_.IsBroken(alternative_service1)); EXPECT_FALSE(broken_services_.WasRecentlyBroken(alternative_service1)); @@ -227,14 +227,14 @@ TEST_F(BrokenAlternativeServicesTest, OnDefaultNetworkChanged) { BrokenAlternativeService alternative_service1( - AlternativeService(kProtoQUIC, "foo", 443), network_isolation_key1_, - true /* use_network_isolation_key */); + AlternativeService(kProtoQUIC, "foo", 443), network_anonymization_key1_, + true /* use_network_anonymization_key */); BrokenAlternativeService alternative_service2( - AlternativeService(kProtoQUIC, "bar", 443), network_isolation_key1_, - true /* use_network_isolation_key */); + AlternativeService(kProtoQUIC, "bar", 443), network_anonymization_key1_, + true /* use_network_anonymization_key */); BrokenAlternativeService alternative_service3( - AlternativeService(kProtoQUIC, "foo", 443), network_isolation_key2_, - true /* use_network_isolation_key */); + AlternativeService(kProtoQUIC, "foo", 443), network_anonymization_key2_, + true /* use_network_anonymization_key */); EXPECT_FALSE(broken_services_.IsBroken(alternative_service1)); EXPECT_FALSE(broken_services_.WasRecentlyBroken(alternative_service1)); @@ -310,8 +310,8 @@ TEST_F(BrokenAlternativeServicesTest, ExpireBrokenAlternativeServiceOnDefaultNetwork) { BrokenAlternativeService alternative_service( - AlternativeService(kProtoQUIC, "foo", 443), network_isolation_key1_, - true /* use_network_isolation_key */); + AlternativeService(kProtoQUIC, "foo", 443), network_anonymization_key1_, + true /* use_network_anonymization_key */); broken_services_.MarkBrokenUntilDefaultNetworkChanges(alternative_service); @@ -338,15 +338,15 @@ EXPECT_EQ(1u, expired_alt_svcs_.size()); EXPECT_EQ(alternative_service.alternative_service, expired_alt_svcs_[0].alternative_service); - EXPECT_EQ(alternative_service.network_isolation_key, - expired_alt_svcs_[0].network_isolation_key); + EXPECT_EQ(alternative_service.network_anonymization_key, + expired_alt_svcs_[0].network_anonymization_key); EXPECT_TRUE(broken_services_.WasRecentlyBroken(alternative_service)); } TEST_F(BrokenAlternativeServicesTest, ExpireBrokenAlternateProtocolMappings) { BrokenAlternativeService alternative_service( - AlternativeService(kProtoQUIC, "foo", 443), network_isolation_key1_, - true /* use_network_isolation_key */); + AlternativeService(kProtoQUIC, "foo", 443), network_anonymization_key1_, + true /* use_network_anonymization_key */); broken_services_.MarkBroken(alternative_service); @@ -373,16 +373,16 @@ EXPECT_EQ(1u, expired_alt_svcs_.size()); EXPECT_EQ(alternative_service.alternative_service, expired_alt_svcs_[0].alternative_service); - EXPECT_EQ(alternative_service.network_isolation_key, - expired_alt_svcs_[0].network_isolation_key); + EXPECT_EQ(alternative_service.network_anonymization_key, + expired_alt_svcs_[0].network_anonymization_key); EXPECT_TRUE(broken_services_.WasRecentlyBroken(alternative_service)); } TEST_F(BrokenAlternativeServicesTest, IsBroken) { // Tests the IsBroken() methods. BrokenAlternativeService alternative_service( - AlternativeService(kProtoQUIC, "foo", 443), NetworkIsolationKey(), - true /* use_network_isolation_key */); + AlternativeService(kProtoQUIC, "foo", 443), NetworkAnonymizationKey(), + true /* use_network_anonymization_key */); base::TimeTicks brokenness_expiration; EXPECT_FALSE(broken_services_.IsBroken(alternative_service)); @@ -425,8 +425,8 @@ // - brokenness expires after two intervals. TEST_F(BrokenAlternativeServicesTest, BrokenAfterBrokenOnDefaultNetwork) { BrokenAlternativeService alternative_service( - AlternativeService(kProtoQUIC, "foo", 443), NetworkIsolationKey(), - true /* use_network_isolation_key */); + AlternativeService(kProtoQUIC, "foo", 443), NetworkAnonymizationKey(), + true /* use_network_anonymization_key */); // Mark the alternative service broken on the default network. broken_services_.MarkBrokenUntilDefaultNetworkChanges(alternative_service); @@ -475,8 +475,8 @@ // - (signal received that default network changes); TEST_F(BrokenAlternativeServicesTest, BrokenOnDefaultNetworkAfterBroken) { BrokenAlternativeService alternative_service( - AlternativeService(kProtoQUIC, "foo", 443), NetworkIsolationKey(), - true /* use_network_isolation_key */); + AlternativeService(kProtoQUIC, "foo", 443), NetworkAnonymizationKey(), + true /* use_network_anonymization_key */); // Mark the alternative service broken. broken_services_.MarkBroken(alternative_service); @@ -518,8 +518,8 @@ TEST_F(BrokenAlternativeServicesTest, BrokenUntilDefaultNetworkChangeWithExponentialBackoff) { BrokenAlternativeService alternative_service( - AlternativeService(kProtoQUIC, "foo", 443), NetworkIsolationKey(), - true /* use_network_isolation_key */); + AlternativeService(kProtoQUIC, "foo", 443), NetworkAnonymizationKey(), + true /* use_network_anonymization_key */); // Mark the alternative service broken on the default network. broken_services_.MarkBrokenUntilDefaultNetworkChanges(alternative_service); @@ -578,8 +578,8 @@ // longer apply. BrokenAlternativeService alternative_service( - AlternativeService(kProtoQUIC, "foo", 443), NetworkIsolationKey(), - true /* use_network_isolation_key */); + AlternativeService(kProtoQUIC, "foo", 443), NetworkAnonymizationKey(), + true /* use_network_anonymization_key */); broken_services_.MarkBroken(alternative_service); test_task_runner_->FastForwardBy(base::Minutes(5) - base::Seconds(1)); @@ -667,8 +667,8 @@ exponential_backoff_on_initial_delay); BrokenAlternativeService alternative_service( - AlternativeService(kProtoQUIC, "foo", 443), NetworkIsolationKey(), - true /* use_network_isolation_key */); + AlternativeService(kProtoQUIC, "foo", 443), NetworkAnonymizationKey(), + true /* use_network_anonymization_key */); broken_services_.MarkBroken(alternative_service); test_task_runner_->FastForwardBy(initial_delay - base::Seconds(1)); @@ -739,11 +739,11 @@ // expire before A. BrokenAlternativeService alternative_service1( - AlternativeService(kProtoQUIC, "foo", 443), network_isolation_key1_, - true /* use_network_isolation_key */); + AlternativeService(kProtoQUIC, "foo", 443), network_anonymization_key1_, + true /* use_network_anonymization_key */); BrokenAlternativeService alternative_service2( - AlternativeService(kProtoQUIC, "bar", 443), network_isolation_key2_, - true /* use_network_isolation_key */); + AlternativeService(kProtoQUIC, "bar", 443), network_anonymization_key2_, + true /* use_network_anonymization_key */); // Repeately mark |alternative_service1| broken and let brokenness expire. // Do this a few times. @@ -754,8 +754,8 @@ EXPECT_EQ(1u, expired_alt_svcs_.size()); EXPECT_EQ(alternative_service1.alternative_service, expired_alt_svcs_.back().alternative_service); - EXPECT_EQ(alternative_service1.network_isolation_key, - expired_alt_svcs_.back().network_isolation_key); + EXPECT_EQ(alternative_service1.network_anonymization_key, + expired_alt_svcs_.back().network_anonymization_key); broken_services_.MarkBroken(alternative_service1); EXPECT_EQ(1u, test_task_runner_->GetPendingTaskCount()); @@ -763,8 +763,8 @@ EXPECT_EQ(2u, expired_alt_svcs_.size()); EXPECT_EQ(alternative_service1.alternative_service, expired_alt_svcs_.back().alternative_service); - EXPECT_EQ(alternative_service1.network_isolation_key, - expired_alt_svcs_.back().network_isolation_key); + EXPECT_EQ(alternative_service1.network_anonymization_key, + expired_alt_svcs_.back().network_anonymization_key); broken_services_.MarkBroken(alternative_service1); EXPECT_EQ(1u, test_task_runner_->GetPendingTaskCount()); @@ -772,8 +772,8 @@ EXPECT_EQ(3u, expired_alt_svcs_.size()); EXPECT_EQ(alternative_service1.alternative_service, expired_alt_svcs_.back().alternative_service); - EXPECT_EQ(alternative_service1.network_isolation_key, - expired_alt_svcs_.back().network_isolation_key); + EXPECT_EQ(alternative_service1.network_anonymization_key, + expired_alt_svcs_.back().network_anonymization_key); expired_alt_svcs_.clear(); @@ -803,8 +803,8 @@ EXPECT_EQ(1u, expired_alt_svcs_.size()); EXPECT_EQ(alternative_service2.alternative_service, expired_alt_svcs_[0].alternative_service); - EXPECT_EQ(alternative_service2.network_isolation_key, - expired_alt_svcs_[0].network_isolation_key); + EXPECT_EQ(alternative_service2.network_anonymization_key, + expired_alt_svcs_[0].network_anonymization_key); // Advance time until one time quantum before |alternative_service1|'s // brokenness expires @@ -816,8 +816,8 @@ EXPECT_EQ(1u, expired_alt_svcs_.size()); EXPECT_EQ(alternative_service2.alternative_service, expired_alt_svcs_[0].alternative_service); - EXPECT_EQ(alternative_service2.network_isolation_key, - expired_alt_svcs_[0].network_isolation_key); + EXPECT_EQ(alternative_service2.network_anonymization_key, + expired_alt_svcs_[0].network_anonymization_key); // Advance time by one time quantum. |alternative_service1| should no longer // be broken. @@ -828,24 +828,24 @@ EXPECT_EQ(2u, expired_alt_svcs_.size()); EXPECT_EQ(alternative_service2.alternative_service, expired_alt_svcs_[0].alternative_service); - EXPECT_EQ(alternative_service2.network_isolation_key, - expired_alt_svcs_[0].network_isolation_key); + EXPECT_EQ(alternative_service2.network_anonymization_key, + expired_alt_svcs_[0].network_anonymization_key); EXPECT_EQ(alternative_service1.alternative_service, expired_alt_svcs_[1].alternative_service); - EXPECT_EQ(alternative_service1.network_isolation_key, - expired_alt_svcs_[1].network_isolation_key); + EXPECT_EQ(alternative_service1.network_anonymization_key, + expired_alt_svcs_[1].network_anonymization_key); } // Same as above, but checks a single alternative service with two different -// NetworkIsolationKeys. +// NetworkAnonymizationKeys. TEST_F(BrokenAlternativeServicesTest, - RemoveExpiredBrokenAltSvcWithNetworkIsolationKey) { + RemoveExpiredBrokenAltSvcWithNetworkAnonymizationKey) { BrokenAlternativeService alternative_service1( - AlternativeService(kProtoQUIC, "foo", 443), network_isolation_key1_, - true /* use_network_isolation_key */); + AlternativeService(kProtoQUIC, "foo", 443), network_anonymization_key1_, + true /* use_network_anonymization_key */); BrokenAlternativeService alternative_service2( - AlternativeService(kProtoQUIC, "foo", 443), network_isolation_key2_, - true /* use_network_isolation_key */); + AlternativeService(kProtoQUIC, "foo", 443), network_anonymization_key2_, + true /* use_network_anonymization_key */); // Repeately mark |alternative_service1| broken and let brokenness expire. // Do this a few times. @@ -856,8 +856,8 @@ EXPECT_EQ(1u, expired_alt_svcs_.size()); EXPECT_EQ(alternative_service1.alternative_service, expired_alt_svcs_.back().alternative_service); - EXPECT_EQ(alternative_service1.network_isolation_key, - expired_alt_svcs_.back().network_isolation_key); + EXPECT_EQ(alternative_service1.network_anonymization_key, + expired_alt_svcs_.back().network_anonymization_key); broken_services_.MarkBroken(alternative_service1); EXPECT_EQ(1u, test_task_runner_->GetPendingTaskCount()); @@ -865,8 +865,8 @@ EXPECT_EQ(2u, expired_alt_svcs_.size()); EXPECT_EQ(alternative_service1.alternative_service, expired_alt_svcs_.back().alternative_service); - EXPECT_EQ(alternative_service1.network_isolation_key, - expired_alt_svcs_.back().network_isolation_key); + EXPECT_EQ(alternative_service1.network_anonymization_key, + expired_alt_svcs_.back().network_anonymization_key); broken_services_.MarkBroken(alternative_service1); EXPECT_EQ(1u, test_task_runner_->GetPendingTaskCount()); @@ -874,8 +874,8 @@ EXPECT_EQ(3u, expired_alt_svcs_.size()); EXPECT_EQ(alternative_service1.alternative_service, expired_alt_svcs_.back().alternative_service); - EXPECT_EQ(alternative_service1.network_isolation_key, - expired_alt_svcs_.back().network_isolation_key); + EXPECT_EQ(alternative_service1.network_anonymization_key, + expired_alt_svcs_.back().network_anonymization_key); expired_alt_svcs_.clear(); @@ -905,8 +905,8 @@ EXPECT_EQ(1u, expired_alt_svcs_.size()); EXPECT_EQ(alternative_service2.alternative_service, expired_alt_svcs_[0].alternative_service); - EXPECT_EQ(alternative_service2.network_isolation_key, - expired_alt_svcs_[0].network_isolation_key); + EXPECT_EQ(alternative_service2.network_anonymization_key, + expired_alt_svcs_[0].network_anonymization_key); // Advance time until one time quantum before |alternative_service1|'s // brokenness expires @@ -918,8 +918,8 @@ EXPECT_EQ(1u, expired_alt_svcs_.size()); EXPECT_EQ(alternative_service2.alternative_service, expired_alt_svcs_[0].alternative_service); - EXPECT_EQ(alternative_service2.network_isolation_key, - expired_alt_svcs_[0].network_isolation_key); + EXPECT_EQ(alternative_service2.network_anonymization_key, + expired_alt_svcs_[0].network_anonymization_key); // Advance time by one time quantum. |alternative_service1| should no longer // be broken. @@ -930,21 +930,21 @@ EXPECT_EQ(2u, expired_alt_svcs_.size()); EXPECT_EQ(alternative_service2.alternative_service, expired_alt_svcs_[0].alternative_service); - EXPECT_EQ(alternative_service2.network_isolation_key, - expired_alt_svcs_[0].network_isolation_key); + EXPECT_EQ(alternative_service2.network_anonymization_key, + expired_alt_svcs_[0].network_anonymization_key); EXPECT_EQ(alternative_service1.alternative_service, expired_alt_svcs_[1].alternative_service); - EXPECT_EQ(alternative_service1.network_isolation_key, - expired_alt_svcs_[1].network_isolation_key); + EXPECT_EQ(alternative_service1.network_anonymization_key, + expired_alt_svcs_[1].network_anonymization_key); } TEST_F(BrokenAlternativeServicesTest, SetBrokenAlternativeServices) { BrokenAlternativeService alternative_service1( - AlternativeService(kProtoQUIC, "foo1", 443), NetworkIsolationKey(), - true /* use_network_isolation_key */); + AlternativeService(kProtoQUIC, "foo1", 443), NetworkAnonymizationKey(), + true /* use_network_anonymization_key */); BrokenAlternativeService alternative_service2( - AlternativeService(kProtoQUIC, "foo2", 443), NetworkIsolationKey(), - true /* use_network_isolation_key */); + AlternativeService(kProtoQUIC, "foo2", 443), NetworkAnonymizationKey(), + true /* use_network_anonymization_key */); base::TimeDelta delay1 = base::Minutes(1); @@ -1000,14 +1000,14 @@ TEST_F(BrokenAlternativeServicesTest, SetBrokenAlternativeServicesWithExisting) { BrokenAlternativeService alternative_service1( - AlternativeService(kProtoQUIC, "foo1", 443), NetworkIsolationKey(), - true /* use_network_isolation_key */); + AlternativeService(kProtoQUIC, "foo1", 443), NetworkAnonymizationKey(), + true /* use_network_anonymization_key */); BrokenAlternativeService alternative_service2( - AlternativeService(kProtoQUIC, "foo2", 443), network_isolation_key1_, - true /* use_network_isolation_key */); + AlternativeService(kProtoQUIC, "foo2", 443), network_anonymization_key1_, + true /* use_network_anonymization_key */); BrokenAlternativeService alternative_service3( - AlternativeService(kProtoQUIC, "foo3", 443), network_isolation_key2_, - true /* use_network_isolation_key */); + AlternativeService(kProtoQUIC, "foo3", 443), network_anonymization_key2_, + true /* use_network_anonymization_key */); std::unique_ptr<BrokenAlternativeServiceList> broken_list = std::make_unique<BrokenAlternativeServiceList>(); @@ -1080,18 +1080,18 @@ auto it = broken_services_.recently_broken_alternative_services().begin(); EXPECT_EQ(alternative_service2.alternative_service, it->first.alternative_service); - EXPECT_EQ(alternative_service2.network_isolation_key, - it->first.network_isolation_key); + EXPECT_EQ(alternative_service2.network_anonymization_key, + it->first.network_anonymization_key); ++it; EXPECT_EQ(alternative_service1.alternative_service, it->first.alternative_service); - EXPECT_EQ(alternative_service1.network_isolation_key, - it->first.network_isolation_key); + EXPECT_EQ(alternative_service1.network_anonymization_key, + it->first.network_anonymization_key); ++it; EXPECT_EQ(alternative_service3.alternative_service, it->first.alternative_service); - EXPECT_EQ(alternative_service3.network_isolation_key, - it->first.network_isolation_key); + EXPECT_EQ(alternative_service3.network_anonymization_key, + it->first.network_anonymization_key); } TEST_F(BrokenAlternativeServicesTest, ScheduleExpireTaskAfterExpire) { @@ -1099,11 +1099,11 @@ // is scheduled for the next broken alt svc in the expiration queue. BrokenAlternativeService alternative_service1( - AlternativeService(kProtoQUIC, "foo", 443), NetworkIsolationKey(), - true /* use_network_isolation_key */); + AlternativeService(kProtoQUIC, "foo", 443), NetworkAnonymizationKey(), + true /* use_network_anonymization_key */); BrokenAlternativeService alternative_service2( - AlternativeService(kProtoQUIC, "bar", 443), NetworkIsolationKey(), - true /* use_network_isolation_key */); + AlternativeService(kProtoQUIC, "bar", 443), NetworkAnonymizationKey(), + true /* use_network_anonymization_key */); // Mark |alternative_service1| broken and let brokenness expire. This will // increase its expiration delay the next time it's marked broken. @@ -1128,11 +1128,11 @@ TEST_F(BrokenAlternativeServicesTest, Clear) { BrokenAlternativeService alternative_service1( - AlternativeService(kProtoQUIC, "foo", 443), NetworkIsolationKey(), - true /* use_network_isolation_key */); + AlternativeService(kProtoQUIC, "foo", 443), NetworkAnonymizationKey(), + true /* use_network_anonymization_key */); BrokenAlternativeService alternative_service2( - AlternativeService(kProtoQUIC, "bar", 443), NetworkIsolationKey(), - true /* use_network_isolation_key */); + AlternativeService(kProtoQUIC, "bar", 443), NetworkAnonymizationKey(), + true /* use_network_anonymization_key */); broken_services_.MarkBroken(alternative_service1); broken_services_.MarkRecentlyBroken(alternative_service2);
diff --git a/net/http/http_network_transaction_unittest.cc b/net/http/http_network_transaction_unittest.cc index bb70dba..0a0f4e1 100644 --- a/net/http/http_network_transaction_unittest.cc +++ b/net/http/http_network_transaction_unittest.cc
@@ -20165,7 +20165,7 @@ public ::testing::WithParamInterface<bool> { protected: HttpNetworkTransactionReportingTest() { - std::vector<base::Feature> required_features = { + std::vector<base::test::FeatureRef> required_features = { features::kPartitionNelAndReportingByNetworkIsolationKey}; if (UseDocumentReporting()) { required_features.push_back(features::kDocumentReporting);
diff --git a/net/http/http_proxy_connect_job.cc b/net/http/http_proxy_connect_job.cc index 14a5167..c6a60d5 100644 --- a/net/http/http_proxy_connect_job.cc +++ b/net/http/http_proxy_connect_job.cc
@@ -130,13 +130,13 @@ const HostPortPair& endpoint, bool tunnel, const NetworkTrafficAnnotationTag traffic_annotation, - const NetworkIsolationKey& network_isolation_key) + const NetworkAnonymizationKey& network_anonymization_key) : transport_params_(std::move(transport_params)), ssl_params_(std::move(ssl_params)), is_quic_(is_quic), endpoint_(endpoint), tunnel_(tunnel), - network_isolation_key_(network_isolation_key), + network_anonymization_key_(network_anonymization_key), traffic_annotation_(traffic_annotation) { // This is either a connection to an HTTP proxy or an SSL/QUIC proxy. DCHECK(transport_params_ || ssl_params_); @@ -194,7 +194,7 @@ HttpAuth::AUTH_PROXY, GURL((params_->ssl_params() ? "https://" : "http://") + GetDestination().ToString()), - params_->network_isolation_key(), + params_->network_anonymization_key(), common_connect_job_params->http_auth_cache, common_connect_job_params->http_auth_handler_factory, host_resolver()) @@ -655,7 +655,7 @@ url::SchemeHostPort(url::kHttpsScheme, proxy_server.host(), proxy_server.port()), quic_version, ssl_params->privacy_mode(), kH2QuicTunnelPriority, - socket_tag(), params_->network_isolation_key(), + socket_tag(), params_->network_anonymization_key(), ssl_params->GetDirectConnectionParams()->secure_dns_policy(), /*use_dns_aliases=*/false, /*require_dns_https_alpn=*/false, ssl_params->ssl_config().GetCertVerifyFlags(), @@ -814,8 +814,7 @@ return SpdySessionKey( GetDestination(), ProxyServer::Direct(), PRIVACY_MODE_DISABLED, SpdySessionKey::IsProxySession::kTrue, socket_tag(), - net::NetworkAnonymizationKey::CreateFromNetworkIsolationKey( - params_->network_isolation_key()), + params_->network_anonymization_key(), params_->ssl_params()->GetDirectConnectionParams()->secure_dns_policy()); }
diff --git a/net/http/http_proxy_connect_job.h b/net/http/http_proxy_connect_job.h index b7125d1..17d26d8 100644 --- a/net/http/http_proxy_connect_job.h +++ b/net/http/http_proxy_connect_job.h
@@ -13,7 +13,7 @@ #include "base/time/time.h" #include "net/base/host_port_pair.h" #include "net/base/net_export.h" -#include "net/base/network_isolation_key.h" +#include "net/base/network_anonymization_key.h" #include "net/base/request_priority.h" #include "net/dns/public/resolve_error_info.h" #include "net/http/http_auth.h" @@ -43,13 +43,14 @@ class NET_EXPORT_PRIVATE HttpProxySocketParams : public base::RefCounted<HttpProxySocketParams> { public: - HttpProxySocketParams(scoped_refptr<TransportSocketParams> transport_params, - scoped_refptr<SSLSocketParams> ssl_params, - bool is_quic, - const HostPortPair& endpoint, - bool tunnel, - const NetworkTrafficAnnotationTag traffic_annotation, - const NetworkIsolationKey& network_isolation_key); + HttpProxySocketParams( + scoped_refptr<TransportSocketParams> transport_params, + scoped_refptr<SSLSocketParams> ssl_params, + bool is_quic, + const HostPortPair& endpoint, + bool tunnel, + const NetworkTrafficAnnotationTag traffic_annotation, + const NetworkAnonymizationKey& network_anonymization_key); HttpProxySocketParams(const HttpProxySocketParams&) = delete; HttpProxySocketParams& operator=(const HttpProxySocketParams&) = delete; @@ -63,8 +64,8 @@ bool is_quic() const { return is_quic_; } const HostPortPair& endpoint() const { return endpoint_; } bool tunnel() const { return tunnel_; } - const NetworkIsolationKey& network_isolation_key() const { - return network_isolation_key_; + const NetworkAnonymizationKey& network_anonymization_key() const { + return network_anonymization_key_; } const NetworkTrafficAnnotationTag traffic_annotation() const { return traffic_annotation_; @@ -79,7 +80,7 @@ bool is_quic_; const HostPortPair endpoint_; const bool tunnel_; - const NetworkIsolationKey network_isolation_key_; + const NetworkAnonymizationKey network_anonymization_key_; const NetworkTrafficAnnotationTag traffic_annotation_; };
diff --git a/net/http/http_proxy_connect_job_unittest.cc b/net/http/http_proxy_connect_job_unittest.cc index 4b23209e..b73e094 100644 --- a/net/http/http_proxy_connect_job_unittest.cc +++ b/net/http/http_proxy_connect_job_unittest.cc
@@ -145,7 +145,7 @@ CreateHttpProxyParams(secure_dns_policy), CreateHttpsProxyParams(secure_dns_policy), false /* is_quic */, HostPortPair(kEndpointHost, tunnel ? 443 : 80), tunnel, - TRAFFIC_ANNOTATION_FOR_TESTS, NetworkIsolationKey()); + TRAFFIC_ANNOTATION_FOR_TESTS, NetworkAnonymizationKey()); } std::unique_ptr<HttpProxyConnectJob> CreateConnectJobForHttpRequest( @@ -945,7 +945,7 @@ auto http_proxy_params = base::MakeRefCounted<HttpProxySocketParams>( nullptr /* tcp_params */, std::move(ssl_params), false /* is_quic */, HostPortPair(kEndpointHost, 443), - /*tunnel=*/true, TRAFFIC_ANNOTATION_FOR_TESTS, NetworkIsolationKey()); + /*tunnel=*/true, TRAFFIC_ANNOTATION_FOR_TESTS, NetworkAnonymizationKey()); std::unique_ptr<ConnectJob> connect_job = CreateConnectJob( std::move(http_proxy_params), &test_delegate, DEFAULT_PRIORITY);
diff --git a/net/http/http_request_info_unittest.cc b/net/http/http_request_info_unittest.cc index 5252853..d5166ef 100644 --- a/net/http/http_request_info_unittest.cc +++ b/net/http/http_request_info_unittest.cc
@@ -17,7 +17,7 @@ // Triple keyed NIK and NAK. base::test::ScopedFeatureList scoped_feature_list_; - std::vector<base::Feature> disabled_features_1 = {}; + std::vector<base::test::FeatureRef> disabled_features_1 = {}; disabled_features_1.push_back( net::features::kForceIsolationInfoFrameOriginToTopLevelFrame); disabled_features_1.push_back( @@ -57,8 +57,8 @@ // Double key NIK and triple key NAK. scoped_feature_list_.Reset(); - std::vector<base::Feature> enabled_features_2 = {}; - std::vector<base::Feature> disabled_features_2 = {}; + std::vector<base::test::FeatureRef> enabled_features_2 = {}; + std::vector<base::test::FeatureRef> disabled_features_2 = {}; enabled_features_2.push_back( net::features::kForceIsolationInfoFrameOriginToTopLevelFrame); disabled_features_2.push_back( @@ -74,8 +74,8 @@ // Triple key NIK and double key NAK. scoped_feature_list_.Reset(); - std::vector<base::Feature> enabled_features_3 = {}; - std::vector<base::Feature> disabled_features_3 = {}; + std::vector<base::test::FeatureRef> enabled_features_3 = {}; + std::vector<base::test::FeatureRef> disabled_features_3 = {}; disabled_features_3.push_back( net::features::kForceIsolationInfoFrameOriginToTopLevelFrame); enabled_features_3.push_back( @@ -90,8 +90,8 @@ // Triple key NIK and double key with cross site flag NAK. scoped_feature_list_.Reset(); - std::vector<base::Feature> enabled_features_4 = {}; - std::vector<base::Feature> disabled_features_4 = {}; + std::vector<base::test::FeatureRef> enabled_features_4 = {}; + std::vector<base::test::FeatureRef> disabled_features_4 = {}; disabled_features_3.push_back( net::features::kForceIsolationInfoFrameOriginToTopLevelFrame); enabled_features_3.push_back( @@ -112,4 +112,4 @@ EXPECT_TRUE(triple_nik_double_xsite_bit_nak_request_info.IsConsistent()); } -} // namespace net \ No newline at end of file +} // namespace net
diff --git a/net/http/http_server_properties.cc b/net/http/http_server_properties.cc index 3140629..24fed5b 100644 --- a/net/http/http_server_properties.cc +++ b/net/http/http_server_properties.cc
@@ -582,16 +582,13 @@ void HttpServerProperties::OnExpireBrokenAlternativeService( const AlternativeService& expired_alternative_service, - const NetworkIsolationKey& network_isolation_key) { + const NetworkAnonymizationKey& network_anonymization_key) { // Remove every occurrence of |expired_alternative_service| from // |alternative_service_map_|. for (auto map_it = server_info_map_.begin(); map_it != server_info_map_.end();) { if (!map_it->second.alternative_services.has_value() || - map_it->first.network_anonymization_key != - NetworkAnonymizationKey:: - CreateFromNetworkIsolationKeyTemporaryMigrationHelper( - network_isolation_key)) { + map_it->first.network_anonymization_key != network_anonymization_key) { ++map_it; continue; } @@ -614,11 +611,8 @@ // from both |canonical_alt_svc_map_| and // |alternative_service_map_|. if (service_info->empty()) { - RemoveAltSvcCanonicalHost( - map_it->first.server, - NetworkAnonymizationKey:: - CreateFromNetworkIsolationKeyTemporaryMigrationHelper( - network_isolation_key)); + RemoveAltSvcCanonicalHost(map_it->first.server, + network_anonymization_key); map_it->second.alternative_services.reset(); map_it = server_info_map_.EraseIfEmpty(map_it); continue;
diff --git a/net/http/http_server_properties.h b/net/http/http_server_properties.h index 1dce793..912b1de 100644 --- a/net/http/http_server_properties.h +++ b/net/http/http_server_properties.h
@@ -437,7 +437,7 @@ // BrokenAlternativeServices::Delegate method. void OnExpireBrokenAlternativeService( const AlternativeService& expired_alternative_service, - const NetworkIsolationKey& network_isolation_key) override; + const NetworkAnonymizationKey& network_anonymization_key) override; static base::TimeDelta GetUpdatePrefsDelayForTesting();
diff --git a/net/http/http_server_properties_manager.cc b/net/http/http_server_properties_manager.cc index 9a2b704..7275447 100644 --- a/net/http/http_server_properties_manager.cc +++ b/net/http/http_server_properties_manager.cc
@@ -42,7 +42,7 @@ const char kServerKey[] = "server"; const char kQuicServerIdKey[] = "server_id"; -const char kNetworkIsolationKey[] = "isolation"; +const char kNetworkAnonymizationKey[] = "anonymization"; const char kVersionKey[] = "version"; const char kServersKey[] = "servers"; const char kSupportsSpdyKey[] = "supports_spdy"; @@ -116,18 +116,19 @@ dict.Set(kProtocolKey, NextProtoToString(alternative_service.protocol)); } -// Fails in the case of NetworkIsolationKeys that can't be persisted to disk, -// like unique origins. +// Fails in the case of NetworkAnonymizationKeys that can't be persisted to +// disk, like unique origins. bool TryAddBrokenAlternativeServiceFieldsToDictionaryValue( const BrokenAlternativeService& broken_alt_service, base::Value::Dict& dict) { base::Value network_anonymization_key_value; - if (!broken_alt_service.network_isolation_key.ToValue( + if (!broken_alt_service.network_anonymization_key.ToValue( &network_anonymization_key_value)) { return false; } - dict.Set(kNetworkIsolationKey, std::move(network_anonymization_key_value)); + dict.Set(kNetworkAnonymizationKey, + std::move(network_anonymization_key_value)); AddAlternativeServiceFieldsToDictionaryValue( broken_alt_service.alternative_service, dict); return true; @@ -153,7 +154,7 @@ // Takes in a base::Value::Dict, and whether NetworkIsolationKeys are enabled // for HttpServerProperties, and extracts the NetworkAnonymizationKey stored -// with the |kNetworkIsolationKey| in the dictionary, and writes it to +// with the |kNetworkAnonymizationKey| in the dictionary, and writes it to // |out_network_anonymization_key|. Returns false if unable to load a // NetworkAnonymizationKey, or the NetworkAnonymizationKey is non-empty, but // |use_network_anonymization_key| is false. @@ -162,7 +163,7 @@ bool use_network_anonymization_key, NetworkAnonymizationKey* out_network_anonymization_key) { const base::Value* network_anonymization_key_value = - dict.Find(kNetworkIsolationKey); + dict.Find(kNetworkAnonymizationKey); NetworkAnonymizationKey network_anonymization_key; if (!network_anonymization_key_value || !NetworkAnonymizationKey::FromValue(*network_anonymization_key_value, @@ -748,7 +749,7 @@ if (server_dict.empty()) continue; server_dict.Set(kServerKey, key.server.Serialize()); - server_dict.Set(kNetworkIsolationKey, + server_dict.Set(kNetworkAnonymizationKey, std::move(network_anonymization_key_value)); servers_list.Append(std::move(server_dict)); } @@ -854,7 +855,7 @@ base::Value::Dict quic_server_pref_dict; quic_server_pref_dict.Set(kQuicServerIdKey, QuicServerIdToString(key.server_id)); - quic_server_pref_dict.Set(kNetworkIsolationKey, + quic_server_pref_dict.Set(kNetworkAnonymizationKey, std::move(network_anonymization_key_value)); quic_server_pref_dict.Set(kServerInfoKey, server_info); @@ -932,8 +933,8 @@ } } - // This can happen if all the entries are for NetworkIsolationKeys for opaque - // origins, which isn't exactly common, but can theoretically happen. + // This can happen if all the entries are for NetworkAnonymizationKeys for + // opaque origins, which isn't exactly common, but can theoretically happen. if (json_list.empty()) return;
diff --git a/net/http/http_server_properties_manager.h b/net/http/http_server_properties_manager.h index b273058..5412cab 100644 --- a/net/http/http_server_properties_manager.h +++ b/net/http/http_server_properties_manager.h
@@ -106,7 +106,7 @@ // by the time this method is called, calling this will prevent it from ever // being invoked, as this method will overwrite any previous preferences. // - // Entries associated with NetworkIsolationKeys for opaque origins are not + // Entries associated with NetworkAnonymizationKeys for opaque origins are not // written to disk. void WriteToPrefs( const HttpServerProperties::ServerInfoMap& server_info_map,
diff --git a/net/http/http_server_properties_manager_unittest.cc b/net/http/http_server_properties_manager_unittest.cc index 6f64ad6..512510b 100644 --- a/net/http/http_server_properties_manager_unittest.cc +++ b/net/http/http_server_properties_manager_unittest.cc
@@ -1060,14 +1060,14 @@ alternative_service_list.Append(std::move(alternative_service_dict)); server_dict.Set("alternative_service", std::move(alternative_service_list)); server_dict.Set("server", StringPrintf("https://www.google.com:%d", i)); - server_dict.Set("isolation", base::Value(base::Value::Type::LIST)); + server_dict.Set("anonymization", base::Value(base::Value::Type::LIST)); servers_list.Append(std::move(server_dict)); } // Set the server preference for http://mail.google.com server. base::Value::Dict server_dict2; server_dict2.Set("server", "https://mail.google.com"); - server_dict2.Set("isolation", base::Value(base::Value::Type::LIST)); + server_dict2.Set("anonymization", base::Value(base::Value::Type::LIST)); servers_list.Append(std::move(server_dict2)); base::Value http_server_properties_dict = DictWithVersion(); @@ -1222,12 +1222,12 @@ const char expected_json[] = "{" "\"broken_alternative_services\":" - "[{\"broken_count\":1,\"host\":\"www.google.com\",\"isolation\":[]," + "[{\"anonymization\":[],\"broken_count\":1,\"host\":\"www.google.com\"," "\"port\":1234,\"protocol_str\":\"h2\"}," - "{\"broken_count\":1,\"host\":\"foo.google.com\",\"isolation\":[]," + "{\"anonymization\":[],\"broken_count\":1,\"host\":\"foo.google.com\"," "\"port\":444,\"protocol_str\":\"h2\"}]," "\"quic_servers\":" - "[{\"isolation\":[]," + "[{\"anonymization\":[]," "\"server_id\":\"https://mail.google.com:80\"," "\"server_info\":\"quic_server_info1\"}]," "\"servers\":[" @@ -1236,12 +1236,12 @@ "\"protocol_str\":\"h2\"}," "{\"advertised_alpns\":[],\"expiration\":\"13758804000000000\"," "\"host\":\"www.google.com\",\"port\":1234,\"protocol_str\":\"h2\"}]," - "\"isolation\":[]," + "\"anonymization\":[]," "\"server\":\"https://www.google.com:80\"}," "{\"alternative_service\":[{\"advertised_alpns\":[]," "\"expiration\":\"9223372036854775807\",\"host\":\"foo.google.com\"," "\"port\":444,\"protocol_str\":\"h2\"}]," - "\"isolation\":[]," + "\"anonymization\":[]," "\"network_stats\":{\"srtt\":42}," "\"server\":\"https://mail.google.com:80\"," "\"supports_spdy\":true}]," @@ -1385,7 +1385,7 @@ EXPECT_EQ("https://www.example.com", *server_str); const base::Value* network_anonymization_key_value = - server_pref_dict.GetDict().Find("isolation"); + server_pref_dict.GetDict().Find("anonymization"); ASSERT_TRUE(network_anonymization_key_value); ASSERT_EQ(base::Value::Type::LIST, network_anonymization_key_value->type()); EXPECT_TRUE(network_anonymization_key_value->GetList().empty()); @@ -1529,7 +1529,7 @@ // Verify preferences with correct advertised version field. const char expected_json[] = "{\"quic_servers\":[" - "{\"isolation\":[]," + "{\"anonymization\":[]," "\"server_id\":\"https://mail.google.com:80\"," "\"server_info\":\"quic_server_info1\"}]," "\"servers\":[" @@ -1539,13 +1539,13 @@ "\"port\":443,\"protocol_str\":\"quic\"},{\"advertised_alpns\":[]," "\"expiration\":\"13758804000000000\",\"host\":\"www.google.com\"," "\"port\":1234,\"protocol_str\":\"h2\"}]," - "\"isolation\":[]," + "\"anonymization\":[]," "\"server\":\"https://www.google.com:80\"}," "{\"alternative_service\":[{" "\"advertised_alpns\":[\"h3\"]," "\"expiration\":\"9223372036854775807\"," "\"host\":\"foo.google.com\",\"port\":444,\"protocol_str\":\"quic\"}]," - "\"isolation\":[]," + "\"anonymization\":[]," "\"network_stats\":{\"srtt\":42}," "\"server\":\"https://mail.google.com:80\"}]," "\"supports_quic\":{" @@ -1650,7 +1650,7 @@ // Verify preferences with correct advertised version field. const char expected_json[] = "{\"quic_servers\":" - "[{\"isolation\":[]," + "[{\"anonymization\":[]," "\"server_id\":\"https://mail.google.com:80\"," "\"server_info\":\"quic_server_info1\"}]," "\"servers\":[" @@ -1658,7 +1658,7 @@ "\"advertised_alpns\":[\"h3\"]," "\"expiration\":\"13756212000000000\",\"port\":443," "\"protocol_str\":\"quic\"}]," - "\"isolation\":[]," + "\"anonymization\":[]," "\"server\":\"https://www.google.com:80\"}]," "\"supports_quic\":" "{\"address\":\"127.0.0.1\",\"used_quic\":true},\"version\":5}"; @@ -1691,7 +1691,7 @@ // Verify preferences updated with new advertised versions. const char expected_json_updated[] = "{\"quic_servers\":" - "[{\"isolation\":[]," + "[{\"anonymization\":[]," "\"server_id\":\"https://mail.google.com:80\"," "\"server_info\":\"quic_server_info1\"}]," "\"servers\":[" @@ -1699,7 +1699,7 @@ "[{\"advertised_alpns\":[\"h3-Q046\",\"h3-Q043\"]," "\"expiration\":\"13756212000000000\",\"port\":443," "\"protocol_str\":\"quic\"}]," - "\"isolation\":[]," + "\"anonymization\":[]," "\"server\":\"https://www.google.com:80\"}]," "\"supports_quic\":" "{\"address\":\"127.0.0.1\",\"used_quic\":true},\"version\":5}"; @@ -1727,7 +1727,7 @@ // Verify preferences updated with new advertised versions. const char expected_json_updated2[] = "{\"quic_servers\":" - "[{\"isolation\":[]," + "[{\"anonymization\":[]," "\"server_id\":\"https://mail.google.com:80\"," "\"server_info\":\"quic_server_info1\"}]," "\"servers\":[" @@ -1735,7 +1735,7 @@ "[{\"advertised_alpns\":[\"h3-Q043\",\"h3-Q046\"]," "\"expiration\":\"13756212000000000\",\"port\":443," "\"protocol_str\":\"quic\"}]," - "\"isolation\":[]," + "\"anonymization\":[]," "\"server\":\"https://www.google.com:80\"}]," "\"supports_quic\":" "{\"address\":\"127.0.0.1\",\"used_quic\":true},\"version\":5}"; @@ -1776,24 +1776,24 @@ "{\"broken_until\":\"" + expiration_str + "\"," - "\"host\":\"www.google.com\",\"isolation\":[]," + "\"host\":\"www.google.com\",\"anonymization\":[]," "\"port\":1234,\"protocol_str\":\"h2\"}," "{\"broken_count\":2,\"broken_until\":\"" + expiration_str + "\"," - "\"host\":\"cached_broken\",\"isolation\":[]," + "\"host\":\"cached_broken\",\"anonymization\":[]," "\"port\":443,\"protocol_str\":\"quic\"}," "{\"broken_count\":3," - "\"host\":\"cached_rbroken\",\"isolation\":[]," + "\"host\":\"cached_rbroken\",\"anonymization\":[]," "\"port\":443,\"protocol_str\":\"quic\"}]," "\"quic_servers\":[" - "{\"isolation\":[]," + "{\"anonymization\":[]," "\"server_id\":\"https://mail.google.com:80\"," "\"server_info\":\"quic_server_info1\"}" "]," "\"servers\":[" "{\"server\":\"https://www.google.com:80\"," - "\"isolation\":[]," + "\"anonymization\":[]," "\"alternative_service\":[" "{\"expiration\":\"13756212000000000\",\"port\":443," "\"protocol_str\":\"h2\"}," @@ -1802,7 +1802,7 @@ "]" "}," "{\"server\":\"https://mail.google.com:80\"," - "\"isolation\":[]," + "\"anonymization\":[]," "\"alternative_service\":[" "{\"expiration\":\"9223372036854775807\",\"host\":\"foo.google.com\"," "\"port\":444,\"protocol_str\":\"h2\"}" @@ -2062,7 +2062,7 @@ base::JSONWriter::Write(saved_value, &preferences_json); EXPECT_EQ( "{\"servers\":[" - "{\"isolation\":[]," + "{\"anonymization\":[]," "\"server\":\"https://foo.test\"," "\"supports_spdy\":true}]," "\"version\":5}", @@ -2186,7 +2186,7 @@ } else if (save_network_anonymization_key_mode == load_network_anonymization_key_mode) { // If the save and load modes are the same, the load should succeed, and - // the network isolation keys should match. + // the network anonymization keys should match. ASSERT_EQ(1u, server_info_map2->size()); const HttpServerProperties::ServerInfoMapKey& server_info_key2 = server_info_map2->begin()->first; @@ -2579,7 +2579,7 @@ } else if (save_network_anonymization_key_mode == load_network_anonymization_key_mode) { // If the save and load modes are the same, the load should succeed, and - // the network isolation keys should match. + // the network anonymization keys should match. EXPECT_TRUE(properties->IsAlternativeServiceBroken( kAlternativeService1, kNetworkAnonymizationKey1)); EXPECT_TRUE(properties->WasAlternativeServiceRecentlyBroken( @@ -2834,7 +2834,7 @@ } else if (save_network_anonymization_key_mode == load_network_anonymization_key_mode) { // If the save and load modes are the same, the load should succeed, and - // the network isolation keys should match. + // the network anonymization keys should match. EXPECT_EQ(kQuicServerInfo1, *properties->GetQuicServerInfo( kServer1, kNetworkAnonymizationKey1)); EXPECT_EQ(nullptr, properties->GetQuicServerInfo(
diff --git a/net/http/http_stream_factory_job.cc b/net/http/http_stream_factory_job.cc index 8ec0f66..c4a4e04 100644 --- a/net/http/http_stream_factory_job.cc +++ b/net/http/http_stream_factory_job.cc
@@ -333,7 +333,7 @@ bool require_dns_https_alpn = (job_type_ == DNS_ALPN_H3); return quic_request_.CanUseExistingSession( origin_url_, request_info_.privacy_mode, request_info_.socket_tag, - request_info_.network_isolation_key, request_info_.secure_dns_policy, + request_info_.network_anonymization_key, request_info_.secure_dns_policy, require_dns_https_alpn, destination_); } @@ -936,10 +936,10 @@ int rv = quic_request_.Request( std::move(destination), quic_version_, request_info_.privacy_mode, - priority_, request_info_.socket_tag, request_info_.network_isolation_key, - request_info_.secure_dns_policy, proxy_info_.is_direct(), - require_dns_https_alpn, ssl_config->GetCertVerifyFlags(), url, net_log_, - &net_error_details_, + priority_, request_info_.socket_tag, + request_info_.network_anonymization_key, request_info_.secure_dns_policy, + proxy_info_.is_direct(), require_dns_https_alpn, + ssl_config->GetCertVerifyFlags(), url, net_log_, &net_error_details_, base::BindOnce(&Job::OnFailedOnDefaultNetwork, ptr_factory_.GetWeakPtr()), io_callback_); if (rv == OK) {
diff --git a/net/quic/quic_stream_factory.cc b/net/quic/quic_stream_factory.cc index 0bb4794..cfe01ee 100644 --- a/net/quic/quic_stream_factory.cc +++ b/net/quic/quic_stream_factory.cc
@@ -1045,7 +1045,7 @@ PrivacyMode privacy_mode, RequestPriority priority, const SocketTag& socket_tag, - const NetworkIsolationKey& network_isolation_key, + const NetworkAnonymizationKey& network_anonymization_key, SecureDnsPolicy secure_dns_policy, bool use_dns_aliases, bool require_dns_https_alpn, @@ -1065,12 +1065,9 @@ failed_on_default_network_callback_ = std::move(failed_on_default_network_callback); - session_key_ = - QuicSessionKey(HostPortPair::FromURL(url), privacy_mode, socket_tag, - NetworkAnonymizationKey:: - CreateFromNetworkIsolationKeyTemporaryMigrationHelper( - network_isolation_key), - secure_dns_policy, require_dns_https_alpn); + session_key_ = QuicSessionKey(HostPortPair::FromURL(url), privacy_mode, + socket_tag, network_anonymization_key, + secure_dns_policy, require_dns_https_alpn); int rv = factory_->Create(session_key_, std::move(destination), quic_version, priority, use_dns_aliases, cert_verify_flags, url, @@ -1146,16 +1143,14 @@ const GURL& url, PrivacyMode privacy_mode, const SocketTag& socket_tag, - const NetworkIsolationKey& network_isolation_key, + const NetworkAnonymizationKey& network_anonymization_key, SecureDnsPolicy secure_dns_policy, bool require_dns_https_alpn, const url::SchemeHostPort& destination) const { return factory_->CanUseExistingSession( QuicSessionKey(HostPortPair::FromURL(url), privacy_mode, socket_tag, - NetworkAnonymizationKey:: - CreateFromNetworkIsolationKeyTemporaryMigrationHelper( - network_isolation_key), - secure_dns_policy, require_dns_https_alpn), + network_anonymization_key, secure_dns_policy, + require_dns_https_alpn), destination); } @@ -1220,7 +1215,7 @@ default_network_(handles::kInvalidNetworkHandle), connectivity_monitor_(default_network_), ssl_config_service_(ssl_config_service), - use_network_isolation_key_for_crypto_configs_( + use_network_anonymization_key_for_crypto_configs_( base::FeatureList::IsEnabled( features::kPartitionHttpServerPropertiesByNetworkIsolationKey)) { DCHECK(transport_security_state_); @@ -2209,21 +2204,22 @@ std::unique_ptr<QuicStreamFactory::CryptoClientConfigHandle> QuicStreamFactory::CreateCryptoConfigHandle( - const NetworkIsolationKey& network_isolation_key) { - NetworkIsolationKey actual_network_isolation_key = - use_network_isolation_key_for_crypto_configs_ ? network_isolation_key - : NetworkIsolationKey(); + const NetworkAnonymizationKey& network_anonymization_key) { + NetworkAnonymizationKey actual_network_anonymization_key = + use_network_anonymization_key_for_crypto_configs_ + ? network_anonymization_key + : NetworkAnonymizationKey(); // If there's a matching entry in |active_crypto_config_map_|, create a // CryptoClientConfigHandle for it. auto map_iterator = - active_crypto_config_map_.find(actual_network_isolation_key); + active_crypto_config_map_.find(actual_network_anonymization_key); if (map_iterator != active_crypto_config_map_.end()) { DCHECK_GT(map_iterator->second->num_refs(), 0); // If there's an active matching crypto config, there shouldn't also be an // inactive matching crypto config. - DCHECK(recent_crypto_config_map_.Peek(actual_network_isolation_key) == + DCHECK(recent_crypto_config_map_.Peek(actual_network_anonymization_key) == recent_crypto_config_map_.end()); return std::make_unique<CryptoClientConfigHandle>(map_iterator); @@ -2232,12 +2228,12 @@ // If there's a matching entry in |recent_crypto_config_map_|, move it to // |active_crypto_config_map_| and create a CryptoClientConfigHandle for it. auto mru_iterator = - recent_crypto_config_map_.Peek(actual_network_isolation_key); + recent_crypto_config_map_.Peek(actual_network_anonymization_key); if (mru_iterator != recent_crypto_config_map_.end()) { DCHECK_EQ(mru_iterator->second->num_refs(), 0); map_iterator = active_crypto_config_map_ - .emplace(std::make_pair(actual_network_isolation_key, + .emplace(std::make_pair(actual_network_anonymization_key, std::move(mru_iterator->second))) .first; recent_crypto_config_map_.Erase(mru_iterator); @@ -2252,7 +2248,7 @@ cert_verifier_, ct_policy_enforcer_, transport_security_state_, sct_auditing_delegate_, HostsFromOrigins(params_.origins_to_force_quic_on), - actual_network_isolation_key), + actual_network_anonymization_key), std::make_unique<quic::QuicClientSessionCache>(), this); quic::QuicCryptoClientConfig* crypto_config = crypto_config_owner->config(); @@ -2277,7 +2273,7 @@ } map_iterator = active_crypto_config_map_ - .emplace(std::make_pair(actual_network_isolation_key, + .emplace(std::make_pair(actual_network_anonymization_key, std::move(crypto_config_owner))) .first; return std::make_unique<CryptoClientConfigHandle>(map_iterator); @@ -2302,24 +2298,25 @@ std::unique_ptr<QuicCryptoClientConfigHandle> QuicStreamFactory::GetCryptoConfigForTesting( - const NetworkIsolationKey& network_isolation_key) { - return CreateCryptoConfigHandle(network_isolation_key); + const NetworkAnonymizationKey& network_anonymization_key) { + return CreateCryptoConfigHandle(network_anonymization_key); } bool QuicStreamFactory::CryptoConfigCacheIsEmptyForTesting( const quic::QuicServerId& server_id, - const NetworkIsolationKey& network_isolation_key) { + const NetworkAnonymizationKey& network_anonymization_key) { quic::QuicCryptoClientConfig::CachedState* cached = nullptr; - NetworkIsolationKey actual_network_isolation_key = - use_network_isolation_key_for_crypto_configs_ ? network_isolation_key - : NetworkIsolationKey(); + NetworkAnonymizationKey actual_network_anonymization_key = + use_network_anonymization_key_for_crypto_configs_ + ? network_anonymization_key + : NetworkAnonymizationKey(); auto map_iterator = - active_crypto_config_map_.find(actual_network_isolation_key); + active_crypto_config_map_.find(actual_network_anonymization_key); if (map_iterator != active_crypto_config_map_.end()) { cached = map_iterator->second->config()->LookupOrCreate(server_id); } else { auto mru_iterator = - recent_crypto_config_map_.Peek(actual_network_isolation_key); + recent_crypto_config_map_.Peek(actual_network_anonymization_key); if (mru_iterator != recent_crypto_config_map_.end()) { cached = mru_iterator->second->config()->LookupOrCreate(server_id); }
diff --git a/net/quic/quic_stream_factory.h b/net/quic/quic_stream_factory.h index 8d4f012..c7d074a 100644 --- a/net/quic/quic_stream_factory.h +++ b/net/quic/quic_stream_factory.h
@@ -71,7 +71,7 @@ class HostResolver; class HttpServerProperties; class NetLog; -class NetworkIsolationKey; +class NetworkAnonymizationKey; class QuicChromiumConnectionHelper; class QuicCryptoClientStreamFactory; class QuicServerInfo; @@ -91,8 +91,8 @@ // // TODO(mmenke): Should figure out a reasonable value of this, using field // trials. The optimal value may increase over time, as QUIC becomes more -// prevalent. Whether or not NetworkIsolationKeys end up including subframe URLs -// will also influence the ideal value. +// prevalent. Whether or not NetworkAnonymizationKeys end up including subframe +// URLs will also influence the ideal value. const int kMaxRecentCryptoConfigs = 100; enum QuicPlatformNotification { @@ -135,7 +135,7 @@ PrivacyMode privacy_mode, RequestPriority priority, const SocketTag& socket_tag, - const NetworkIsolationKey& network_isolation_key, + const NetworkAnonymizationKey& network_anonymization_key, SecureDnsPolicy secure_dns_policy, bool use_dns_aliases, bool require_dns_https_alpn, @@ -190,13 +190,14 @@ const NetLogWithSource& net_log() const { return net_log_; } - bool CanUseExistingSession(const GURL& url, - PrivacyMode privacy_mode, - const SocketTag& socket_tag, - const NetworkIsolationKey& network_isolation_key, - SecureDnsPolicy secure_dns_policy, - bool require_dns_https_alpn, - const url::SchemeHostPort& destination) const; + bool CanUseExistingSession( + const GURL& url, + PrivacyMode privacy_mode, + const SocketTag& socket_tag, + const NetworkAnonymizationKey& network_anonymization_key, + SecureDnsPolicy secure_dns_policy, + bool require_dns_https_alpn, + const url::SchemeHostPort& destination) const; private: raw_ptr<QuicStreamFactory> factory_; @@ -407,7 +408,7 @@ using DnsAliasesBySessionKeyMap = std::map<QuicSessionKey, std::set<std::string>>; using QuicCryptoClientConfigMap = - std::map<NetworkIsolationKey, + std::map<NetworkAnonymizationKey, std::unique_ptr<QuicCryptoClientConfigOwner>>; bool HasMatchingIpSession(const QuicSessionAliasKey& key, @@ -488,13 +489,14 @@ // `session` from `session_aliases_`. void UnmapSessionFromSessionAliases(QuicChromiumClientSession* session); - // Creates a CreateCryptoConfigHandle for the specified NetworkIsolationKey. - // If there's already a corresponding entry in |active_crypto_config_map_|, - // reuses it. If there's a corresponding entry in |recent_crypto_config_map_|, - // promotes it to |active_crypto_config_map_| and then reuses it. Otherwise, - // creates a new entry in |active_crypto_config_map_|. + // Creates a CreateCryptoConfigHandle for the specified + // NetworkAnonymizationKey. If there's already a corresponding entry in + // |active_crypto_config_map_|, reuses it. If there's a corresponding entry in + // |recent_crypto_config_map_|, promotes it to |active_crypto_config_map_| and + // then reuses it. Otherwise, creates a new entry in + // |active_crypto_config_map_|. std::unique_ptr<CryptoClientConfigHandle> CreateCryptoConfigHandle( - const NetworkIsolationKey& network_isolation_key); + const NetworkAnonymizationKey& network_anonymization_key); // Salled when the indicated member of |active_crypto_config_map_| has no // outstanding references. The QuicCryptoClientConfigOwner is then moved to @@ -511,11 +513,11 @@ handles::NetworkHandle affected_network) const; std::unique_ptr<QuicCryptoClientConfigHandle> GetCryptoConfigForTesting( - const NetworkIsolationKey& network_isolation_key); + const NetworkAnonymizationKey& network_anonymization_key); bool CryptoConfigCacheIsEmptyForTesting( const quic::QuicServerId& server_id, - const NetworkIsolationKey& network_isolation_key); + const NetworkAnonymizationKey& network_anonymization_key); const quic::ParsedQuicVersionVector& supported_versions() const { return params_.supported_versions; @@ -577,9 +579,9 @@ // |recent_crypto_config_map_|. If reused before it is evicted from LRUCache, // it will be removed from the cache and return to the active config map. // These two maps should never both have entries with the same - // NetworkIsolationKey. + // NetworkAnonymizationKey. QuicCryptoClientConfigMap active_crypto_config_map_; - base::LRUCache<NetworkIsolationKey, + base::LRUCache<NetworkAnonymizationKey, std::unique_ptr<QuicCryptoClientConfigOwner>> recent_crypto_config_map_; @@ -624,15 +626,15 @@ const raw_ptr<SSLConfigService> ssl_config_service_; - // Whether NetworkIsolationKeys should be used for + // Whether NetworkAnonymizationKeys should be used for // |active_crypto_config_map_|. If false, there will just be one config with - // an empty NetworkIsolationKey. Whether QuicSessionAliasKeys all have an + // an empty NetworkAnonymizationKey. Whether QuicSessionAliasKeys all have an // empty NIK is based on whether socket pools are respecting NIKs, but whether // those NIKs are also used when accessing |active_crypto_config_map_| is also // gated this, which is set based on whether HttpServerProperties is // respecting NIKs, as that data is fed into the crypto config map using the // corresponding NIK. - const bool use_network_isolation_key_for_crypto_configs_; + const bool use_network_anonymization_key_for_crypto_configs_; quic::DeterministicConnectionIdGenerator connection_id_generator_{ quic::kQuicDefaultConnectionIdLength};
diff --git a/net/quic/quic_stream_factory_fuzzer.cc b/net/quic/quic_stream_factory_fuzzer.cc index d891c70..ea974e5e 100644 --- a/net/quic/quic_stream_factory_fuzzer.cc +++ b/net/quic/quic_stream_factory_fuzzer.cc
@@ -159,7 +159,7 @@ request.Request( env->scheme_host_port, version, PRIVACY_MODE_DISABLED, DEFAULT_PRIORITY, - SocketTag(), NetworkIsolationKey(), SecureDnsPolicy::kAllow, + SocketTag(), NetworkAnonymizationKey(), SecureDnsPolicy::kAllow, true /* use_dns_aliases */, false /* require_dns_https_alpn */, kCertVerifyFlags, GURL(kUrl), env->net_log, &net_error_details, /*failed_on_default_network_callback=*/CompletionOnceCallback(),
diff --git a/net/socket/client_socket_pool.cc b/net/socket/client_socket_pool.cc index 2f8057aa..8531095 100644 --- a/net/socket/client_socket_pool.cc +++ b/net/socket/client_socket_pool.cc
@@ -186,24 +186,20 @@ resolution_callback = base::BindRepeating( &OnHostResolution, common_connect_job_params_->spdy_session_pool, // TODO(crbug.com/1206799): Pass along as SchemeHostPort. - SpdySessionKey( - HostPortPair::FromSchemeHostPort(group_id.destination()), - proxy_server, group_id.privacy_mode(), - SpdySessionKey::IsProxySession::kFalse, socket_tag, - net::NetworkAnonymizationKey::CreateFromNetworkIsolationKey( - group_id.network_anonymization_key()), - group_id.secure_dns_policy()), + SpdySessionKey(HostPortPair::FromSchemeHostPort(group_id.destination()), + proxy_server, group_id.privacy_mode(), + SpdySessionKey::IsProxySession::kFalse, socket_tag, + group_id.network_anonymization_key(), + group_id.secure_dns_policy()), is_for_websockets_); } else if (proxy_server.is_https()) { resolution_callback = base::BindRepeating( &OnHostResolution, common_connect_job_params_->spdy_session_pool, - SpdySessionKey( - proxy_server.host_port_pair(), ProxyServer::Direct(), - group_id.privacy_mode(), SpdySessionKey::IsProxySession::kTrue, - socket_tag, - net::NetworkAnonymizationKey::CreateFromNetworkIsolationKey( - group_id.network_anonymization_key()), - group_id.secure_dns_policy()), + SpdySessionKey(proxy_server.host_port_pair(), ProxyServer::Direct(), + group_id.privacy_mode(), + SpdySessionKey::IsProxySession::kTrue, socket_tag, + group_id.network_anonymization_key(), + group_id.secure_dns_policy()), is_for_websockets_); }
diff --git a/net/socket/client_socket_pool_base_unittest.cc b/net/socket/client_socket_pool_base_unittest.cc index a64a4e21..1b780a7 100644 --- a/net/socket/client_socket_pool_base_unittest.cc +++ b/net/socket/client_socket_pool_base_unittest.cc
@@ -31,7 +31,6 @@ #include "net/base/load_timing_info_test_util.h" #include "net/base/net_errors.h" #include "net/base/network_anonymization_key.h" -#include "net/base/network_isolation_key.h" #include "net/base/privacy_mode.h" #include "net/base/proxy_server.h" #include "net/base/proxy_string_util.h" @@ -554,7 +553,7 @@ const OnHostResolutionCallback& resolution_callback, RequestPriority request_priority, SocketTag socket_tag, - const NetworkIsolationKey& network_isolation_key, + const NetworkAnonymizationKey& network_anonymization_key, SecureDnsPolicy secure_dns_policy, const CommonConnectJobParams* common_connect_job_params, ConnectJob::Delegate* delegate) const override { @@ -5741,7 +5740,7 @@ static ClientSocketPool::GroupId GetGroupIdInPartition() { // Note this GroupId will match GetGroupId() unless - // kPartitionConnectionsByNetworkIsolationKey is enabled. + // kPartitionConnectionsByNetworkAnonymizationKey is enabled. const SchemefulSite kSite(GURL("https://b/")); const NetworkAnonymizationKey kNetworkAnonymizationKey( kSite, kSite, /*is_cross_site=*/false);
diff --git a/net/socket/connect_job_factory.cc b/net/socket/connect_job_factory.cc index e8313d9..778faf5 100644 --- a/net/socket/connect_job_factory.cc +++ b/net/socket/connect_job_factory.cc
@@ -11,7 +11,7 @@ #include "base/containers/flat_set.h" #include "base/memory/scoped_refptr.h" #include "net/base/host_port_pair.h" -#include "net/base/network_isolation_key.h" +#include "net/base/network_anonymization_key.h" #include "net/base/privacy_mode.h" #include "net/base/proxy_server.h" #include "net/base/request_priority.h" @@ -114,15 +114,16 @@ const OnHostResolutionCallback& resolution_callback, RequestPriority request_priority, SocketTag socket_tag, - const NetworkIsolationKey& network_isolation_key, + const NetworkAnonymizationKey& network_anonymization_key, SecureDnsPolicy secure_dns_policy, const CommonConnectJobParams* common_connect_job_params, ConnectJob::Delegate* delegate) const { - return CreateConnectJob( - Endpoint(std::move(endpoint)), proxy_server, proxy_annotation_tag, - ssl_config_for_origin, ssl_config_for_proxy, force_tunnel, privacy_mode, - resolution_callback, request_priority, socket_tag, network_isolation_key, - secure_dns_policy, common_connect_job_params, delegate); + return CreateConnectJob(Endpoint(std::move(endpoint)), proxy_server, + proxy_annotation_tag, ssl_config_for_origin, + ssl_config_for_proxy, force_tunnel, privacy_mode, + resolution_callback, request_priority, socket_tag, + network_anonymization_key, secure_dns_policy, + common_connect_job_params, delegate); } std::unique_ptr<ConnectJob> ConnectJobFactory::CreateConnectJob( @@ -137,16 +138,17 @@ const OnHostResolutionCallback& resolution_callback, RequestPriority request_priority, SocketTag socket_tag, - const NetworkIsolationKey& network_isolation_key, + const NetworkAnonymizationKey& network_anonymization_key, SecureDnsPolicy secure_dns_policy, const CommonConnectJobParams* common_connect_job_params, ConnectJob::Delegate* delegate) const { SchemelessEndpoint schemeless_endpoint{using_ssl, std::move(endpoint)}; - return CreateConnectJob( - std::move(schemeless_endpoint), proxy_server, proxy_annotation_tag, - ssl_config_for_origin, ssl_config_for_proxy, force_tunnel, privacy_mode, - resolution_callback, request_priority, socket_tag, network_isolation_key, - secure_dns_policy, common_connect_job_params, delegate); + return CreateConnectJob(std::move(schemeless_endpoint), proxy_server, + proxy_annotation_tag, ssl_config_for_origin, + ssl_config_for_proxy, force_tunnel, privacy_mode, + resolution_callback, request_priority, socket_tag, + network_anonymization_key, secure_dns_policy, + common_connect_job_params, delegate); } std::unique_ptr<ConnectJob> ConnectJobFactory::CreateConnectJob( @@ -160,7 +162,7 @@ const OnHostResolutionCallback& resolution_callback, RequestPriority request_priority, SocketTag socket_tag, - const NetworkIsolationKey& network_isolation_key, + const NetworkAnonymizationKey& network_anonymization_key, SecureDnsPolicy secure_dns_policy, const CommonConnectJobParams* common_connect_job_params, ConnectJob::Delegate* delegate) const { @@ -173,7 +175,7 @@ // `SchemeHostPort`, so proxies can participate in ECH? Note doing so with // `SCHEME_HTTP` requires handling the HTTPS record upgrade. auto proxy_tcp_params = base::MakeRefCounted<TransportSocketParams>( - proxy_server.host_port_pair(), proxy_dns_network_isolation_key_, + proxy_server.host_port_pair(), proxy_dns_network_anonymization_key_, secure_dns_policy, resolution_callback, proxy_server.is_secure_http_like() ? SupportedProtocolsFromSSLConfig(*ssl_config_for_proxy) @@ -187,10 +189,7 @@ ssl_params = base::MakeRefCounted<SSLSocketParams>( std::move(proxy_tcp_params), nullptr, nullptr, proxy_server.host_port_pair(), *ssl_config_for_proxy, - PRIVACY_MODE_DISABLED, - NetworkAnonymizationKey:: - CreateFromNetworkIsolationKeyTemporaryMigrationHelper( - network_isolation_key)); + PRIVACY_MODE_DISABLED, network_anonymization_key); proxy_tcp_params = nullptr; } @@ -200,7 +199,7 @@ std::move(proxy_tcp_params), std::move(ssl_params), proxy_server.is_quic(), ToHostPortPair(endpoint), force_tunnel || UsingSsl(endpoint), *proxy_annotation_tag, - network_isolation_key); + network_anonymization_key); } else { DCHECK(proxy_server.is_socks()); // TODO(crbug.com/1206799): Pass `endpoint` directly (preserving scheme @@ -208,7 +207,7 @@ socks_params = base::MakeRefCounted<SOCKSSocketParams>( std::move(proxy_tcp_params), proxy_server.scheme() == ProxyServer::SCHEME_SOCKS5, - ToHostPortPair(endpoint), network_isolation_key, + ToHostPortPair(endpoint), network_anonymization_key, *proxy_annotation_tag); } } @@ -219,7 +218,7 @@ scoped_refptr<TransportSocketParams> ssl_tcp_params; if (proxy_server.is_direct()) { ssl_tcp_params = base::MakeRefCounted<TransportSocketParams>( - ToTransportEndpoint(endpoint), network_isolation_key, + ToTransportEndpoint(endpoint), network_anonymization_key, secure_dns_policy, resolution_callback, SupportedProtocolsFromSSLConfig(*ssl_config_for_origin)); } @@ -228,10 +227,7 @@ auto ssl_params = base::MakeRefCounted<SSLSocketParams>( std::move(ssl_tcp_params), std::move(socks_params), std::move(http_proxy_params), ToHostPortPair(endpoint), - *ssl_config_for_origin, privacy_mode, - NetworkAnonymizationKey:: - CreateFromNetworkIsolationKeyTemporaryMigrationHelper( - network_isolation_key)); + *ssl_config_for_origin, privacy_mode, network_anonymization_key); return ssl_connect_job_factory_->Create( request_priority, socket_tag, common_connect_job_params, std::move(ssl_params), delegate, /*net_log=*/nullptr); @@ -252,8 +248,8 @@ // Only SSL/TLS-based endpoints have ALPN protocols. DCHECK(proxy_server.is_direct()); auto tcp_params = base::MakeRefCounted<TransportSocketParams>( - ToTransportEndpoint(endpoint), network_isolation_key, secure_dns_policy, - resolution_callback, no_alpn_protocols); + ToTransportEndpoint(endpoint), network_anonymization_key, + secure_dns_policy, resolution_callback, no_alpn_protocols); return transport_connect_job_factory_->Create( request_priority, socket_tag, common_connect_job_params, tcp_params, delegate, /*net_log=*/nullptr);
diff --git a/net/socket/connect_job_factory.h b/net/socket/connect_job_factory.h index 02f19e6..6ea30912 100644 --- a/net/socket/connect_job_factory.h +++ b/net/socket/connect_job_factory.h
@@ -8,7 +8,7 @@ #include <memory> #include "net/base/host_port_pair.h" -#include "net/base/network_isolation_key.h" +#include "net/base/network_anonymization_key.h" #include "net/base/privacy_mode.h" #include "net/base/request_priority.h" #include "net/dns/public/secure_dns_policy.h" @@ -24,7 +24,7 @@ namespace net { -class NetworkIsolationKey; +class NetworkAnonymizationKey; struct NetworkTrafficAnnotationTag; class ProxyServer; struct SSLConfig; @@ -73,7 +73,7 @@ const OnHostResolutionCallback& resolution_callback, RequestPriority request_priority, SocketTag socket_tag, - const NetworkIsolationKey& network_isolation_key, + const NetworkAnonymizationKey& network_anonymization_key, SecureDnsPolicy secure_dns_policy, const CommonConnectJobParams* common_connect_job_params, ConnectJob::Delegate* delegate) const; @@ -92,7 +92,7 @@ const OnHostResolutionCallback& resolution_callback, RequestPriority request_priority, SocketTag socket_tag, - const NetworkIsolationKey& network_isolation_key, + const NetworkAnonymizationKey& network_anonymization_key, SecureDnsPolicy secure_dns_policy, const CommonConnectJobParams* common_connect_job_params, ConnectJob::Delegate* delegate) const; @@ -109,7 +109,7 @@ const OnHostResolutionCallback& resolution_callback, RequestPriority request_priority, SocketTag socket_tag, - const NetworkIsolationKey& network_isolation_key, + const NetworkAnonymizationKey& network_anonymization_key, SecureDnsPolicy secure_dns_policy, const CommonConnectJobParams* common_connect_job_params, ConnectJob::Delegate* delegate) const; @@ -119,12 +119,12 @@ std::unique_ptr<SSLConnectJob::Factory> ssl_connect_job_factory_; std::unique_ptr<TransportConnectJob::Factory> transport_connect_job_factory_; - // Use a single NetworkIsolationKey for looking up proxy hostnames. Proxies - // are typically used across sites, but cached proxy IP addresses don't - // really expose useful information to destination sites, and not caching - // them has a performance cost. - net::NetworkIsolationKey proxy_dns_network_isolation_key_ = - net::NetworkIsolationKey::CreateTransient(); + // Use a single NetworkAnonymizationKey for looking up proxy hostnames. + // Proxies are typically used across sites, but cached proxy IP addresses + // don't really expose useful information to destination sites, and not + // caching them has a performance cost. + net::NetworkAnonymizationKey proxy_dns_network_anonymization_key_ = + net::NetworkAnonymizationKey::CreateTransient(); }; } // namespace net
diff --git a/net/socket/connect_job_factory_unittest.cc b/net/socket/connect_job_factory_unittest.cc index a5ce24f..45d59922 100644 --- a/net/socket/connect_job_factory_unittest.cc +++ b/net/socket/connect_job_factory_unittest.cc
@@ -203,7 +203,7 @@ /*ssl_config_for_proxy=*/nullptr, /*force_tunnel=*/false, PrivacyMode::PRIVACY_MODE_DISABLED, OnHostResolutionCallback(), DEFAULT_PRIORITY, SocketTag(), - NetworkIsolationKey(), SecureDnsPolicy::kAllow, + NetworkAnonymizationKey(), SecureDnsPolicy::kAllow, &common_connect_job_params_, &delegate_); EXPECT_EQ(GetCreationCount(), 1u); @@ -224,7 +224,7 @@ /*ssl_config_for_proxy=*/nullptr, /*force_tunnel=*/false, PrivacyMode::PRIVACY_MODE_DISABLED, OnHostResolutionCallback(), DEFAULT_PRIORITY, SocketTag(), - NetworkIsolationKey(), SecureDnsPolicy::kAllow, + NetworkAnonymizationKey(), SecureDnsPolicy::kAllow, &common_connect_job_params_, &delegate_); EXPECT_EQ(GetCreationCount(), 1u); @@ -247,7 +247,7 @@ /*ssl_config_for_proxy=*/nullptr, /*force_tunnel=*/false, PrivacyMode::PRIVACY_MODE_DISABLED, OnHostResolutionCallback(), DEFAULT_PRIORITY, SocketTag(), - NetworkIsolationKey(), SecureDnsPolicy::kAllow, + NetworkAnonymizationKey(), SecureDnsPolicy::kAllow, &common_connect_job_params_, &delegate_); EXPECT_EQ(GetCreationCount(), 1u); @@ -276,7 +276,7 @@ /*ssl_config_for_proxy=*/nullptr, /*force_tunnel=*/false, PrivacyMode::PRIVACY_MODE_DISABLED, OnHostResolutionCallback(), DEFAULT_PRIORITY, SocketTag(), - NetworkIsolationKey(), SecureDnsPolicy::kAllow, + NetworkAnonymizationKey(), SecureDnsPolicy::kAllow, &common_connect_job_params_, &delegate_); EXPECT_EQ(GetCreationCount(), 1u); @@ -302,7 +302,7 @@ /*ssl_config_for_proxy=*/nullptr, /*force_tunnel=*/false, PrivacyMode::PRIVACY_MODE_DISABLED, OnHostResolutionCallback(), DEFAULT_PRIORITY, SocketTag(), - NetworkIsolationKey(), SecureDnsPolicy::kAllow, + NetworkAnonymizationKey(), SecureDnsPolicy::kAllow, &common_connect_job_params_, &delegate_); EXPECT_EQ(GetCreationCount(), 1u); @@ -329,7 +329,7 @@ /*ssl_config_for_proxy=*/nullptr, /*force_tunnel=*/false, PrivacyMode::PRIVACY_MODE_DISABLED, OnHostResolutionCallback(), DEFAULT_PRIORITY, SocketTag(), - NetworkIsolationKey(), SecureDnsPolicy::kAllow, + NetworkAnonymizationKey(), SecureDnsPolicy::kAllow, &common_connect_job_params_, &delegate_); EXPECT_EQ(GetCreationCount(), 1u); @@ -357,7 +357,7 @@ /*ssl_config_for_proxy=*/nullptr, /*force_tunnel=*/false, PrivacyMode::PRIVACY_MODE_DISABLED, OnHostResolutionCallback(), DEFAULT_PRIORITY, SocketTag(), - NetworkIsolationKey(), SecureDnsPolicy::kAllow, + NetworkAnonymizationKey(), SecureDnsPolicy::kAllow, &common_connect_job_params_, &delegate_); EXPECT_EQ(GetCreationCount(), 1u); @@ -392,7 +392,7 @@ /*ssl_config_for_proxy=*/nullptr, /*force_tunnel=*/false, PrivacyMode::PRIVACY_MODE_DISABLED, OnHostResolutionCallback(), DEFAULT_PRIORITY, SocketTag(), - NetworkIsolationKey(), SecureDnsPolicy::kAllow, + NetworkAnonymizationKey(), SecureDnsPolicy::kAllow, &common_connect_job_params_, &delegate_); EXPECT_EQ(GetCreationCount(), 1u); @@ -425,7 +425,7 @@ /*ssl_config_for_proxy=*/&ssl_config, /*force_tunnel=*/false, PrivacyMode::PRIVACY_MODE_DISABLED, OnHostResolutionCallback(), DEFAULT_PRIORITY, SocketTag(), - NetworkIsolationKey(), SecureDnsPolicy::kAllow, + NetworkAnonymizationKey(), SecureDnsPolicy::kAllow, &common_connect_job_params_, &delegate_); EXPECT_EQ(GetCreationCount(), 1u); @@ -458,7 +458,7 @@ /*ssl_config_for_proxy=*/&ssl_config, /*force_tunnel=*/false, PrivacyMode::PRIVACY_MODE_DISABLED, OnHostResolutionCallback(), DEFAULT_PRIORITY, SocketTag(), - NetworkIsolationKey(), SecureDnsPolicy::kAllow, + NetworkAnonymizationKey(), SecureDnsPolicy::kAllow, &common_connect_job_params_, &delegate_); EXPECT_EQ(GetCreationCount(), 1u); @@ -490,7 +490,7 @@ /*ssl_config_for_proxy=*/nullptr, /*force_tunnel=*/false, PrivacyMode::PRIVACY_MODE_DISABLED, OnHostResolutionCallback(), DEFAULT_PRIORITY, SocketTag(), - NetworkIsolationKey(), SecureDnsPolicy::kAllow, + NetworkAnonymizationKey(), SecureDnsPolicy::kAllow, &common_connect_job_params_, &delegate_); EXPECT_EQ(GetCreationCount(), 1u); @@ -515,7 +515,7 @@ /*ssl_config_for_proxy=*/nullptr, /*force_tunnel=*/false, PrivacyMode::PRIVACY_MODE_DISABLED, OnHostResolutionCallback(), DEFAULT_PRIORITY, SocketTag(), - NetworkIsolationKey(), SecureDnsPolicy::kAllow, + NetworkAnonymizationKey(), SecureDnsPolicy::kAllow, &common_connect_job_params_, &delegate_); EXPECT_EQ(GetCreationCount(), 1u); @@ -544,7 +544,7 @@ /*ssl_config_for_proxy=*/nullptr, /*force_tunnel=*/false, PrivacyMode::PRIVACY_MODE_DISABLED, OnHostResolutionCallback(), DEFAULT_PRIORITY, SocketTag(), - NetworkIsolationKey(), SecureDnsPolicy::kAllow, + NetworkAnonymizationKey(), SecureDnsPolicy::kAllow, &common_connect_job_params, &delegate_); EXPECT_EQ(GetCreationCount(), 1u); @@ -570,7 +570,7 @@ /*ssl_config_for_proxy=*/nullptr, /*force_tunnel=*/false, PrivacyMode::PRIVACY_MODE_DISABLED, OnHostResolutionCallback(), DEFAULT_PRIORITY, SocketTag(), - NetworkIsolationKey(), SecureDnsPolicy::kAllow, + NetworkAnonymizationKey(), SecureDnsPolicy::kAllow, &common_connect_job_params, &delegate_); EXPECT_EQ(GetCreationCount(), 1u);
diff --git a/net/socket/ssl_connect_job_unittest.cc b/net/socket/ssl_connect_job_unittest.cc index 327c3b1c..a0ad43f 100644 --- a/net/socket/ssl_connect_job_unittest.cc +++ b/net/socket/ssl_connect_job_unittest.cc
@@ -103,7 +103,7 @@ direct_transport_socket_params_( base::MakeRefCounted<TransportSocketParams>( url::SchemeHostPort(url::kHttpsScheme, "host", 443), - NetworkIsolationKey(), + NetworkAnonymizationKey(), SecureDnsPolicy::kAllow, OnHostResolutionCallback(), /*supported_alpns=*/ @@ -111,7 +111,7 @@ proxy_transport_socket_params_( base::MakeRefCounted<TransportSocketParams>( HostPortPair("proxy", 443), - NetworkIsolationKey(), + NetworkAnonymizationKey(), SecureDnsPolicy::kAllow, OnHostResolutionCallback(), /*supported_alpns=*/base::flat_set<std::string>({}))), @@ -119,7 +119,7 @@ proxy_transport_socket_params_, true, HostPortPair("sockshost", 443), - NetworkIsolationKey(), + NetworkAnonymizationKey(), TRAFFIC_ANNOTATION_FOR_TESTS)), http_proxy_socket_params_(base::MakeRefCounted<HttpProxySocketParams>( proxy_transport_socket_params_, @@ -128,7 +128,7 @@ HostPortPair("host", 80), /*tunnel=*/true, TRAFFIC_ANNOTATION_FOR_TESTS, - NetworkIsolationKey())), + NetworkAnonymizationKey())), common_connect_job_params_(session_->CreateCommonConnectJobParams()) {} ~SSLConnectJobTest() override = default; @@ -157,7 +157,7 @@ const std::u16string kBar(u"bar"); session_->http_auth_cache()->Add( url::SchemeHostPort(GURL("http://proxy:443/")), HttpAuth::AUTH_PROXY, - "MyRealm1", HttpAuth::AUTH_SCHEME_BASIC, NetworkIsolationKey(), + "MyRealm1", HttpAuth::AUTH_SCHEME_BASIC, NetworkAnonymizationKey(), "Basic realm=MyRealm1", AuthCredentials(kFoo, kBar), "/"); } @@ -447,7 +447,7 @@ direct_transport_socket_params_ = base::MakeRefCounted<TransportSocketParams>( url::SchemeHostPort(url::kHttpsScheme, "host", 443), - NetworkIsolationKey(), secure_dns_policy, + NetworkAnonymizationKey(), secure_dns_policy, OnHostResolutionCallback(), /*supported_alpns=*/base::flat_set<std::string>{"h2", "http/1.1"}); auto common_connect_job_params = session_->CreateCommonConnectJobParams();
diff --git a/net/test/spawned_test_server/base_test_server.cc b/net/test/spawned_test_server/base_test_server.cc index ea60deb..a2ebd3e 100644 --- a/net/test/spawned_test_server/base_test_server.cc +++ b/net/test/spawned_test_server/base_test_server.cc
@@ -225,12 +225,10 @@ } ScopedTestRoot BaseTestServer::RegisterTestCerts() { - auto root1 = - ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem"); - auto root2 = ImportCertFromFile(GetTestCertsDirectory(), "root_ca_cert.pem"); - if (!root1 || !root2) + auto root = ImportCertFromFile(GetTestCertsDirectory(), "root_ca_cert.pem"); + if (!root) return ScopedTestRoot(); - return ScopedTestRoot(CertificateList{root1, root2}); + return ScopedTestRoot(CertificateList{root}); } bool BaseTestServer::LoadTestRootCert() {
diff --git a/net/url_request/url_request_unittest.cc b/net/url_request/url_request_unittest.cc index fb4708a..ac28f78 100644 --- a/net/url_request/url_request_unittest.cc +++ b/net/url_request/url_request_unittest.cc
@@ -13089,8 +13089,8 @@ TEST_F(URLRequestTest, SetIsolationInfoFromNakTripleNikTripleNak) { base::test::ScopedFeatureList scoped_feature_list_; - std::vector<base::Feature> enabled_features = {}; - std::vector<base::Feature> disabled_features = { + std::vector<base::test::FeatureRef> enabled_features = {}; + std::vector<base::test::FeatureRef> disabled_features = { net::features::kEnableDoubleKeyNetworkAnonymizationKey, net::features::kForceIsolationInfoFrameOriginToTopLevelFrame, net::features::kEnableCrossSiteFlagNetworkAnonymizationKey}; @@ -13150,10 +13150,10 @@ TEST_F(URLRequestTest, SetIsolationInfoFromNakDoubleNikDoubleNak) { base::test::ScopedFeatureList scoped_feature_list_; - std::vector<base::Feature> enabled_features = { + std::vector<base::test::FeatureRef> enabled_features = { net::features::kEnableDoubleKeyNetworkAnonymizationKey, net::features::kForceIsolationInfoFrameOriginToTopLevelFrame}; - std::vector<base::Feature> disabled_features = { + std::vector<base::test::FeatureRef> disabled_features = { net::features::kEnableCrossSiteFlagNetworkAnonymizationKey}; scoped_feature_list_.InitWithFeatures(enabled_features, disabled_features); @@ -13208,9 +13208,9 @@ TEST_F(URLRequestTest, SetIsolationInfoFromNakTripleNikDoubleNak) { base::test::ScopedFeatureList scoped_feature_list_; - std::vector<base::Feature> enabled_features = { + std::vector<base::test::FeatureRef> enabled_features = { net::features::kEnableDoubleKeyNetworkAnonymizationKey}; - std::vector<base::Feature> disabled_features = { + std::vector<base::test::FeatureRef> disabled_features = { net::features::kForceIsolationInfoFrameOriginToTopLevelFrame, net::features::kEnableCrossSiteFlagNetworkAnonymizationKey}; scoped_feature_list_.InitWithFeatures(enabled_features, disabled_features); @@ -13270,10 +13270,10 @@ TEST_F(URLRequestTest, SetIsolationInfoFromNakTripleNikDoubleWithCrossSiteFlagNak) { base::test::ScopedFeatureList scoped_feature_list_; - std::vector<base::Feature> enabled_features = { + std::vector<base::test::FeatureRef> enabled_features = { net::features::kEnableDoubleKeyNetworkAnonymizationKey, net::features::kEnableCrossSiteFlagNetworkAnonymizationKey}; - std::vector<base::Feature> disabled_features = { + std::vector<base::test::FeatureRef> disabled_features = { net::features::kForceIsolationInfoFrameOriginToTopLevelFrame}; scoped_feature_list_.InitWithFeatures(enabled_features, disabled_features);
diff --git a/pdf/pdf_view_plugin_base.h b/pdf/pdf_view_plugin_base.h index 86d5669..8b276e7 100644 --- a/pdf/pdf_view_plugin_base.h +++ b/pdf/pdf_view_plugin_base.h
@@ -61,12 +61,6 @@ void DocumentLoadFailed() override; void SelectionChanged(const gfx::Rect& left, const gfx::Rect& right) override; - // Gets the content restrictions based on the permissions which `engine_` has. - int GetContentRestrictions() const; - - // Gets the accessibility doc info based on the information from `engine_`. - AccessibilityDocInfo GetAccessibilityDocInfo() const; - protected: PdfViewPluginBase(); ~PdfViewPluginBase() override; @@ -152,6 +146,12 @@ // Starts loading accessibility information. void LoadAccessibility(); + + // Gets the content restrictions based on the permissions which `engine_` has. + int GetContentRestrictions() const; + + // Gets the accessibility doc info based on the information from `engine_`. + AccessibilityDocInfo GetAccessibilityDocInfo() const; }; } // namespace chrome_pdf
diff --git a/pdf/pdf_view_web_plugin.h b/pdf/pdf_view_web_plugin.h index f183a8e..e6c9a6f 100644 --- a/pdf/pdf_view_web_plugin.h +++ b/pdf/pdf_view_web_plugin.h
@@ -384,6 +384,14 @@ return document_load_state_; } + int GetContentRestrictionsForTesting() const { + return GetContentRestrictions(); + } + + AccessibilityDocInfo GetAccessibilityDocInfoForTesting() const { + return GetAccessibilityDocInfo(); + } + protected: // PdfViewPluginBase: const PDFiumEngine* engine() const override;
diff --git a/pdf/pdf_view_web_plugin_unittest.cc b/pdf/pdf_view_web_plugin_unittest.cc index e679510..611198869 100644 --- a/pdf/pdf_view_web_plugin_unittest.cc +++ b/pdf/pdf_view_web_plugin_unittest.cc
@@ -35,7 +35,6 @@ #include "pdf/mojom/pdf.mojom.h" #include "pdf/paint_ready_rect.h" #include "pdf/pdf_accessibility_data_handler.h" -#include "pdf/pdf_view_plugin_base.h" #include "pdf/test/mock_web_associated_url_loader.h" #include "pdf/test/test_helpers.h" #include "pdf/test/test_pdfium_engine.h" @@ -594,7 +593,7 @@ EXPECT_CALL(pdf_service_, UpdateContentRestrictions).Times(0); plugin_->CreateUrlLoader(); - EXPECT_EQ(PdfViewPluginBase::DocumentLoadState::kLoading, + EXPECT_EQ(PdfViewWebPlugin::DocumentLoadState::kLoading, plugin_->document_load_state_for_testing()); pdf_receiver_.FlushForTesting(); } @@ -606,7 +605,7 @@ kContentRestrictionPrint)); plugin_->CreateUrlLoader(); - EXPECT_EQ(PdfViewPluginBase::DocumentLoadState::kLoading, + EXPECT_EQ(PdfViewWebPlugin::DocumentLoadState::kLoading, plugin_->document_load_state_for_testing()); pdf_receiver_.FlushForTesting(); } @@ -646,7 +645,7 @@ EXPECT_CALL(pdf_service_, UpdateContentRestrictions).Times(0); plugin_->DocumentLoadComplete(); - EXPECT_EQ(PdfViewPluginBase::DocumentLoadState::kComplete, + EXPECT_EQ(PdfViewWebPlugin::DocumentLoadState::kComplete, plugin_->document_load_state_for_testing()); pdf_receiver_.FlushForTesting(); } @@ -678,7 +677,7 @@ kContentRestrictionCopy)); plugin_->DocumentLoadComplete(); - EXPECT_EQ(PdfViewPluginBase::DocumentLoadState::kComplete, + EXPECT_EQ(PdfViewWebPlugin::DocumentLoadState::kComplete, plugin_->document_load_state_for_testing()); pdf_receiver_.FlushForTesting(); } @@ -690,7 +689,7 @@ EXPECT_CALL(*client_ptr_, DidStopLoading).Times(0); plugin_->DocumentLoadFailed(); - EXPECT_EQ(PdfViewPluginBase::DocumentLoadState::kFailed, + EXPECT_EQ(PdfViewWebPlugin::DocumentLoadState::kFailed, plugin_->document_load_state_for_testing()); } @@ -701,7 +700,7 @@ EXPECT_CALL(*client_ptr_, DidStopLoading); plugin_->DocumentLoadFailed(); - EXPECT_EQ(PdfViewPluginBase::DocumentLoadState::kFailed, + EXPECT_EQ(PdfViewWebPlugin::DocumentLoadState::kFailed, plugin_->document_load_state_for_testing()); } @@ -834,7 +833,7 @@ TEST_F(PdfViewWebPluginTest, GetContentRestrictionsWithNoPermissions) { EXPECT_EQ(kContentRestrictionCopy | kContentRestrictionCut | kContentRestrictionPaste | kContentRestrictionPrint, - plugin_->GetContentRestrictions()); + plugin_->GetContentRestrictionsForTesting()); EXPECT_FALSE(plugin_->CanCopy()); } @@ -845,7 +844,7 @@ EXPECT_EQ(kContentRestrictionCut | kContentRestrictionPaste | kContentRestrictionPrint, - plugin_->GetContentRestrictions()); + plugin_->GetContentRestrictionsForTesting()); EXPECT_TRUE(plugin_->CanCopy()); } @@ -856,7 +855,7 @@ EXPECT_EQ(kContentRestrictionCopy | kContentRestrictionCut | kContentRestrictionPaste, - plugin_->GetContentRestrictions()); + plugin_->GetContentRestrictionsForTesting()); } TEST_F(PdfViewWebPluginTest, @@ -868,7 +867,7 @@ .WillRepeatedly(Return(true)); EXPECT_EQ(kContentRestrictionCut | kContentRestrictionPaste, - plugin_->GetContentRestrictions()); + plugin_->GetContentRestrictionsForTesting()); } TEST_F(PdfViewWebPluginTest, GetContentRestrictionsWithPrintAllowed) { @@ -881,7 +880,7 @@ EXPECT_EQ(kContentRestrictionCopy | kContentRestrictionCut | kContentRestrictionPaste, - plugin_->GetContentRestrictions()); + plugin_->GetContentRestrictionsForTesting()); } TEST_F(PdfViewWebPluginTest, GetContentRestrictionsWithCopyAndPrintAllowed) { @@ -895,11 +894,11 @@ .WillRepeatedly(Return(true)); EXPECT_EQ(kContentRestrictionCut | kContentRestrictionPaste, - plugin_->GetContentRestrictions()); + plugin_->GetContentRestrictionsForTesting()); } TEST_F(PdfViewWebPluginTest, GetAccessibilityDocInfoWithNoPermissions) { - AccessibilityDocInfo doc_info = plugin_->GetAccessibilityDocInfo(); + AccessibilityDocInfo doc_info = plugin_->GetAccessibilityDocInfoForTesting(); EXPECT_EQ(TestPDFiumEngine::kPageNumber, doc_info.page_count); EXPECT_FALSE(doc_info.text_accessible); @@ -911,7 +910,7 @@ EXPECT_CALL(*engine_ptr_, HasPermission(DocumentPermission::kCopy)) .WillRepeatedly(Return(true)); - AccessibilityDocInfo doc_info = plugin_->GetAccessibilityDocInfo(); + AccessibilityDocInfo doc_info = plugin_->GetAccessibilityDocInfoForTesting(); EXPECT_EQ(TestPDFiumEngine::kPageNumber, doc_info.page_count); EXPECT_FALSE(doc_info.text_accessible); @@ -923,7 +922,7 @@ EXPECT_CALL(*engine_ptr_, HasPermission(DocumentPermission::kCopyAccessible)) .WillRepeatedly(Return(true)); - AccessibilityDocInfo doc_info = plugin_->GetAccessibilityDocInfo(); + AccessibilityDocInfo doc_info = plugin_->GetAccessibilityDocInfoForTesting(); EXPECT_EQ(TestPDFiumEngine::kPageNumber, doc_info.page_count); EXPECT_TRUE(doc_info.text_accessible); @@ -938,7 +937,7 @@ EXPECT_CALL(*engine_ptr_, HasPermission(DocumentPermission::kCopyAccessible)) .WillRepeatedly(Return(true)); - AccessibilityDocInfo doc_info = plugin_->GetAccessibilityDocInfo(); + AccessibilityDocInfo doc_info = plugin_->GetAccessibilityDocInfoForTesting(); EXPECT_EQ(TestPDFiumEngine::kPageNumber, doc_info.page_count); EXPECT_TRUE(doc_info.text_accessible); @@ -2256,7 +2255,7 @@ EXPECT_CALL(pdf_service_, UpdateContentRestrictions).Times(0); plugin_->DocumentLoadComplete(); - EXPECT_EQ(PdfViewPluginBase::DocumentLoadState::kComplete, + EXPECT_EQ(PdfViewWebPlugin::DocumentLoadState::kComplete, plugin_->document_load_state_for_testing()); pdf_receiver_.FlushForTesting(); }
diff --git a/remoting/host/file_transfer/ipc_file_operations.cc b/remoting/host/file_transfer/ipc_file_operations.cc index 7e0ae9f..ff25fa8c 100644 --- a/remoting/host/file_transfer/ipc_file_operations.cc +++ b/remoting/host/file_transfer/ipc_file_operations.cc
@@ -94,7 +94,7 @@ void OnChannelDisconnected(); - base::WeakPtr<IpcReader> GetWeakPtr() const; + base::WeakPtr<IpcReader> GetWeakPtr(); private: void OnOpenResult(mojom::BeginFileReadResultPtr result); @@ -130,7 +130,7 @@ void OnChannelDisconnected(); - base::WeakPtr<IpcWriter> GetWeakPtr() const; + base::WeakPtr<IpcWriter> GetWeakPtr(); private: void OnOpenResult(mojom::BeginFileWriteResultPtr result); @@ -248,7 +248,7 @@ } base::WeakPtr<IpcFileOperations::IpcReader> -IpcFileOperations::IpcReader::GetWeakPtr() const { +IpcFileOperations::IpcReader::GetWeakPtr() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); return weak_ptr_factory_.GetWeakPtr(); } @@ -376,7 +376,7 @@ } base::WeakPtr<IpcFileOperations::IpcWriter> -IpcFileOperations::IpcWriter::GetWeakPtr() const { +IpcFileOperations::IpcWriter::GetWeakPtr() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); return weak_ptr_factory_.GetWeakPtr(); }
diff --git a/sandbox/linux/services/libc_interceptor.cc b/sandbox/linux/services/libc_interceptor.cc index 109dc9b..e742a90c 100644 --- a/sandbox/linux/services/libc_interceptor.cc +++ b/sandbox/linux/services/libc_interceptor.cc
@@ -6,7 +6,6 @@ #include <dlfcn.h> #include <fcntl.h> -#include <netdb.h> #include <pthread.h> #include <signal.h> #include <stddef.h> @@ -22,7 +21,6 @@ #include <string> #include "base/compiler_specific.h" -#include "base/debug/dump_without_crashing.h" #include "base/lazy_instance.h" #include "base/logging.h" #include "base/pickle.h" @@ -338,45 +336,4 @@ InitLibcLocaltimeFunctionsImpl)); } -namespace { -std::atomic<bool> g_getaddrinfo_discouraged; - -DISABLE_CFI_DLSYM -int CallRealGetaddrinfo(const char* node, - const char* service, - const struct addrinfo* hints, - struct addrinfo** res) { - using GetaddrinfoFunction = decltype(getaddrinfo)*; - static GetaddrinfoFunction fn_ptr = - reinterpret_cast<GetaddrinfoFunction>(dlsym(RTLD_NEXT, "getaddrinfo")); - - if (!fn_ptr) { - LOG(ERROR) << "Cannot find getaddrinfo with dlsym."; - return EAI_SYSTEM; - } - - return fn_ptr(node, service, hints, res); -} -} // namespace - -extern "C" { -__attribute__((visibility("default"), noinline)) int getaddrinfo( - const char* node, - const char* service, - const struct addrinfo* hints, - struct addrinfo** res) { - if (g_getaddrinfo_discouraged.load(std::memory_order_relaxed)) { - DLOG(FATAL) << "Called getaddrinfo() in a sandboxed process."; - base::debug::DumpWithoutCrashing(); - // In non-debug builds, deliberately fall through to call the real version. - } - - return CallRealGetaddrinfo(node, service, hints, res); -} -} - -void DiscourageGetaddrinfo() { - g_getaddrinfo_discouraged = true; -} - } // namespace sandbox
diff --git a/sandbox/linux/services/libc_interceptor.h b/sandbox/linux/services/libc_interceptor.h index 90e2120e..1089a382 100644 --- a/sandbox/linux/services/libc_interceptor.h +++ b/sandbox/linux/services/libc_interceptor.h
@@ -16,40 +16,26 @@ // Sandbox interception of libc calls. // -// When we are running in a sandbox, sometimes certain libc functions will fail. -// E.g. getaddrinfo() can fail in all sandboxes as glibc can run arbitrary -// third-party DNS resolution libraries which we have no hope of sandboxing. +// When we are running in a namespace sandbox certain libc calls will fail +// (localtime being the motivating example - it needs to read /etc/localtime). +// We need to intercept these calls and proxy them to a parent process. +// However, these calls may come from us or from our third_party libraries, so +// in some cases we can't just change the code. // -// These libc functions need to be run in a separate process. If they are not -// called by third party code we can use Chrome's IPC (Mojo) to avoid ever -// calling these libc functions in a sandboxed process. For example -// getaddrinfo() is only called by first-party Chrome code and so it can be -// brokered to an unsandboxed process with regular IPC. +// It's for these cases that we have the following setup: // -// But some of the libc calls are from third party libraries in the sandboxed -// process and they still must succeed. The motivating example is localtime - it -// needs to read /etc/localtime and sometimes a variety of locale files. We need -// to intercept these calls and proxy them to a parent process. +// We define global functions for those functions which we wish to override. +// Since we will be first in the dynamic resolution order, the dynamic linker +// will point callers to our versions of these functions. However, we have the +// same binary for both the browser and the renderers, which means that our +// overrides will apply in the browser too. // -// For first-party cases we want to ensure the offending libc function is never -// called in a sandboxed process, and in third-party cases we want to proxy the -// call to a parent process. So in both cases we override the libc symbol: we -// define global functions for those functions which we wish to override. Since -// our own binary will be first in the dynamic resolution order, the dynamic -// linker will point callers to our versions of these functions. -// -// However, we have the same binary for both the browser and the renderers, -// which means that our overrides will apply in the browser too. In the browser -// process, the replacement functions must use dlsym with RTLD_NEXT to resolve -// the actual libc symbol, ignoring any symbols in the current module. In the -// sandboxed process, we need to either proxy the call to the parent over the -// IPC back-channel (see -// https://chromium.googlesource.com/chromium/src/+/main/docs/linux/sandbox_ipc.md), -// or if the libc call is not allowed ("first-party case") then we should -// generate a crash dump and possibly continue with the libc call. -// -// Use SetAmZygoteOrRenderer() below to control the proxying of libc calls such -// as localtime, which defaults using the dlsym approach. +// Our replacement functions must handle both cases, and either proxy the call +// to the parent over the IPC back-channel (see +// https://chromium.googlesource.com/chromium/src/+/main/docs/linux/sandbox_ipc.md) +// or use dlsym with RTLD_NEXT to resolve the symbol, ignoring any symbols in +// the current module. Use SetAmZygoteOrRenderer() below to control the mode of +// operation, which defaults using the dlsym approach. // // Other avenues: // @@ -81,13 +67,6 @@ // Initializes libc interception. Must be called before sandbox lock down. SANDBOX_EXPORT void InitLibcLocaltimeFunctions(); -// Any calls to getaddrinfo() will crash in debug builds, or in release/official -// builds will trigger a crash dump and continue to call the actual -// getaddrinfo(). -// TODO(mdpenton): change to DisallowGetaddrinfo() once this has been -// sufficiently tested in the wild. -SANDBOX_EXPORT void DiscourageGetaddrinfo(); - } // namespace sandbox #endif // SANDBOX_LINUX_SERVICES_LIBC_INTERCEPTOR_H_
diff --git a/sandbox/policy/linux/sandbox_linux.cc b/sandbox/policy/linux/sandbox_linux.cc index 4cd29571..04dec1ae 100644 --- a/sandbox/policy/linux/sandbox_linux.cc +++ b/sandbox/policy/linux/sandbox_linux.cc
@@ -405,13 +405,6 @@ InitLibcLocaltimeFunctions(); - if (!IsUnsandboxedSandboxType(sandbox_type)) { - // No sandboxed process should make use of getaddrinfo() as it is impossible - // to sandbox (e.g. glibc loads arbitrary third party DNS resolution - // libraries). - DiscourageGetaddrinfo(); - } - // Attempt to limit the future size of the address space of the process. // Fine to call with multiple threads as we don't use RLIMIT_STACK. int error = 0;
diff --git a/services/network/network_service_unittest.cc b/services/network/network_service_unittest.cc index 035fe5d..aef7f8c 100644 --- a/services/network/network_service_unittest.cc +++ b/services/network/network_service_unittest.cc
@@ -632,7 +632,8 @@ } TEST_F(NetworkServiceTest, DisableDohUpgradeProviders) { - auto FindProviderFeature = [](base::StringPiece provider) -> base::Feature { + auto FindProviderFeature = + [](base::StringPiece provider) -> base::test::FeatureRef { const auto it = base::ranges::find(net::DohProviderEntry::GetList(), provider, &net::DohProviderEntry::provider);
diff --git a/services/network/p2p/socket.h b/services/network/p2p/socket.h index 9efd146..1a4ec90 100644 --- a/services/network/p2p/socket.h +++ b/services/network/p2p/socket.h
@@ -26,7 +26,7 @@ namespace net { class NetLog; -class NetworkIsolationKey; +class NetworkAnonymizationKey; } namespace network { @@ -84,11 +84,12 @@ // If |local_address.port()| is nonzero and not in the valid range, // initialization will fail. // |network_isolation_key| specifies the network stack cache shard to used. - virtual void Init(const net::IPEndPoint& local_address, - uint16_t min_port, - uint16_t max_port, - const P2PHostAndIPEndPoint& remote_address, - const net::NetworkIsolationKey& network_isolation_key) = 0; + virtual void Init( + const net::IPEndPoint& local_address, + uint16_t min_port, + uint16_t max_port, + const P2PHostAndIPEndPoint& remote_address, + const net::NetworkAnonymizationKey& network_isolation_key) = 0; mojo::PendingRemote<mojom::P2PSocketClient> ReleaseClientForTesting(); mojo::PendingReceiver<mojom::P2PSocket> ReleaseReceiverForTesting();
diff --git a/services/network/p2p/socket_manager.cc b/services/network/p2p/socket_manager.cc index 6f06a607..7d0f854 100644 --- a/services/network/p2p/socket_manager.cc +++ b/services/network/p2p/socket_manager.cc
@@ -380,7 +380,9 @@ // Init() may call SocketManager::DestroySocket(), so it must be called after // adding the socket to |sockets_|. socket_ptr->Init(local_address, port_range.min_port, port_range.max_port, - remote_address, network_isolation_key_); + remote_address, + net::NetworkAnonymizationKey::CreateFromNetworkIsolationKeyTemporaryMigrationHelper( + network_isolation_key_)); } void P2PSocketManager::StartRtpDump(bool incoming, bool outgoing) {
diff --git a/services/network/p2p/socket_tcp.cc b/services/network/p2p/socket_tcp.cc index 891dc603..12bd52f 100644 --- a/services/network/p2p/socket_tcp.cc +++ b/services/network/p2p/socket_tcp.cc
@@ -14,7 +14,7 @@ #include "components/webrtc/fake_ssl_client_socket.h" #include "net/base/io_buffer.h" #include "net/base/net_errors.h" -#include "net/base/network_isolation_key.h" +#include "net/base/network_anonymization_key.h" #include "net/socket/client_socket_factory.h" #include "net/socket/client_socket_handle.h" #include "net/socket/ssl_client_socket.h" @@ -84,7 +84,7 @@ uint16_t min_port, uint16_t max_port, const P2PHostAndIPEndPoint& remote_address, - const net::NetworkIsolationKey& network_isolation_key) { + const net::NetworkAnonymizationKey& network_anonymization_key) { DCHECK(!socket_); remote_address_ = remote_address; @@ -108,8 +108,8 @@ // a problem on multi-homed host. socket_ = proxy_resolving_socket_factory_->CreateSocket( - GURL("https://" + dest_host_port_pair.ToString()), network_isolation_key, - IsTlsClientSocket(type_)); + GURL("https://" + dest_host_port_pair.ToString()), + network_anonymization_key, IsTlsClientSocket(type_)); if (IsPseudoTlsClientSocket(type_)) { socket_ = std::make_unique<webrtc::FakeSSLClientSocket>(std::move(socket_));
diff --git a/services/network/p2p/socket_tcp.h b/services/network/p2p/socket_tcp.h index 2a32aa8..751a7db 100644 --- a/services/network/p2p/socket_tcp.h +++ b/services/network/p2p/socket_tcp.h
@@ -48,11 +48,12 @@ std::unique_ptr<net::StreamSocket> socket); // P2PSocket overrides. - void Init(const net::IPEndPoint& local_address, - uint16_t min_port, - uint16_t max_port, - const P2PHostAndIPEndPoint& remote_address, - const net::NetworkIsolationKey& network_isolation_key) override; + void Init( + const net::IPEndPoint& local_address, + uint16_t min_port, + uint16_t max_port, + const P2PHostAndIPEndPoint& remote_address, + const net::NetworkAnonymizationKey& network_anonymization_key) override; // mojom::P2PSocket implementation: void Send(const std::vector<int8_t>& data,
diff --git a/services/network/p2p/socket_tcp_unittest.cc b/services/network/p2p/socket_tcp_unittest.cc index cb9a6708..915ea47 100644 --- a/services/network/p2p/socket_tcp_unittest.cc +++ b/services/network/p2p/socket_tcp_unittest.cc
@@ -20,7 +20,7 @@ #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "net/base/features.h" -#include "net/base/network_isolation_key.h" +#include "net/base/network_anonymization_key.h" #include "net/dns/mock_host_resolver.h" #include "net/socket/socket_test_util.h" #include "net/socket/stream_socket.h" @@ -532,7 +532,7 @@ P2PHostAndIPEndPoint dest; dest.ip_address = server_addr; host.Init(net::IPEndPoint(net::IPAddress::IPv4Localhost(), 0), 0, 0, dest, - net::NetworkIsolationKey()); + net::NetworkAnonymizationKey()); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(data_provider.AllReadDataConsumed()); @@ -540,7 +540,7 @@ } // Test the case where P2PHostAndIPEndPoint::hostname is populated. Make sure -// there's a DNS lookup using the right hostname and NetworkIsolationKey. +// there's a DNS lookup using the right hostname and NetworkAnonymizationKey. TEST(P2PSocketTcpWithPseudoTlsTest, Hostname) { base::test::ScopedFeatureList feature_list; feature_list.InitAndEnableFeature( @@ -590,13 +590,10 @@ P2PHostAndIPEndPoint dest; dest.ip_address = server_addr; dest.hostname = kHostname; - net::NetworkIsolationKey network_isolation_key = - net::NetworkIsolationKey::CreateTransient(); net::NetworkAnonymizationKey network_anonymization_key = - net::NetworkAnonymizationKey::CreateFromNetworkIsolationKey( - network_isolation_key); + net::NetworkAnonymizationKey::CreateTransient(); host.Init(net::IPEndPoint(net::IPAddress::IPv4Localhost(), 0), 0, 0, dest, - network_isolation_key); + network_anonymization_key); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(data_provider.AllReadDataConsumed()); @@ -690,7 +687,7 @@ P2PHostAndIPEndPoint dest; dest.ip_address = server_addr; host->Init(net::IPEndPoint(net::IPAddress::IPv4Localhost(), 0), 0, 0, dest, - net::NetworkIsolationKey()); + net::NetworkAnonymizationKey()); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(data_provider.AllReadDataConsumed());
diff --git a/services/network/p2p/socket_udp.cc b/services/network/p2p/socket_udp.cc index d187bc6..bca72ef 100644 --- a/services/network/p2p/socket_udp.cc +++ b/services/network/p2p/socket_udp.cc
@@ -128,11 +128,12 @@ P2PSocketUdp::~P2PSocketUdp() = default; -void P2PSocketUdp::Init(const net::IPEndPoint& local_address, - uint16_t min_port, - uint16_t max_port, - const P2PHostAndIPEndPoint& remote_address, - const net::NetworkIsolationKey& network_isolation_key) { +void P2PSocketUdp::Init( + const net::IPEndPoint& local_address, + uint16_t min_port, + uint16_t max_port, + const P2PHostAndIPEndPoint& remote_address, + const net::NetworkAnonymizationKey& network_anonymization_key) { DCHECK(!socket_); DCHECK((min_port == 0 && max_port == 0) || min_port > 0); DCHECK_LE(min_port, max_port);
diff --git a/services/network/p2p/socket_udp.h b/services/network/p2p/socket_udp.h index a06c9c2..9e933e3 100644 --- a/services/network/p2p/socket_udp.h +++ b/services/network/p2p/socket_udp.h
@@ -58,11 +58,12 @@ ~P2PSocketUdp() override; // P2PSocket overrides. - void Init(const net::IPEndPoint& local_address, - uint16_t min_port, - uint16_t max_port, - const P2PHostAndIPEndPoint& remote_address, - const net::NetworkIsolationKey& network_isolation_key) override; + void Init( + const net::IPEndPoint& local_address, + uint16_t min_port, + uint16_t max_port, + const P2PHostAndIPEndPoint& remote_address, + const net::NetworkAnonymizationKey& network_anonymization_key) override; // mojom::P2PSocket implementation: void Send(const std::vector<int8_t>& data,
diff --git a/services/network/p2p/socket_udp_unittest.cc b/services/network/p2p/socket_udp_unittest.cc index a6beec3..c7f68bc 100644 --- a/services/network/p2p/socket_udp_unittest.cc +++ b/services/network/p2p/socket_udp_unittest.cc
@@ -22,7 +22,7 @@ #include "net/base/io_buffer.h" #include "net/base/ip_endpoint.h" #include "net/base/net_errors.h" -#include "net/base/network_isolation_key.h" +#include "net/base/network_anonymization_key.h" #include "net/log/net_log_with_source.h" #include "net/socket/datagram_server_socket.h" #include "net/traffic_annotation/network_traffic_annotation_test_helper.h" @@ -236,7 +236,7 @@ local_address_, 0, 0, P2PHostAndIPEndPoint(std::string(), ParseAddress(kTestIpAddress1, kTestPort1)), - net::NetworkIsolationKey()); + net::NetworkAnonymizationKey()); socket_ = GetSocketFromHost(socket_impl_.get()); dest1_ = ParseAddress(kTestIpAddress1, kTestPort1); @@ -581,7 +581,7 @@ local_address, min_port, max_port, P2PHostAndIPEndPoint(std::string(), ParseAddress(kTestIpAddress1, kTestPort1)), - net::NetworkIsolationKey()); + net::NetworkAnonymizationKey()); FakeDatagramServerSocket* datagram_socket = GetSocketFromHost(socket_impl.get()); @@ -607,7 +607,7 @@ local_address, min_port, max_port, P2PHostAndIPEndPoint(std::string(), ParseAddress(kTestIpAddress1, kTestPort1)), - net::NetworkIsolationKey()); + net::NetworkAnonymizationKey()); base::RunLoop().RunUntilIdle(); @@ -645,7 +645,7 @@ local_address, min_port, max_port, P2PHostAndIPEndPoint(std::string(), ParseAddress(kTestIpAddress1, kTestPort1)), - net::NetworkIsolationKey()); + net::NetworkAnonymizationKey()); FakeDatagramServerSocket* fake_socket = GetSocketFromHost(socket_host.get()); net::IPEndPoint bound_address; @@ -687,7 +687,7 @@ local_address, min_port, max_port, P2PHostAndIPEndPoint(std::string(), ParseAddress(kTestIpAddress1, kTestPort1)), - net::NetworkIsolationKey()); + net::NetworkAnonymizationKey()); base::RunLoop().RunUntilIdle();
diff --git a/services/network/proxy_resolving_client_socket.cc b/services/network/proxy_resolving_client_socket.cc index ff51b55..eaa2612 100644 --- a/services/network/proxy_resolving_client_socket.cc +++ b/services/network/proxy_resolving_client_socket.cc
@@ -17,7 +17,7 @@ #include "net/base/ip_address.h" #include "net/base/load_flags.h" #include "net/base/net_errors.h" -#include "net/base/network_isolation_key.h" +#include "net/base/network_anonymization_key.h" #include "net/base/privacy_mode.h" #include "net/dns/public/secure_dns_policy.h" #include "net/http/http_auth_controller.h" @@ -40,14 +40,14 @@ net::HttpNetworkSession* network_session, const net::CommonConnectJobParams* common_connect_job_params, const GURL& url, - const net::NetworkIsolationKey& network_isolation_key, + const net::NetworkAnonymizationKey& network_anonymization_key, bool use_tls, const net::ConnectJobFactory* connect_job_factory) : network_session_(network_session), common_connect_job_params_(common_connect_job_params), connect_job_factory_(connect_job_factory), url_(url), - network_isolation_key_(network_isolation_key), + network_anonymization_key_(network_anonymization_key), use_tls_(use_tls), net_log_(net::NetLogWithSource::Make(network_session_->net_log(), net::NetLogSourceType::SOCKET)), @@ -245,9 +245,9 @@ // base::Unretained(this) is safe because resolution request is canceled when // |proxy_resolve_request_| is destroyed. // - // TODO(https://crbug.com/1023439): Pass along a NetworkIsolationKey. + // TODO(https://crbug.com/1023439): Pass along a NetworkAnonymizationKey. return network_session_->proxy_resolution_service()->ResolveProxy( - url_, net::HttpRequestHeaders::kPostMethod, network_isolation_key_, + url_, net::HttpRequestHeaders::kPostMethod, network_anonymization_key_, &proxy_info_, base::BindOnce(&ProxyResolvingClientSocket::OnIOComplete, base::Unretained(this)), @@ -291,9 +291,9 @@ proxy_info_.traffic_annotation()); // Now that the proxy is resolved, create and start a ConnectJob. Using an - // empty NetworkIsolationKey means that tunnels over H2 or QUIC proxies will - // be shared, which may result in privacy leaks, depending on the nature of - // the consumer. + // empty NetworkAnonymizationKey means that tunnels over H2 or QUIC proxies + // will be shared, which may result in privacy leaks, depending on the nature + // of the consumer. // // TODO(mmenke): Investigate that. net::SSLConfig ssl_config; @@ -301,7 +301,7 @@ use_tls_, net::HostPortPair::FromURL(url_), proxy_info_.proxy_server(), proxy_annotation_tag, &ssl_config, &ssl_config, true /* force_tunnel */, net::PRIVACY_MODE_DISABLED, net::OnHostResolutionCallback(), - net::MAXIMUM_PRIORITY, net::SocketTag(), network_isolation_key_, + net::MAXIMUM_PRIORITY, net::SocketTag(), network_anonymization_key_, net::SecureDnsPolicy::kAllow, common_connect_job_params_, this); return connect_job_->Connect(); }
diff --git a/services/network/proxy_resolving_client_socket.h b/services/network/proxy_resolving_client_socket.h index e908f80..1aabaae 100644 --- a/services/network/proxy_resolving_client_socket.h +++ b/services/network/proxy_resolving_client_socket.h
@@ -17,7 +17,7 @@ #include "base/memory/weak_ptr.h" #include "net/base/host_port_pair.h" #include "net/base/net_errors.h" -#include "net/base/network_isolation_key.h" +#include "net/base/network_anonymization_key.h" #include "net/log/net_log_with_source.h" #include "net/proxy_resolution/proxy_info.h" #include "net/proxy_resolution/proxy_resolution_service.h" @@ -33,7 +33,7 @@ class HttpAuthController; class HttpResponseInfo; class HttpNetworkSession; -class NetworkIsolationKey; +class NetworkAnonymizationKey; class ProxyResolutionRequest; } // namespace net @@ -58,7 +58,7 @@ net::HttpNetworkSession* network_session, const net::CommonConnectJobParams* common_connect_job_params, const GURL& url, - const net::NetworkIsolationKey& network_isolation_key, + const net::NetworkAnonymizationKey& network_anonymization_key, bool use_tls, const net::ConnectJobFactory* connect_job_factory); @@ -139,7 +139,7 @@ std::unique_ptr<net::ProxyResolutionRequest> proxy_resolve_request_; net::ProxyInfo proxy_info_; const GURL url_; - const net::NetworkIsolationKey network_isolation_key_; + const net::NetworkAnonymizationKey network_anonymization_key_; const bool use_tls_; net::NetLogWithSource net_log_;
diff --git a/services/network/proxy_resolving_client_socket_factory.cc b/services/network/proxy_resolving_client_socket_factory.cc index c3dd48e..31394b1 100644 --- a/services/network/proxy_resolving_client_socket_factory.cc +++ b/services/network/proxy_resolving_client_socket_factory.cc
@@ -76,7 +76,7 @@ std::unique_ptr<ProxyResolvingClientSocket> ProxyResolvingClientSocketFactory::CreateSocket( const GURL& url, - const net::NetworkIsolationKey& network_isolation_key, + const net::NetworkAnonymizationKey& network_anonymization_key, bool use_tls) { // |request_context|'s HttpAuthCache might have updates. For example, a user // might have since entered proxy credentials. Clear the http auth of @@ -98,7 +98,7 @@ network_session_->http_auth_cache()->CopyProxyEntriesFrom(*other_auth_cache); return std::make_unique<ProxyResolvingClientSocket>( network_session_.get(), common_connect_job_params_.get(), url, - network_isolation_key, use_tls, connect_job_factory_.get()); + network_anonymization_key, use_tls, connect_job_factory_.get()); } } // namespace network
diff --git a/services/network/proxy_resolving_client_socket_factory.h b/services/network/proxy_resolving_client_socket_factory.h index 318f1ac..e34e00a6 100644 --- a/services/network/proxy_resolving_client_socket_factory.h +++ b/services/network/proxy_resolving_client_socket_factory.h
@@ -17,7 +17,7 @@ namespace net { struct CommonConnectJobParams; class HttpNetworkSession; -class NetworkIsolationKey; +class NetworkAnonymizationKey; class URLRequestContext; } // namespace net @@ -47,7 +47,7 @@ // will be sanitized by net::ProxyResolutionService before the url is // disclosed to the PAC script. // - // |network_isolation_key| indicates the network shard to use for storing + // |network_anonymization_key| indicates the network shard to use for storing // shared network state (DNS cache entries, shared H2/QUIC proxy connections, // etc). Proxy connections will only be shared with other // ProxyResolvingClientSockets, not with standards HTTP/HTTPS requests. @@ -57,7 +57,7 @@ // establishing a TLS connection. std::unique_ptr<ProxyResolvingClientSocket> CreateSocket( const GURL& url, - const net::NetworkIsolationKey& network_isolation_key, + const net::NetworkAnonymizationKey& network_anonymization_key, bool use_tls); private:
diff --git a/services/network/proxy_resolving_client_socket_unittest.cc b/services/network/proxy_resolving_client_socket_unittest.cc index 1587fd5..d521caf 100644 --- a/services/network/proxy_resolving_client_socket_unittest.cc +++ b/services/network/proxy_resolving_client_socket_unittest.cc
@@ -91,7 +91,7 @@ ProxyResolvingClientSocketTest, ::testing::Bool()); -// Checks the correct NetworkIsolationKey is used for host resolution in the +// Checks the correct NetworkAnonymizationKey is used for host resolution in the // case no proxy is in use. TEST_P(ProxyResolvingClientSocketTest, NetworkIsolationKeyDirect) { // This deliberately uses a different origin than the one being connected to. @@ -115,7 +115,7 @@ url_request_context.get()); std::unique_ptr<ProxyResolvingClientSocket> socket = proxy_resolving_socket_factory.CreateSocket( - kDestination, kNetworkIsolationKey, use_tls_); + kDestination, kNetworkAnonymizationKey, use_tls_); net::TestCompletionCallback callback; int status = socket->Connect(callback.callback()); EXPECT_THAT(callback.GetResult(status), net::test::IsOk()); @@ -179,7 +179,7 @@ net::NetworkAnonymizationKey kNetworkAnonymizationKey1 = net::NetworkAnonymizationKey::CreateFromNetworkIsolationKey( kNetworkIsolationKey1); - net::NetworkIsolationKey kNetworkAnonymizationKey2 = + net::NetworkAnonymizationKey kNetworkAnonymizationKey2 = net::NetworkAnonymizationKey::CreateFromNetworkIsolationKey( kNetworkIsolationKey2); const GURL kDestination1("https://dest1.test/"); @@ -249,7 +249,7 @@ http_network_session->CreateCommonConnectJobParams(); ProxyResolvingClientSocket socket1( http_network_session.get(), &common_connect_job_params, kDestination1, - kNetworkIsolationKey1, false /* use_tls */, &connect_job_factory); + kNetworkAnonymizationKey1, false /* use_tls */, &connect_job_factory); net::TestCompletionCallback callback1; int result = socket1.Connect(callback1.callback()); EXPECT_THAT(callback1.GetResult(result), net::test::IsOk()); @@ -258,7 +258,7 @@ // H2 session. ProxyResolvingClientSocket socket2( http_network_session.get(), &common_connect_job_params, kDestination2, - kNetworkIsolationKey2, false /* use_tls */, &connect_job_factory); + kNetworkAnonymizationKey2, false /* use_tls */, &connect_job_factory); net::TestCompletionCallback callback2; result = socket2.Connect(callback2.callback()); EXPECT_THAT(callback2.GetResult(result), net::test::IsOk()); @@ -269,7 +269,7 @@ // first H2 session. ProxyResolvingClientSocket socket3( http_network_session.get(), &common_connect_job_params, kDestination3, - kNetworkIsolationKey1, false /* use_tls */, &connect_job_factory); + kNetworkAnonymizationKey1, false /* use_tls */, &connect_job_factory); net::TestCompletionCallback callback3; result = socket3.Connect(callback3.callback()); EXPECT_THAT(callback3.GetResult(result), net::test::IsOk()); @@ -310,7 +310,7 @@ for (int i = 0; i < kNumSockets; ++i) { std::unique_ptr<ProxyResolvingClientSocket> socket = proxy_resolving_socket_factory.CreateSocket( - kDestination, net::NetworkIsolationKey(), use_tls_); + kDestination, net::NetworkAnonymizationKey(), use_tls_); net::TestCompletionCallback callback; int status = socket->Connect(callback.callback()); EXPECT_THAT(callback.GetResult(status), net::test::IsOk()); @@ -347,7 +347,7 @@ context.get()); std::unique_ptr<ProxyResolvingClientSocket> socket = proxy_resolving_socket_factory.CreateSocket( - kDestination, net::NetworkIsolationKey(), use_tls_); + kDestination, net::NetworkAnonymizationKey(), use_tls_); net::TestCompletionCallback callback; int status = socket->Connect(callback.callback()); EXPECT_EQ(net::ERR_IO_PENDING, status); @@ -396,7 +396,7 @@ context.get()); std::unique_ptr<ProxyResolvingClientSocket> socket = proxy_resolving_socket_factory.CreateSocket( - kDestination, net::NetworkIsolationKey(), use_tls_); + kDestination, net::NetworkAnonymizationKey(), use_tls_); net::TestCompletionCallback callback; int status = socket->Connect(callback.callback()); EXPECT_EQ(net::ERR_IO_PENDING, status); @@ -431,7 +431,7 @@ context.get()); std::unique_ptr<ProxyResolvingClientSocket> socket = proxy_resolving_socket_factory.CreateSocket( - kDestination, net::NetworkIsolationKey(), use_tls_); + kDestination, net::NetworkAnonymizationKey(), use_tls_); net::TestCompletionCallback callback; int status = socket->Connect(callback.callback()); EXPECT_EQ(net::ERR_IO_PENDING, status); @@ -497,7 +497,7 @@ context.get()); std::unique_ptr<ProxyResolvingClientSocket> socket = proxy_resolving_socket_factory.CreateSocket( - kDestination, net::NetworkIsolationKey(), use_tls_); + kDestination, net::NetworkAnonymizationKey(), use_tls_); net::TestCompletionCallback callback; int status = socket->Connect(callback.callback()); EXPECT_EQ(net::ERR_IO_PENDING, status); @@ -563,7 +563,7 @@ context.get()); std::unique_ptr<ProxyResolvingClientSocket> socket = proxy_resolving_socket_factory.CreateSocket( - kDestination, net::NetworkIsolationKey(), use_tls_); + kDestination, net::NetworkAnonymizationKey(), use_tls_); net::TestCompletionCallback callback; int status = socket->Connect(callback.callback()); EXPECT_EQ(net::ERR_IO_PENDING, status); @@ -601,7 +601,7 @@ context.get()); std::unique_ptr<ProxyResolvingClientSocket> socket = proxy_resolving_socket_factory.CreateSocket( - kDestination, net::NetworkIsolationKey(), use_tls_); + kDestination, net::NetworkAnonymizationKey(), use_tls_); net::TestCompletionCallback callback; int status = socket->Connect(callback.callback()); EXPECT_THAT(callback.GetResult(status), @@ -664,21 +664,21 @@ auth_cache->Add(url::SchemeHostPort(GURL("http://bad:99")), net::HttpAuth::AUTH_PROXY, "test_realm", - net::HttpAuth::AUTH_SCHEME_BASIC, net::NetworkIsolationKey(), - "Basic realm=\"test_realm\"", + net::HttpAuth::AUTH_SCHEME_BASIC, + net::NetworkAnonymizationKey(), "Basic realm=\"test_realm\"", net::AuthCredentials(u"user", u"password"), std::string()); auth_cache->Add(url::SchemeHostPort(GURL("http://bad:99")), net::HttpAuth::AUTH_PROXY, "test_realm2", - net::HttpAuth::AUTH_SCHEME_BASIC, net::NetworkIsolationKey(), - "Basic realm=\"test_realm2\"", + net::HttpAuth::AUTH_SCHEME_BASIC, + net::NetworkAnonymizationKey(), "Basic realm=\"test_realm2\"", net::AuthCredentials(u"user2", u"password2"), std::string()); ProxyResolvingClientSocketFactory proxy_resolving_socket_factory( context.get()); std::unique_ptr<ProxyResolvingClientSocket> socket = proxy_resolving_socket_factory.CreateSocket( - kDestination, net::NetworkIsolationKey(), use_tls_); + kDestination, net::NetworkAnonymizationKey(), use_tls_); net::TestCompletionCallback callback; int status = socket->Connect(callback.callback()); EXPECT_THAT(callback.GetResult(status), net::test::IsOk()); @@ -727,15 +727,15 @@ // origin + realm + scheme lookup. auth_cache->Add(url::SchemeHostPort(GURL("http://bad:99")), net::HttpAuth::AUTH_PROXY, "test_realm", - net::HttpAuth::AUTH_SCHEME_BASIC, net::NetworkIsolationKey(), - "Basic realm=\"test_realm\"", + net::HttpAuth::AUTH_SCHEME_BASIC, + net::NetworkAnonymizationKey(), "Basic realm=\"test_realm\"", net::AuthCredentials(u"user", u"password"), std::string()); ProxyResolvingClientSocketFactory proxy_resolving_socket_factory( context.get()); std::unique_ptr<ProxyResolvingClientSocket> socket = proxy_resolving_socket_factory.CreateSocket( - kDestination, net::NetworkIsolationKey(), use_tls_); + kDestination, net::NetworkAnonymizationKey(), use_tls_); net::TestCompletionCallback callback; int status = socket->Connect(callback.callback()); EXPECT_THAT(callback.GetResult(status), net::test::IsOk()); @@ -761,8 +761,8 @@ // origin + realm + scheme lookup. auth_cache->Add(url::SchemeHostPort(GURL("http://bad:99")), net::HttpAuth::AUTH_PROXY, "test_realm", - net::HttpAuth::AUTH_SCHEME_BASIC, net::NetworkIsolationKey(), - "Basic realm=\"test_realm\"", + net::HttpAuth::AUTH_SCHEME_BASIC, + net::NetworkAnonymizationKey(), "Basic realm=\"test_realm\"", net::AuthCredentials(u"user", u"password"), std::string()); const GURL kDestination("https://example.com:443"); @@ -793,7 +793,7 @@ std::unique_ptr<ProxyResolvingClientSocket> socket = proxy_resolving_socket_factory.CreateSocket( - kDestination, net::NetworkIsolationKey(), use_tls_); + kDestination, net::NetworkAnonymizationKey(), use_tls_); net::TestCompletionCallback callback; int status = socket->Connect(callback.callback()); EXPECT_THAT(callback.GetResult(status), net::test::IsOk()); @@ -825,15 +825,15 @@ auth_cache->Add(url::SchemeHostPort(GURL("http://bad:99")), net::HttpAuth::AUTH_PROXY, "test_realm", - net::HttpAuth::AUTH_SCHEME_BASIC, net::NetworkIsolationKey(), - "Basic realm=\"test_realm\"", + net::HttpAuth::AUTH_SCHEME_BASIC, + net::NetworkAnonymizationKey(), "Basic realm=\"test_realm\"", net::AuthCredentials(u"user", u"password"), "/"); ProxyResolvingClientSocketFactory proxy_resolving_socket_factory( context.get()); std::unique_ptr<ProxyResolvingClientSocket> socket = proxy_resolving_socket_factory.CreateSocket( - kDestination, net::NetworkIsolationKey(), use_tls_); + kDestination, net::NetworkAnonymizationKey(), use_tls_); net::TestCompletionCallback callback; int status = socket->Connect(callback.callback()); @@ -864,7 +864,7 @@ context.get()); std::unique_ptr<ProxyResolvingClientSocket> socket = proxy_resolving_socket_factory.CreateSocket( - kDestination, net::NetworkIsolationKey(), use_tls_); + kDestination, net::NetworkAnonymizationKey(), use_tls_); net::TestCompletionCallback callback; int status = socket->Connect(callback.callback()); @@ -897,7 +897,7 @@ context.get()); std::unique_ptr<ProxyResolvingClientSocket> socket = proxy_resolving_socket_factory.CreateSocket( - url, net::NetworkIsolationKey(), use_tls_); + url, net::NetworkAnonymizationKey(), use_tls_); net::TestCompletionCallback callback; int status = socket->Connect(callback.callback()); EXPECT_EQ(net::ERR_IO_PENDING, status); @@ -942,7 +942,7 @@ context.get()); std::unique_ptr<ProxyResolvingClientSocket> socket = proxy_resolving_socket_factory.CreateSocket( - url, net::NetworkIsolationKey(), use_tls_); + url, net::NetworkAnonymizationKey(), use_tls_); net::TestCompletionCallback callback; EXPECT_EQ(net::ERR_IO_PENDING, socket->Connect(callback.callback())); socket.reset(); @@ -977,7 +977,7 @@ context.get()); std::unique_ptr<ProxyResolvingClientSocket> socket = proxy_resolving_socket_factory.CreateSocket( - kDestination, net::NetworkIsolationKey(), use_tls_); + kDestination, net::NetworkAnonymizationKey(), use_tls_); net::TestCompletionCallback callback; int status = socket->Connect(callback.callback()); status = callback.GetResult(status); @@ -1069,7 +1069,7 @@ context.get()); std::unique_ptr<ProxyResolvingClientSocket> socket = proxy_resolving_socket_factory.CreateSocket( - kDestination, net::NetworkIsolationKey(), use_tls_); + kDestination, net::NetworkAnonymizationKey(), use_tls_); net::TestCompletionCallback callback; int status = socket->Connect(callback.callback()); EXPECT_EQ(net::ERR_IO_PENDING, status);
diff --git a/services/network/proxy_resolving_socket_factory_mojo.cc b/services/network/proxy_resolving_socket_factory_mojo.cc index f5ca1be..d2948e14 100644 --- a/services/network/proxy_resolving_socket_factory_mojo.cc +++ b/services/network/proxy_resolving_socket_factory_mojo.cc
@@ -23,14 +23,14 @@ void ProxyResolvingSocketFactoryMojo::CreateProxyResolvingSocket( const GURL& url, - const net::NetworkIsolationKey& network_isolation_key, + const net::NetworkAnonymizationKey& network_anonymization_key, mojom::ProxyResolvingSocketOptionsPtr options, const net::MutableNetworkTrafficAnnotationTag& traffic_annotation, mojo::PendingReceiver<mojom::ProxyResolvingSocket> receiver, mojo::PendingRemote<mojom::SocketObserver> observer, CreateProxyResolvingSocketCallback callback) { std::unique_ptr<net::StreamSocket> net_socket = factory_impl_.CreateSocket( - url, network_isolation_key, options && options->use_tls); + url, network_anonymization_key, options && options->use_tls); if (options && options->fake_tls_handshake) { DCHECK(!options->use_tls); net_socket =
diff --git a/services/network/proxy_resolving_socket_factory_mojo.h b/services/network/proxy_resolving_socket_factory_mojo.h index 0e40a8ab..fdb1bb9 100644 --- a/services/network/proxy_resolving_socket_factory_mojo.h +++ b/services/network/proxy_resolving_socket_factory_mojo.h
@@ -16,7 +16,7 @@ #include "services/network/tls_socket_factory.h" namespace net { -class NetworkIsolationKey; +class NetworkAnonymizationKey; class URLRequestContext; } // namespace net @@ -37,7 +37,7 @@ // mojom::ProxyResolvingSocketFactory implementation. void CreateProxyResolvingSocket( const GURL& url, - const net::NetworkIsolationKey& network_isolation_key, + const net::NetworkAnonymizationKey& network_anonymization_key, mojom::ProxyResolvingSocketOptionsPtr options, const net::MutableNetworkTrafficAnnotationTag& traffic_annotation, mojo::PendingReceiver<mojom::ProxyResolvingSocket> receiver,
diff --git a/services/network/proxy_resolving_socket_mojo_unittest.cc b/services/network/proxy_resolving_socket_mojo_unittest.cc index 9c073db..58e269a 100644 --- a/services/network/proxy_resolving_socket_mojo_unittest.cc +++ b/services/network/proxy_resolving_socket_mojo_unittest.cc
@@ -109,7 +109,7 @@ options->use_tls = use_tls_; options->fake_tls_handshake = fake_tls_handshake_; factory_remote_->CreateProxyResolvingSocket( - url, net::NetworkIsolationKey(), std::move(options), + url, net::NetworkAnonymizationKey(), std::move(options), net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS), std::move(receiver), std::move(socket_observer), base::BindLambdaForTesting( @@ -385,7 +385,7 @@ base::RunLoop run_loop; int net_error = net::OK; factory()->CreateProxyResolvingSocket( - kDestination, net::NetworkIsolationKey(), nullptr, + kDestination, net::NetworkAnonymizationKey(), nullptr, net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS), socket.InitWithNewPipeAndPassReceiver(), mojo::NullRemote() /* observer */,
diff --git a/services/network/public/cpp/network_anonymization_key_mojom_traits_unittest.cc b/services/network/public/cpp/network_anonymization_key_mojom_traits_unittest.cc index 33e1ff0..5780cb8c 100644 --- a/services/network/public/cpp/network_anonymization_key_mojom_traits_unittest.cc +++ b/services/network/public/cpp/network_anonymization_key_mojom_traits_unittest.cc
@@ -19,8 +19,8 @@ TEST(NetworkAnonymizationKeyMojomTraitsTest, SerializeAndDeserializeTripleKey) { // Enable triple keying. base::test::ScopedFeatureList scoped_feature_list_; - std::vector<base::Feature> enabled_features = {}; - std::vector<base::Feature> disabled_features = { + std::vector<base::test::FeatureRef> enabled_features = {}; + std::vector<base::test::FeatureRef> disabled_features = { net::features::kEnableDoubleKeyNetworkAnonymizationKey, net::features::kEnableCrossSiteFlagNetworkAnonymizationKey}; scoped_feature_list_.InitWithFeatures(enabled_features, disabled_features); @@ -61,9 +61,9 @@ TEST(NetworkAnonymizationKeyMojomTraitsTest, SerializeAndDeserializeDoubleKey) { // Enable double keying. base::test::ScopedFeatureList scoped_feature_list_; - std::vector<base::Feature> enabled_features = { + std::vector<base::test::FeatureRef> enabled_features = { net::features::kEnableDoubleKeyNetworkAnonymizationKey}; - std::vector<base::Feature> disabled_features = { + std::vector<base::test::FeatureRef> disabled_features = { net::features::kEnableCrossSiteFlagNetworkAnonymizationKey}; scoped_feature_list_.InitWithFeatures(enabled_features, disabled_features); @@ -90,9 +90,9 @@ DISABLED_SerializeAndDeserializeDoubleKeyWithCrossSiteFlag) { // Enable double keying with cross site flag. base::test::ScopedFeatureList scoped_feature_list_; - std::vector<base::Feature> enabled_features = { + std::vector<base::test::FeatureRef> enabled_features = { net::features::kEnableCrossSiteFlagNetworkAnonymizationKey}; - std::vector<base::Feature> disabled_features = { + std::vector<base::test::FeatureRef> disabled_features = { net::features::kEnableDoubleKeyNetworkAnonymizationKey}; scoped_feature_list_.InitWithFeatures(enabled_features, disabled_features);
diff --git a/services/network/public/mojom/proxy_resolving_socket.mojom b/services/network/public/mojom/proxy_resolving_socket.mojom index 0790b45e..3543bc4 100644 --- a/services/network/public/mojom/proxy_resolving_socket.mojom +++ b/services/network/public/mojom/proxy_resolving_socket.mojom
@@ -6,7 +6,7 @@ import "services/network/public/mojom/ip_endpoint.mojom"; import "services/network/public/mojom/mutable_network_traffic_annotation_tag.mojom"; -import "services/network/public/mojom/network_isolation_key.mojom"; +import "services/network/public/mojom/network_anonymization_key.mojom"; import "services/network/public/mojom/network_param.mojom"; import "services/network/public/mojom/ssl_config.mojom"; import "services/network/public/mojom/tcp_socket.mojom"; @@ -55,7 +55,7 @@ // Creates a socket connected to |url|. This connection might be done through // proxies if any is set in system's proxy settings. // - // |network_isolation_key| indicates the network storage shard to use for + // |network_anonymization_key| indicates the network storage shard to use for // shared resources, such as the DNS cache and shared proxy connections. // // On success, |result| is net::OK. Caller is to use |send_stream| to send @@ -71,7 +71,7 @@ // when the implementation of this factory goes away. CreateProxyResolvingSocket( url.mojom.Url url, - NetworkIsolationKey network_isolation_key, + NetworkAnonymizationKey network_anonymization_key, ProxyResolvingSocketOptions? options, MutableNetworkTrafficAnnotationTag traffic_annotation, pending_receiver<ProxyResolvingSocket> socket,
diff --git a/services/network/tls_client_socket_unittest.cc b/services/network/tls_client_socket_unittest.cc index 56e7e0b..3e97380 100644 --- a/services/network/tls_client_socket_unittest.cc +++ b/services/network/tls_client_socket_unittest.cc
@@ -18,7 +18,7 @@ #include "mojo/public/cpp/bindings/remote.h" #include "net/base/completion_once_callback.h" #include "net/base/net_errors.h" -#include "net/base/network_isolation_key.h" +#include "net/base/network_anonymization_key.h" #include "net/base/test_completion_callback.h" #include "net/proxy_resolution/configured_proxy_resolution_service.h" #include "net/socket/server_socket.h" @@ -180,7 +180,7 @@ base::RunLoop run_loop; int net_error = net::ERR_FAILED; proxy_resolving_factory_->CreateProxyResolvingSocket( - url, net::NetworkIsolationKey(), nullptr /* options */, + url, net::NetworkAnonymizationKey(), nullptr /* options */, net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS), std::move(receiver), mojo::NullRemote() /* observer */, base::BindLambdaForTesting(
diff --git a/services/preferences/public/cpp/dictionary_value_update.cc b/services/preferences/public/cpp/dictionary_value_update.cc index 22b80d2..8c8d6d7 100644 --- a/services/preferences/public/cpp/dictionary_value_update.cc +++ b/services/preferences/public/cpp/dictionary_value_update.cc
@@ -8,7 +8,6 @@ #include <iterator> #include <utility> -#include "base/as_const.h" #include "base/strings/string_piece.h" #include "base/strings/string_split.h" #include "base/strings/utf_string_conversions.h" @@ -168,7 +167,7 @@ bool DictionaryValueUpdate::GetDictionary( base::StringPiece path, const base::DictionaryValue** out_value) const { - return base::as_const(value_)->GetDictionary(path, out_value); + return std::as_const(value_)->GetDictionary(path, out_value); } bool DictionaryValueUpdate::GetDictionary( @@ -253,7 +252,7 @@ base::StringPiece key, std::unique_ptr<DictionaryValueUpdate>* out_value) { base::DictionaryValue* dictionary_value = nullptr; - if (!base::as_const(*this).GetDictionaryWithoutPathExpansion( + if (!std::as_const(*this).GetDictionaryWithoutPathExpansion( key, const_cast<const base::DictionaryValue**>(&dictionary_value))) { return false; } @@ -280,7 +279,7 @@ base::StringPiece key, base::Value::List** out_value) { RecordKey(key); - return base::as_const(*this).GetListWithoutPathExpansion( + return std::as_const(*this).GetListWithoutPathExpansion( key, const_cast<const base::Value::List**>(out_value)); }
diff --git a/styleguide/c++/c++-features.md b/styleguide/c++/c++-features.md index 7ee94089..0940602 100644 --- a/styleguide/c++/c++-features.md +++ b/styleguide/c++/c++-features.md
@@ -700,6 +700,22 @@ [Discussion thread](https://groups.google.com/a/chromium.org/g/cxx/c/cNZm_g39fyM) *** +### std::as_const <sup>[allowed]</sup> + +```c++ +auto&& const_ref = std::as_const(mutable_obj); +``` + +**Description:** Forms reference to const T. + +**Documentation:** +[std::as_const](https://en.cppreference.com/w/cpp/utility/as_const) + +**Notes:** +*** promo +[Discussion thread](https://groups.google.com/a/chromium.org/g/cxx/c/5Uo4iJK6Mf4) +*** + ### Non-member std::size/std::empty/std::data <sup>[allowed]</sup> ```c++ @@ -1230,22 +1246,6 @@ None *** -### std::as_const <sup>[tbd]</sup> - -```c++ -auto&& const_ref = std::as_const(mutable_obj); -``` - -**Description:** Forms reference to const T. - -**Documentation:** -[std::as_const](https://en.cppreference.com/w/cpp/utility/as_const) - -**Notes:** -*** promo -See also `base::as_const`. -*** - ### std::not_fn <sup>[tbd]</sup> ```c++
diff --git a/styleguide/c++/const.md b/styleguide/c++/const.md index e83fe846..769f8c1 100644 --- a/styleguide/c++/const.md +++ b/styleguide/c++/const.md
@@ -141,7 +141,7 @@ courtesy of _Effective C++_: ```cpp -T* Foo::GetT() { return const_cast<T*>(base::as_const(*this).GetT()); } +T* Foo::GetT() { return const_cast<T*>(std::as_const(*this).GetT()); } ``` While this is a mouthful, it does guarantee the implementations won't get out of
diff --git a/testing/scripts/run_finch_smoke_tests_android.py b/testing/scripts/run_finch_smoke_tests_android.py index a796616c..58fdeb9 100755 --- a/testing/scripts/run_finch_smoke_tests_android.py +++ b/testing/scripts/run_finch_smoke_tests_android.py
@@ -183,22 +183,6 @@ end_point], check_return=True) - with open(filename, 'r+') as logcat_file: - logcat_lines = [] - store_line = False - for line in logcat_file.readlines(): - if start_point in line: - store_line = True - elif end_point in line: - store_line = False - logcat_lines.append(line) - - if store_line: - logcat_lines.append(line) - - with open(filename, 'w') as logcat_file: - logcat_file.write(''.join(logcat_lines)) - def parse_args(self, args=None): super(FinchTestCase, self).parse_args(args) if (not self.options.finch_seed_path or
diff --git a/testing/variations/fieldtrial_testing_config.json b/testing/variations/fieldtrial_testing_config.json index 31b9c7a0..52ffa552 100644 --- a/testing/variations/fieldtrial_testing_config.json +++ b/testing/variations/fieldtrial_testing_config.json
@@ -2047,21 +2047,6 @@ ] } ], - "CCTNewDownloadTab": [ - { - "platforms": [ - "android" - ], - "experiments": [ - { - "name": "Enabled_20220525", - "enable_features": [ - "CCTNewDownloadTab" - ] - } - ] - } - ], "CPSS": [ { "platforms": [
diff --git a/third_party/.gitignore b/third_party/.gitignore index 0c5b9f5..bb50e8d 100644 --- a/third_party/.gitignore +++ b/third_party/.gitignore
@@ -73,6 +73,7 @@ /cpuinfo/src /crc32c/src /cros +/cros_components /cros_system_api /custom_tabs_client/src /cygwin
diff --git a/third_party/android_deps/build.gradle b/third_party/android_deps/build.gradle index 9393d51..0f6b2d1 100644 --- a/third_party/android_deps/build.gradle +++ b/third_party/android_deps/build.gradle
@@ -117,6 +117,11 @@ compile 'com.android.tools:desugar_jdk_libs:1.1.5' compile 'com.android.tools:desugar_jdk_libs_configuration:1.1.5' + compile 'io.grpc:grpc-binder:1.49.0' + compile 'io.grpc:grpc-protobuf-lite:1.49.0' + compile 'io.grpc:grpc-stub:1.49.0' + compile 'io.grpc:grpc-api:1.49.0' + // Needed by androidx and by doubledown targets. // Note: These have version overrides set in ChromiumDepGraph.groovy. compile "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.1"
diff --git a/third_party/android_deps/buildSrc/src/main/groovy/ChromiumDepGraph.groovy b/third_party/android_deps/buildSrc/src/main/groovy/ChromiumDepGraph.groovy index e6692b26..5de21a2 100644 --- a/third_party/android_deps/buildSrc/src/main/groovy/ChromiumDepGraph.groovy +++ b/third_party/android_deps/buildSrc/src/main/groovy/ChromiumDepGraph.groovy
@@ -59,6 +59,7 @@ licenseName: 'Apache 2.0'), com_google_code_gson_gson: new PropertyOverride( url: 'https://github.com/google/gson', + description: "A Java serialization/deserialization library to convert Java Objects into JSON and back", licenseUrl: 'https://raw.githubusercontent.com/google/gson/master/LICENSE', licenseName: 'Apache 2.0'), com_google_errorprone_error_prone_annotation: new PropertyOverride( @@ -122,6 +123,8 @@ overrideLatest: true), org_codehaus_mojo_animal_sniffer_annotations: new PropertyOverride( url: 'http://www.mojohaus.org/animal-sniffer/animal-sniffer-annotations/', + description: 'Animal Sniffer Annotations allow marking methods which Animal Sniffer should ignore ' + + 'signature violations of.', /* groovylint-disable-next-line LineLength */ licenseUrl: 'https://raw.githubusercontent.com/mojohaus/animal-sniffer/master/animal-sniffer-annotations/pom.xml', licensePath: 'licenses/Codehaus_License-2009.txt', @@ -257,6 +260,31 @@ resolveVersion: '1.6.20'), org_jetbrains_kotlin_kotlin_stdlib_jdk7: new PropertyOverride( resolveVersion: '1.6.20'), + org_jetbrains_kotlin_kotlin_stdlib: new PropertyOverride( + resolveVersion: '1.7.10'), + org_jetbrains_kotlin_kotlin_stdlib_common: new PropertyOverride( + resolveVersion: '1.7.10'), + io_grpc_grpc_binder: new PropertyOverride( + licenseUrl: 'https://www.apache.org/licenses/LICENSE-2.0.txt', + licenseName: 'Apache 2.0', overrideLatest: true), + io_grpc_grpc_core: new PropertyOverride( + licenseUrl: 'https://www.apache.org/licenses/LICENSE-2.0.txt', + licenseName: 'Apache 2.0', overrideLatest: true), + io_grpc_grpc_api: new PropertyOverride( + licenseUrl: 'https://www.apache.org/licenses/LICENSE-2.0.txt', + licenseName: 'Apache 2.0', overrideLatest: true), + io_grpc_grpc_context: new PropertyOverride( + licenseUrl: 'https://www.apache.org/licenses/LICENSE-2.0.txt', + licenseName: 'Apache 2.0', overrideLatest: true), + io_grpc_grpc_protobuf_lite: new PropertyOverride( + licenseUrl: 'https://www.apache.org/licenses/LICENSE-2.0.txt', + licenseName: 'Apache 2.0', overrideLatest: true), + io_grpc_grpc_stub: new PropertyOverride( + licenseUrl: 'https://www.apache.org/licenses/LICENSE-2.0.txt', + licenseName: 'Apache 2.0', overrideLatest: true), + io_perfmark_perfmark_api: new PropertyOverride( + licenseUrl: 'https://www.apache.org/licenses/LICENSE-2.0.txt', + licenseName: 'Apache 2.0', overrideLatest: true), ] private static final Set<String> ALLOWED_EMPTY_DEPS = [ @@ -407,8 +435,11 @@ private void recursivelyOverrideLatestVersion(DependencyDescription dep) { dep.overrideLatest = true dep.children.each { childID -> - DependencyDescription child = dependencies.get(childID) - recursivelyOverrideLatestVersion(child) + PropertyOverride overrides = PROPERTY_OVERRIDES.get(childID) + if (!overrides?.resolveVersion) { + DependencyDescription child = dependencies.get(childID) + recursivelyOverrideLatestVersion(child) + } } }
diff --git a/third_party/android_deps/libs/com_google_android_annotations/3pp/3pp.pb b/third_party/android_deps/libs/com_google_android_annotations/3pp/3pp.pb new file mode 100644 index 0000000..d743b51b --- /dev/null +++ b/third_party/android_deps/libs/com_google_android_annotations/3pp/3pp.pb
@@ -0,0 +1,16 @@ +# Copyright 2021 The Chromium Authors +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +# This is generated, do not edit. Update BuildConfigGenerator.groovy instead. + +create { + source { + script { name: "fetch.py" } + } +} + +upload { + pkg_prefix: "chromium/third_party/android_deps/libs" + universal: true +}
diff --git a/third_party/android_deps/libs/com_google_android_annotations/3pp/fetch.py b/third_party/android_deps/libs/com_google_android_annotations/3pp/fetch.py new file mode 100755 index 0000000..44fa01da --- /dev/null +++ b/third_party/android_deps/libs/com_google_android_annotations/3pp/fetch.py
@@ -0,0 +1,78 @@ +#!/usr/bin/env python3 +# Copyright 2021 The Chromium Authors +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +# This is generated, do not edit. Update BuildConfigGenerator.groovy and +# 3ppFetch.template instead. + +import argparse +import json +import os +import re +import urllib.request + +_REPO_URL = 'https://repo.maven.apache.org/maven2' +_GROUP_NAME = 'com/google/android' +_MODULE_NAME = 'annotations' +_FILE_EXT = 'jar' +_OVERRIDE_LATEST = '4.1.1.4' +_PATCH_VERSION = 'cr1' + + +def do_latest(): + if _OVERRIDE_LATEST is not None: + print(_OVERRIDE_LATEST + f'.{_PATCH_VERSION}') + return + maven_metadata_url = '{}/{}/{}/maven-metadata.xml'.format( + _REPO_URL, _GROUP_NAME, _MODULE_NAME) + metadata = urllib.request.urlopen(maven_metadata_url).read().decode( + 'utf-8') + # Do not parse xml with the python included parser since it is susceptible + # to maliciously crafted xmls. Only use regular expression parsing to be + # safe. RE should be enough to handle what we need to extract. + match = re.search('<latest>([^<]+)</latest>', metadata) + if match: + latest = match.group(1) + else: + # if no latest info was found just hope the versions are sorted and the + # last one is the latest (as is commonly the case). + latest = re.findall('<version>([^<]+)</version>', metadata)[-1] + print(latest + f'.{_PATCH_VERSION}') + + +def get_download_url(version): + # Remove the patch version when getting the download url + version_no_patch, patch = version.rsplit('.', 1) + if patch.startswith('cr'): + version = version_no_patch + file_url = '{0}/{1}/{2}/{3}/{2}-{3}.{4}'.format(_REPO_URL, _GROUP_NAME, + _MODULE_NAME, version, + _FILE_EXT) + file_name = file_url.rsplit('/', 1)[-1] + + partial_manifest = { + 'url': [file_url], + 'name': [file_name], + 'ext': '.' + _FILE_EXT, + } + print(json.dumps(partial_manifest)) + + +def main(): + ap = argparse.ArgumentParser() + sub = ap.add_subparsers() + + latest = sub.add_parser('latest') + latest.set_defaults(func=lambda _opts: do_latest()) + + download = sub.add_parser('get_url') + download.set_defaults( + func=lambda _opts: get_download_url(os.environ['_3PP_VERSION'])) + + opts = ap.parse_args() + opts.func(opts) + + +if __name__ == '__main__': + main()
diff --git a/third_party/android_deps/libs/com_google_android_annotations/OWNERS b/third_party/android_deps/libs/com_google_android_annotations/OWNERS new file mode 100644 index 0000000..aea47a05 --- /dev/null +++ b/third_party/android_deps/libs/com_google_android_annotations/OWNERS
@@ -0,0 +1 @@ +file://third_party/android_deps/OWNERS
diff --git a/third_party/android_deps/libs/com_google_android_annotations/README.chromium b/third_party/android_deps/libs/com_google_android_annotations/README.chromium new file mode 100644 index 0000000..b1f04b3 --- /dev/null +++ b/third_party/android_deps/libs/com_google_android_annotations/README.chromium
@@ -0,0 +1,14 @@ +Name: Google Android Annotations Library +Short Name: annotations +URL: http://source.android.com/ +Version: 4.1.1.4 +License: Android Software Development Kit License +License File: LICENSE +CPEPrefix: unknown +Security Critical: yes + +Description: +A library jar that provides annotations for the Google Android Platform. + +Local Modifications: +No modifications.
diff --git a/third_party/android_deps/libs/com_google_android_annotations/cipd.yaml b/third_party/android_deps/libs/com_google_android_annotations/cipd.yaml new file mode 100644 index 0000000..80dacf4e --- /dev/null +++ b/third_party/android_deps/libs/com_google_android_annotations/cipd.yaml
@@ -0,0 +1,10 @@ +# 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. + +# To create CIPD package run the following command. +# cipd create --pkg-def cipd.yaml -tag version:2@4.1.1.4.cr1 +package: chromium/third_party/android_deps/libs/com_google_android_annotations +description: "Google Android Annotations Library" +data: +- file: annotations-4.1.1.4.jar
diff --git a/third_party/android_deps/libs/com_google_code_findbugs_jsr305/3pp/fetch.py b/third_party/android_deps/libs/com_google_code_findbugs_jsr305/3pp/fetch.py index 01c6e1b..d8a2eb56 100755 --- a/third_party/android_deps/libs/com_google_code_findbugs_jsr305/3pp/fetch.py +++ b/third_party/android_deps/libs/com_google_code_findbugs_jsr305/3pp/fetch.py
@@ -16,7 +16,7 @@ _GROUP_NAME = 'com/google/code/findbugs' _MODULE_NAME = 'jsr305' _FILE_EXT = 'jar' -_OVERRIDE_LATEST = None +_OVERRIDE_LATEST = '3.0.2' _PATCH_VERSION = 'cr1'
diff --git a/third_party/android_deps/libs/com_google_code_gson_gson/3pp/fetch.py b/third_party/android_deps/libs/com_google_code_gson_gson/3pp/fetch.py index 6f4864a..a65dbd2 100755 --- a/third_party/android_deps/libs/com_google_code_gson_gson/3pp/fetch.py +++ b/third_party/android_deps/libs/com_google_code_gson_gson/3pp/fetch.py
@@ -16,7 +16,7 @@ _GROUP_NAME = 'com/google/code/gson' _MODULE_NAME = 'gson' _FILE_EXT = 'jar' -_OVERRIDE_LATEST = None +_OVERRIDE_LATEST = '2.9.0' _PATCH_VERSION = 'cr1'
diff --git a/third_party/android_deps/libs/com_google_code_gson_gson/README.chromium b/third_party/android_deps/libs/com_google_code_gson_gson/README.chromium index 2bfef92..44453d89 100644 --- a/third_party/android_deps/libs/com_google_code_gson_gson/README.chromium +++ b/third_party/android_deps/libs/com_google_code_gson_gson/README.chromium
@@ -1,14 +1,14 @@ Name: Gson Short Name: gson URL: https://github.com/google/gson -Version: 2.8.0 +Version: 2.9.0 License: Apache 2.0 -License File: NOT_SHIPPED +License File: LICENSE CPEPrefix: unknown -Security Critical: no +Security Critical: yes Description: - +A Java serialization/deserialization library to convert Java Objects into JSON and back Local Modifications: No modifications.
diff --git a/third_party/android_deps/libs/com_google_code_gson_gson/cipd.yaml b/third_party/android_deps/libs/com_google_code_gson_gson/cipd.yaml index 335293e5..f6dd71f 100644 --- a/third_party/android_deps/libs/com_google_code_gson_gson/cipd.yaml +++ b/third_party/android_deps/libs/com_google_code_gson_gson/cipd.yaml
@@ -3,8 +3,8 @@ # found in the LICENSE file. # To create CIPD package run the following command. -# cipd create --pkg-def cipd.yaml -tag version:2@2.8.0.cr1 +# cipd create --pkg-def cipd.yaml -tag version:2@2.9.0.cr1 package: chromium/third_party/android_deps/libs/com_google_code_gson_gson description: "Gson" data: -- file: gson-2.8.0.jar +- file: gson-2.9.0.jar
diff --git a/third_party/android_deps/libs/com_google_errorprone_error_prone_annotations/3pp/fetch.py b/third_party/android_deps/libs/com_google_errorprone_error_prone_annotations/3pp/fetch.py index af181b3a..176857e 100755 --- a/third_party/android_deps/libs/com_google_errorprone_error_prone_annotations/3pp/fetch.py +++ b/third_party/android_deps/libs/com_google_errorprone_error_prone_annotations/3pp/fetch.py
@@ -16,7 +16,7 @@ _GROUP_NAME = 'com/google/errorprone' _MODULE_NAME = 'error_prone_annotations' _FILE_EXT = 'jar' -_OVERRIDE_LATEST = None +_OVERRIDE_LATEST = '2.14.0' _PATCH_VERSION = 'cr1'
diff --git a/third_party/android_deps/libs/com_google_guava_failureaccess/3pp/fetch.py b/third_party/android_deps/libs/com_google_guava_failureaccess/3pp/fetch.py index 0f07566..d99d5fb 100755 --- a/third_party/android_deps/libs/com_google_guava_failureaccess/3pp/fetch.py +++ b/third_party/android_deps/libs/com_google_guava_failureaccess/3pp/fetch.py
@@ -16,7 +16,7 @@ _GROUP_NAME = 'com/google/guava' _MODULE_NAME = 'failureaccess' _FILE_EXT = 'jar' -_OVERRIDE_LATEST = None +_OVERRIDE_LATEST = '1.0.1' _PATCH_VERSION = 'cr1'
diff --git a/third_party/android_deps/libs/com_google_guava_guava_android/3pp/fetch.py b/third_party/android_deps/libs/com_google_guava_guava_android/3pp/fetch.py index 786ebc4..538d4dd 100755 --- a/third_party/android_deps/libs/com_google_guava_guava_android/3pp/fetch.py +++ b/third_party/android_deps/libs/com_google_guava_guava_android/3pp/fetch.py
@@ -16,7 +16,7 @@ _GROUP_NAME = 'com/google/guava' _MODULE_NAME = 'guava' _FILE_EXT = 'jar' -_OVERRIDE_LATEST = None +_OVERRIDE_LATEST = '31.1-android' _PATCH_VERSION = 'cr1'
diff --git a/third_party/android_deps/libs/com_google_guava_guava_android/README.chromium b/third_party/android_deps/libs/com_google_guava_guava_android/README.chromium index a1f87dc..4e827bc 100644 --- a/third_party/android_deps/libs/com_google_guava_guava_android/README.chromium +++ b/third_party/android_deps/libs/com_google_guava_guava_android/README.chromium
@@ -1,7 +1,7 @@ Name: Guava: Google Core Libraries for Java Short Name: guava URL: https://github.com/google/guava -Version: 31.0-android +Version: 31.1-android License: Apache 2.0 License File: LICENSE CPEPrefix: unknown
diff --git a/third_party/android_deps/libs/com_google_guava_guava_android/cipd.yaml b/third_party/android_deps/libs/com_google_guava_guava_android/cipd.yaml index 5cbfa974..66f68519 100644 --- a/third_party/android_deps/libs/com_google_guava_guava_android/cipd.yaml +++ b/third_party/android_deps/libs/com_google_guava_guava_android/cipd.yaml
@@ -3,8 +3,8 @@ # found in the LICENSE file. # To create CIPD package run the following command. -# cipd create --pkg-def cipd.yaml -tag version:2@31.0-android.cr1 +# cipd create --pkg-def cipd.yaml -tag version:2@31.1-android.cr1 package: chromium/third_party/android_deps/libs/com_google_guava_guava_android description: "Guava: Google Core Libraries for Java" data: -- file: guava-31.0-android.jar +- file: guava-31.1-android.jar
diff --git a/third_party/android_deps/libs/com_google_j2objc_j2objc_annotations/3pp/fetch.py b/third_party/android_deps/libs/com_google_j2objc_j2objc_annotations/3pp/fetch.py index 9030b77..e2ce451 100755 --- a/third_party/android_deps/libs/com_google_j2objc_j2objc_annotations/3pp/fetch.py +++ b/third_party/android_deps/libs/com_google_j2objc_j2objc_annotations/3pp/fetch.py
@@ -16,7 +16,7 @@ _GROUP_NAME = 'com/google/j2objc' _MODULE_NAME = 'j2objc-annotations' _FILE_EXT = 'jar' -_OVERRIDE_LATEST = None +_OVERRIDE_LATEST = '1.3' _PATCH_VERSION = 'cr1'
diff --git a/third_party/android_deps/libs/com_google_protobuf_protobuf_javalite/3pp/fetch.py b/third_party/android_deps/libs/com_google_protobuf_protobuf_javalite/3pp/fetch.py index 47112d4..c765e34a 100755 --- a/third_party/android_deps/libs/com_google_protobuf_protobuf_javalite/3pp/fetch.py +++ b/third_party/android_deps/libs/com_google_protobuf_protobuf_javalite/3pp/fetch.py
@@ -16,7 +16,7 @@ _GROUP_NAME = 'com/google/protobuf' _MODULE_NAME = 'protobuf-javalite' _FILE_EXT = 'jar' -_OVERRIDE_LATEST = None +_OVERRIDE_LATEST = '3.21.1' _PATCH_VERSION = 'cr1'
diff --git a/third_party/android_deps/libs/com_google_protobuf_protobuf_javalite/README.chromium b/third_party/android_deps/libs/com_google_protobuf_protobuf_javalite/README.chromium index 386ef5fe..c0e8816 100644 --- a/third_party/android_deps/libs/com_google_protobuf_protobuf_javalite/README.chromium +++ b/third_party/android_deps/libs/com_google_protobuf_protobuf_javalite/README.chromium
@@ -1,7 +1,7 @@ Name: Protocol Buffers [Lite] Short Name: protobuf-javalite URL: https://github.com/protocolbuffers/protobuf/blob/master/java/lite.md -Version: 3.19.3 +Version: 3.21.1 License: BSD License File: LICENSE CPEPrefix: unknown
diff --git a/third_party/android_deps/libs/com_google_protobuf_protobuf_javalite/cipd.yaml b/third_party/android_deps/libs/com_google_protobuf_protobuf_javalite/cipd.yaml index 43b586a..0e1d51a 100644 --- a/third_party/android_deps/libs/com_google_protobuf_protobuf_javalite/cipd.yaml +++ b/third_party/android_deps/libs/com_google_protobuf_protobuf_javalite/cipd.yaml
@@ -3,8 +3,8 @@ # found in the LICENSE file. # To create CIPD package run the following command. -# cipd create --pkg-def cipd.yaml -tag version:2@3.19.3.cr1 +# cipd create --pkg-def cipd.yaml -tag version:2@3.21.1.cr1 package: chromium/third_party/android_deps/libs/com_google_protobuf_protobuf_javalite description: "Protocol Buffers [Lite]" data: -- file: protobuf-javalite-3.19.3.jar +- file: protobuf-javalite-3.21.1.jar
diff --git a/third_party/android_deps/libs/io_grpc_grpc_api/3pp/3pp.pb b/third_party/android_deps/libs/io_grpc_grpc_api/3pp/3pp.pb new file mode 100644 index 0000000..d743b51b --- /dev/null +++ b/third_party/android_deps/libs/io_grpc_grpc_api/3pp/3pp.pb
@@ -0,0 +1,16 @@ +# Copyright 2021 The Chromium Authors +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +# This is generated, do not edit. Update BuildConfigGenerator.groovy instead. + +create { + source { + script { name: "fetch.py" } + } +} + +upload { + pkg_prefix: "chromium/third_party/android_deps/libs" + universal: true +}
diff --git a/third_party/android_deps/libs/io_grpc_grpc_api/3pp/fetch.py b/third_party/android_deps/libs/io_grpc_grpc_api/3pp/fetch.py new file mode 100755 index 0000000..f8bda868 --- /dev/null +++ b/third_party/android_deps/libs/io_grpc_grpc_api/3pp/fetch.py
@@ -0,0 +1,78 @@ +#!/usr/bin/env python3 +# Copyright 2021 The Chromium Authors +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +# This is generated, do not edit. Update BuildConfigGenerator.groovy and +# 3ppFetch.template instead. + +import argparse +import json +import os +import re +import urllib.request + +_REPO_URL = 'https://repo.maven.apache.org/maven2' +_GROUP_NAME = 'io/grpc' +_MODULE_NAME = 'grpc-api' +_FILE_EXT = 'jar' +_OVERRIDE_LATEST = '1.49.0' +_PATCH_VERSION = 'cr1' + + +def do_latest(): + if _OVERRIDE_LATEST is not None: + print(_OVERRIDE_LATEST + f'.{_PATCH_VERSION}') + return + maven_metadata_url = '{}/{}/{}/maven-metadata.xml'.format( + _REPO_URL, _GROUP_NAME, _MODULE_NAME) + metadata = urllib.request.urlopen(maven_metadata_url).read().decode( + 'utf-8') + # Do not parse xml with the python included parser since it is susceptible + # to maliciously crafted xmls. Only use regular expression parsing to be + # safe. RE should be enough to handle what we need to extract. + match = re.search('<latest>([^<]+)</latest>', metadata) + if match: + latest = match.group(1) + else: + # if no latest info was found just hope the versions are sorted and the + # last one is the latest (as is commonly the case). + latest = re.findall('<version>([^<]+)</version>', metadata)[-1] + print(latest + f'.{_PATCH_VERSION}') + + +def get_download_url(version): + # Remove the patch version when getting the download url + version_no_patch, patch = version.rsplit('.', 1) + if patch.startswith('cr'): + version = version_no_patch + file_url = '{0}/{1}/{2}/{3}/{2}-{3}.{4}'.format(_REPO_URL, _GROUP_NAME, + _MODULE_NAME, version, + _FILE_EXT) + file_name = file_url.rsplit('/', 1)[-1] + + partial_manifest = { + 'url': [file_url], + 'name': [file_name], + 'ext': '.' + _FILE_EXT, + } + print(json.dumps(partial_manifest)) + + +def main(): + ap = argparse.ArgumentParser() + sub = ap.add_subparsers() + + latest = sub.add_parser('latest') + latest.set_defaults(func=lambda _opts: do_latest()) + + download = sub.add_parser('get_url') + download.set_defaults( + func=lambda _opts: get_download_url(os.environ['_3PP_VERSION'])) + + opts = ap.parse_args() + opts.func(opts) + + +if __name__ == '__main__': + main()
diff --git a/third_party/android_deps/libs/io_grpc_grpc_api/OWNERS b/third_party/android_deps/libs/io_grpc_grpc_api/OWNERS new file mode 100644 index 0000000..aea47a05 --- /dev/null +++ b/third_party/android_deps/libs/io_grpc_grpc_api/OWNERS
@@ -0,0 +1 @@ +file://third_party/android_deps/OWNERS
diff --git a/third_party/android_deps/libs/io_grpc_grpc_api/README.chromium b/third_party/android_deps/libs/io_grpc_grpc_api/README.chromium new file mode 100644 index 0000000..ce02eff --- /dev/null +++ b/third_party/android_deps/libs/io_grpc_grpc_api/README.chromium
@@ -0,0 +1,14 @@ +Name: io.grpc:grpc-api +Short Name: grpc-api +URL: https://github.com/grpc/grpc-java +Version: 1.49.0 +License: Apache 2.0 +License File: LICENSE +CPEPrefix: unknown +Security Critical: yes + +Description: +gRPC: API + +Local Modifications: +No modifications.
diff --git a/third_party/android_deps/libs/io_grpc_grpc_api/cipd.yaml b/third_party/android_deps/libs/io_grpc_grpc_api/cipd.yaml new file mode 100644 index 0000000..437da67 --- /dev/null +++ b/third_party/android_deps/libs/io_grpc_grpc_api/cipd.yaml
@@ -0,0 +1,10 @@ +# 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. + +# To create CIPD package run the following command. +# cipd create --pkg-def cipd.yaml -tag version:2@1.49.0.cr1 +package: chromium/third_party/android_deps/libs/io_grpc_grpc_api +description: "io.grpc:grpc-api" +data: +- file: grpc-api-1.49.0.jar
diff --git a/third_party/android_deps/libs/io_grpc_grpc_binder/3pp/3pp.pb b/third_party/android_deps/libs/io_grpc_grpc_binder/3pp/3pp.pb new file mode 100644 index 0000000..d743b51b --- /dev/null +++ b/third_party/android_deps/libs/io_grpc_grpc_binder/3pp/3pp.pb
@@ -0,0 +1,16 @@ +# Copyright 2021 The Chromium Authors +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +# This is generated, do not edit. Update BuildConfigGenerator.groovy instead. + +create { + source { + script { name: "fetch.py" } + } +} + +upload { + pkg_prefix: "chromium/third_party/android_deps/libs" + universal: true +}
diff --git a/third_party/android_deps/libs/io_grpc_grpc_binder/3pp/fetch.py b/third_party/android_deps/libs/io_grpc_grpc_binder/3pp/fetch.py new file mode 100755 index 0000000..22d7d36 --- /dev/null +++ b/third_party/android_deps/libs/io_grpc_grpc_binder/3pp/fetch.py
@@ -0,0 +1,78 @@ +#!/usr/bin/env python3 +# Copyright 2021 The Chromium Authors +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +# This is generated, do not edit. Update BuildConfigGenerator.groovy and +# 3ppFetch.template instead. + +import argparse +import json +import os +import re +import urllib.request + +_REPO_URL = 'https://repo.maven.apache.org/maven2' +_GROUP_NAME = 'io/grpc' +_MODULE_NAME = 'grpc-binder' +_FILE_EXT = 'aar' +_OVERRIDE_LATEST = '1.49.0' +_PATCH_VERSION = 'cr1' + + +def do_latest(): + if _OVERRIDE_LATEST is not None: + print(_OVERRIDE_LATEST + f'.{_PATCH_VERSION}') + return + maven_metadata_url = '{}/{}/{}/maven-metadata.xml'.format( + _REPO_URL, _GROUP_NAME, _MODULE_NAME) + metadata = urllib.request.urlopen(maven_metadata_url).read().decode( + 'utf-8') + # Do not parse xml with the python included parser since it is susceptible + # to maliciously crafted xmls. Only use regular expression parsing to be + # safe. RE should be enough to handle what we need to extract. + match = re.search('<latest>([^<]+)</latest>', metadata) + if match: + latest = match.group(1) + else: + # if no latest info was found just hope the versions are sorted and the + # last one is the latest (as is commonly the case). + latest = re.findall('<version>([^<]+)</version>', metadata)[-1] + print(latest + f'.{_PATCH_VERSION}') + + +def get_download_url(version): + # Remove the patch version when getting the download url + version_no_patch, patch = version.rsplit('.', 1) + if patch.startswith('cr'): + version = version_no_patch + file_url = '{0}/{1}/{2}/{3}/{2}-{3}.{4}'.format(_REPO_URL, _GROUP_NAME, + _MODULE_NAME, version, + _FILE_EXT) + file_name = file_url.rsplit('/', 1)[-1] + + partial_manifest = { + 'url': [file_url], + 'name': [file_name], + 'ext': '.' + _FILE_EXT, + } + print(json.dumps(partial_manifest)) + + +def main(): + ap = argparse.ArgumentParser() + sub = ap.add_subparsers() + + latest = sub.add_parser('latest') + latest.set_defaults(func=lambda _opts: do_latest()) + + download = sub.add_parser('get_url') + download.set_defaults( + func=lambda _opts: get_download_url(os.environ['_3PP_VERSION'])) + + opts = ap.parse_args() + opts.func(opts) + + +if __name__ == '__main__': + main()
diff --git a/third_party/android_deps/libs/io_grpc_grpc_binder/OWNERS b/third_party/android_deps/libs/io_grpc_grpc_binder/OWNERS new file mode 100644 index 0000000..aea47a05 --- /dev/null +++ b/third_party/android_deps/libs/io_grpc_grpc_binder/OWNERS
@@ -0,0 +1 @@ +file://third_party/android_deps/OWNERS
diff --git a/third_party/android_deps/libs/io_grpc_grpc_binder/README.chromium b/third_party/android_deps/libs/io_grpc_grpc_binder/README.chromium new file mode 100644 index 0000000..c9b625d --- /dev/null +++ b/third_party/android_deps/libs/io_grpc_grpc_binder/README.chromium
@@ -0,0 +1,14 @@ +Name: io.grpc:grpc-binder +Short Name: grpc-binder +URL: https://github.com/grpc/grpc-java +Version: 1.49.0 +License: Apache 2.0 +License File: LICENSE +CPEPrefix: unknown +Security Critical: yes + +Description: +gRPC BinderChannel + +Local Modifications: +No modifications.
diff --git a/third_party/android_deps/libs/io_grpc_grpc_binder/cipd.yaml b/third_party/android_deps/libs/io_grpc_grpc_binder/cipd.yaml new file mode 100644 index 0000000..cc61f8d7 --- /dev/null +++ b/third_party/android_deps/libs/io_grpc_grpc_binder/cipd.yaml
@@ -0,0 +1,10 @@ +# 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. + +# To create CIPD package run the following command. +# cipd create --pkg-def cipd.yaml -tag version:2@1.49.0.cr1 +package: chromium/third_party/android_deps/libs/io_grpc_grpc_binder +description: "io.grpc:grpc-binder" +data: +- file: grpc-binder-1.49.0.aar
diff --git a/third_party/android_deps/libs/io_grpc_grpc_context/3pp/3pp.pb b/third_party/android_deps/libs/io_grpc_grpc_context/3pp/3pp.pb new file mode 100644 index 0000000..d743b51b --- /dev/null +++ b/third_party/android_deps/libs/io_grpc_grpc_context/3pp/3pp.pb
@@ -0,0 +1,16 @@ +# Copyright 2021 The Chromium Authors +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +# This is generated, do not edit. Update BuildConfigGenerator.groovy instead. + +create { + source { + script { name: "fetch.py" } + } +} + +upload { + pkg_prefix: "chromium/third_party/android_deps/libs" + universal: true +}
diff --git a/third_party/android_deps/libs/io_grpc_grpc_context/3pp/fetch.py b/third_party/android_deps/libs/io_grpc_grpc_context/3pp/fetch.py new file mode 100755 index 0000000..b92d303 --- /dev/null +++ b/third_party/android_deps/libs/io_grpc_grpc_context/3pp/fetch.py
@@ -0,0 +1,78 @@ +#!/usr/bin/env python3 +# Copyright 2021 The Chromium Authors +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +# This is generated, do not edit. Update BuildConfigGenerator.groovy and +# 3ppFetch.template instead. + +import argparse +import json +import os +import re +import urllib.request + +_REPO_URL = 'https://repo.maven.apache.org/maven2' +_GROUP_NAME = 'io/grpc' +_MODULE_NAME = 'grpc-context' +_FILE_EXT = 'jar' +_OVERRIDE_LATEST = '1.49.0' +_PATCH_VERSION = 'cr1' + + +def do_latest(): + if _OVERRIDE_LATEST is not None: + print(_OVERRIDE_LATEST + f'.{_PATCH_VERSION}') + return + maven_metadata_url = '{}/{}/{}/maven-metadata.xml'.format( + _REPO_URL, _GROUP_NAME, _MODULE_NAME) + metadata = urllib.request.urlopen(maven_metadata_url).read().decode( + 'utf-8') + # Do not parse xml with the python included parser since it is susceptible + # to maliciously crafted xmls. Only use regular expression parsing to be + # safe. RE should be enough to handle what we need to extract. + match = re.search('<latest>([^<]+)</latest>', metadata) + if match: + latest = match.group(1) + else: + # if no latest info was found just hope the versions are sorted and the + # last one is the latest (as is commonly the case). + latest = re.findall('<version>([^<]+)</version>', metadata)[-1] + print(latest + f'.{_PATCH_VERSION}') + + +def get_download_url(version): + # Remove the patch version when getting the download url + version_no_patch, patch = version.rsplit('.', 1) + if patch.startswith('cr'): + version = version_no_patch + file_url = '{0}/{1}/{2}/{3}/{2}-{3}.{4}'.format(_REPO_URL, _GROUP_NAME, + _MODULE_NAME, version, + _FILE_EXT) + file_name = file_url.rsplit('/', 1)[-1] + + partial_manifest = { + 'url': [file_url], + 'name': [file_name], + 'ext': '.' + _FILE_EXT, + } + print(json.dumps(partial_manifest)) + + +def main(): + ap = argparse.ArgumentParser() + sub = ap.add_subparsers() + + latest = sub.add_parser('latest') + latest.set_defaults(func=lambda _opts: do_latest()) + + download = sub.add_parser('get_url') + download.set_defaults( + func=lambda _opts: get_download_url(os.environ['_3PP_VERSION'])) + + opts = ap.parse_args() + opts.func(opts) + + +if __name__ == '__main__': + main()
diff --git a/third_party/android_deps/libs/io_grpc_grpc_context/OWNERS b/third_party/android_deps/libs/io_grpc_grpc_context/OWNERS new file mode 100644 index 0000000..aea47a05 --- /dev/null +++ b/third_party/android_deps/libs/io_grpc_grpc_context/OWNERS
@@ -0,0 +1 @@ +file://third_party/android_deps/OWNERS
diff --git a/third_party/android_deps/libs/io_grpc_grpc_context/README.chromium b/third_party/android_deps/libs/io_grpc_grpc_context/README.chromium new file mode 100644 index 0000000..5c7e02a2 --- /dev/null +++ b/third_party/android_deps/libs/io_grpc_grpc_context/README.chromium
@@ -0,0 +1,14 @@ +Name: io.grpc:grpc-context +Short Name: grpc-context +URL: https://github.com/grpc/grpc-java +Version: 1.49.0 +License: Apache 2.0 +License File: LICENSE +CPEPrefix: unknown +Security Critical: yes + +Description: +gRPC: Context + +Local Modifications: +No modifications.
diff --git a/third_party/android_deps/libs/io_grpc_grpc_context/cipd.yaml b/third_party/android_deps/libs/io_grpc_grpc_context/cipd.yaml new file mode 100644 index 0000000..52251f0 --- /dev/null +++ b/third_party/android_deps/libs/io_grpc_grpc_context/cipd.yaml
@@ -0,0 +1,10 @@ +# 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. + +# To create CIPD package run the following command. +# cipd create --pkg-def cipd.yaml -tag version:2@1.49.0.cr1 +package: chromium/third_party/android_deps/libs/io_grpc_grpc_context +description: "io.grpc:grpc-context" +data: +- file: grpc-context-1.49.0.jar
diff --git a/third_party/android_deps/libs/io_grpc_grpc_core/3pp/3pp.pb b/third_party/android_deps/libs/io_grpc_grpc_core/3pp/3pp.pb new file mode 100644 index 0000000..d743b51b --- /dev/null +++ b/third_party/android_deps/libs/io_grpc_grpc_core/3pp/3pp.pb
@@ -0,0 +1,16 @@ +# Copyright 2021 The Chromium Authors +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +# This is generated, do not edit. Update BuildConfigGenerator.groovy instead. + +create { + source { + script { name: "fetch.py" } + } +} + +upload { + pkg_prefix: "chromium/third_party/android_deps/libs" + universal: true +}
diff --git a/third_party/android_deps/libs/io_grpc_grpc_core/3pp/fetch.py b/third_party/android_deps/libs/io_grpc_grpc_core/3pp/fetch.py new file mode 100755 index 0000000..dd64ddb --- /dev/null +++ b/third_party/android_deps/libs/io_grpc_grpc_core/3pp/fetch.py
@@ -0,0 +1,78 @@ +#!/usr/bin/env python3 +# Copyright 2021 The Chromium Authors +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +# This is generated, do not edit. Update BuildConfigGenerator.groovy and +# 3ppFetch.template instead. + +import argparse +import json +import os +import re +import urllib.request + +_REPO_URL = 'https://repo.maven.apache.org/maven2' +_GROUP_NAME = 'io/grpc' +_MODULE_NAME = 'grpc-core' +_FILE_EXT = 'jar' +_OVERRIDE_LATEST = '1.49.0' +_PATCH_VERSION = 'cr1' + + +def do_latest(): + if _OVERRIDE_LATEST is not None: + print(_OVERRIDE_LATEST + f'.{_PATCH_VERSION}') + return + maven_metadata_url = '{}/{}/{}/maven-metadata.xml'.format( + _REPO_URL, _GROUP_NAME, _MODULE_NAME) + metadata = urllib.request.urlopen(maven_metadata_url).read().decode( + 'utf-8') + # Do not parse xml with the python included parser since it is susceptible + # to maliciously crafted xmls. Only use regular expression parsing to be + # safe. RE should be enough to handle what we need to extract. + match = re.search('<latest>([^<]+)</latest>', metadata) + if match: + latest = match.group(1) + else: + # if no latest info was found just hope the versions are sorted and the + # last one is the latest (as is commonly the case). + latest = re.findall('<version>([^<]+)</version>', metadata)[-1] + print(latest + f'.{_PATCH_VERSION}') + + +def get_download_url(version): + # Remove the patch version when getting the download url + version_no_patch, patch = version.rsplit('.', 1) + if patch.startswith('cr'): + version = version_no_patch + file_url = '{0}/{1}/{2}/{3}/{2}-{3}.{4}'.format(_REPO_URL, _GROUP_NAME, + _MODULE_NAME, version, + _FILE_EXT) + file_name = file_url.rsplit('/', 1)[-1] + + partial_manifest = { + 'url': [file_url], + 'name': [file_name], + 'ext': '.' + _FILE_EXT, + } + print(json.dumps(partial_manifest)) + + +def main(): + ap = argparse.ArgumentParser() + sub = ap.add_subparsers() + + latest = sub.add_parser('latest') + latest.set_defaults(func=lambda _opts: do_latest()) + + download = sub.add_parser('get_url') + download.set_defaults( + func=lambda _opts: get_download_url(os.environ['_3PP_VERSION'])) + + opts = ap.parse_args() + opts.func(opts) + + +if __name__ == '__main__': + main()
diff --git a/third_party/android_deps/libs/io_grpc_grpc_core/OWNERS b/third_party/android_deps/libs/io_grpc_grpc_core/OWNERS new file mode 100644 index 0000000..aea47a05 --- /dev/null +++ b/third_party/android_deps/libs/io_grpc_grpc_core/OWNERS
@@ -0,0 +1 @@ +file://third_party/android_deps/OWNERS
diff --git a/third_party/android_deps/libs/io_grpc_grpc_core/README.chromium b/third_party/android_deps/libs/io_grpc_grpc_core/README.chromium new file mode 100644 index 0000000..43270627 --- /dev/null +++ b/third_party/android_deps/libs/io_grpc_grpc_core/README.chromium
@@ -0,0 +1,14 @@ +Name: io.grpc:grpc-core +Short Name: grpc-core +URL: https://github.com/grpc/grpc-java +Version: 1.49.0 +License: Apache 2.0 +License File: LICENSE +CPEPrefix: unknown +Security Critical: yes + +Description: +gRPC: Core + +Local Modifications: +No modifications.
diff --git a/third_party/android_deps/libs/io_grpc_grpc_core/cipd.yaml b/third_party/android_deps/libs/io_grpc_grpc_core/cipd.yaml new file mode 100644 index 0000000..7f02300 --- /dev/null +++ b/third_party/android_deps/libs/io_grpc_grpc_core/cipd.yaml
@@ -0,0 +1,10 @@ +# 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. + +# To create CIPD package run the following command. +# cipd create --pkg-def cipd.yaml -tag version:2@1.49.0.cr1 +package: chromium/third_party/android_deps/libs/io_grpc_grpc_core +description: "io.grpc:grpc-core" +data: +- file: grpc-core-1.49.0.jar
diff --git a/third_party/android_deps/libs/io_grpc_grpc_protobuf_lite/3pp/3pp.pb b/third_party/android_deps/libs/io_grpc_grpc_protobuf_lite/3pp/3pp.pb new file mode 100644 index 0000000..d743b51b --- /dev/null +++ b/third_party/android_deps/libs/io_grpc_grpc_protobuf_lite/3pp/3pp.pb
@@ -0,0 +1,16 @@ +# Copyright 2021 The Chromium Authors +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +# This is generated, do not edit. Update BuildConfigGenerator.groovy instead. + +create { + source { + script { name: "fetch.py" } + } +} + +upload { + pkg_prefix: "chromium/third_party/android_deps/libs" + universal: true +}
diff --git a/third_party/android_deps/libs/io_grpc_grpc_protobuf_lite/3pp/fetch.py b/third_party/android_deps/libs/io_grpc_grpc_protobuf_lite/3pp/fetch.py new file mode 100755 index 0000000..25435a4 --- /dev/null +++ b/third_party/android_deps/libs/io_grpc_grpc_protobuf_lite/3pp/fetch.py
@@ -0,0 +1,78 @@ +#!/usr/bin/env python3 +# Copyright 2021 The Chromium Authors +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +# This is generated, do not edit. Update BuildConfigGenerator.groovy and +# 3ppFetch.template instead. + +import argparse +import json +import os +import re +import urllib.request + +_REPO_URL = 'https://repo.maven.apache.org/maven2' +_GROUP_NAME = 'io/grpc' +_MODULE_NAME = 'grpc-protobuf-lite' +_FILE_EXT = 'jar' +_OVERRIDE_LATEST = '1.49.0' +_PATCH_VERSION = 'cr1' + + +def do_latest(): + if _OVERRIDE_LATEST is not None: + print(_OVERRIDE_LATEST + f'.{_PATCH_VERSION}') + return + maven_metadata_url = '{}/{}/{}/maven-metadata.xml'.format( + _REPO_URL, _GROUP_NAME, _MODULE_NAME) + metadata = urllib.request.urlopen(maven_metadata_url).read().decode( + 'utf-8') + # Do not parse xml with the python included parser since it is susceptible + # to maliciously crafted xmls. Only use regular expression parsing to be + # safe. RE should be enough to handle what we need to extract. + match = re.search('<latest>([^<]+)</latest>', metadata) + if match: + latest = match.group(1) + else: + # if no latest info was found just hope the versions are sorted and the + # last one is the latest (as is commonly the case). + latest = re.findall('<version>([^<]+)</version>', metadata)[-1] + print(latest + f'.{_PATCH_VERSION}') + + +def get_download_url(version): + # Remove the patch version when getting the download url + version_no_patch, patch = version.rsplit('.', 1) + if patch.startswith('cr'): + version = version_no_patch + file_url = '{0}/{1}/{2}/{3}/{2}-{3}.{4}'.format(_REPO_URL, _GROUP_NAME, + _MODULE_NAME, version, + _FILE_EXT) + file_name = file_url.rsplit('/', 1)[-1] + + partial_manifest = { + 'url': [file_url], + 'name': [file_name], + 'ext': '.' + _FILE_EXT, + } + print(json.dumps(partial_manifest)) + + +def main(): + ap = argparse.ArgumentParser() + sub = ap.add_subparsers() + + latest = sub.add_parser('latest') + latest.set_defaults(func=lambda _opts: do_latest()) + + download = sub.add_parser('get_url') + download.set_defaults( + func=lambda _opts: get_download_url(os.environ['_3PP_VERSION'])) + + opts = ap.parse_args() + opts.func(opts) + + +if __name__ == '__main__': + main()
diff --git a/third_party/android_deps/libs/io_grpc_grpc_protobuf_lite/OWNERS b/third_party/android_deps/libs/io_grpc_grpc_protobuf_lite/OWNERS new file mode 100644 index 0000000..aea47a05 --- /dev/null +++ b/third_party/android_deps/libs/io_grpc_grpc_protobuf_lite/OWNERS
@@ -0,0 +1 @@ +file://third_party/android_deps/OWNERS
diff --git a/third_party/android_deps/libs/io_grpc_grpc_protobuf_lite/README.chromium b/third_party/android_deps/libs/io_grpc_grpc_protobuf_lite/README.chromium new file mode 100644 index 0000000..bfa17e80 --- /dev/null +++ b/third_party/android_deps/libs/io_grpc_grpc_protobuf_lite/README.chromium
@@ -0,0 +1,14 @@ +Name: io.grpc:grpc-protobuf-lite +Short Name: grpc-protobuf-lite +URL: https://github.com/grpc/grpc-java +Version: 1.49.0 +License: Apache 2.0 +License File: LICENSE +CPEPrefix: unknown +Security Critical: yes + +Description: +gRPC: Protobuf Lite + +Local Modifications: +No modifications.
diff --git a/third_party/android_deps/libs/io_grpc_grpc_protobuf_lite/cipd.yaml b/third_party/android_deps/libs/io_grpc_grpc_protobuf_lite/cipd.yaml new file mode 100644 index 0000000..0259310 --- /dev/null +++ b/third_party/android_deps/libs/io_grpc_grpc_protobuf_lite/cipd.yaml
@@ -0,0 +1,10 @@ +# 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. + +# To create CIPD package run the following command. +# cipd create --pkg-def cipd.yaml -tag version:2@1.49.0.cr1 +package: chromium/third_party/android_deps/libs/io_grpc_grpc_protobuf_lite +description: "io.grpc:grpc-protobuf-lite" +data: +- file: grpc-protobuf-lite-1.49.0.jar
diff --git a/third_party/android_deps/libs/io_grpc_grpc_stub/3pp/3pp.pb b/third_party/android_deps/libs/io_grpc_grpc_stub/3pp/3pp.pb new file mode 100644 index 0000000..d743b51b --- /dev/null +++ b/third_party/android_deps/libs/io_grpc_grpc_stub/3pp/3pp.pb
@@ -0,0 +1,16 @@ +# Copyright 2021 The Chromium Authors +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +# This is generated, do not edit. Update BuildConfigGenerator.groovy instead. + +create { + source { + script { name: "fetch.py" } + } +} + +upload { + pkg_prefix: "chromium/third_party/android_deps/libs" + universal: true +}
diff --git a/third_party/android_deps/libs/io_grpc_grpc_stub/3pp/fetch.py b/third_party/android_deps/libs/io_grpc_grpc_stub/3pp/fetch.py new file mode 100755 index 0000000..dac9450 --- /dev/null +++ b/third_party/android_deps/libs/io_grpc_grpc_stub/3pp/fetch.py
@@ -0,0 +1,78 @@ +#!/usr/bin/env python3 +# Copyright 2021 The Chromium Authors +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +# This is generated, do not edit. Update BuildConfigGenerator.groovy and +# 3ppFetch.template instead. + +import argparse +import json +import os +import re +import urllib.request + +_REPO_URL = 'https://repo.maven.apache.org/maven2' +_GROUP_NAME = 'io/grpc' +_MODULE_NAME = 'grpc-stub' +_FILE_EXT = 'jar' +_OVERRIDE_LATEST = '1.49.0' +_PATCH_VERSION = 'cr1' + + +def do_latest(): + if _OVERRIDE_LATEST is not None: + print(_OVERRIDE_LATEST + f'.{_PATCH_VERSION}') + return + maven_metadata_url = '{}/{}/{}/maven-metadata.xml'.format( + _REPO_URL, _GROUP_NAME, _MODULE_NAME) + metadata = urllib.request.urlopen(maven_metadata_url).read().decode( + 'utf-8') + # Do not parse xml with the python included parser since it is susceptible + # to maliciously crafted xmls. Only use regular expression parsing to be + # safe. RE should be enough to handle what we need to extract. + match = re.search('<latest>([^<]+)</latest>', metadata) + if match: + latest = match.group(1) + else: + # if no latest info was found just hope the versions are sorted and the + # last one is the latest (as is commonly the case). + latest = re.findall('<version>([^<]+)</version>', metadata)[-1] + print(latest + f'.{_PATCH_VERSION}') + + +def get_download_url(version): + # Remove the patch version when getting the download url + version_no_patch, patch = version.rsplit('.', 1) + if patch.startswith('cr'): + version = version_no_patch + file_url = '{0}/{1}/{2}/{3}/{2}-{3}.{4}'.format(_REPO_URL, _GROUP_NAME, + _MODULE_NAME, version, + _FILE_EXT) + file_name = file_url.rsplit('/', 1)[-1] + + partial_manifest = { + 'url': [file_url], + 'name': [file_name], + 'ext': '.' + _FILE_EXT, + } + print(json.dumps(partial_manifest)) + + +def main(): + ap = argparse.ArgumentParser() + sub = ap.add_subparsers() + + latest = sub.add_parser('latest') + latest.set_defaults(func=lambda _opts: do_latest()) + + download = sub.add_parser('get_url') + download.set_defaults( + func=lambda _opts: get_download_url(os.environ['_3PP_VERSION'])) + + opts = ap.parse_args() + opts.func(opts) + + +if __name__ == '__main__': + main()
diff --git a/third_party/android_deps/libs/io_grpc_grpc_stub/OWNERS b/third_party/android_deps/libs/io_grpc_grpc_stub/OWNERS new file mode 100644 index 0000000..aea47a05 --- /dev/null +++ b/third_party/android_deps/libs/io_grpc_grpc_stub/OWNERS
@@ -0,0 +1 @@ +file://third_party/android_deps/OWNERS
diff --git a/third_party/android_deps/libs/io_grpc_grpc_stub/README.chromium b/third_party/android_deps/libs/io_grpc_grpc_stub/README.chromium new file mode 100644 index 0000000..dbc0cca --- /dev/null +++ b/third_party/android_deps/libs/io_grpc_grpc_stub/README.chromium
@@ -0,0 +1,14 @@ +Name: io.grpc:grpc-stub +Short Name: grpc-stub +URL: https://github.com/grpc/grpc-java +Version: 1.49.0 +License: Apache 2.0 +License File: LICENSE +CPEPrefix: unknown +Security Critical: yes + +Description: +gRPC: Stub + +Local Modifications: +No modifications.
diff --git a/third_party/android_deps/libs/io_grpc_grpc_stub/cipd.yaml b/third_party/android_deps/libs/io_grpc_grpc_stub/cipd.yaml new file mode 100644 index 0000000..ee74945 --- /dev/null +++ b/third_party/android_deps/libs/io_grpc_grpc_stub/cipd.yaml
@@ -0,0 +1,10 @@ +# 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. + +# To create CIPD package run the following command. +# cipd create --pkg-def cipd.yaml -tag version:2@1.49.0.cr1 +package: chromium/third_party/android_deps/libs/io_grpc_grpc_stub +description: "io.grpc:grpc-stub" +data: +- file: grpc-stub-1.49.0.jar
diff --git a/third_party/android_deps/libs/io_perfmark_perfmark_api/3pp/3pp.pb b/third_party/android_deps/libs/io_perfmark_perfmark_api/3pp/3pp.pb new file mode 100644 index 0000000..d743b51b --- /dev/null +++ b/third_party/android_deps/libs/io_perfmark_perfmark_api/3pp/3pp.pb
@@ -0,0 +1,16 @@ +# Copyright 2021 The Chromium Authors +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +# This is generated, do not edit. Update BuildConfigGenerator.groovy instead. + +create { + source { + script { name: "fetch.py" } + } +} + +upload { + pkg_prefix: "chromium/third_party/android_deps/libs" + universal: true +}
diff --git a/third_party/android_deps/libs/io_perfmark_perfmark_api/3pp/fetch.py b/third_party/android_deps/libs/io_perfmark_perfmark_api/3pp/fetch.py new file mode 100755 index 0000000..52c6097 --- /dev/null +++ b/third_party/android_deps/libs/io_perfmark_perfmark_api/3pp/fetch.py
@@ -0,0 +1,78 @@ +#!/usr/bin/env python3 +# Copyright 2021 The Chromium Authors +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +# This is generated, do not edit. Update BuildConfigGenerator.groovy and +# 3ppFetch.template instead. + +import argparse +import json +import os +import re +import urllib.request + +_REPO_URL = 'https://repo.maven.apache.org/maven2' +_GROUP_NAME = 'io/perfmark' +_MODULE_NAME = 'perfmark-api' +_FILE_EXT = 'jar' +_OVERRIDE_LATEST = '0.25.0' +_PATCH_VERSION = 'cr1' + + +def do_latest(): + if _OVERRIDE_LATEST is not None: + print(_OVERRIDE_LATEST + f'.{_PATCH_VERSION}') + return + maven_metadata_url = '{}/{}/{}/maven-metadata.xml'.format( + _REPO_URL, _GROUP_NAME, _MODULE_NAME) + metadata = urllib.request.urlopen(maven_metadata_url).read().decode( + 'utf-8') + # Do not parse xml with the python included parser since it is susceptible + # to maliciously crafted xmls. Only use regular expression parsing to be + # safe. RE should be enough to handle what we need to extract. + match = re.search('<latest>([^<]+)</latest>', metadata) + if match: + latest = match.group(1) + else: + # if no latest info was found just hope the versions are sorted and the + # last one is the latest (as is commonly the case). + latest = re.findall('<version>([^<]+)</version>', metadata)[-1] + print(latest + f'.{_PATCH_VERSION}') + + +def get_download_url(version): + # Remove the patch version when getting the download url + version_no_patch, patch = version.rsplit('.', 1) + if patch.startswith('cr'): + version = version_no_patch + file_url = '{0}/{1}/{2}/{3}/{2}-{3}.{4}'.format(_REPO_URL, _GROUP_NAME, + _MODULE_NAME, version, + _FILE_EXT) + file_name = file_url.rsplit('/', 1)[-1] + + partial_manifest = { + 'url': [file_url], + 'name': [file_name], + 'ext': '.' + _FILE_EXT, + } + print(json.dumps(partial_manifest)) + + +def main(): + ap = argparse.ArgumentParser() + sub = ap.add_subparsers() + + latest = sub.add_parser('latest') + latest.set_defaults(func=lambda _opts: do_latest()) + + download = sub.add_parser('get_url') + download.set_defaults( + func=lambda _opts: get_download_url(os.environ['_3PP_VERSION'])) + + opts = ap.parse_args() + opts.func(opts) + + +if __name__ == '__main__': + main()
diff --git a/third_party/android_deps/libs/io_perfmark_perfmark_api/OWNERS b/third_party/android_deps/libs/io_perfmark_perfmark_api/OWNERS new file mode 100644 index 0000000..aea47a05 --- /dev/null +++ b/third_party/android_deps/libs/io_perfmark_perfmark_api/OWNERS
@@ -0,0 +1 @@ +file://third_party/android_deps/OWNERS
diff --git a/third_party/android_deps/libs/io_perfmark_perfmark_api/README.chromium b/third_party/android_deps/libs/io_perfmark_perfmark_api/README.chromium new file mode 100644 index 0000000..b443bf8 --- /dev/null +++ b/third_party/android_deps/libs/io_perfmark_perfmark_api/README.chromium
@@ -0,0 +1,14 @@ +Name: perfmark:perfmark-api +Short Name: perfmark-api +URL: https://github.com/perfmark/perfmark +Version: 0.25.0 +License: Apache 2.0 +License File: LICENSE +CPEPrefix: unknown +Security Critical: yes + +Description: +PerfMark API + +Local Modifications: +No modifications.
diff --git a/third_party/android_deps/libs/io_perfmark_perfmark_api/cipd.yaml b/third_party/android_deps/libs/io_perfmark_perfmark_api/cipd.yaml new file mode 100644 index 0000000..8dd732c2 --- /dev/null +++ b/third_party/android_deps/libs/io_perfmark_perfmark_api/cipd.yaml
@@ -0,0 +1,10 @@ +# 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. + +# To create CIPD package run the following command. +# cipd create --pkg-def cipd.yaml -tag version:2@0.25.0.cr1 +package: chromium/third_party/android_deps/libs/io_perfmark_perfmark_api +description: "perfmark:perfmark-api" +data: +- file: perfmark-api-0.25.0.jar
diff --git a/third_party/android_deps/libs/org_checkerframework_checker_compat_qual/README.chromium b/third_party/android_deps/libs/org_checkerframework_checker_compat_qual/README.chromium index 659eb8d..7027b01 100644 --- a/third_party/android_deps/libs/org_checkerframework_checker_compat_qual/README.chromium +++ b/third_party/android_deps/libs/org_checkerframework_checker_compat_qual/README.chromium
@@ -1,7 +1,7 @@ Name: Checker Qual Short Name: checker-compat-qual URL: https://checkerframework.org -Version: 2.5.5 +Version: 2.5.3 License: GPL v2 with the classpath exception License File: LICENSE CPEPrefix: unknown
diff --git a/third_party/android_deps/libs/org_checkerframework_checker_compat_qual/cipd.yaml b/third_party/android_deps/libs/org_checkerframework_checker_compat_qual/cipd.yaml index cfaffdb..81683c9 100644 --- a/third_party/android_deps/libs/org_checkerframework_checker_compat_qual/cipd.yaml +++ b/third_party/android_deps/libs/org_checkerframework_checker_compat_qual/cipd.yaml
@@ -3,8 +3,8 @@ # found in the LICENSE file. # To create CIPD package run the following command. -# cipd create --pkg-def cipd.yaml -tag version:2@2.5.5.cr1 +# cipd create --pkg-def cipd.yaml -tag version:2@2.5.3.cr1 package: chromium/third_party/android_deps/libs/org_checkerframework_checker_compat_qual description: "Checker Qual" data: -- file: checker-compat-qual-2.5.5.jar +- file: checker-compat-qual-2.5.3.jar
diff --git a/third_party/android_deps/libs/org_checkerframework_checker_qual/3pp/fetch.py b/third_party/android_deps/libs/org_checkerframework_checker_qual/3pp/fetch.py index 99de559..6e1f081d 100755 --- a/third_party/android_deps/libs/org_checkerframework_checker_qual/3pp/fetch.py +++ b/third_party/android_deps/libs/org_checkerframework_checker_qual/3pp/fetch.py
@@ -16,7 +16,7 @@ _GROUP_NAME = 'org/checkerframework' _MODULE_NAME = 'checker-qual' _FILE_EXT = 'jar' -_OVERRIDE_LATEST = None +_OVERRIDE_LATEST = '3.25.0' _PATCH_VERSION = 'cr1'
diff --git a/third_party/android_deps/libs/org_codehaus_mojo_animal_sniffer_annotations/3pp/fetch.py b/third_party/android_deps/libs/org_codehaus_mojo_animal_sniffer_annotations/3pp/fetch.py index 4d05da70..9ef2c9d 100755 --- a/third_party/android_deps/libs/org_codehaus_mojo_animal_sniffer_annotations/3pp/fetch.py +++ b/third_party/android_deps/libs/org_codehaus_mojo_animal_sniffer_annotations/3pp/fetch.py
@@ -16,7 +16,7 @@ _GROUP_NAME = 'org/codehaus/mojo' _MODULE_NAME = 'animal-sniffer-annotations' _FILE_EXT = 'jar' -_OVERRIDE_LATEST = None +_OVERRIDE_LATEST = '1.21' _PATCH_VERSION = 'cr1'
diff --git a/third_party/android_deps/libs/org_codehaus_mojo_animal_sniffer_annotations/README.chromium b/third_party/android_deps/libs/org_codehaus_mojo_animal_sniffer_annotations/README.chromium index 7a16991..1972fb01 100644 --- a/third_party/android_deps/libs/org_codehaus_mojo_animal_sniffer_annotations/README.chromium +++ b/third_party/android_deps/libs/org_codehaus_mojo_animal_sniffer_annotations/README.chromium
@@ -1,14 +1,14 @@ Name: Animal Sniffer Annotations Short Name: animal-sniffer-annotations URL: http://www.mojohaus.org/animal-sniffer/animal-sniffer-annotations/ -Version: 1.17 +Version: 1.21 License: MIT License File: LICENSE CPEPrefix: unknown Security Critical: yes Description: - +Animal Sniffer Annotations allow marking methods which Animal Sniffer should ignore signature violations of. Local Modifications: No modifications.
diff --git a/third_party/android_deps/libs/org_codehaus_mojo_animal_sniffer_annotations/cipd.yaml b/third_party/android_deps/libs/org_codehaus_mojo_animal_sniffer_annotations/cipd.yaml index 2f5bf0f..8071fe2b 100644 --- a/third_party/android_deps/libs/org_codehaus_mojo_animal_sniffer_annotations/cipd.yaml +++ b/third_party/android_deps/libs/org_codehaus_mojo_animal_sniffer_annotations/cipd.yaml
@@ -3,8 +3,8 @@ # found in the LICENSE file. # To create CIPD package run the following command. -# cipd create --pkg-def cipd.yaml -tag version:2@1.17.cr1 +# cipd create --pkg-def cipd.yaml -tag version:2@1.21.cr1 package: chromium/third_party/android_deps/libs/org_codehaus_mojo_animal_sniffer_annotations description: "Animal Sniffer Annotations" data: -- file: animal-sniffer-annotations-1.17.jar +- file: animal-sniffer-annotations-1.21.jar
diff --git a/third_party/bidimapper/README.chromium b/third_party/bidimapper/README.chromium index 43cfc9e..fbbe485b 100644 --- a/third_party/bidimapper/README.chromium +++ b/third_party/bidimapper/README.chromium
@@ -1,10 +1,10 @@ Name: Implementation of WebDriver BiDi standard Short Name: chromium-bidi -URL: https://github.com/GoogleChromeLabs/chromium-bidi/archive/ea20be0c4c6de57c0f7618fce54ce34ee95ba023.zip +URL: https://github.com/GoogleChromeLabs/chromium-bidi/archive/71278c7d2a09b0bce034e8fb8b77fb78c8245aff.zip Version: 0 -Date: 2022-09-30 -Revision: ea20be0c4c6de57c0f7618fce54ce34ee95ba023 -SHA-512: ccd0727926c10b7f692f635847747aa637cefa327a857722691454f3846a4d7e53d484499e3606c43f469b6036b12c3d85530738bc731cd75bddcbe7440a84d8 +Date: 2022-10-06 +Revision: 71278c7d2a09b0bce034e8fb8b77fb78c8245aff +SHA-512: bd7936fa55542f7c2b0d4e1f9cdb7c12d889b7d361fc3aac6176a1d927732e284bd191a3c0c0eb18ddc8b637513697e443a40294a72735fb981f174b0586d4b7 License: Apache 2.0 License File: LICENSE Security Critical: no
diff --git a/third_party/bidimapper/mapper.js b/third_party/bidimapper/mapper.js index 77c6631..88d00ffb 100644 --- a/third_party/bidimapper/mapper.js +++ b/third_party/bidimapper/mapper.js
@@ -1,4 +1,4 @@ -!function(){"use strict";function e(e){return(...t)=>{if(globalThis.document?.documentElement){console.log(e,...t);const n=function(e){const t=e+"_log",n=document.getElementById(t);if(n)return n;const s=document.createElement("div");return s.id=t,s.innerHTML=`<h3>${e}:</h3>`,document.body.appendChild(s),s}(e),s=document.createElement("pre");s.textContent=t.join(", "),n.appendChild(s)}}}class t{constructor(e,t,n){this.error=e,this.message=t,this.stacktrace=n}error;message;stacktrace;toErrorResponse(e){return{id:e,error:this.error,message:this.message,stacktrace:this.stacktrace}}}class n extends t{constructor(e,t){super("unknown error",e,t)}}class s extends t{constructor(e,t){super("unknown command",e,t)}}class r extends t{constructor(e,t){super("invalid argument",e,t)}}class a extends t{constructor(e){super("no such frame",e)}}class i{method;params;constructor(e,t){this.method=e,this.params=t}}var o;!function(e){e.assertEqual=e=>e,e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const n of e)t[n]=n;return t},e.getValidEnumValues=t=>{const n=e.objectKeys(t).filter((e=>"number"!=typeof t[t[e]])),s={};for(const e of n)s[e]=t[e];return e.objectValues(s)},e.objectValues=t=>e.objectKeys(t).map((function(e){return t[e]})),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(const n of e)if(t(n))return n},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map((e=>"string"==typeof e?`'${e}'`:e)).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(o||(o={}));const c=o.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),d=e=>{switch(typeof e){case"undefined":return c.undefined;case"string":return c.string;case"number":return isNaN(e)?c.nan:c.number;case"boolean":return c.boolean;case"function":return c.function;case"bigint":return c.bigint;case"object":return Array.isArray(e)?c.array:null===e?c.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?c.promise:"undefined"!=typeof Map&&e instanceof Map?c.map:"undefined"!=typeof Set&&e instanceof Set?c.set:"undefined"!=typeof Date&&e instanceof Date?c.date:c.object;default:return c.unknown}},l=o.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of"]);class u extends Error{constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}get errors(){return this.issues}format(e){const t=e||function(e){return e.message},n={_errors:[]},s=e=>{for(const r of e.issues)if("invalid_union"===r.code)r.unionErrors.map(s);else if("invalid_return_type"===r.code)s(r.returnTypeError);else if("invalid_arguments"===r.code)s(r.argumentsError);else if(0===r.path.length)n._errors.push(t(r));else{let e=n,s=0;for(;s<r.path.length;){const n=r.path[s];s===r.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(r))):e[n]=e[n]||{_errors:[]},e=e[n],s++}}};return s(this),n}toString(){return this.message}get message(){return JSON.stringify(this.issues,o.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=(e=>e.message)){const t={},n=[];for(const s of this.issues)s.path.length>0?(t[s.path[0]]=t[s.path[0]]||[],t[s.path[0]].push(e(s))):n.push(e(s));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}}u.create=e=>new u(e);const p=(e,t)=>{let n;switch(e.code){case l.invalid_type:n=e.received===c.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case l.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,o.jsonStringifyReplacer)}`;break;case l.unrecognized_keys:n=`Unrecognized key(s) in object: ${o.joinValues(e.keys,", ")}`;break;case l.invalid_union:n="Invalid input";break;case l.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${o.joinValues(e.options)}`;break;case l.invalid_enum_value:n=`Invalid enum value. Expected ${o.joinValues(e.options)}, received '${e.received}'`;break;case l.invalid_arguments:n="Invalid function arguments";break;case l.invalid_return_type:n="Invalid function return type";break;case l.invalid_date:n="Invalid date";break;case l.invalid_string:"object"==typeof e.validation?"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:o.assertNever(e.validation):n="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case l.too_small:n="array"===e.type?`Array must contain ${e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type?`Number must be greater than ${e.inclusive?"or equal to ":""}${e.minimum}`:"date"===e.type?`Date must be greater than ${e.inclusive?"or equal to ":""}${new Date(e.minimum)}`:"Invalid input";break;case l.too_big:n="array"===e.type?`Array must contain ${e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be less than ${e.inclusive?"or equal to ":""}${e.maximum}`:"date"===e.type?`Date must be smaller than ${e.inclusive?"or equal to ":""}${new Date(e.maximum)}`:"Invalid input";break;case l.custom:n="Invalid input";break;case l.invalid_intersection_types:n="Intersection results could not be merged";break;case l.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;default:n=t.defaultError,o.assertNever(e)}return{message:n}};let h=p;function m(){return h}const g=e=>{const{data:t,path:n,errorMaps:s,issueData:r}=e,a=[...n,...r.path||[]],i={...r,path:a};let o="";const c=s.filter((e=>!!e)).slice().reverse();for(const e of c)o=e(i,{data:t,defaultError:o}).message;return{...r,path:a,message:r.message||o}};function f(e,t){const n=g({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,m(),p].filter((e=>!!e))});e.common.issues.push(n)}class v{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const n=[];for(const s of t){if("aborted"===s.status)return y;"dirty"===s.status&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){const n=[];for(const e of t)n.push({key:await e.key,value:await e.value});return v.mergeObjectSync(e,n)}static mergeObjectSync(e,t){const n={};for(const s of t){const{key:t,value:r}=s;if("aborted"===t.status)return y;if("aborted"===r.status)return y;"dirty"===t.status&&e.dirty(),"dirty"===r.status&&e.dirty(),(void 0!==r.value||s.alwaysSet)&&(n[t.value]=r.value)}return{status:e.value,value:n}}}const y=Object.freeze({status:"aborted"}),b=e=>({status:"valid",value:e}),w=e=>"aborted"===e.status,_=e=>"dirty"===e.status,x=e=>"valid"===e.status,C=e=>void 0!==typeof Promise&&e instanceof Promise;var S;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:null==e?void 0:e.message}(S||(S={}));class I{constructor(e,t,n,s){this.parent=e,this.data=t,this._path=n,this._key=s}get path(){return this._path.concat(this._key)}}const T=(e,t)=>{if(x(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,error:new u(e.common.issues)}};function k(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:s,description:r}=e;if(t&&(n||s))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:r};return{errorMap:(e,t)=>"invalid_type"!==e.code?{message:t.defaultError}:void 0===t.data?{message:null!=s?s:t.defaultError}:{message:null!=n?n:t.defaultError},description:r}}class O{constructor(e){this.spa=this.safeParseAsync,this.superRefine=this._refinement,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.default=this.default.bind(this),this.describe=this.describe.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(e){return d(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:d(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new v,ctx:{common:e.parent.common,data:e.data,parsedType:d(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(C(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){var n;const s={common:{issues:[],async:null!==(n=null==t?void 0:t.async)&&void 0!==n&&n,contextualErrorMap:null==t?void 0:t.errorMap},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:d(e)},r=this._parseSync({data:e,path:s.path,parent:s});return T(s,r)}async parseAsync(e,t){const n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){const n={common:{issues:[],contextualErrorMap:null==t?void 0:t.errorMap,async:!0},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:d(e)},s=this._parse({data:e,path:[],parent:n}),r=await(C(s)?s:Promise.resolve(s));return T(n,r)}refine(e,t){const n=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement(((t,s)=>{const r=e(t),a=()=>s.addIssue({code:l.custom,...n(t)});return"undefined"!=typeof Promise&&r instanceof Promise?r.then((e=>!!e||(a(),!1))):!!r||(a(),!1)}))}refinement(e,t){return this._refinement(((n,s)=>!!e(n)||(s.addIssue("function"==typeof t?t(n,s):t),!1)))}_refinement(e){return new le({schema:this,typeName:be.ZodEffects,effect:{type:"refinement",refinement:e}})}optional(){return ue.create(this)}nullable(){return pe.create(this)}nullish(){return this.optional().nullable()}array(){return U.create(this)}promise(){return de.create(this)}or(e){return q.create([this,e])}and(e){return Q.create(this,e)}transform(e){return new le({schema:this,typeName:be.ZodEffects,effect:{type:"transform",transform:e}})}default(e){return new he({innerType:this,defaultValue:"function"==typeof e?e:()=>e,typeName:be.ZodDefault})}brand(){return new fe({typeName:be.ZodBranded,type:this,...k(void 0)})}describe(e){return new(0,this.constructor)({...this._def,description:e})}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const E=/^c[^\s-]{8,}$/i,P=/^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i,D=/^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;class N extends O{constructor(){super(...arguments),this._regex=(e,t,n)=>this.refinement((t=>e.test(t)),{validation:t,code:l.invalid_string,...S.errToObj(n)}),this.nonempty=e=>this.min(1,S.errToObj(e)),this.trim=()=>new N({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}_parse(e){if(this._getType(e)!==c.string){const t=this._getOrReturnCtx(e);return f(t,{code:l.invalid_type,expected:c.string,received:t.parsedType}),y}const t=new v;let n;for(const s of this._def.checks)if("min"===s.kind)e.data.length<s.value&&(n=this._getOrReturnCtx(e,n),f(n,{code:l.too_small,minimum:s.value,type:"string",inclusive:!0,message:s.message}),t.dirty());else if("max"===s.kind)e.data.length>s.value&&(n=this._getOrReturnCtx(e,n),f(n,{code:l.too_big,maximum:s.value,type:"string",inclusive:!0,message:s.message}),t.dirty());else if("email"===s.kind)D.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"email",code:l.invalid_string,message:s.message}),t.dirty());else if("uuid"===s.kind)P.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"uuid",code:l.invalid_string,message:s.message}),t.dirty());else if("cuid"===s.kind)E.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"cuid",code:l.invalid_string,message:s.message}),t.dirty());else if("url"===s.kind)try{new URL(e.data)}catch(r){n=this._getOrReturnCtx(e,n),f(n,{validation:"url",code:l.invalid_string,message:s.message}),t.dirty()}else if("regex"===s.kind){s.regex.lastIndex=0;s.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"regex",code:l.invalid_string,message:s.message}),t.dirty())}else"trim"===s.kind?e.data=e.data.trim():"startsWith"===s.kind?e.data.startsWith(s.value)||(n=this._getOrReturnCtx(e,n),f(n,{code:l.invalid_string,validation:{startsWith:s.value},message:s.message}),t.dirty()):"endsWith"===s.kind?e.data.endsWith(s.value)||(n=this._getOrReturnCtx(e,n),f(n,{code:l.invalid_string,validation:{endsWith:s.value},message:s.message}),t.dirty()):o.assertNever(s);return{status:t.value,value:e.data}}_addCheck(e){return new N({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...S.errToObj(e)})}url(e){return this._addCheck({kind:"url",...S.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...S.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...S.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...S.errToObj(t)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...S.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...S.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...S.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...S.errToObj(t)})}length(e,t){return this.min(e,t).max(e,t)}get isEmail(){return!!this._def.checks.find((e=>"email"===e.kind))}get isURL(){return!!this._def.checks.find((e=>"url"===e.kind))}get isUUID(){return!!this._def.checks.find((e=>"uuid"===e.kind))}get isCUID(){return!!this._def.checks.find((e=>"cuid"===e.kind))}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function j(e,t){const n=(e.toString().split(".")[1]||"").length,s=(t.toString().split(".")[1]||"").length,r=n>s?n:s;return parseInt(e.toFixed(r).replace(".",""))%parseInt(t.toFixed(r).replace(".",""))/Math.pow(10,r)}N.create=e=>new N({checks:[],typeName:be.ZodString,...k(e)});class R extends O{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._getType(e)!==c.number){const t=this._getOrReturnCtx(e);return f(t,{code:l.invalid_type,expected:c.number,received:t.parsedType}),y}let t;const n=new v;for(const s of this._def.checks)if("int"===s.kind)o.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),f(t,{code:l.invalid_type,expected:"integer",received:"float",message:s.message}),n.dirty());else if("min"===s.kind){(s.inclusive?e.data<s.value:e.data<=s.value)&&(t=this._getOrReturnCtx(e,t),f(t,{code:l.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,message:s.message}),n.dirty())}else if("max"===s.kind){(s.inclusive?e.data>s.value:e.data>=s.value)&&(t=this._getOrReturnCtx(e,t),f(t,{code:l.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,message:s.message}),n.dirty())}else"multipleOf"===s.kind?0!==j(e.data,s.value)&&(t=this._getOrReturnCtx(e,t),f(t,{code:l.not_multiple_of,multipleOf:s.value,message:s.message}),n.dirty()):o.assertNever(s);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,S.toString(t))}gt(e,t){return this.setLimit("min",e,!1,S.toString(t))}lte(e,t){return this.setLimit("max",e,!0,S.toString(t))}lt(e,t){return this.setLimit("max",e,!1,S.toString(t))}setLimit(e,t,n,s){return new R({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:S.toString(s)}]})}_addCheck(e){return new R({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:S.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:S.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:S.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:S.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:S.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:S.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find((e=>"int"===e.kind))}}R.create=e=>new R({checks:[],typeName:be.ZodNumber,...k(e)});class M extends O{_parse(e){if(this._getType(e)!==c.bigint){const t=this._getOrReturnCtx(e);return f(t,{code:l.invalid_type,expected:c.bigint,received:t.parsedType}),y}return b(e.data)}}M.create=e=>new M({typeName:be.ZodBigInt,...k(e)});class L extends O{_parse(e){if(this._getType(e)!==c.boolean){const t=this._getOrReturnCtx(e);return f(t,{code:l.invalid_type,expected:c.boolean,received:t.parsedType}),y}return b(e.data)}}L.create=e=>new L({typeName:be.ZodBoolean,...k(e)});class A extends O{_parse(e){if(this._getType(e)!==c.date){const t=this._getOrReturnCtx(e);return f(t,{code:l.invalid_type,expected:c.date,received:t.parsedType}),y}if(isNaN(e.data.getTime())){return f(this._getOrReturnCtx(e),{code:l.invalid_date}),y}const t=new v;let n;for(const s of this._def.checks)"min"===s.kind?e.data.getTime()<s.value&&(n=this._getOrReturnCtx(e,n),f(n,{code:l.too_small,message:s.message,inclusive:!0,minimum:s.value,type:"date"}),t.dirty()):"max"===s.kind?e.data.getTime()>s.value&&(n=this._getOrReturnCtx(e,n),f(n,{code:l.too_big,message:s.message,inclusive:!0,maximum:s.value,type:"date"}),t.dirty()):o.assertNever(s);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new A({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:S.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:S.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}A.create=e=>new A({checks:[],typeName:be.ZodDate,...k(e)});class Z extends O{_parse(e){if(this._getType(e)!==c.undefined){const t=this._getOrReturnCtx(e);return f(t,{code:l.invalid_type,expected:c.undefined,received:t.parsedType}),y}return b(e.data)}}Z.create=e=>new Z({typeName:be.ZodUndefined,...k(e)});class B extends O{_parse(e){if(this._getType(e)!==c.null){const t=this._getOrReturnCtx(e);return f(t,{code:l.invalid_type,expected:c.null,received:t.parsedType}),y}return b(e.data)}}B.create=e=>new B({typeName:be.ZodNull,...k(e)});class F extends O{constructor(){super(...arguments),this._any=!0}_parse(e){return b(e.data)}}F.create=e=>new F({typeName:be.ZodAny,...k(e)});class z extends O{constructor(){super(...arguments),this._unknown=!0}_parse(e){return b(e.data)}}z.create=e=>new z({typeName:be.ZodUnknown,...k(e)});class V extends O{_parse(e){const t=this._getOrReturnCtx(e);return f(t,{code:l.invalid_type,expected:c.never,received:t.parsedType}),y}}V.create=e=>new V({typeName:be.ZodNever,...k(e)});class $ extends O{_parse(e){if(this._getType(e)!==c.undefined){const t=this._getOrReturnCtx(e);return f(t,{code:l.invalid_type,expected:c.void,received:t.parsedType}),y}return b(e.data)}}$.create=e=>new $({typeName:be.ZodVoid,...k(e)});class U extends O{_parse(e){const{ctx:t,status:n}=this._processInputParams(e),s=this._def;if(t.parsedType!==c.array)return f(t,{code:l.invalid_type,expected:c.array,received:t.parsedType}),y;if(null!==s.minLength&&t.data.length<s.minLength.value&&(f(t,{code:l.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,message:s.minLength.message}),n.dirty()),null!==s.maxLength&&t.data.length>s.maxLength.value&&(f(t,{code:l.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,message:s.maxLength.message}),n.dirty()),t.common.async)return Promise.all(t.data.map(((e,n)=>s.type._parseAsync(new I(t,e,t.path,n))))).then((e=>v.mergeArray(n,e)));const r=t.data.map(((e,n)=>s.type._parseSync(new I(t,e,t.path,n))));return v.mergeArray(n,r)}get element(){return this._def.type}min(e,t){return new U({...this._def,minLength:{value:e,message:S.toString(t)}})}max(e,t){return new U({...this._def,maxLength:{value:e,message:S.toString(t)}})}length(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}var W;U.create=(e,t)=>new U({type:e,minLength:null,maxLength:null,typeName:be.ZodArray,...k(t)}),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(W||(W={}));const K=e=>t=>new J({...e,shape:()=>({...e.shape(),...t})});function H(e){if(e instanceof J){const t={};for(const n in e.shape){const s=e.shape[n];t[n]=ue.create(H(s))}return new J({...e._def,shape:()=>t})}return e instanceof U?U.create(H(e.element)):e instanceof ue?ue.create(H(e.unwrap())):e instanceof pe?pe.create(H(e.unwrap())):e instanceof Y?Y.create(e.items.map((e=>H(e)))):e}class J extends O{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=K(this._def),this.extend=K(this._def)}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=o.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==c.object){const t=this._getOrReturnCtx(e);return f(t,{code:l.invalid_type,expected:c.object,received:t.parsedType}),y}const{status:t,ctx:n}=this._processInputParams(e),{shape:s,keys:r}=this._getCached(),a=[];if(!(this._def.catchall instanceof V&&"strip"===this._def.unknownKeys))for(const e in n.data)r.includes(e)||a.push(e);const i=[];for(const e of r){const t=s[e],r=n.data[e];i.push({key:{status:"valid",value:e},value:t._parse(new I(n,r,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof V){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of a)i.push({key:{status:"valid",value:e},value:{status:"valid",value:n.data[e]}});else if("strict"===e)a.length>0&&(f(n,{code:l.unrecognized_keys,keys:a}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of a){const s=n.data[t];i.push({key:{status:"valid",value:t},value:e._parse(new I(n,s,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then((async()=>{const e=[];for(const t of i){const n=await t.key;e.push({key:n,value:await t.value,alwaysSet:t.alwaysSet})}return e})).then((e=>v.mergeObjectSync(t,e))):v.mergeObjectSync(t,i)}get shape(){return this._def.shape()}strict(e){return S.errToObj,new J({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,n)=>{var s,r,a,i;const o=null!==(a=null===(r=(s=this._def).errorMap)||void 0===r?void 0:r.call(s,t,n).message)&&void 0!==a?a:n.defaultError;return"unrecognized_keys"===t.code?{message:null!==(i=S.errToObj(e).message)&&void 0!==i?i:o}:{message:o}}}:{}})}strip(){return new J({...this._def,unknownKeys:"strip"})}passthrough(){return new J({...this._def,unknownKeys:"passthrough"})}setKey(e,t){return this.augment({[e]:t})}merge(e){return new J({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>W.mergeShapes(this._def.shape(),e._def.shape()),typeName:be.ZodObject})}catchall(e){return new J({...this._def,catchall:e})}pick(e){const t={};return o.objectKeys(e).map((e=>{this.shape[e]&&(t[e]=this.shape[e])})),new J({...this._def,shape:()=>t})}omit(e){const t={};return o.objectKeys(this.shape).map((n=>{-1===o.objectKeys(e).indexOf(n)&&(t[n]=this.shape[n])})),new J({...this._def,shape:()=>t})}deepPartial(){return H(this)}partial(e){const t={};if(e)return o.objectKeys(this.shape).map((n=>{-1===o.objectKeys(e).indexOf(n)?t[n]=this.shape[n]:t[n]=this.shape[n].optional()})),new J({...this._def,shape:()=>t});for(const e in this.shape){const n=this.shape[e];t[e]=n.optional()}return new J({...this._def,shape:()=>t})}required(){const e={};for(const t in this.shape){let n=this.shape[t];for(;n instanceof ue;)n=n._def.innerType;e[t]=n}return new J({...this._def,shape:()=>e})}keyof(){return ie(o.objectKeys(this.shape))}}J.create=(e,t)=>new J({shape:()=>e,unknownKeys:"strip",catchall:V.create(),typeName:be.ZodObject,...k(t)}),J.strictCreate=(e,t)=>new J({shape:()=>e,unknownKeys:"strict",catchall:V.create(),typeName:be.ZodObject,...k(t)}),J.lazycreate=(e,t)=>new J({shape:e,unknownKeys:"strip",catchall:V.create(),typeName:be.ZodObject,...k(t)});class q extends O{_parse(e){const{ctx:t}=this._processInputParams(e),n=this._def.options;if(t.common.async)return Promise.all(n.map((async e=>{const n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}}))).then((function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const n of e)if("dirty"===n.result.status)return t.common.issues.push(...n.ctx.common.issues),n.result;const n=e.map((e=>new u(e.ctx.common.issues)));return f(t,{code:l.invalid_union,unionErrors:n}),y}));{let e;const s=[];for(const r of n){const n={...t,common:{...t.common,issues:[]},parent:null},a=r._parseSync({data:t.data,path:t.path,parent:n});if("valid"===a.status)return a;"dirty"!==a.status||e||(e={result:a,ctx:n}),n.common.issues.length&&s.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const r=s.map((e=>new u(e)));return f(t,{code:l.invalid_union,unionErrors:r}),y}}get options(){return this._def.options}}q.create=(e,t)=>new q({options:e,typeName:be.ZodUnion,...k(t)});class G extends O{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==c.object)return f(t,{code:l.invalid_type,expected:c.object,received:t.parsedType}),y;const n=this.discriminator,s=t.data[n],r=this.options.get(s);return r?t.common.async?r._parseAsync({data:t.data,path:t.path,parent:t}):r._parseSync({data:t.data,path:t.path,parent:t}):(f(t,{code:l.invalid_union_discriminator,options:this.validDiscriminatorValues,path:[n]}),y)}get discriminator(){return this._def.discriminator}get validDiscriminatorValues(){return Array.from(this.options.keys())}get options(){return this._def.options}static create(e,t,n){const s=new Map;try{t.forEach((t=>{const n=t.shape[e].value;s.set(n,t)}))}catch(e){throw new Error("The discriminator value could not be extracted from all the provided schemas")}if(s.size!==t.length)throw new Error("Some of the discriminator values are not unique");return new G({typeName:be.ZodDiscriminatedUnion,discriminator:e,options:s,...k(n)})}}function X(e,t){const n=d(e),s=d(t);if(e===t)return{valid:!0,data:e};if(n===c.object&&s===c.object){const n=o.objectKeys(t),s=o.objectKeys(e).filter((e=>-1!==n.indexOf(e))),r={...e,...t};for(const n of s){const s=X(e[n],t[n]);if(!s.valid)return{valid:!1};r[n]=s.data}return{valid:!0,data:r}}if(n===c.array&&s===c.array){if(e.length!==t.length)return{valid:!1};const n=[];for(let s=0;s<e.length;s++){const r=X(e[s],t[s]);if(!r.valid)return{valid:!1};n.push(r.data)}return{valid:!0,data:n}}return n===c.date&&s===c.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class Q extends O{_parse(e){const{status:t,ctx:n}=this._processInputParams(e),s=(e,s)=>{if(w(e)||w(s))return y;const r=X(e.value,s.value);return r.valid?((_(e)||_(s))&&t.dirty(),{status:t.value,value:r.data}):(f(n,{code:l.invalid_intersection_types}),y)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then((([e,t])=>s(e,t))):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}Q.create=(e,t,n)=>new Q({left:e,right:t,typeName:be.ZodIntersection,...k(n)});class Y extends O{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==c.array)return f(n,{code:l.invalid_type,expected:c.array,received:n.parsedType}),y;if(n.data.length<this._def.items.length)return f(n,{code:l.too_small,minimum:this._def.items.length,inclusive:!0,type:"array"}),y;!this._def.rest&&n.data.length>this._def.items.length&&(f(n,{code:l.too_big,maximum:this._def.items.length,inclusive:!0,type:"array"}),t.dirty());const s=n.data.map(((e,t)=>{const s=this._def.items[t]||this._def.rest;return s?s._parse(new I(n,e,n.path,t)):null})).filter((e=>!!e));return n.common.async?Promise.all(s).then((e=>v.mergeArray(t,e))):v.mergeArray(t,s)}get items(){return this._def.items}rest(e){return new Y({...this._def,rest:e})}}Y.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Y({items:e,typeName:be.ZodTuple,rest:null,...k(t)})};class ee extends O{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==c.object)return f(n,{code:l.invalid_type,expected:c.object,received:n.parsedType}),y;const s=[],r=this._def.keyType,a=this._def.valueType;for(const e in n.data)s.push({key:r._parse(new I(n,e,n.path,e)),value:a._parse(new I(n,n.data[e],n.path,e))});return n.common.async?v.mergeObjectAsync(t,s):v.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,n){return new ee(t instanceof O?{keyType:e,valueType:t,typeName:be.ZodRecord,...k(n)}:{keyType:N.create(),valueType:e,typeName:be.ZodRecord,...k(t)})}}class te extends O{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==c.map)return f(n,{code:l.invalid_type,expected:c.map,received:n.parsedType}),y;const s=this._def.keyType,r=this._def.valueType,a=[...n.data.entries()].map((([e,t],a)=>({key:s._parse(new I(n,e,n.path,[a,"key"])),value:r._parse(new I(n,t,n.path,[a,"value"]))})));if(n.common.async){const e=new Map;return Promise.resolve().then((async()=>{for(const n of a){const s=await n.key,r=await n.value;if("aborted"===s.status||"aborted"===r.status)return y;"dirty"!==s.status&&"dirty"!==r.status||t.dirty(),e.set(s.value,r.value)}return{status:t.value,value:e}}))}{const e=new Map;for(const n of a){const s=n.key,r=n.value;if("aborted"===s.status||"aborted"===r.status)return y;"dirty"!==s.status&&"dirty"!==r.status||t.dirty(),e.set(s.value,r.value)}return{status:t.value,value:e}}}}te.create=(e,t,n)=>new te({valueType:t,keyType:e,typeName:be.ZodMap,...k(n)});class ne extends O{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==c.set)return f(n,{code:l.invalid_type,expected:c.set,received:n.parsedType}),y;const s=this._def;null!==s.minSize&&n.data.size<s.minSize.value&&(f(n,{code:l.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,message:s.minSize.message}),t.dirty()),null!==s.maxSize&&n.data.size>s.maxSize.value&&(f(n,{code:l.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,message:s.maxSize.message}),t.dirty());const r=this._def.valueType;function a(e){const n=new Set;for(const s of e){if("aborted"===s.status)return y;"dirty"===s.status&&t.dirty(),n.add(s.value)}return{status:t.value,value:n}}const i=[...n.data.values()].map(((e,t)=>r._parse(new I(n,e,n.path,t))));return n.common.async?Promise.all(i).then((e=>a(e))):a(i)}min(e,t){return new ne({...this._def,minSize:{value:e,message:S.toString(t)}})}max(e,t){return new ne({...this._def,maxSize:{value:e,message:S.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ne.create=(e,t)=>new ne({valueType:e,minSize:null,maxSize:null,typeName:be.ZodSet,...k(t)});class se extends O{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==c.function)return f(t,{code:l.invalid_type,expected:c.function,received:t.parsedType}),y;function n(e,n){return g({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,m(),p].filter((e=>!!e)),issueData:{code:l.invalid_arguments,argumentsError:n}})}function s(e,n){return g({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,m(),p].filter((e=>!!e)),issueData:{code:l.invalid_return_type,returnTypeError:n}})}const r={errorMap:t.common.contextualErrorMap},a=t.data;return this._def.returns instanceof de?b((async(...e)=>{const t=new u([]),i=await this._def.args.parseAsync(e,r).catch((s=>{throw t.addIssue(n(e,s)),t})),o=await a(...i);return await this._def.returns._def.type.parseAsync(o,r).catch((e=>{throw t.addIssue(s(o,e)),t}))})):b(((...e)=>{const t=this._def.args.safeParse(e,r);if(!t.success)throw new u([n(e,t.error)]);const i=a(...t.data),o=this._def.returns.safeParse(i,r);if(!o.success)throw new u([s(i,o.error)]);return o.data}))}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new se({...this._def,args:Y.create(e).rest(z.create())})}returns(e){return new se({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new se({args:e||Y.create([]).rest(z.create()),returns:t||z.create(),typeName:be.ZodFunction,...k(n)})}}class re extends O{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}re.create=(e,t)=>new re({getter:e,typeName:be.ZodLazy,...k(t)});class ae extends O{_parse(e){if(e.data!==this._def.value){return f(this._getOrReturnCtx(e),{code:l.invalid_literal,expected:this._def.value}),y}return{status:"valid",value:e.data}}get value(){return this._def.value}}function ie(e,t){return new oe({values:e,typeName:be.ZodEnum,...k(t)})}ae.create=(e,t)=>new ae({value:e,typeName:be.ZodLiteral,...k(t)});class oe extends O{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),n=this._def.values;return f(t,{expected:o.joinValues(n),received:t.parsedType,code:l.invalid_type}),y}if(-1===this._def.values.indexOf(e.data)){const t=this._getOrReturnCtx(e),n=this._def.values;return f(t,{received:t.data,code:l.invalid_enum_value,options:n}),y}return b(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}}oe.create=ie;class ce extends O{_parse(e){const t=o.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==c.string&&n.parsedType!==c.number){const e=o.objectValues(t);return f(n,{expected:o.joinValues(e),received:n.parsedType,code:l.invalid_type}),y}if(-1===t.indexOf(e.data)){const e=o.objectValues(t);return f(n,{received:n.data,code:l.invalid_enum_value,options:e}),y}return b(e.data)}get enum(){return this._def.values}}ce.create=(e,t)=>new ce({values:e,typeName:be.ZodNativeEnum,...k(t)});class de extends O{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==c.promise&&!1===t.common.async)return f(t,{code:l.invalid_type,expected:c.promise,received:t.parsedType}),y;const n=t.parsedType===c.promise?t.data:Promise.resolve(t.data);return b(n.then((e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap}))))}}de.create=(e,t)=>new de({type:e,typeName:be.ZodPromise,...k(t)});class le extends O{innerType(){return this._def.schema}_parse(e){const{status:t,ctx:n}=this._processInputParams(e),s=this._def.effect||null;if("preprocess"===s.type){const e=s.transform(n.data);return n.common.async?Promise.resolve(e).then((e=>this._def.schema._parseAsync({data:e,path:n.path,parent:n}))):this._def.schema._parseSync({data:e,path:n.path,parent:n})}const r={addIssue:e=>{f(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(r.addIssue=r.addIssue.bind(r),"refinement"===s.type){const e=e=>{const t=s.refinement(e,r);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===n.common.async){const s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return"aborted"===s.status?y:("dirty"===s.status&&t.dirty(),e(s.value),{status:t.value,value:s.value})}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then((n=>"aborted"===n.status?y:("dirty"===n.status&&t.dirty(),e(n.value).then((()=>({status:t.value,value:n.value}))))))}if("transform"===s.type){if(!1===n.common.async){const e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!x(e))return e;const a=s.transform(e.value,r);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:a}}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then((e=>x(e)?Promise.resolve(s.transform(e.value,r)).then((e=>({status:t.value,value:e}))):e))}o.assertNever(s)}}le.create=(e,t,n)=>new le({schema:e,typeName:be.ZodEffects,effect:t,...k(n)}),le.createWithPreprocess=(e,t,n)=>new le({schema:t,effect:{type:"preprocess",transform:e},typeName:be.ZodEffects,...k(n)});class ue extends O{_parse(e){return this._getType(e)===c.undefined?b(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ue.create=(e,t)=>new ue({innerType:e,typeName:be.ZodOptional,...k(t)});class pe extends O{_parse(e){return this._getType(e)===c.null?b(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}pe.create=(e,t)=>new pe({innerType:e,typeName:be.ZodNullable,...k(t)});class he extends O{_parse(e){const{ctx:t}=this._processInputParams(e);let n=t.data;return t.parsedType===c.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}he.create=(e,t)=>new ue({innerType:e,typeName:be.ZodOptional,...k(t)});class me extends O{_parse(e){if(this._getType(e)!==c.nan){const t=this._getOrReturnCtx(e);return f(t,{code:l.invalid_type,expected:c.nan,received:t.parsedType}),y}return{status:"valid",value:e.data}}}me.create=e=>new me({typeName:be.ZodNaN,...k(e)});const ge=Symbol("zod_brand");class fe extends O{_parse(e){const{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}}const ve=(e,t={},n)=>e?F.create().superRefine(((s,r)=>{if(!e(s)){const e="function"==typeof t?t(s):t,a="string"==typeof e?{message:e}:e;r.addIssue({code:"custom",...a,fatal:n})}})):F.create(),ye={object:J.lazycreate};var be;!function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded"}(be||(be={}));const we=N.create,_e=R.create,xe=me.create,Ce=M.create,Se=L.create,Ie=A.create,Te=Z.create,ke=B.create,Oe=F.create,Ee=z.create,Pe=V.create,De=$.create,Ne=U.create,je=J.create,Re=J.strictCreate,Me=q.create,Le=G.create,Ae=Q.create,Ze=Y.create,Be=ee.create,Fe=te.create,ze=ne.create,Ve=se.create,$e=re.create,Ue=ae.create,We=oe.create,Ke=ce.create,He=de.create,Je=le.create,qe=ue.create,Ge=pe.create,Xe=le.createWithPreprocess,Qe=y;var Ye=Object.freeze({__proto__:null,getParsedType:d,ZodParsedType:c,defaultErrorMap:p,setErrorMap:function(e){h=e},getErrorMap:m,makeIssue:g,EMPTY_PATH:[],addIssueToContext:f,ParseStatus:v,INVALID:y,DIRTY:e=>({status:"dirty",value:e}),OK:b,isAborted:w,isDirty:_,isValid:x,isAsync:C,ZodType:O,ZodString:N,ZodNumber:R,ZodBigInt:M,ZodBoolean:L,ZodDate:A,ZodUndefined:Z,ZodNull:B,ZodAny:F,ZodUnknown:z,ZodNever:V,ZodVoid:$,ZodArray:U,get objectUtil(){return W},ZodObject:J,ZodUnion:q,ZodDiscriminatedUnion:G,ZodIntersection:Q,ZodTuple:Y,ZodRecord:ee,ZodMap:te,ZodSet:ne,ZodFunction:se,ZodLazy:re,ZodLiteral:ae,ZodEnum:oe,ZodNativeEnum:ce,ZodPromise:de,ZodEffects:le,ZodTransformer:le,ZodOptional:ue,ZodNullable:pe,ZodDefault:he,ZodNaN:me,BRAND:ge,ZodBranded:fe,custom:ve,Schema:O,ZodSchema:O,late:ye,get ZodFirstPartyTypeKind(){return be},any:Oe,array:Ne,bigint:Ce,boolean:Se,date:Ie,discriminatedUnion:Le,effect:Je,enum:We,function:Ve,instanceof:(e,t={message:`Input not instance of ${e.name}`})=>ve((t=>t instanceof e),t,!0),intersection:Ae,lazy:$e,literal:Ue,map:Fe,nan:xe,nativeEnum:Ke,never:Pe,null:ke,nullable:Ge,number:_e,object:je,oboolean:()=>Se().optional(),onumber:()=>_e().optional(),optional:qe,ostring:()=>we().optional(),preprocess:Xe,promise:He,record:Be,set:ze,strictObject:Re,string:we,transformer:Je,tuple:Ze,undefined:Te,union:Me,unknown:Ee,void:De,NEVER:Qe,ZodIssueCode:l,quotelessJson:e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),ZodError:u});const et=e("command parser");function tt(e,t){const n=t.safeParse(e);if(n.success)return n.data;et(`Command ${JSON.stringify(e)} parse failed: ${JSON.stringify(n)}.`);const s=n.error.errors.map((e=>`${e.message} in ${e.path.map((e=>JSON.stringify(e))).join("/")}.`)).join(" ");throw new r(s)}var nt,st,rt,at,it,ot;!function(e){e.RemoteReferenceSchema=Ye.object({handle:Ye.string().min(1)});const t=Ye.object({type:Ye.literal("undefined")}),n=Ye.object({type:Ye.literal("null")}),s=Ye.object({type:Ye.literal("string"),value:Ye.string()}),r=Ye.enum(["NaN","-0","Infinity","+Infinity","-Infinity"]),a=Ye.object({type:Ye.literal("number"),value:Ye.union([r,Ye.number()])}),i=Ye.object({type:Ye.literal("boolean"),value:Ye.boolean()}),o=Ye.object({type:Ye.literal("bigint"),value:Ye.string()}),c=Ye.union([t,n,s,a,i,o]);e.LocalValueSchema=Ye.lazy((()=>Ye.union([c,l,u,h,m,g,f])));const d=Ye.array(e.LocalValueSchema),l=Ye.lazy((()=>Ye.object({type:Ye.literal("array"),value:d}))),u=Ye.object({type:Ye.literal("date"),value:Ye.string().min(1)}),p=Ye.lazy((()=>Ye.tuple([Ye.union([Ye.string(),e.LocalValueSchema]),e.LocalValueSchema]))),h=Ye.object({type:Ye.literal("map"),value:Ye.array(p)}),m=Ye.object({type:Ye.literal("object"),value:Ye.array(p)}),g=Ye.lazy((()=>Ye.object({type:Ye.literal("regexp"),value:Ye.object({pattern:Ye.string(),flags:Ye.string().optional()})}))),f=Ye.lazy((()=>Ye.object({type:Ye.literal("set"),value:d})));e.BrowsingContextSchema=Ye.string()}(nt||(nt={})),function(e){const t=Ye.enum(["window","dedicated-worker","shared-worker","service-worker","worker","paint-worklet","audio-worklet","worklet"]),n=Ye.object({context:nt.BrowsingContextSchema.optional(),type:t.optional()});e.parseGetRealmsParams=function(e){return tt(e,n)};const s=Ye.object({context:nt.BrowsingContextSchema,sandbox:Ye.string().min(1).optional()}),r=Ye.object({realm:Ye.string().min(1)}),a=Ye.union([s,r]),i=Ye.enum(["root","none"]),o=Ye.object({expression:Ye.string(),awaitPromise:Ye.boolean(),target:a,resultOwnership:i.optional()});e.parseEvaluateParams=function(e){return tt(e,o)};const c=Ye.union([nt.RemoteReferenceSchema,nt.LocalValueSchema]),d=Ye.object({functionDeclaration:Ye.string(),target:a,arguments:Ye.array(c).optional(),this:c.optional(),awaitPromise:Ye.boolean(),resultOwnership:i.optional()});e.parseCallFunctionParams=function(e){return tt(e,d)}}(st||(st={})),function(e){const t=Ye.object({maxDepth:Ye.number().int().nonnegative().max(9007199254740991).optional(),root:nt.BrowsingContextSchema.optional()});e.parseGetTreeParams=function(e){return tt(e,t)};const n=Ye.enum(["none","interactive","complete"]),s=Ye.object({context:nt.BrowsingContextSchema,url:Ye.string().url(),wait:n.optional()});e.parseNavigateParams=function(e){return tt(e,s)};const r=Ye.object({type:Ye.enum(["tab","window"])});e.parseCreateParams=function(e){return tt(e,r)};const a=Ye.object({context:nt.BrowsingContextSchema});e.parseCloseParams=function(e){return tt(e,a)};class o extends i{static method="browsingContext.load";constructor(e){super(o.method,e)}}e.LoadEvent=o;class c extends i{static method="browsingContext.domContentLoaded";constructor(e){super(c.method,e)}}e.DomContentLoadedEvent=c;class d extends i{static method="browsingContext.contextCreated";constructor(e){super(d.method,e)}}e.ContextCreatedEvent=d;class l extends i{static method="browsingContext.contextDestroyed";constructor(e){super(l.method,e)}}e.ContextDestroyedEvent=l,function(e){const t=Ye.object({context:nt.BrowsingContextSchema,selector:Ye.string()});e.parseFindElementParams=function(e){return tt(e,t)}}(e.PROTO||(e.PROTO={})),e.EventNames=[o.method,c.method,d.method,l.method]}(rt||(rt={})),function(e){class t extends i{static method="log.entryAdded";constructor(e){super(t.method,e)}}e.LogEntryAddedEvent=t,e.EventNames=[t.method]}(at||(at={})),function(e){let t;!function(e){const t=Ye.object({cdpMethod:Ye.string(),cdpParams:Ye.object({}).passthrough(),cdpSession:Ye.string().optional()});e.parseSendCommandParams=function(e){return tt(e,t)};const n=Ye.object({context:nt.BrowsingContextSchema});e.parseGetSessionParams=function(e){return tt(e,n)};class s extends i{static method="PROTO.cdp.eventReceived";constructor(e){super(s.method,e)}}e.EventReceivedEvent=s}(t=e.PROTO||(e.PROTO={})),e.EventNames=[t.EventReceivedEvent.method]}(it||(it={})),function(e){const t=Ye.enum([...rt.EventNames,...at.EventNames,...it.EventNames]),n=Ye.object({events:Ye.array(t),contexts:Ye.array(nt.BrowsingContextSchema).optional()});e.parseSubscribeParams=function(e){return tt(e,n)}}(ot||(ot={}));class ct{#e=()=>{};#t=()=>{};#n;#s=!1;get isFinished(){return this.#s}constructor(){this.#n=new Promise(((e,t)=>{this.#e=e,this.#t=t}))}then(e,t){return this.#n.then(e,t)}catch(e){return this.#n.catch(e)}resolve(e){this.#s=!0,this.#e(e)}reject(e){this.#s=!0,this.#t(e)}finally(e){return this.#n.finally(e)}[Symbol.toStringTag]="Promise"}const dt=["%s","%d","%i","%f","%o","%O","%c"];function lt(e){return dt.some((t=>e.includes(t)))}function ut(e){if(!["array","bigint","date","number","object","string"].includes(e.type))return pt(e);if("bigint"===e.type)return e.value.toString()+"n";if("number"===e.type)return e.value.toString();if(["date","string"].includes(e.type))return JSON.stringify(e.value);if("object"===e.type)return"{"+e.value.map((e=>`${JSON.stringify(e[0])}:${ut(e[1])}`)).join(",")+"}";if("array"===e.type)return"["+e.value.map((e=>ut(e))).join(",")+"]";throw Error("Invalid value type: "+e.toString())}function pt(e){if(!e.hasOwnProperty("value"))return e.type;switch(e.type){case"string":case"number":case"boolean":case"bigint":return e.value;case"regexp":return`/${e.value.pattern}/${e.value.flags}`;case"date":return new Date(e.value).toString();case"object":return`Object(${e.value.length})`;case"array":return`Array(${e.value.length})`;case"map":return`Map(${e.value.length})`;case"set":return`Set(${e.value.length})`;case"node":return"node";default:return e.type}}function ht(e,t){return 0==e.length?"":"string"===e[0].type&<(e[0].value.toString())&&t?function(e){let t="";const n=e[0].value.toString(),s=e.slice(1,void 0),r=n.split(new RegExp(dt.map((e=>"("+e+")")).join("|"),"g"));for(const n of r)if(void 0!==n&&""!=n)if(lt(n)){const r=s.shift();if(void 0===r)throw new Error('Less value is provided: "'+ht(e,!1)+'"');"%s"===n?t+=pt(r):"%d"===n||"%i"===n?["bigint","number","string"].includes(r.type)?t+=parseInt(r.value.toString(),10):t+="NaN":"%f"===n?["bigint","number","string"].includes(r.type)?t+=parseFloat(r.value.toString()):t+="NaN":t+=ut(r)}else t+=n;if(s.length>0)throw new Error('More value is provided: "'+ht(e,!1)+'"');return t}(e):e.map((e=>pt(e))).join(" ")}class mt{static#r=0;static#a=1;static async serializeCdpObject(e,t,n){const s=await n.cdpClient.Runtime.callFunctionOn({functionDeclaration:String((e=>e)),awaitPromise:!1,arguments:[e],generateWebDriverValue:!0,executionContextId:n.executionContextId});return await this.#i(s,n,t)}static async stringifyObject(e,t){return(await t.cdpClient.Runtime.callFunctionOn({functionDeclaration:String((function(e){return String(e)})),awaitPromise:!1,arguments:[e],returnByValue:!0,executionContextId:t.executionContextId})).result.value}static async callFunction(e,t,n,s,r,a){const i=`(...args)=>{ return _callFunction((\n${t}\n), args);\n function _callFunction(f, args) {\n const deserializedThis = args.shift();\n const deserializedArgs = args;\n return f.apply(deserializedThis, deserializedArgs);\n }}`,o=[await this.#o(n,e)];o.push(...await Promise.all(s.map((async t=>await this.#o(t,e)))));const c=await e.cdpClient.Runtime.callFunctionOn({functionDeclaration:i,awaitPromise:r,arguments:o,generateWebDriverValue:!0,executionContextId:e.executionContextId});return c.exceptionDetails?{exceptionDetails:await this.#c(c.exceptionDetails,this.#a,a,e),realm:e.realmId}:{result:await mt.#i(c,e,a),realm:e.realmId}}static async#c(e,t,n,s){const r=e.stackTrace?.callFrames.map((e=>({url:e.url,functionName:e.functionName,lineNumber:e.lineNumber-t,columnNumber:e.columnNumber}))),a=await this.serializeCdpObject(e.exception,n,s),i=await this.stringifyObject(e.exception,s);return{exception:a,columnNumber:e.columnNumber,lineNumber:e.lineNumber-t,stackTrace:{callFrames:r||[]},text:i||e.text}}static async#i(e,t,n){const s=e.result.webDriverValue;if(!e.result.objectId)return s;const r=e.result.objectId,a=s;return"root"===n?a.handle=r:await t.cdpClient.Runtime.releaseObject({objectId:r}),a}static async scriptEvaluate(e,t,n,s){let r=await e.cdpClient.Runtime.evaluate({contextId:e.executionContextId,expression:t,awaitPromise:n,generateWebDriverValue:!0});return r.exceptionDetails?{result:{exceptionDetails:await this.#c(r.exceptionDetails,this.#r,s,e),realm:e.realmId}}:{result:{result:await mt.#i(r,e,s),realm:e.realmId}}}static async#o(e,t){if("handle"in e)return{objectId:e.handle};switch(e.type){case"undefined":return{unserializableValue:"undefined"};case"null":return{unserializableValue:"null"};case"string":return{value:e.value};case"number":return"NaN"===e.value?{unserializableValue:"NaN"}:"-0"===e.value?{unserializableValue:"-0"}:"+Infinity"===e.value?{unserializableValue:"+Infinity"}:"Infinity"===e.value?{unserializableValue:"Infinity"}:"-Infinity"===e.value?{unserializableValue:"-Infinity"}:{value:e.value};case"boolean":return{value:!!e.value};case"bigint":return{unserializableValue:`BigInt(${JSON.stringify(e.value)})`};case"date":return{unserializableValue:`new Date(Date.parse(${JSON.stringify(e.value)}))`};case"regexp":return{unserializableValue:`new RegExp(${JSON.stringify(e.value.pattern)}, ${JSON.stringify(e.value.flags)})`};case"map":{const n=await this.#d(e.value,t);return{objectId:(await t.cdpClient.Runtime.callFunctionOn({functionDeclaration:String((function(...e){const t=new Map;for(let n=0;n<e.length;n+=2)t.set(e[n],e[n+1]);return t})),awaitPromise:!1,arguments:n,returnByValue:!1,executionContextId:t.executionContextId})).result.objectId}}case"object":{const n=await this.#d(e.value,t);return{objectId:(await t.cdpClient.Runtime.callFunctionOn({functionDeclaration:String((function(...e){const t={};for(let n=0;n<e.length;n+=2){t[e[n]]=e[n+1]}return t})),awaitPromise:!1,arguments:n,returnByValue:!1,executionContextId:t.executionContextId})).result.objectId}}case"array":{const n=await mt.#l(e.value,t);return{objectId:(await t.cdpClient.Runtime.callFunctionOn({functionDeclaration:String((function(...e){return e})),awaitPromise:!1,arguments:n,returnByValue:!1,executionContextId:t.executionContextId})).result.objectId}}case"set":{const n=await this.#l(e.value,t);return{objectId:(await t.cdpClient.Runtime.callFunctionOn({functionDeclaration:String((function(...e){return new Set(e)})),awaitPromise:!1,arguments:n,returnByValue:!1,executionContextId:t.executionContextId})).result.objectId}}default:throw new Error(`Value ${JSON.stringify(e)} is not deserializable.`)}}static async#d(e,t){const n=[];for(let s of e){const e=s[0],r=s[1];let a,i;a="string"==typeof e?{value:e}:await this.#o(e,t),i=await this.#o(r,t),n.push(a),n.push(i)}return n}static async#l(e,t){const n=[];for(let s of e)n.push(await this.#o(s,t));return n}}class gt{static#u=new Map;static getTopLevelContexts(){return Array.from(gt.#u.values()).filter((e=>null===e.parentId))}static removeContext(e){gt.#u.delete(e)}static addContext(e){gt.#u.set(e.contextId,e),null!==e.parentId&>.getKnownContext(e.parentId).addChild(e)}static hasKnownContext(e){return gt.#u.has(e)}static findContext(e){return gt.#u.get(e)}static getKnownContext(e){const t=gt.findContext(e);if(void 0===t)throw new a(`Context ${e} not found`);return t}}var ft;!function(e){e.window="window"}(ft||(ft={}));class vt{static#p=new Map;static create(e,t,n,s,r,a,i,o){const c=new vt(e,t,n,s,r,a,i,o);return vt.#p.set(c.realmId,c),c}static findRealms(e={}){return Array.from(vt.#p.values()).filter((t=>(void 0===e.realmId||e.realmId===t.realmId)&&((void 0===e.browsingContextId||e.browsingContextId===t.browsingContextId)&&((void 0===e.executionContextId||e.executionContextId===t.executionContextId)&&((void 0===e.type||e.type===t.type)&&((void 0===e.sandbox||e.sandbox===t.#h)&&(void 0===e.cdpSessionId||e.cdpSessionId===t.#m)))))))}static getRealm(e){const t=vt.findRealms(e);if(t.length>1)throw Error(`Multiple realms found. Filter: ${JSON.stringify(e)}.`);if(t.length<1)throw new a(`Realm ${JSON.stringify(e)} not found`);return t[0]}static clearBrowsingContext(e){vt.findRealms({browsingContextId:e}).map((e=>e.delete()))}delete(){vt.#p.delete(this.realmId)}#g;#f;#v;#y;#b;#h;#m;#w;constructor(e,t,n,s,r,a,i,o){this.#g=e,this.#f=t,this.#v=n,this.#h=a,this.#y=s,this.#b=r,this.#m=i,this.#w=o}toBiDi(){return{realm:this.realmId,origin:this.origin,type:this.type,context:this.browsingContextId,...void 0!==this.#h?{sandbox:this.#h}:{}}}get realmId(){return this.#g}get browsingContextId(){return this.#f}get executionContextId(){return this.#v}get origin(){return this.#y}get type(){return this.#b}get cdpClient(){return this.#w}async callFunction(e,t,n,s,r){const a=gt.getKnownContext(this.browsingContextId);return await a.awaitUnblocked(),{result:await mt.callFunction(this,e,t,n,s,r)}}async scriptEvaluate(e,t,n){const s=gt.getKnownContext(this.browsingContextId);return await s.awaitUnblocked(),mt.scriptEvaluate(this,e,t,n)}async serializeCdpObject(e,t){return await mt.serializeCdpObject(e,t,this)}async stringifyObject(e,t){return mt.stringifyObject(e,this)}}class yt{#_;#w;#x;#m;constructor(e,t,n,s){this.#m=n,this.#x=s,this.#w=t,this.#_=e}static create(e,t,n,s){const r=new yt(e,t,n,s);return r.#C(),r}#C(){this.#S()}#S(){this.#I()}#I(){this.#w.Runtime.on("consoleAPICalled",(async e=>{const t=vt.getRealm({cdpSessionId:this.#m,executionContextId:e.executionContextId}),n=await Promise.all(e.args.map((async e=>t.serializeCdpObject(e,"none"))));await this.#x.sendMessage(new at.LogEntryAddedEvent({level:yt.#T(e.type),source:{realm:e.executionContextId.toString(),context:this.#_},text:ht(n,!0),timestamp:Math.round(e.timestamp),stackTrace:yt.#k(e.stackTrace),type:"console",method:"warning"===e.type?"warn":e.type,args:n}))})),this.#w.Runtime.on("exceptionThrown",(async e=>{const t=(()=>{if(void 0!==e.exceptionDetails.executionContextId)return vt.getRealm({cdpSessionId:this.#m,executionContextId:e.exceptionDetails.executionContextId})})(),n=await(async()=>e.exceptionDetails.exception?void 0===t?JSON.stringify(e.exceptionDetails.exception):await t.stringifyObject(e.exceptionDetails.exception,t):e.exceptionDetails.text)();await this.#x.sendMessage(new at.LogEntryAddedEvent({level:"error",source:{realm:t?.realmId??"UNKNOWN",context:t?.browsingContextId??"UNKNOWN"},text:n,timestamp:Math.round(e.timestamp),stackTrace:yt.#k(e.exceptionDetails.stackTrace),type:"javascript"}))}))}static#T(e){return["assert","error"].includes(e)?"error":["debug","trace"].includes(e)?"debug":["warn","warning"].includes(e)?"warning":"info"}static#k(e){const t=e?.callFrames.map((e=>({columnNumber:e.columnNumber,functionName:e.functionName,lineNumber:e.lineNumber,url:e.url})));return t?{callFrames:t}:void 0}}var bt=rt.LoadEvent;class wt{#O={documentInitialized:new ct,targetUnblocked:new ct,Page:{navigatedWithinDocument:new ct,lifecycleEvent:{DOMContentLoaded:new ct,load:new ct}}};#_;#E;#P="about:blank";#D=null;#m;#w;#x;#N;#j=new Map;#R;get#M(){if(void 0===this.#R)throw new Error(`No default realm for browsing context ${this.#_}`);return this.#R}constructor(e,t,n,s,r,a){this.#_=e,this.#E=t,this.#w=n,this.#N=a,this.#m=r,this.#x=s,this.#L(),gt.addContext(this)}static async createFrameContext(e,t,n,s,r,a){const i=new wt(e,t,n,s,r,a);i.#O.targetUnblocked.resolve(),await a.sendEvent(new rt.ContextCreatedEvent(i.serializeToBidiValue()),i.contextId)}static async createTargetContext(e,t,n,s,r,a){const i=new wt(e,t,n,s,r,a);i.#A(),await a.sendEvent(new rt.ContextCreatedEvent(i.serializeToBidiValue()),i.contextId)}convertFrameToTargetContext(e,t){this.#Z(e,t),this.#A()}async delete(){if(await this.#B(),null!==this.parentId){gt.getKnownContext(this.parentId).#j.delete(this.contextId)}await this.#N.sendEvent(new rt.ContextDestroyedEvent(this.serializeToBidiValue()),this.contextId),gt.removeContext(this.contextId)}async#B(){await Promise.all(this.children.map((e=>e.delete())))}#Z(e,t){this.#O.targetUnblocked.isFinished||this.#O.targetUnblocked.reject("OOPiF"),this.#O.targetUnblocked=new ct,this.#w=e,this.#m=t,this.#L()}async#A(){yt.create(this.#_,this.#w,this.#m,this.#x),await this.#w.Runtime.enable(),await this.#w.Page.enable(),await this.#w.Page.setLifecycleEventsEnabled({enabled:!0}),await this.#w.Target.setAutoAttach({autoAttach:!0,waitForDebuggerOnStart:!0,flatten:!0}),await this.#w.Runtime.runIfWaitingForDebugger(),this.#O.targetUnblocked.resolve()}get contextId(){return this.#_}get parentId(){return this.#E}get cdpSessionId(){return this.#m}get children(){return Array.from(this.#j.values())}get url(){return this.#P}addChild(e){this.#j.set(e.contextId,e)}async awaitLoaded(){await this.#O.Page.lifecycleEvent.load}async awaitUnblocked(){await this.#O.targetUnblocked}serializeToBidiValue(e=0,t=!0){return{context:this.#_,url:this.url,children:e>0?this.children.map((t=>t.serializeToBidiValue(e-1,!1))):null,...t?{parent:this.#E}:{}}}#L(){this.#w.Target.on("targetInfoChanged",(e=>{this.contextId===e.targetInfo.targetId&&(this.#P=e.targetInfo.url)})),this.#w.Page.on("frameNavigated",(async e=>{this.contextId===e.frame.id&&(this.#P=e.frame.url+(e.frame.urlFragment??""),await this.#B(),vt.clearBrowsingContext(this.contextId))})),this.#w.Page.on("navigatedWithinDocument",(e=>{this.contextId===e.frameId&&(this.#P=e.url,this.#O.Page.navigatedWithinDocument.resolve(e))})),this.#w.Page.on("lifecycleEvent",(async e=>{if(this.contextId===e.frameId)if("init"===e.name&&(this.#F(e.loaderId),this.#O.documentInitialized.resolve()),"commit"!==e.name){if(e.loaderId===this.#D)switch(e.name){case"DOMContentLoaded":this.#O.Page.lifecycleEvent.DOMContentLoaded.resolve(e),await this.#N.sendEvent(new rt.DomContentLoadedEvent({context:this.contextId,navigation:this.#D,url:this.#P}),this.contextId);break;case"load":this.#O.Page.lifecycleEvent.load.resolve(e),await this.#N.sendEvent(new bt({context:this.contextId,navigation:this.#D,url:this.#P}),this.contextId)}}else this.#D=e.loaderId})),this.#w.Runtime.on("executionContextCreated",(e=>{if(e.context.auxData.frameId!==this.contextId)return;if(!["default","isolated"].includes(e.context.auxData.type))return;const t=vt.create(e.context.uniqueId,this.contextId,e.context.id,this.#z(e),ft.window,"isolated"===e.context.auxData.type?e.context.name:void 0,this.#m,this.#w);e.context.auxData.isDefault&&(this.#R=t)})),this.#w.Runtime.on("executionContextDestroyed",(e=>{vt.findRealms({cdpSessionId:this.#m,executionContextId:e.executionContextId}).map((e=>e.delete()))}))}#z(e){return"isolated"===e.context.auxData.type?this.#M.origin:["://",""].includes(e.context.origin)?"null":e.context.origin}#F(e){this.#D!==e&&(this.#O.documentInitialized.isFinished||this.#O.documentInitialized.reject("Document changed"),this.#O.documentInitialized=new ct,this.#O.Page.navigatedWithinDocument.isFinished||this.#O.Page.navigatedWithinDocument.reject("Document changed"),this.#O.Page.navigatedWithinDocument=new ct,this.#O.Page.lifecycleEvent.DOMContentLoaded.isFinished||this.#O.Page.lifecycleEvent.DOMContentLoaded.reject("Document changed"),this.#O.Page.lifecycleEvent.DOMContentLoaded=new ct,this.#O.Page.lifecycleEvent.load.isFinished||this.#O.Page.lifecycleEvent.load.reject("Document changed"),this.#O.Page.lifecycleEvent.load=new ct,this.#D=e)}async navigate(e,t){await this.#O.targetUnblocked;const s=await this.#w.Page.navigate({url:e,frameId:this.contextId});if(s.errorText)throw new n(s.errorText);switch(void 0!==s.loaderId&&s.loaderId!==this.#D&&this.#F(s.loaderId),t){case"none":break;case"interactive":void 0===s.loaderId?await this.#O.Page.navigatedWithinDocument:await this.#O.Page.lifecycleEvent.DOMContentLoaded;break;case"complete":void 0===s.loaderId?await this.#O.Page.navigatedWithinDocument:await this.#O.Page.lifecycleEvent.load;break;default:throw new Error(`Not implemented wait '${t}'`)}return{result:{navigation:s.loaderId||null,url:e}}}async findElement(e){await this.#O.targetUnblocked;const t=String((e=>document.querySelector(e))),n=[{type:"string",value:e}];return await this.#M.callFunction(t,{type:"undefined"},n,!0,"root")}async getOrCreateSandbox(e){if(void 0===e)return this.#M;let t=vt.findRealms({browsingContextId:this.contextId,sandbox:e});if(0==t.length&&(await this.#w.Page.createIsolatedWorld({frameId:this.contextId,worldName:e}),t=vt.findRealms({browsingContextId:this.contextId,sandbox:e})),1!==t.length)throw Error(`Sandbox ${e} wasn't created.`);return t[0]}}const _t=e("context");class xt{sessions=new Set;#V;#$;#x;#N;constructor(e,t,n,s){this.#V=e,this.#$=t,this.#x=n,this.#N=s,this.#U(this.#V.browserClient())}#U(e){this.#W(e)}#W(e){e.Target.on("attachedToTarget",(async t=>{await this.#K(t,e)})),e.Target.on("detachedFromTarget",(async e=>{await xt.#H(e)}))}#J(e){if(this.sessions.has(e))return;this.sessions.add(e);const t=this.#V.getCdpClient(e);this.#W(t),t.on("event",(async(t,n)=>{await this.#N.sendEvent({method:"PROTO.cdp.eventReceived",params:{cdpMethod:t,cdpParams:n,cdpSession:e}},null)})),t.Page.on("frameAttached",(async n=>{await wt.createFrameContext(n.frameId,n.parentFrameId,t,this.#x,e,this.#N)}))}async#K(e,t){_t("AttachedToTarget event received: "+JSON.stringify(e));const{sessionId:n,targetInfo:s}=e;let r=this.#V.getCdpClient(n);if(!this.#q(s))return await r.Runtime.runIfWaitingForDebugger(),void await t.Target.detachFromTarget(e);this.#J(n),gt.hasKnownContext(s.targetId)?gt.getKnownContext(s.targetId).convertFrameToTargetContext(r,n):await wt.createTargetContext(s.targetId,null,r,this.#x,n,this.#N)}static async#H(e){const t=e.targetId;await(gt.findContext(t)?.delete())}async process_browsingContext_getTree(e){return{result:{contexts:(void 0===e.root?gt.getTopLevelContexts():[gt.getKnownContext(e.root)]).map((t=>t.serializeToBidiValue(e.maxDepth??Number.MAX_VALUE)))}}}async process_browsingContext_create(e){const t=this.#V.browserClient(),n=(await t.Target.createTarget({url:"about:blank",newWindow:"window"===e.type})).targetId,s=gt.getKnownContext(n);return await s.awaitLoaded(),{result:s.serializeToBidiValue(1)}}async process_browsingContext_navigate(e){const t=gt.getKnownContext(e.context);return await t.navigate(e.url,void 0!==e.wait?e.wait:"none")}static async#G(e){if("realm"in e)return vt.getRealm({realmId:e.realm});const t=gt.getKnownContext(e.context);return await t.getOrCreateSandbox(e.sandbox)}async process_script_evaluate(e){const t=await xt.#G(e.target);return await t.scriptEvaluate(e.expression,e.awaitPromise,e.resultOwnership??"none")}process_script_getRealms(e){void 0!==e.context&>.getKnownContext(e.context);return{result:{realms:vt.findRealms({browsingContextId:e.context,type:e.type}).map((e=>e.toBiDi()))}}}async process_script_callFunction(e){const t=await xt.#G(e.target);return await t.callFunction(e.functionDeclaration,e.this||{type:"undefined"},e.arguments||[],e.awaitPromise,e.resultOwnership??"none")}async process_PROTO_browsingContext_findElement(e){const t=gt.getKnownContext(e.context);return await t.findElement(e.selector)}async process_browsingContext_close(e){const t=this.#V.browserClient();if(null!==gt.getKnownContext(e.context).parentId)throw new r("Not a top-level browsing context cannot be closed.");const n=new Promise((async n=>{const s=r=>{r.targetId===e.context&&(t.Target.removeListener("detachedFromTarget",s),n())};t.Target.on("detachedFromTarget",s)}));return await this.#V.browserClient().Target.closeTarget({targetId:e.context}),await n,{result:{}}}#q(e){return e.targetId!==this.#$&&["page","iframe"].includes(e.type)}async process_PROTO_cdp_sendCommand(e){return{result:await this.#V.sendCommand(e.cdpMethod,e.cdpParams,e.cdpSession??null),cdpSession:e.cdpSession}}async process_PROTO_cdp_getSession(e){const t=e.context,n=gt.getKnownContext(t).cdpSessionId;return void 0===n?{result:{cdpSession:null}}:{result:{cdpSession:n}}}}class Ct{#X;#x;#N;static run(e,t,n,s){new Ct(e,t,n,s).#Q()}constructor(e,t,n,s){this.#N=n,this.#x=t,this.#X=new xt(e,s,t,n)}#Q(){this.#x.on("message",(e=>this.#Y(e)))}async#ee(){return{result:{ready:!1,message:"already connected"}}}async#te(e){return await this.#N.subscribe(e.events,e.contexts??null),{result:{}}}async#ne(e){return await this.#N.unsubscribe(e.events,e.contexts??null),{result:{}}}async#se(e){switch(e.method){case"session.status":return await this.#ee();case"session.subscribe":return await this.#te(ot.parseSubscribeParams(e.params));case"session.unsubscribe":return await this.#ne(ot.parseSubscribeParams(e.params));case"browsingContext.create":return await this.#X.process_browsingContext_create(rt.parseCreateParams(e.params));case"browsingContext.close":return await this.#X.process_browsingContext_close(rt.parseCloseParams(e.params));case"browsingContext.getTree":return await this.#X.process_browsingContext_getTree(rt.parseGetTreeParams(e.params));case"browsingContext.navigate":return await this.#X.process_browsingContext_navigate(rt.parseNavigateParams(e.params));case"script.getRealms":return this.#X.process_script_getRealms(st.parseGetRealmsParams(e.params));case"script.callFunction":return await this.#X.process_script_callFunction(st.parseCallFunctionParams(e.params));case"script.evaluate":return await this.#X.process_script_evaluate(st.parseEvaluateParams(e.params));case"PROTO.browsingContext.findElement":return await this.#X.process_PROTO_browsingContext_findElement(rt.PROTO.parseFindElementParams(e.params));case"PROTO.cdp.sendCommand":return await this.#X.process_PROTO_cdp_sendCommand(it.PROTO.parseSendCommandParams(e.params));case"PROTO.cdp.getSession":return await this.#X.process_PROTO_cdp_getSession(it.PROTO.parseGetSessionParams(e.params));default:throw new s(`Unknown command '${e.method}'.`)}}#Y=async e=>{try{const t=await this.#se(e),n={id:e.id,...t};await this.#x.sendMessage(n)}catch(s){if(s instanceof t){const t=s;await this.#x.sendMessage(t.toErrorResponse(e.id))}else{const t=s;console.error(t),await this.#x.sendMessage(new n(t.message).toErrorResponse(e.id))}}}}function St(){}function It(){It.init.call(this)}function Tt(e){return void 0===e._maxListeners?It.defaultMaxListeners:e._maxListeners}function kt(e,t,n){if(t)e.call(n);else for(var s=e.length,r=Mt(e,s),a=0;a<s;++a)r[a].call(n)}function Ot(e,t,n,s){if(t)e.call(n,s);else for(var r=e.length,a=Mt(e,r),i=0;i<r;++i)a[i].call(n,s)}function Et(e,t,n,s,r){if(t)e.call(n,s,r);else for(var a=e.length,i=Mt(e,a),o=0;o<a;++o)i[o].call(n,s,r)}function Pt(e,t,n,s,r,a){if(t)e.call(n,s,r,a);else for(var i=e.length,o=Mt(e,i),c=0;c<i;++c)o[c].call(n,s,r,a)}function Dt(e,t,n,s){if(t)e.apply(n,s);else for(var r=e.length,a=Mt(e,r),i=0;i<r;++i)a[i].apply(n,s)}function Nt(e,t,n,s){var r,a,i,o;if("function"!=typeof n)throw new TypeError('"listener" argument must be a function');if((a=e._events)?(a.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),a=e._events),i=a[t]):(a=e._events=new St,e._eventsCount=0),i){if("function"==typeof i?i=a[t]=s?[n,i]:[i,n]:s?i.unshift(n):i.push(n),!i.warned&&(r=Tt(e))&&r>0&&i.length>r){i.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+i.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=i.length,o=c,"function"==typeof console.warn?console.warn(o):console.log(o)}}else i=a[t]=n,++e._eventsCount;return e}function jt(e,t,n){var s=!1;function r(){e.removeListener(t,r),s||(s=!0,n.apply(e,arguments))}return r.listener=n,r}function Rt(e){var t=this._events;if(t){var n=t[e];if("function"==typeof n)return 1;if(n)return n.length}return 0}function Mt(e,t){for(var n=new Array(t);t--;)n[t]=e[t];return n}St.prototype=Object.create(null),It.EventEmitter=It,It.usingDomains=!1,It.prototype.domain=void 0,It.prototype._events=void 0,It.prototype._maxListeners=void 0,It.defaultMaxListeners=10,It.init=function(){this.domain=null,It.usingDomains&&undefined.active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new St,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},It.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},It.prototype.getMaxListeners=function(){return Tt(this)},It.prototype.emit=function(e){var t,n,s,r,a,i,o,c="error"===e;if(i=this._events)c=c&&null==i.error;else if(!c)return!1;if(o=this.domain,c){if(t=arguments[1],!o){if(t instanceof Error)throw t;var d=new Error('Uncaught, unspecified "error" event. ('+t+")");throw d.context=t,d}return t||(t=new Error('Uncaught, unspecified "error" event')),t.domainEmitter=this,t.domain=o,t.domainThrown=!1,o.emit("error",t),!1}if(!(n=i[e]))return!1;var l="function"==typeof n;switch(s=arguments.length){case 1:kt(n,l,this);break;case 2:Ot(n,l,this,arguments[1]);break;case 3:Et(n,l,this,arguments[1],arguments[2]);break;case 4:Pt(n,l,this,arguments[1],arguments[2],arguments[3]);break;default:for(r=new Array(s-1),a=1;a<s;a++)r[a-1]=arguments[a];Dt(n,l,this,r)}return!0},It.prototype.addListener=function(e,t){return Nt(this,e,t,!1)},It.prototype.on=It.prototype.addListener,It.prototype.prependListener=function(e,t){return Nt(this,e,t,!0)},It.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,jt(this,e,t)),this},It.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,jt(this,e,t)),this},It.prototype.removeListener=function(e,t){var n,s,r,a,i;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(s=this._events))return this;if(!(n=s[e]))return this;if(n===t||n.listener&&n.listener===t)0==--this._eventsCount?this._events=new St:(delete s[e],s.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(r=-1,a=n.length;a-- >0;)if(n[a]===t||n[a].listener&&n[a].listener===t){i=n[a].listener,r=a;break}if(r<0)return this;if(1===n.length){if(n[0]=void 0,0==--this._eventsCount)return this._events=new St,this;delete s[e]}else!function(e,t){for(var n=t,s=n+1,r=e.length;s<r;n+=1,s+=1)e[n]=e[s];e.pop()}(n,r);s.removeListener&&this.emit("removeListener",e,i||t)}return this},It.prototype.removeAllListeners=function(e){var t,n;if(!(n=this._events))return this;if(!n.removeListener)return 0===arguments.length?(this._events=new St,this._eventsCount=0):n[e]&&(0==--this._eventsCount?this._events=new St:delete n[e]),this;if(0===arguments.length){for(var s,r=Object.keys(n),a=0;a<r.length;++a)"removeListener"!==(s=r[a])&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=new St,this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(t)do{this.removeListener(e,t[t.length-1])}while(t[0]);return this},It.prototype.listeners=function(e){var t,n=this._events;return n&&(t=n[e])?"function"==typeof t?[t.listener||t]:function(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(t):[]},It.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):Rt.call(e,t)},It.prototype.listenerCount=Rt,It.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};const Lt=[{domain:"Accessibility",commands:["disable","enable","getPartialAXTree","getFullAXTree","getRootAXNode","getAXNodeAndAncestors","getChildAXNodes","queryAXTree"]},{domain:"Animation",commands:["disable","enable","getCurrentTime","getPlaybackRate","releaseAnimations","resolveAnimation","seekAnimations","setPaused","setPlaybackRate","setTiming"]},{domain:"Audits",commands:["getEncodedResponse","disable","enable","checkContrast"]},{domain:"BackgroundService",commands:["startObserving","stopObserving","setRecording","clearEvents"]},{domain:"Browser",commands:["setPermission","grantPermissions","resetPermissions","setDownloadBehavior","cancelDownload","close","crash","crashGpuProcess","getVersion","getBrowserCommandLine","getHistograms","getHistogram","getWindowBounds","getWindowForTarget","setWindowBounds","setDockTile","executeBrowserCommand"]},{domain:"CSS",commands:["addRule","collectClassNames","createStyleSheet","disable","enable","forcePseudoState","getBackgroundColors","getComputedStyleForNode","getInlineStylesForNode","getMatchedStylesForNode","getMediaQueries","getPlatformFontsForNode","getStyleSheetText","getLayersForNode","trackComputedStyleUpdates","takeComputedStyleUpdates","setEffectivePropertyValueForNode","setKeyframeKey","setMediaText","setContainerQueryText","setSupportsText","setRuleSelector","setStyleSheetText","setStyleTexts","startRuleUsageTracking","stopRuleUsageTracking","takeCoverageDelta","setLocalFontsEnabled"]},{domain:"CacheStorage",commands:["deleteCache","deleteEntry","requestCacheNames","requestCachedResponse","requestEntries"]},{domain:"Cast",commands:["enable","disable","setSinkToUse","startDesktopMirroring","startTabMirroring","stopCasting"]},{domain:"DOM",commands:["collectClassNamesFromSubtree","copyTo","describeNode","scrollIntoViewIfNeeded","disable","discardSearchResults","enable","focus","getAttributes","getBoxModel","getContentQuads","getDocument","getFlattenedDocument","getNodesForSubtreeByStyle","getNodeForLocation","getOuterHTML","getRelayoutBoundary","getSearchResults","hideHighlight","highlightNode","highlightRect","markUndoableState","moveTo","performSearch","pushNodeByPathToFrontend","pushNodesByBackendIdsToFrontend","querySelector","querySelectorAll","redo","removeAttribute","removeNode","requestChildNodes","requestNode","resolveNode","setAttributeValue","setAttributesAsText","setFileInputFiles","setNodeStackTracesEnabled","getNodeStackTraces","getFileInfo","setInspectedNode","setNodeName","setNodeValue","setOuterHTML","undo","getFrameOwner","getContainerForNode","getQueryingDescendantsForContainer"]},{domain:"DOMDebugger",commands:["getEventListeners","removeDOMBreakpoint","removeEventListenerBreakpoint","removeInstrumentationBreakpoint","removeXHRBreakpoint","setBreakOnCSPViolation","setDOMBreakpoint","setEventListenerBreakpoint","setInstrumentationBreakpoint","setXHRBreakpoint"]},{domain:"EventBreakpoints",commands:["setInstrumentationBreakpoint","removeInstrumentationBreakpoint"]},{domain:"DOMSnapshot",commands:["disable","enable","getSnapshot","captureSnapshot"]},{domain:"DOMStorage",commands:["clear","disable","enable","getDOMStorageItems","removeDOMStorageItem","setDOMStorageItem"]},{domain:"Database",commands:["disable","enable","executeSQL","getDatabaseTableNames"]},{domain:"DeviceOrientation",commands:["clearDeviceOrientationOverride","setDeviceOrientationOverride"]},{domain:"Emulation",commands:["canEmulate","clearDeviceMetricsOverride","clearGeolocationOverride","resetPageScaleFactor","setFocusEmulationEnabled","setAutoDarkModeOverride","setCPUThrottlingRate","setDefaultBackgroundColorOverride","setDeviceMetricsOverride","setScrollbarsHidden","setDocumentCookieDisabled","setEmitTouchEventsForMouse","setEmulatedMedia","setEmulatedVisionDeficiency","setGeolocationOverride","setIdleOverride","clearIdleOverride","setNavigatorOverrides","setPageScaleFactor","setScriptExecutionDisabled","setTouchEmulationEnabled","setVirtualTimePolicy","setLocaleOverride","setTimezoneOverride","setVisibleSize","setDisabledImageTypes","setHardwareConcurrencyOverride","setUserAgentOverride","setAutomationOverride"]},{domain:"HeadlessExperimental",commands:["beginFrame","disable","enable"]},{domain:"IO",commands:["close","read","resolveBlob"]},{domain:"IndexedDB",commands:["clearObjectStore","deleteDatabase","deleteObjectStoreEntries","disable","enable","requestData","getMetadata","requestDatabase","requestDatabaseNames"]},{domain:"Input",commands:["dispatchDragEvent","dispatchKeyEvent","insertText","imeSetComposition","dispatchMouseEvent","dispatchTouchEvent","emulateTouchFromMouseEvent","setIgnoreInputEvents","setInterceptDrags","synthesizePinchGesture","synthesizeScrollGesture","synthesizeTapGesture"]},{domain:"Inspector",commands:["disable","enable"]},{domain:"LayerTree",commands:["compositingReasons","disable","enable","loadSnapshot","makeSnapshot","profileSnapshot","releaseSnapshot","replaySnapshot","snapshotCommandLog"]},{domain:"Log",commands:["clear","disable","enable","startViolationsReport","stopViolationsReport"]},{domain:"Memory",commands:["getDOMCounters","prepareForLeakDetection","forciblyPurgeJavaScriptMemory","setPressureNotificationsSuppressed","simulatePressureNotification","startSampling","stopSampling","getAllTimeSamplingProfile","getBrowserSamplingProfile","getSamplingProfile"]},{domain:"Network",commands:["setAcceptedEncodings","clearAcceptedEncodingsOverride","canClearBrowserCache","canClearBrowserCookies","canEmulateNetworkConditions","clearBrowserCache","clearBrowserCookies","continueInterceptedRequest","deleteCookies","disable","emulateNetworkConditions","enable","getAllCookies","getCertificate","getCookies","getResponseBody","getRequestPostData","getResponseBodyForInterception","takeResponseBodyForInterceptionAsStream","replayXHR","searchInResponseBody","setBlockedURLs","setBypassServiceWorker","setCacheDisabled","setCookie","setCookies","setExtraHTTPHeaders","setAttachDebugStack","setRequestInterception","setUserAgentOverride","getSecurityIsolationStatus","enableReportingApi","loadNetworkResource"]},{domain:"Overlay",commands:["disable","enable","getHighlightObjectForTest","getGridHighlightObjectsForTest","getSourceOrderHighlightObjectForTest","hideHighlight","highlightFrame","highlightNode","highlightQuad","highlightRect","highlightSourceOrder","setInspectMode","setShowAdHighlights","setPausedInDebuggerMessage","setShowDebugBorders","setShowFPSCounter","setShowGridOverlays","setShowFlexOverlays","setShowScrollSnapOverlays","setShowContainerQueryOverlays","setShowPaintRects","setShowLayoutShiftRegions","setShowScrollBottleneckRects","setShowHitTestBorders","setShowWebVitals","setShowViewportSizeOnResize","setShowHinge","setShowIsolatedElements"]},{domain:"Page",commands:["addScriptToEvaluateOnLoad","addScriptToEvaluateOnNewDocument","bringToFront","captureScreenshot","captureSnapshot","clearDeviceMetricsOverride","clearDeviceOrientationOverride","clearGeolocationOverride","createIsolatedWorld","deleteCookie","disable","enable","getAppManifest","getInstallabilityErrors","getManifestIcons","getAppId","getCookies","getFrameTree","getLayoutMetrics","getNavigationHistory","resetNavigationHistory","getResourceContent","getResourceTree","handleJavaScriptDialog","navigate","navigateToHistoryEntry","printToPDF","reload","removeScriptToEvaluateOnLoad","removeScriptToEvaluateOnNewDocument","screencastFrameAck","searchInResource","setAdBlockingEnabled","setBypassCSP","getPermissionsPolicyState","getOriginTrials","setDeviceMetricsOverride","setDeviceOrientationOverride","setFontFamilies","setFontSizes","setDocumentContent","setDownloadBehavior","setGeolocationOverride","setLifecycleEventsEnabled","setTouchEmulationEnabled","startScreencast","stopLoading","crash","close","setWebLifecycleState","stopScreencast","produceCompilationCache","addCompilationCache","clearCompilationCache","setSPCTransactionMode","generateTestReport","waitForDebugger","setInterceptFileChooserDialog"]},{domain:"Performance",commands:["disable","enable","setTimeDomain","getMetrics"]},{domain:"PerformanceTimeline",commands:["enable"]},{domain:"Security",commands:["disable","enable","setIgnoreCertificateErrors","handleCertificateError","setOverrideCertificateErrors"]},{domain:"ServiceWorker",commands:["deliverPushMessage","disable","dispatchSyncEvent","dispatchPeriodicSyncEvent","enable","inspectWorker","setForceUpdateOnPageLoad","skipWaiting","startWorker","stopAllWorkers","stopWorker","unregister","updateRegistration"]},{domain:"Storage",commands:["getStorageKeyForFrame","clearDataForOrigin","getCookies","setCookies","clearCookies","getUsageAndQuota","overrideQuotaForOrigin","trackCacheStorageForOrigin","trackIndexedDBForOrigin","untrackCacheStorageForOrigin","untrackIndexedDBForOrigin","getTrustTokens","clearTrustTokens","getInterestGroupDetails","setInterestGroupTracking"]},{domain:"SystemInfo",commands:["getInfo","getProcessInfo"]},{domain:"Target",commands:["activateTarget","attachToTarget","attachToBrowserTarget","closeTarget","exposeDevToolsProtocol","createBrowserContext","getBrowserContexts","createTarget","detachFromTarget","disposeBrowserContext","getTargetInfo","getTargets","sendMessageToTarget","setAutoAttach","autoAttachRelated","setDiscoverTargets","setRemoteLocations"]},{domain:"Tethering",commands:["bind","unbind"]},{domain:"Tracing",commands:["end","getCategories","recordClockSyncMarker","requestMemoryDump","start"]},{domain:"Fetch",commands:["disable","enable","failRequest","fulfillRequest","continueRequest","continueWithAuth","continueResponse","getResponseBody","takeResponseBodyAsStream"]},{domain:"WebAudio",commands:["enable","disable","getRealtimeData"]},{domain:"WebAuthn",commands:["enable","disable","addVirtualAuthenticator","removeVirtualAuthenticator","addCredential","getCredential","getCredentials","removeCredential","clearCredentials","setUserVerified","setAutomaticPresenceSimulation"]},{domain:"Media",commands:["enable","disable"]},{domain:"Console",commands:["clearMessages","disable","enable"]},{domain:"Debugger",commands:["continueToLocation","disable","enable","evaluateOnCallFrame","getPossibleBreakpoints","getScriptSource","getWasmBytecode","getStackTrace","pause","pauseOnAsyncCall","removeBreakpoint","restartFrame","resume","searchInContent","setAsyncCallStackDepth","setBlackboxPatterns","setBlackboxedRanges","setBreakpoint","setInstrumentationBreakpoint","setBreakpointByUrl","setBreakpointOnFunctionCall","setBreakpointsActive","setPauseOnExceptions","setReturnValue","setScriptSource","setSkipAllPauses","setVariableValue","stepInto","stepOut","stepOver"]},{domain:"HeapProfiler",commands:["addInspectedHeapObject","collectGarbage","disable","enable","getHeapObjectId","getObjectByHeapObjectId","getSamplingProfile","startSampling","startTrackingHeapObjects","stopSampling","stopTrackingHeapObjects","takeHeapSnapshot"]},{domain:"Profiler",commands:["disable","enable","getBestEffortCoverage","setSamplingInterval","start","startPreciseCoverage","startTypeProfile","stop","stopPreciseCoverage","stopTypeProfile","takePreciseCoverage","takeTypeProfile"]},{domain:"Runtime",commands:["awaitPromise","callFunctionOn","compileScript","disable","discardConsoleEntries","enable","evaluate","getIsolateId","getHeapUsage","getProperties","globalLexicalScopeNames","queryObjects","releaseObject","releaseObjectGroup","runIfWaitingForDebugger","runScript","setAsyncCallStackDepth","setCustomObjectFormatterEnabled","setMaxCallStackSizeToCapture","terminateExecution","addBinding","removeBinding","getExceptionDetails"]},{domain:"Schema",commands:["getDomains"]}],At=new Map;class Zt extends It{_client;constructor(e){super(),this._client=e}}for(let e of Lt){class t extends Zt{constructor(e){super(e)}}for(let n of e.commands)Object.defineProperty(t.prototype,n,{value:async function(t){return await this._client.sendCommand(`${e.domain}.${n}`,t)}});At.set(e.domain,t)}class Bt extends It{_cdpConnection;_sessionId;_domains;constructor(e,t){super(),this._cdpConnection=e,this._sessionId=t,this._domains=new Map;for(const[e,t]of At.entries())this._domains.set(e,new t(this)),Object.defineProperty(this,e,{get(){return this._domains.get(e)}})}sendCommand(e,t){return this._cdpConnection.sendCommand(e,t,this._sessionId)}_onCdpEvent(e,t){this.emit("event",e,t);const[n,s]=e.split("."),r=this._domains.get(n);r&&r.emit(s,t)}}function Ft(e,t){return new Bt(e,t)}const zt=e("cdp");class Vt{_transport;_browserCdpClient;_sessionCdpClients=new Map;_commandCallbacks=new Map;_nextId;constructor(e){this._transport=e,this._nextId=0,this._transport.setOnMessage(this._onMessage),this._browserCdpClient=Ft(this,null)}close(){this._transport.close();for(const[e,{reject:t}]of this._commandCallbacks)t(new Error("Disconnected"));this._commandCallbacks.clear(),this._sessionCdpClients.clear()}browserClient(){return this._browserCdpClient}getCdpClient(e){const t=this._sessionCdpClients.get(e);if(!t)throw new Error("Unknown CDP session ID");return t}sendCommand(e,t,n){return new Promise(((s,r)=>{const a=this._nextId++;this._commandCallbacks.set(a,{resolve:s,reject:r});let i={id:a,method:e,params:t};n&&(i.sessionId=n);const o=JSON.stringify(i);this._transport.sendMessage(o),zt("sent > "+o)}))}_onMessage=async e=>{zt("received < "+e);const t=JSON.parse(e);if("Target.attachedToTarget"===t.method){const{sessionId:e}=t.params;this._sessionCdpClients.set(e,Ft(this,e))}else if("Target.detachedFromTarget"===t.method){const{sessionId:e}=t.params;this._sessionCdpClients.get(e)&&this._sessionCdpClients.delete(e)}if(void 0!==t.id){const e=this._commandCallbacks.get(t.id);e&&(t.result?e.resolve(t.result):t.error&&e.reject(t.error))}else if(t.method){const e=t.sessionId?this._sessionCdpClients.get(t.sessionId):this._browserCdpClient;e&&e._onCdpEvent(t.method,t.params||{})}}}const $t=e("bidi");class Ut extends It{_transport;constructor(e){super(),this._transport=e,this._transport.setOnMessage(this._onBidiMessage)}async sendMessage(e){const t=JSON.stringify(e);$t("sent > "+t),this._transport.sendMessage(t)}close(){this._transport.close()}_onBidiMessage=async e=>{let t;$t("received < "+e);try{t=this._parseBidiMessage(e)}catch(t){return void this._respondWithError(e,"invalid argument",t.message)}this.emit("message",t)};_respondWithError(e,t,n){const s=this._getErrorResponse(e,t,n);this.sendMessage(s)}_getJsonType(e){return null===e?"null":Array.isArray(e)?"array":typeof e}_getErrorResponse(e,t,n){let s;try{const t=JSON.parse(e);"object"===this._getJsonType(t)&&"id"in t&&(s=t.id)}catch{}return{id:s,error:t,message:n}}_parseBidiMessage(e){let t;try{t=JSON.parse(e)}catch{throw new Error("Cannot parse data as JSON")}const n=this._getJsonType(t);if("object"!==n)throw new Error(`Expected JSON object but got ${n}`);const{id:s,method:r,params:a}=t,i=this._getJsonType(s);if("number"!==i||!Number.isInteger(s)||s<0)throw new Error(`Expected unsigned integer but got ${i}`);const o=this._getJsonType(r);if("string"!==o)throw new Error(`Expected string method but got ${o}`);const c=this._getJsonType(a);if("object"!==c)throw new Error(`Expected object params but got ${c}`);return{id:s,method:r,params:a}}}class Wt{#re=new Map;#x;constructor(e){this.#x=e}async sendEvent(e,t){(this.#ae(e.method,null)||null!==t&&this.#ae(e.method,t))&&await this.#x.sendMessage(e)}#ae(e,t){return this.#re.has(t)&&this.#re.get(t).has(e)}async subscribe(e,t){for(let n of e)if(null===t)this.#ie(n,null);else for(let e of t)this.#ie(n,e)}#ie(e,t){this.#re.has(t)||this.#re.set(t,new Set),this.#re.get(t).add(e)}async unsubscribe(e,t){for(let n of e)if(null===t)this.#oe(n,null);else for(let e of t)this.#oe(n,e)}#oe(e,t){const n=this.#re.get(t);n?.delete(e),0===n?.size&&this.#re.delete(t)}} +!function(){"use strict";function e(e){return(...t)=>{if(globalThis.document?.documentElement){console.log(e,...t);const n=function(e){const t=e+"_log",n=document.getElementById(t);if(n)return n;const s=document.createElement("div");return s.id=t,s.innerHTML=`<h3>${e}:</h3>`,document.body.appendChild(s),s}(e),s=document.createElement("pre");s.textContent=t.join(", "),n.appendChild(s)}}}class t{constructor(e,t,n){this.error=e,this.message=t,this.stacktrace=n}error;message;stacktrace;toErrorResponse(e){return{id:e,error:this.error,message:this.message,stacktrace:this.stacktrace}}}class n extends t{constructor(e,t){super("unknown error",e,t)}}class s extends t{constructor(e,t){super("unknown command",e,t)}}class a extends t{constructor(e,t){super("invalid argument",e,t)}}class r extends t{constructor(e){super("no such frame",e)}}class i{method;params;constructor(e,t){this.method=e,this.params=t}}var o;!function(e){e.assertEqual=e=>e,e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const n of e)t[n]=n;return t},e.getValidEnumValues=t=>{const n=e.objectKeys(t).filter((e=>"number"!=typeof t[t[e]])),s={};for(const e of n)s[e]=t[e];return e.objectValues(s)},e.objectValues=t=>e.objectKeys(t).map((function(e){return t[e]})),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(const n of e)if(t(n))return n},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map((e=>"string"==typeof e?`'${e}'`:e)).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(o||(o={}));const c=o.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),d=e=>{switch(typeof e){case"undefined":return c.undefined;case"string":return c.string;case"number":return isNaN(e)?c.nan:c.number;case"boolean":return c.boolean;case"function":return c.function;case"bigint":return c.bigint;case"object":return Array.isArray(e)?c.array:null===e?c.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?c.promise:"undefined"!=typeof Map&&e instanceof Map?c.map:"undefined"!=typeof Set&&e instanceof Set?c.set:"undefined"!=typeof Date&&e instanceof Date?c.date:c.object;default:return c.unknown}},l=o.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of"]);class u extends Error{constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}get errors(){return this.issues}format(e){const t=e||function(e){return e.message},n={_errors:[]},s=e=>{for(const a of e.issues)if("invalid_union"===a.code)a.unionErrors.map(s);else if("invalid_return_type"===a.code)s(a.returnTypeError);else if("invalid_arguments"===a.code)s(a.argumentsError);else if(0===a.path.length)n._errors.push(t(a));else{let e=n,s=0;for(;s<a.path.length;){const n=a.path[s];s===a.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(a))):e[n]=e[n]||{_errors:[]},e=e[n],s++}}};return s(this),n}toString(){return this.message}get message(){return JSON.stringify(this.issues,o.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=(e=>e.message)){const t={},n=[];for(const s of this.issues)s.path.length>0?(t[s.path[0]]=t[s.path[0]]||[],t[s.path[0]].push(e(s))):n.push(e(s));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}}u.create=e=>new u(e);const p=(e,t)=>{let n;switch(e.code){case l.invalid_type:n=e.received===c.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case l.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,o.jsonStringifyReplacer)}`;break;case l.unrecognized_keys:n=`Unrecognized key(s) in object: ${o.joinValues(e.keys,", ")}`;break;case l.invalid_union:n="Invalid input";break;case l.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${o.joinValues(e.options)}`;break;case l.invalid_enum_value:n=`Invalid enum value. Expected ${o.joinValues(e.options)}, received '${e.received}'`;break;case l.invalid_arguments:n="Invalid function arguments";break;case l.invalid_return_type:n="Invalid function return type";break;case l.invalid_date:n="Invalid date";break;case l.invalid_string:"object"==typeof e.validation?"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:o.assertNever(e.validation):n="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case l.too_small:n="array"===e.type?`Array must contain ${e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type?`Number must be greater than ${e.inclusive?"or equal to ":""}${e.minimum}`:"date"===e.type?`Date must be greater than ${e.inclusive?"or equal to ":""}${new Date(e.minimum)}`:"Invalid input";break;case l.too_big:n="array"===e.type?`Array must contain ${e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be less than ${e.inclusive?"or equal to ":""}${e.maximum}`:"date"===e.type?`Date must be smaller than ${e.inclusive?"or equal to ":""}${new Date(e.maximum)}`:"Invalid input";break;case l.custom:n="Invalid input";break;case l.invalid_intersection_types:n="Intersection results could not be merged";break;case l.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;default:n=t.defaultError,o.assertNever(e)}return{message:n}};let h=p;function m(){return h}const g=e=>{const{data:t,path:n,errorMaps:s,issueData:a}=e,r=[...n,...a.path||[]],i={...a,path:r};let o="";const c=s.filter((e=>!!e)).slice().reverse();for(const e of c)o=e(i,{data:t,defaultError:o}).message;return{...a,path:r,message:a.message||o}};function f(e,t){const n=g({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,m(),p].filter((e=>!!e))});e.common.issues.push(n)}class v{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const n=[];for(const s of t){if("aborted"===s.status)return y;"dirty"===s.status&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){const n=[];for(const e of t)n.push({key:await e.key,value:await e.value});return v.mergeObjectSync(e,n)}static mergeObjectSync(e,t){const n={};for(const s of t){const{key:t,value:a}=s;if("aborted"===t.status)return y;if("aborted"===a.status)return y;"dirty"===t.status&&e.dirty(),"dirty"===a.status&&e.dirty(),(void 0!==a.value||s.alwaysSet)&&(n[t.value]=a.value)}return{status:e.value,value:n}}}const y=Object.freeze({status:"aborted"}),b=e=>({status:"valid",value:e}),w=e=>"aborted"===e.status,_=e=>"dirty"===e.status,x=e=>"valid"===e.status,C=e=>void 0!==typeof Promise&&e instanceof Promise;var S;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:null==e?void 0:e.message}(S||(S={}));class I{constructor(e,t,n,s){this.parent=e,this.data=t,this._path=n,this._key=s}get path(){return this._path.concat(this._key)}}const T=(e,t)=>{if(x(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,error:new u(e.common.issues)}};function k(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:s,description:a}=e;if(t&&(n||s))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:a};return{errorMap:(e,t)=>"invalid_type"!==e.code?{message:t.defaultError}:void 0===t.data?{message:null!=s?s:t.defaultError}:{message:null!=n?n:t.defaultError},description:a}}class O{constructor(e){this.spa=this.safeParseAsync,this.superRefine=this._refinement,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.default=this.default.bind(this),this.describe=this.describe.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(e){return d(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:d(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new v,ctx:{common:e.parent.common,data:e.data,parsedType:d(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(C(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){var n;const s={common:{issues:[],async:null!==(n=null==t?void 0:t.async)&&void 0!==n&&n,contextualErrorMap:null==t?void 0:t.errorMap},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:d(e)},a=this._parseSync({data:e,path:s.path,parent:s});return T(s,a)}async parseAsync(e,t){const n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){const n={common:{issues:[],contextualErrorMap:null==t?void 0:t.errorMap,async:!0},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:d(e)},s=this._parse({data:e,path:[],parent:n}),a=await(C(s)?s:Promise.resolve(s));return T(n,a)}refine(e,t){const n=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement(((t,s)=>{const a=e(t),r=()=>s.addIssue({code:l.custom,...n(t)});return"undefined"!=typeof Promise&&a instanceof Promise?a.then((e=>!!e||(r(),!1))):!!a||(r(),!1)}))}refinement(e,t){return this._refinement(((n,s)=>!!e(n)||(s.addIssue("function"==typeof t?t(n,s):t),!1)))}_refinement(e){return new le({schema:this,typeName:be.ZodEffects,effect:{type:"refinement",refinement:e}})}optional(){return ue.create(this)}nullable(){return pe.create(this)}nullish(){return this.optional().nullable()}array(){return U.create(this)}promise(){return de.create(this)}or(e){return q.create([this,e])}and(e){return Q.create(this,e)}transform(e){return new le({schema:this,typeName:be.ZodEffects,effect:{type:"transform",transform:e}})}default(e){return new he({innerType:this,defaultValue:"function"==typeof e?e:()=>e,typeName:be.ZodDefault})}brand(){return new fe({typeName:be.ZodBranded,type:this,...k(void 0)})}describe(e){return new(0,this.constructor)({...this._def,description:e})}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const E=/^c[^\s-]{8,}$/i,P=/^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i,D=/^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;class N extends O{constructor(){super(...arguments),this._regex=(e,t,n)=>this.refinement((t=>e.test(t)),{validation:t,code:l.invalid_string,...S.errToObj(n)}),this.nonempty=e=>this.min(1,S.errToObj(e)),this.trim=()=>new N({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}_parse(e){if(this._getType(e)!==c.string){const t=this._getOrReturnCtx(e);return f(t,{code:l.invalid_type,expected:c.string,received:t.parsedType}),y}const t=new v;let n;for(const s of this._def.checks)if("min"===s.kind)e.data.length<s.value&&(n=this._getOrReturnCtx(e,n),f(n,{code:l.too_small,minimum:s.value,type:"string",inclusive:!0,message:s.message}),t.dirty());else if("max"===s.kind)e.data.length>s.value&&(n=this._getOrReturnCtx(e,n),f(n,{code:l.too_big,maximum:s.value,type:"string",inclusive:!0,message:s.message}),t.dirty());else if("email"===s.kind)D.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"email",code:l.invalid_string,message:s.message}),t.dirty());else if("uuid"===s.kind)P.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"uuid",code:l.invalid_string,message:s.message}),t.dirty());else if("cuid"===s.kind)E.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"cuid",code:l.invalid_string,message:s.message}),t.dirty());else if("url"===s.kind)try{new URL(e.data)}catch(a){n=this._getOrReturnCtx(e,n),f(n,{validation:"url",code:l.invalid_string,message:s.message}),t.dirty()}else if("regex"===s.kind){s.regex.lastIndex=0;s.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"regex",code:l.invalid_string,message:s.message}),t.dirty())}else"trim"===s.kind?e.data=e.data.trim():"startsWith"===s.kind?e.data.startsWith(s.value)||(n=this._getOrReturnCtx(e,n),f(n,{code:l.invalid_string,validation:{startsWith:s.value},message:s.message}),t.dirty()):"endsWith"===s.kind?e.data.endsWith(s.value)||(n=this._getOrReturnCtx(e,n),f(n,{code:l.invalid_string,validation:{endsWith:s.value},message:s.message}),t.dirty()):o.assertNever(s);return{status:t.value,value:e.data}}_addCheck(e){return new N({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...S.errToObj(e)})}url(e){return this._addCheck({kind:"url",...S.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...S.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...S.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...S.errToObj(t)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...S.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...S.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...S.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...S.errToObj(t)})}length(e,t){return this.min(e,t).max(e,t)}get isEmail(){return!!this._def.checks.find((e=>"email"===e.kind))}get isURL(){return!!this._def.checks.find((e=>"url"===e.kind))}get isUUID(){return!!this._def.checks.find((e=>"uuid"===e.kind))}get isCUID(){return!!this._def.checks.find((e=>"cuid"===e.kind))}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function R(e,t){const n=(e.toString().split(".")[1]||"").length,s=(t.toString().split(".")[1]||"").length,a=n>s?n:s;return parseInt(e.toFixed(a).replace(".",""))%parseInt(t.toFixed(a).replace(".",""))/Math.pow(10,a)}N.create=e=>new N({checks:[],typeName:be.ZodString,...k(e)});class j extends O{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._getType(e)!==c.number){const t=this._getOrReturnCtx(e);return f(t,{code:l.invalid_type,expected:c.number,received:t.parsedType}),y}let t;const n=new v;for(const s of this._def.checks)if("int"===s.kind)o.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),f(t,{code:l.invalid_type,expected:"integer",received:"float",message:s.message}),n.dirty());else if("min"===s.kind){(s.inclusive?e.data<s.value:e.data<=s.value)&&(t=this._getOrReturnCtx(e,t),f(t,{code:l.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,message:s.message}),n.dirty())}else if("max"===s.kind){(s.inclusive?e.data>s.value:e.data>=s.value)&&(t=this._getOrReturnCtx(e,t),f(t,{code:l.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,message:s.message}),n.dirty())}else"multipleOf"===s.kind?0!==R(e.data,s.value)&&(t=this._getOrReturnCtx(e,t),f(t,{code:l.not_multiple_of,multipleOf:s.value,message:s.message}),n.dirty()):o.assertNever(s);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,S.toString(t))}gt(e,t){return this.setLimit("min",e,!1,S.toString(t))}lte(e,t){return this.setLimit("max",e,!0,S.toString(t))}lt(e,t){return this.setLimit("max",e,!1,S.toString(t))}setLimit(e,t,n,s){return new j({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:S.toString(s)}]})}_addCheck(e){return new j({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:S.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:S.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:S.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:S.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:S.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:S.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find((e=>"int"===e.kind))}}j.create=e=>new j({checks:[],typeName:be.ZodNumber,...k(e)});class M extends O{_parse(e){if(this._getType(e)!==c.bigint){const t=this._getOrReturnCtx(e);return f(t,{code:l.invalid_type,expected:c.bigint,received:t.parsedType}),y}return b(e.data)}}M.create=e=>new M({typeName:be.ZodBigInt,...k(e)});class A extends O{_parse(e){if(this._getType(e)!==c.boolean){const t=this._getOrReturnCtx(e);return f(t,{code:l.invalid_type,expected:c.boolean,received:t.parsedType}),y}return b(e.data)}}A.create=e=>new A({typeName:be.ZodBoolean,...k(e)});class L extends O{_parse(e){if(this._getType(e)!==c.date){const t=this._getOrReturnCtx(e);return f(t,{code:l.invalid_type,expected:c.date,received:t.parsedType}),y}if(isNaN(e.data.getTime())){return f(this._getOrReturnCtx(e),{code:l.invalid_date}),y}const t=new v;let n;for(const s of this._def.checks)"min"===s.kind?e.data.getTime()<s.value&&(n=this._getOrReturnCtx(e,n),f(n,{code:l.too_small,message:s.message,inclusive:!0,minimum:s.value,type:"date"}),t.dirty()):"max"===s.kind?e.data.getTime()>s.value&&(n=this._getOrReturnCtx(e,n),f(n,{code:l.too_big,message:s.message,inclusive:!0,maximum:s.value,type:"date"}),t.dirty()):o.assertNever(s);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new L({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:S.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:S.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}L.create=e=>new L({checks:[],typeName:be.ZodDate,...k(e)});class Z extends O{_parse(e){if(this._getType(e)!==c.undefined){const t=this._getOrReturnCtx(e);return f(t,{code:l.invalid_type,expected:c.undefined,received:t.parsedType}),y}return b(e.data)}}Z.create=e=>new Z({typeName:be.ZodUndefined,...k(e)});class B extends O{_parse(e){if(this._getType(e)!==c.null){const t=this._getOrReturnCtx(e);return f(t,{code:l.invalid_type,expected:c.null,received:t.parsedType}),y}return b(e.data)}}B.create=e=>new B({typeName:be.ZodNull,...k(e)});class F extends O{constructor(){super(...arguments),this._any=!0}_parse(e){return b(e.data)}}F.create=e=>new F({typeName:be.ZodAny,...k(e)});class z extends O{constructor(){super(...arguments),this._unknown=!0}_parse(e){return b(e.data)}}z.create=e=>new z({typeName:be.ZodUnknown,...k(e)});class V extends O{_parse(e){const t=this._getOrReturnCtx(e);return f(t,{code:l.invalid_type,expected:c.never,received:t.parsedType}),y}}V.create=e=>new V({typeName:be.ZodNever,...k(e)});class $ extends O{_parse(e){if(this._getType(e)!==c.undefined){const t=this._getOrReturnCtx(e);return f(t,{code:l.invalid_type,expected:c.void,received:t.parsedType}),y}return b(e.data)}}$.create=e=>new $({typeName:be.ZodVoid,...k(e)});class U extends O{_parse(e){const{ctx:t,status:n}=this._processInputParams(e),s=this._def;if(t.parsedType!==c.array)return f(t,{code:l.invalid_type,expected:c.array,received:t.parsedType}),y;if(null!==s.minLength&&t.data.length<s.minLength.value&&(f(t,{code:l.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,message:s.minLength.message}),n.dirty()),null!==s.maxLength&&t.data.length>s.maxLength.value&&(f(t,{code:l.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,message:s.maxLength.message}),n.dirty()),t.common.async)return Promise.all(t.data.map(((e,n)=>s.type._parseAsync(new I(t,e,t.path,n))))).then((e=>v.mergeArray(n,e)));const a=t.data.map(((e,n)=>s.type._parseSync(new I(t,e,t.path,n))));return v.mergeArray(n,a)}get element(){return this._def.type}min(e,t){return new U({...this._def,minLength:{value:e,message:S.toString(t)}})}max(e,t){return new U({...this._def,maxLength:{value:e,message:S.toString(t)}})}length(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}var W;U.create=(e,t)=>new U({type:e,minLength:null,maxLength:null,typeName:be.ZodArray,...k(t)}),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(W||(W={}));const K=e=>t=>new J({...e,shape:()=>({...e.shape(),...t})});function H(e){if(e instanceof J){const t={};for(const n in e.shape){const s=e.shape[n];t[n]=ue.create(H(s))}return new J({...e._def,shape:()=>t})}return e instanceof U?U.create(H(e.element)):e instanceof ue?ue.create(H(e.unwrap())):e instanceof pe?pe.create(H(e.unwrap())):e instanceof Y?Y.create(e.items.map((e=>H(e)))):e}class J extends O{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=K(this._def),this.extend=K(this._def)}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=o.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==c.object){const t=this._getOrReturnCtx(e);return f(t,{code:l.invalid_type,expected:c.object,received:t.parsedType}),y}const{status:t,ctx:n}=this._processInputParams(e),{shape:s,keys:a}=this._getCached(),r=[];if(!(this._def.catchall instanceof V&&"strip"===this._def.unknownKeys))for(const e in n.data)a.includes(e)||r.push(e);const i=[];for(const e of a){const t=s[e],a=n.data[e];i.push({key:{status:"valid",value:e},value:t._parse(new I(n,a,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof V){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of r)i.push({key:{status:"valid",value:e},value:{status:"valid",value:n.data[e]}});else if("strict"===e)r.length>0&&(f(n,{code:l.unrecognized_keys,keys:r}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of r){const s=n.data[t];i.push({key:{status:"valid",value:t},value:e._parse(new I(n,s,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then((async()=>{const e=[];for(const t of i){const n=await t.key;e.push({key:n,value:await t.value,alwaysSet:t.alwaysSet})}return e})).then((e=>v.mergeObjectSync(t,e))):v.mergeObjectSync(t,i)}get shape(){return this._def.shape()}strict(e){return S.errToObj,new J({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,n)=>{var s,a,r,i;const o=null!==(r=null===(a=(s=this._def).errorMap)||void 0===a?void 0:a.call(s,t,n).message)&&void 0!==r?r:n.defaultError;return"unrecognized_keys"===t.code?{message:null!==(i=S.errToObj(e).message)&&void 0!==i?i:o}:{message:o}}}:{}})}strip(){return new J({...this._def,unknownKeys:"strip"})}passthrough(){return new J({...this._def,unknownKeys:"passthrough"})}setKey(e,t){return this.augment({[e]:t})}merge(e){return new J({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>W.mergeShapes(this._def.shape(),e._def.shape()),typeName:be.ZodObject})}catchall(e){return new J({...this._def,catchall:e})}pick(e){const t={};return o.objectKeys(e).map((e=>{this.shape[e]&&(t[e]=this.shape[e])})),new J({...this._def,shape:()=>t})}omit(e){const t={};return o.objectKeys(this.shape).map((n=>{-1===o.objectKeys(e).indexOf(n)&&(t[n]=this.shape[n])})),new J({...this._def,shape:()=>t})}deepPartial(){return H(this)}partial(e){const t={};if(e)return o.objectKeys(this.shape).map((n=>{-1===o.objectKeys(e).indexOf(n)?t[n]=this.shape[n]:t[n]=this.shape[n].optional()})),new J({...this._def,shape:()=>t});for(const e in this.shape){const n=this.shape[e];t[e]=n.optional()}return new J({...this._def,shape:()=>t})}required(){const e={};for(const t in this.shape){let n=this.shape[t];for(;n instanceof ue;)n=n._def.innerType;e[t]=n}return new J({...this._def,shape:()=>e})}keyof(){return ie(o.objectKeys(this.shape))}}J.create=(e,t)=>new J({shape:()=>e,unknownKeys:"strip",catchall:V.create(),typeName:be.ZodObject,...k(t)}),J.strictCreate=(e,t)=>new J({shape:()=>e,unknownKeys:"strict",catchall:V.create(),typeName:be.ZodObject,...k(t)}),J.lazycreate=(e,t)=>new J({shape:e,unknownKeys:"strip",catchall:V.create(),typeName:be.ZodObject,...k(t)});class q extends O{_parse(e){const{ctx:t}=this._processInputParams(e),n=this._def.options;if(t.common.async)return Promise.all(n.map((async e=>{const n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}}))).then((function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const n of e)if("dirty"===n.result.status)return t.common.issues.push(...n.ctx.common.issues),n.result;const n=e.map((e=>new u(e.ctx.common.issues)));return f(t,{code:l.invalid_union,unionErrors:n}),y}));{let e;const s=[];for(const a of n){const n={...t,common:{...t.common,issues:[]},parent:null},r=a._parseSync({data:t.data,path:t.path,parent:n});if("valid"===r.status)return r;"dirty"!==r.status||e||(e={result:r,ctx:n}),n.common.issues.length&&s.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const a=s.map((e=>new u(e)));return f(t,{code:l.invalid_union,unionErrors:a}),y}}get options(){return this._def.options}}q.create=(e,t)=>new q({options:e,typeName:be.ZodUnion,...k(t)});class G extends O{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==c.object)return f(t,{code:l.invalid_type,expected:c.object,received:t.parsedType}),y;const n=this.discriminator,s=t.data[n],a=this.options.get(s);return a?t.common.async?a._parseAsync({data:t.data,path:t.path,parent:t}):a._parseSync({data:t.data,path:t.path,parent:t}):(f(t,{code:l.invalid_union_discriminator,options:this.validDiscriminatorValues,path:[n]}),y)}get discriminator(){return this._def.discriminator}get validDiscriminatorValues(){return Array.from(this.options.keys())}get options(){return this._def.options}static create(e,t,n){const s=new Map;try{t.forEach((t=>{const n=t.shape[e].value;s.set(n,t)}))}catch(e){throw new Error("The discriminator value could not be extracted from all the provided schemas")}if(s.size!==t.length)throw new Error("Some of the discriminator values are not unique");return new G({typeName:be.ZodDiscriminatedUnion,discriminator:e,options:s,...k(n)})}}function X(e,t){const n=d(e),s=d(t);if(e===t)return{valid:!0,data:e};if(n===c.object&&s===c.object){const n=o.objectKeys(t),s=o.objectKeys(e).filter((e=>-1!==n.indexOf(e))),a={...e,...t};for(const n of s){const s=X(e[n],t[n]);if(!s.valid)return{valid:!1};a[n]=s.data}return{valid:!0,data:a}}if(n===c.array&&s===c.array){if(e.length!==t.length)return{valid:!1};const n=[];for(let s=0;s<e.length;s++){const a=X(e[s],t[s]);if(!a.valid)return{valid:!1};n.push(a.data)}return{valid:!0,data:n}}return n===c.date&&s===c.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class Q extends O{_parse(e){const{status:t,ctx:n}=this._processInputParams(e),s=(e,s)=>{if(w(e)||w(s))return y;const a=X(e.value,s.value);return a.valid?((_(e)||_(s))&&t.dirty(),{status:t.value,value:a.data}):(f(n,{code:l.invalid_intersection_types}),y)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then((([e,t])=>s(e,t))):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}Q.create=(e,t,n)=>new Q({left:e,right:t,typeName:be.ZodIntersection,...k(n)});class Y extends O{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==c.array)return f(n,{code:l.invalid_type,expected:c.array,received:n.parsedType}),y;if(n.data.length<this._def.items.length)return f(n,{code:l.too_small,minimum:this._def.items.length,inclusive:!0,type:"array"}),y;!this._def.rest&&n.data.length>this._def.items.length&&(f(n,{code:l.too_big,maximum:this._def.items.length,inclusive:!0,type:"array"}),t.dirty());const s=n.data.map(((e,t)=>{const s=this._def.items[t]||this._def.rest;return s?s._parse(new I(n,e,n.path,t)):null})).filter((e=>!!e));return n.common.async?Promise.all(s).then((e=>v.mergeArray(t,e))):v.mergeArray(t,s)}get items(){return this._def.items}rest(e){return new Y({...this._def,rest:e})}}Y.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Y({items:e,typeName:be.ZodTuple,rest:null,...k(t)})};class ee extends O{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==c.object)return f(n,{code:l.invalid_type,expected:c.object,received:n.parsedType}),y;const s=[],a=this._def.keyType,r=this._def.valueType;for(const e in n.data)s.push({key:a._parse(new I(n,e,n.path,e)),value:r._parse(new I(n,n.data[e],n.path,e))});return n.common.async?v.mergeObjectAsync(t,s):v.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,n){return new ee(t instanceof O?{keyType:e,valueType:t,typeName:be.ZodRecord,...k(n)}:{keyType:N.create(),valueType:e,typeName:be.ZodRecord,...k(t)})}}class te extends O{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==c.map)return f(n,{code:l.invalid_type,expected:c.map,received:n.parsedType}),y;const s=this._def.keyType,a=this._def.valueType,r=[...n.data.entries()].map((([e,t],r)=>({key:s._parse(new I(n,e,n.path,[r,"key"])),value:a._parse(new I(n,t,n.path,[r,"value"]))})));if(n.common.async){const e=new Map;return Promise.resolve().then((async()=>{for(const n of r){const s=await n.key,a=await n.value;if("aborted"===s.status||"aborted"===a.status)return y;"dirty"!==s.status&&"dirty"!==a.status||t.dirty(),e.set(s.value,a.value)}return{status:t.value,value:e}}))}{const e=new Map;for(const n of r){const s=n.key,a=n.value;if("aborted"===s.status||"aborted"===a.status)return y;"dirty"!==s.status&&"dirty"!==a.status||t.dirty(),e.set(s.value,a.value)}return{status:t.value,value:e}}}}te.create=(e,t,n)=>new te({valueType:t,keyType:e,typeName:be.ZodMap,...k(n)});class ne extends O{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==c.set)return f(n,{code:l.invalid_type,expected:c.set,received:n.parsedType}),y;const s=this._def;null!==s.minSize&&n.data.size<s.minSize.value&&(f(n,{code:l.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,message:s.minSize.message}),t.dirty()),null!==s.maxSize&&n.data.size>s.maxSize.value&&(f(n,{code:l.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,message:s.maxSize.message}),t.dirty());const a=this._def.valueType;function r(e){const n=new Set;for(const s of e){if("aborted"===s.status)return y;"dirty"===s.status&&t.dirty(),n.add(s.value)}return{status:t.value,value:n}}const i=[...n.data.values()].map(((e,t)=>a._parse(new I(n,e,n.path,t))));return n.common.async?Promise.all(i).then((e=>r(e))):r(i)}min(e,t){return new ne({...this._def,minSize:{value:e,message:S.toString(t)}})}max(e,t){return new ne({...this._def,maxSize:{value:e,message:S.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ne.create=(e,t)=>new ne({valueType:e,minSize:null,maxSize:null,typeName:be.ZodSet,...k(t)});class se extends O{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==c.function)return f(t,{code:l.invalid_type,expected:c.function,received:t.parsedType}),y;function n(e,n){return g({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,m(),p].filter((e=>!!e)),issueData:{code:l.invalid_arguments,argumentsError:n}})}function s(e,n){return g({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,m(),p].filter((e=>!!e)),issueData:{code:l.invalid_return_type,returnTypeError:n}})}const a={errorMap:t.common.contextualErrorMap},r=t.data;return this._def.returns instanceof de?b((async(...e)=>{const t=new u([]),i=await this._def.args.parseAsync(e,a).catch((s=>{throw t.addIssue(n(e,s)),t})),o=await r(...i);return await this._def.returns._def.type.parseAsync(o,a).catch((e=>{throw t.addIssue(s(o,e)),t}))})):b(((...e)=>{const t=this._def.args.safeParse(e,a);if(!t.success)throw new u([n(e,t.error)]);const i=r(...t.data),o=this._def.returns.safeParse(i,a);if(!o.success)throw new u([s(i,o.error)]);return o.data}))}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new se({...this._def,args:Y.create(e).rest(z.create())})}returns(e){return new se({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new se({args:e||Y.create([]).rest(z.create()),returns:t||z.create(),typeName:be.ZodFunction,...k(n)})}}class ae extends O{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}ae.create=(e,t)=>new ae({getter:e,typeName:be.ZodLazy,...k(t)});class re extends O{_parse(e){if(e.data!==this._def.value){return f(this._getOrReturnCtx(e),{code:l.invalid_literal,expected:this._def.value}),y}return{status:"valid",value:e.data}}get value(){return this._def.value}}function ie(e,t){return new oe({values:e,typeName:be.ZodEnum,...k(t)})}re.create=(e,t)=>new re({value:e,typeName:be.ZodLiteral,...k(t)});class oe extends O{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),n=this._def.values;return f(t,{expected:o.joinValues(n),received:t.parsedType,code:l.invalid_type}),y}if(-1===this._def.values.indexOf(e.data)){const t=this._getOrReturnCtx(e),n=this._def.values;return f(t,{received:t.data,code:l.invalid_enum_value,options:n}),y}return b(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}}oe.create=ie;class ce extends O{_parse(e){const t=o.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==c.string&&n.parsedType!==c.number){const e=o.objectValues(t);return f(n,{expected:o.joinValues(e),received:n.parsedType,code:l.invalid_type}),y}if(-1===t.indexOf(e.data)){const e=o.objectValues(t);return f(n,{received:n.data,code:l.invalid_enum_value,options:e}),y}return b(e.data)}get enum(){return this._def.values}}ce.create=(e,t)=>new ce({values:e,typeName:be.ZodNativeEnum,...k(t)});class de extends O{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==c.promise&&!1===t.common.async)return f(t,{code:l.invalid_type,expected:c.promise,received:t.parsedType}),y;const n=t.parsedType===c.promise?t.data:Promise.resolve(t.data);return b(n.then((e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap}))))}}de.create=(e,t)=>new de({type:e,typeName:be.ZodPromise,...k(t)});class le extends O{innerType(){return this._def.schema}_parse(e){const{status:t,ctx:n}=this._processInputParams(e),s=this._def.effect||null;if("preprocess"===s.type){const e=s.transform(n.data);return n.common.async?Promise.resolve(e).then((e=>this._def.schema._parseAsync({data:e,path:n.path,parent:n}))):this._def.schema._parseSync({data:e,path:n.path,parent:n})}const a={addIssue:e=>{f(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(a.addIssue=a.addIssue.bind(a),"refinement"===s.type){const e=e=>{const t=s.refinement(e,a);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===n.common.async){const s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return"aborted"===s.status?y:("dirty"===s.status&&t.dirty(),e(s.value),{status:t.value,value:s.value})}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then((n=>"aborted"===n.status?y:("dirty"===n.status&&t.dirty(),e(n.value).then((()=>({status:t.value,value:n.value}))))))}if("transform"===s.type){if(!1===n.common.async){const e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!x(e))return e;const r=s.transform(e.value,a);if(r instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:r}}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then((e=>x(e)?Promise.resolve(s.transform(e.value,a)).then((e=>({status:t.value,value:e}))):e))}o.assertNever(s)}}le.create=(e,t,n)=>new le({schema:e,typeName:be.ZodEffects,effect:t,...k(n)}),le.createWithPreprocess=(e,t,n)=>new le({schema:t,effect:{type:"preprocess",transform:e},typeName:be.ZodEffects,...k(n)});class ue extends O{_parse(e){return this._getType(e)===c.undefined?b(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ue.create=(e,t)=>new ue({innerType:e,typeName:be.ZodOptional,...k(t)});class pe extends O{_parse(e){return this._getType(e)===c.null?b(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}pe.create=(e,t)=>new pe({innerType:e,typeName:be.ZodNullable,...k(t)});class he extends O{_parse(e){const{ctx:t}=this._processInputParams(e);let n=t.data;return t.parsedType===c.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}he.create=(e,t)=>new ue({innerType:e,typeName:be.ZodOptional,...k(t)});class me extends O{_parse(e){if(this._getType(e)!==c.nan){const t=this._getOrReturnCtx(e);return f(t,{code:l.invalid_type,expected:c.nan,received:t.parsedType}),y}return{status:"valid",value:e.data}}}me.create=e=>new me({typeName:be.ZodNaN,...k(e)});const ge=Symbol("zod_brand");class fe extends O{_parse(e){const{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}}const ve=(e,t={},n)=>e?F.create().superRefine(((s,a)=>{if(!e(s)){const e="function"==typeof t?t(s):t,r="string"==typeof e?{message:e}:e;a.addIssue({code:"custom",...r,fatal:n})}})):F.create(),ye={object:J.lazycreate};var be;!function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded"}(be||(be={}));const we=N.create,_e=j.create,xe=me.create,Ce=M.create,Se=A.create,Ie=L.create,Te=Z.create,ke=B.create,Oe=F.create,Ee=z.create,Pe=V.create,De=$.create,Ne=U.create,Re=J.create,je=J.strictCreate,Me=q.create,Ae=G.create,Le=Q.create,Ze=Y.create,Be=ee.create,Fe=te.create,ze=ne.create,Ve=se.create,$e=ae.create,Ue=re.create,We=oe.create,Ke=ce.create,He=de.create,Je=le.create,qe=ue.create,Ge=pe.create,Xe=le.createWithPreprocess,Qe=y;var Ye=Object.freeze({__proto__:null,getParsedType:d,ZodParsedType:c,defaultErrorMap:p,setErrorMap:function(e){h=e},getErrorMap:m,makeIssue:g,EMPTY_PATH:[],addIssueToContext:f,ParseStatus:v,INVALID:y,DIRTY:e=>({status:"dirty",value:e}),OK:b,isAborted:w,isDirty:_,isValid:x,isAsync:C,ZodType:O,ZodString:N,ZodNumber:j,ZodBigInt:M,ZodBoolean:A,ZodDate:L,ZodUndefined:Z,ZodNull:B,ZodAny:F,ZodUnknown:z,ZodNever:V,ZodVoid:$,ZodArray:U,get objectUtil(){return W},ZodObject:J,ZodUnion:q,ZodDiscriminatedUnion:G,ZodIntersection:Q,ZodTuple:Y,ZodRecord:ee,ZodMap:te,ZodSet:ne,ZodFunction:se,ZodLazy:ae,ZodLiteral:re,ZodEnum:oe,ZodNativeEnum:ce,ZodPromise:de,ZodEffects:le,ZodTransformer:le,ZodOptional:ue,ZodNullable:pe,ZodDefault:he,ZodNaN:me,BRAND:ge,ZodBranded:fe,custom:ve,Schema:O,ZodSchema:O,late:ye,get ZodFirstPartyTypeKind(){return be},any:Oe,array:Ne,bigint:Ce,boolean:Se,date:Ie,discriminatedUnion:Ae,effect:Je,enum:We,function:Ve,instanceof:(e,t={message:`Input not instance of ${e.name}`})=>ve((t=>t instanceof e),t,!0),intersection:Le,lazy:$e,literal:Ue,map:Fe,nan:xe,nativeEnum:Ke,never:Pe,null:ke,nullable:Ge,number:_e,object:Re,oboolean:()=>Se().optional(),onumber:()=>_e().optional(),optional:qe,ostring:()=>we().optional(),preprocess:Xe,promise:He,record:Be,set:ze,strictObject:je,string:we,transformer:Je,tuple:Ze,undefined:Te,union:Me,unknown:Ee,void:De,NEVER:Qe,ZodIssueCode:l,quotelessJson:e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),ZodError:u});const et=e("command parser");function tt(e,t){const n=t.safeParse(e);if(n.success)return n.data;et(`Command ${JSON.stringify(e)} parse failed: ${JSON.stringify(n)}.`);const s=n.error.errors.map((e=>`${e.message} in ${e.path.map((e=>JSON.stringify(e))).join("/")}.`)).join(" ");throw new a(s)}var nt,st,at,rt,it,ot;!function(e){e.RemoteReferenceSchema=Ye.object({handle:Ye.string().min(1)});const t=Ye.object({type:Ye.literal("undefined")}),n=Ye.object({type:Ye.literal("null")}),s=Ye.object({type:Ye.literal("string"),value:Ye.string()}),a=Ye.enum(["NaN","-0","Infinity","+Infinity","-Infinity"]),r=Ye.object({type:Ye.literal("number"),value:Ye.union([a,Ye.number()])}),i=Ye.object({type:Ye.literal("boolean"),value:Ye.boolean()}),o=Ye.object({type:Ye.literal("bigint"),value:Ye.string()}),c=Ye.union([t,n,s,r,i,o]);e.LocalValueSchema=Ye.lazy((()=>Ye.union([c,u,p,m,g,f,v])));const d=Ye.union([e.RemoteReferenceSchema,e.LocalValueSchema]),l=Ye.array(d),u=Ye.lazy((()=>Ye.object({type:Ye.literal("array"),value:l}))),p=Ye.object({type:Ye.literal("date"),value:Ye.string().min(1)}),h=Ye.lazy((()=>Ye.tuple([Ye.union([Ye.string(),d]),d]))),m=Ye.object({type:Ye.literal("map"),value:Ye.array(h)}),g=Ye.object({type:Ye.literal("object"),value:Ye.array(h)}),f=Ye.lazy((()=>Ye.object({type:Ye.literal("regexp"),value:Ye.object({pattern:Ye.string(),flags:Ye.string().optional()})}))),v=Ye.lazy((()=>Ye.object({type:Ye.literal("set"),value:l})));e.BrowsingContextSchema=Ye.string()}(nt||(nt={})),function(e){const t=Ye.enum(["window","dedicated-worker","shared-worker","service-worker","worker","paint-worklet","audio-worklet","worklet"]),n=Ye.object({context:nt.BrowsingContextSchema.optional(),type:t.optional()});e.parseGetRealmsParams=function(e){return tt(e,n)};const s=Ye.object({context:nt.BrowsingContextSchema,sandbox:Ye.string().optional()}),a=Ye.object({realm:Ye.string().min(1)}),r=Ye.union([a,s]),i=Ye.enum(["root","none"]),o=Ye.object({expression:Ye.string(),awaitPromise:Ye.boolean(),target:r,resultOwnership:i.optional()});e.parseEvaluateParams=function(e){return tt(e,o)};const c=Ye.object({target:r,handles:Ye.array(Ye.string())});e.parseDisownParams=function(e){return tt(e,c)};const d=Ye.union([nt.RemoteReferenceSchema,nt.LocalValueSchema]),l=Ye.object({functionDeclaration:Ye.string(),target:r,arguments:Ye.array(d).optional(),this:d.optional(),awaitPromise:Ye.boolean(),resultOwnership:i.optional()});e.parseCallFunctionParams=function(e){return tt(e,l)}}(st||(st={})),function(e){const t=Ye.object({maxDepth:Ye.number().int().nonnegative().max(9007199254740991).optional(),root:nt.BrowsingContextSchema.optional()});e.parseGetTreeParams=function(e){return tt(e,t)};const n=Ye.enum(["none","interactive","complete"]),s=Ye.object({context:nt.BrowsingContextSchema,url:Ye.string().url(),wait:n.optional()});e.parseNavigateParams=function(e){return tt(e,s)};const a=Ye.object({type:Ye.enum(["tab","window"])});e.parseCreateParams=function(e){return tt(e,a)};const r=Ye.object({context:nt.BrowsingContextSchema});e.parseCloseParams=function(e){return tt(e,r)};class o extends i{static method="browsingContext.load";constructor(e){super(o.method,e)}}e.LoadEvent=o;class c extends i{static method="browsingContext.domContentLoaded";constructor(e){super(c.method,e)}}e.DomContentLoadedEvent=c;class d extends i{static method="browsingContext.contextCreated";constructor(e){super(d.method,e)}}e.ContextCreatedEvent=d;class l extends i{static method="browsingContext.contextDestroyed";constructor(e){super(l.method,e)}}e.ContextDestroyedEvent=l,function(e){const t=Ye.object({context:nt.BrowsingContextSchema,selector:Ye.string()});e.parseFindElementParams=function(e){return tt(e,t)}}(e.PROTO||(e.PROTO={})),e.EventNames=[o.method,c.method,d.method,l.method]}(at||(at={})),function(e){class t extends i{static method="log.entryAdded";constructor(e){super(t.method,e)}}e.LogEntryAddedEvent=t,e.EventNames=[t.method]}(rt||(rt={})),function(e){let t;!function(e){const t=Ye.object({cdpMethod:Ye.string(),cdpParams:Ye.object({}).passthrough(),cdpSession:Ye.string().optional()});e.parseSendCommandParams=function(e){return tt(e,t)};const n=Ye.object({context:nt.BrowsingContextSchema});e.parseGetSessionParams=function(e){return tt(e,n)};class s extends i{static method="PROTO.cdp.eventReceived";constructor(e){super(s.method,e)}}e.EventReceivedEvent=s}(t=e.PROTO||(e.PROTO={})),e.EventNames=[t.EventReceivedEvent.method]}(it||(it={})),function(e){const t=Ye.enum([...at.EventNames,...rt.EventNames,...it.EventNames]),n=Ye.object({events:Ye.array(t),contexts:Ye.array(nt.BrowsingContextSchema).optional()});e.parseSubscribeParams=function(e){return tt(e,n)}}(ot||(ot={}));class ct{#e=()=>{};#t=()=>{};#n;#s=!1;get isFinished(){return this.#s}constructor(){this.#n=new Promise(((e,t)=>{this.#e=e,this.#t=t}))}then(e,t){return this.#n.then(e,t)}catch(e){return this.#n.catch(e)}resolve(e){this.#s=!0,this.#e(e)}reject(e){this.#s=!0,this.#t(e)}finally(e){return this.#n.finally(e)}[Symbol.toStringTag]="Promise"}const dt=["%s","%d","%i","%f","%o","%O","%c"];function lt(e){return dt.some((t=>e.includes(t)))}function ut(e){if(!["array","bigint","date","number","object","string"].includes(e.type))return pt(e);if("bigint"===e.type)return e.value.toString()+"n";if("number"===e.type)return e.value.toString();if(["date","string"].includes(e.type))return JSON.stringify(e.value);if("object"===e.type)return"{"+e.value.map((e=>`${JSON.stringify(e[0])}:${ut(e[1])}`)).join(",")+"}";if("array"===e.type)return"["+e.value.map((e=>ut(e))).join(",")+"]";throw Error("Invalid value type: "+e.toString())}function pt(e){if(!e.hasOwnProperty("value"))return e.type;switch(e.type){case"string":case"number":case"boolean":case"bigint":return e.value;case"regexp":return`/${e.value.pattern}/${e.value.flags}`;case"date":return new Date(e.value).toString();case"object":return`Object(${e.value.length})`;case"array":return`Array(${e.value.length})`;case"map":return`Map(${e.value.length})`;case"set":return`Set(${e.value.length})`;case"node":return"node";default:return e.type}}function ht(e,t){return 0==e.length?"":"string"===e[0].type&<(e[0].value.toString())&&t?function(e){let t="";const n=e[0].value.toString(),s=e.slice(1,void 0),a=n.split(new RegExp(dt.map((e=>"("+e+")")).join("|"),"g"));for(const n of a)if(void 0!==n&&""!=n)if(lt(n)){const a=s.shift();if(void 0===a)throw new Error('Less value is provided: "'+ht(e,!1)+'"');"%s"===n?t+=pt(a):"%d"===n||"%i"===n?["bigint","number","string"].includes(a.type)?t+=parseInt(a.value.toString(),10):t+="NaN":"%f"===n?["bigint","number","string"].includes(a.type)?t+=parseFloat(a.value.toString()):t+="NaN":t+=ut(a)}else t+=n;if(s.length>0)throw new Error('More value is provided: "'+ht(e,!1)+'"');return t}(e):e.map((e=>pt(e))).join(" ")}class mt{static#a=0;static#r=1;static#i=new Map;static async serializeCdpObject(e,t,n){const s=await n.cdpClient.Runtime.callFunctionOn({functionDeclaration:String((e=>e)),awaitPromise:!1,arguments:[e],generateWebDriverValue:!0,executionContextId:n.executionContextId});return await this.#o(s,n,t)}static async stringifyObject(e,t){return(await t.cdpClient.Runtime.callFunctionOn({functionDeclaration:String((function(e){return String(e)})),awaitPromise:!1,arguments:[e],returnByValue:!0,executionContextId:t.executionContextId})).result.value}static async callFunction(e,t,n,s,r,i){const o=`(...args)=>{ return _callFunction((\n${t}\n), args);\n function _callFunction(f, args) {\n const deserializedThis = args.shift();\n const deserializedArgs = args;\n return f.apply(deserializedThis, deserializedArgs);\n }}`,c=[await this.#c(n,e)];let d;c.push(...await Promise.all(s.map((async t=>await this.#c(t,e)))));try{d=await e.cdpClient.Runtime.callFunctionOn({functionDeclaration:o,awaitPromise:r,arguments:c,generateWebDriverValue:!0,executionContextId:e.executionContextId})}catch(e){if(-32e3===e.code&&["Could not find object with given id","Argument should belong to the same JavaScript world as target object"].includes(e.message))throw new a("Handle was not found.");throw e}return d.exceptionDetails?{exceptionDetails:await this.#d(d.exceptionDetails,this.#r,i,e),realm:e.realmId}:{result:await mt.#o(d,e,i),realm:e.realmId}}static realmDestroyed(e){return Array.from(this.#i.entries()).filter((([t,n])=>n===e.realmId)).map((([e,t])=>this.#i.delete(e)))}static async disown(e,t){if(mt.#i.get(t)===e.realmId){try{await e.cdpClient.Runtime.releaseObject({objectId:t})}catch(e){if(-32e3!==e.code||"Invalid remote object id"!==e.message)throw e}this.#i.delete(t)}}static async#d(e,t,n,s){const a=e.stackTrace?.callFrames.map((e=>({url:e.url,functionName:e.functionName,lineNumber:e.lineNumber-t,columnNumber:e.columnNumber}))),r=await this.serializeCdpObject(e.exception,n,s),i=await this.stringifyObject(e.exception,s);return{exception:r,columnNumber:e.columnNumber,lineNumber:e.lineNumber-t,stackTrace:{callFrames:a||[]},text:i||e.text}}static async#o(e,t,n){const s=e.result.webDriverValue;if(!e.result.objectId)return s;const a=e.result.objectId,r=s;return"root"===n?(r.handle=a,this.#i.set(a,t.realmId)):await t.cdpClient.Runtime.releaseObject({objectId:a}),r}static async scriptEvaluate(e,t,n,s){let a=await e.cdpClient.Runtime.evaluate({contextId:e.executionContextId,expression:t,awaitPromise:n,generateWebDriverValue:!0});return a.exceptionDetails?{exceptionDetails:await this.#d(a.exceptionDetails,this.#a,s,e),realm:e.realmId}:{result:await mt.#o(a,e,s),realm:e.realmId}}static async#c(e,t){if("handle"in e)return{objectId:e.handle};switch(e.type){case"undefined":return{unserializableValue:"undefined"};case"null":return{unserializableValue:"null"};case"string":return{value:e.value};case"number":return"NaN"===e.value?{unserializableValue:"NaN"}:"-0"===e.value?{unserializableValue:"-0"}:"+Infinity"===e.value?{unserializableValue:"+Infinity"}:"Infinity"===e.value?{unserializableValue:"Infinity"}:"-Infinity"===e.value?{unserializableValue:"-Infinity"}:{value:e.value};case"boolean":return{value:!!e.value};case"bigint":return{unserializableValue:`BigInt(${JSON.stringify(e.value)})`};case"date":return{unserializableValue:`new Date(Date.parse(${JSON.stringify(e.value)}))`};case"regexp":return{unserializableValue:`new RegExp(${JSON.stringify(e.value.pattern)}, ${JSON.stringify(e.value.flags)})`};case"map":{const n=await this.#l(e.value,t);return{objectId:(await t.cdpClient.Runtime.callFunctionOn({functionDeclaration:String((function(...e){const t=new Map;for(let n=0;n<e.length;n+=2)t.set(e[n],e[n+1]);return t})),awaitPromise:!1,arguments:n,returnByValue:!1,executionContextId:t.executionContextId})).result.objectId}}case"object":{const n=await this.#l(e.value,t);return{objectId:(await t.cdpClient.Runtime.callFunctionOn({functionDeclaration:String((function(...e){const t={};for(let n=0;n<e.length;n+=2){t[e[n]]=e[n+1]}return t})),awaitPromise:!1,arguments:n,returnByValue:!1,executionContextId:t.executionContextId})).result.objectId}}case"array":{const n=await mt.#u(e.value,t);return{objectId:(await t.cdpClient.Runtime.callFunctionOn({functionDeclaration:String((function(...e){return e})),awaitPromise:!1,arguments:n,returnByValue:!1,executionContextId:t.executionContextId})).result.objectId}}case"set":{const n=await this.#u(e.value,t);return{objectId:(await t.cdpClient.Runtime.callFunctionOn({functionDeclaration:String((function(...e){return new Set(e)})),awaitPromise:!1,arguments:n,returnByValue:!1,executionContextId:t.executionContextId})).result.objectId}}default:throw new Error(`Value ${JSON.stringify(e)} is not deserializable.`)}}static async#l(e,t){const n=[];for(let s of e){const e=s[0],a=s[1];let r,i;r="string"==typeof e?{value:e}:await this.#c(e,t),i=await this.#c(a,t),n.push(r),n.push(i)}return n}static async#u(e,t){const n=[];for(let s of e)n.push(await this.#c(s,t));return n}}class gt{static#p=new Map;static getTopLevelContexts(){return Array.from(gt.#p.values()).filter((e=>null===e.parentId))}static removeContext(e){gt.#p.delete(e)}static addContext(e){gt.#p.set(e.contextId,e),null!==e.parentId&>.getKnownContext(e.parentId).addChild(e)}static hasKnownContext(e){return gt.#p.has(e)}static findContext(e){return gt.#p.get(e)}static getKnownContext(e){const t=gt.findContext(e);if(void 0===t)throw new r(`Context ${e} not found`);return t}}var ft;!function(e){e.window="window"}(ft||(ft={}));class vt{static#h=new Map;static create(e,t,n,s,a,r,i,o){const c=new vt(e,t,n,s,a,r,i,o);return vt.#h.set(c.realmId,c),c}static findRealms(e={}){return Array.from(vt.#h.values()).filter((t=>(void 0===e.realmId||e.realmId===t.realmId)&&((void 0===e.browsingContextId||e.browsingContextId===t.browsingContextId)&&((void 0===e.executionContextId||e.executionContextId===t.executionContextId)&&((void 0===e.type||e.type===t.type)&&((void 0===e.sandbox||e.sandbox===t.#m)&&(void 0===e.cdpSessionId||e.cdpSessionId===t.#g)))))))}static getRealm(e){const t=vt.findRealms(e);if(t.length>1)throw Error(`Multiple realms found. Filter: ${JSON.stringify(e)}.`);if(t.length<1)throw new r(`Realm ${JSON.stringify(e)} not found`);return t[0]}static clearBrowsingContext(e){vt.findRealms({browsingContextId:e}).map((e=>e.delete()))}delete(){vt.#h.delete(this.realmId),mt.realmDestroyed(this)}#f;#v;#y;#b;#w;#m;#g;#_;constructor(e,t,n,s,a,r,i,o){this.#f=e,this.#v=t,this.#y=n,this.#m=r,this.#b=s,this.#w=a,this.#g=i,this.#_=o}toBiDi(){return{realm:this.realmId,origin:this.origin,type:this.type,context:this.browsingContextId,...void 0!==this.#m?{sandbox:this.#m}:{}}}get realmId(){return this.#f}get browsingContextId(){return this.#v}get executionContextId(){return this.#y}get origin(){return this.#b}get type(){return this.#w}get cdpClient(){return this.#_}async callFunction(e,t,n,s,a){const r=gt.getKnownContext(this.browsingContextId);return await r.awaitUnblocked(),{result:await mt.callFunction(this,e,t,n,s,a)}}async scriptEvaluate(e,t,n){const s=gt.getKnownContext(this.browsingContextId);return await s.awaitUnblocked(),{result:await mt.scriptEvaluate(this,e,t,n)}}async disown(e){await mt.disown(this,e)}async serializeCdpObject(e,t){return await mt.serializeCdpObject(e,t,this)}async stringifyObject(e,t){return mt.stringifyObject(e,this)}}class yt{#x;#_;#C;#g;constructor(e,t,n,s){this.#g=n,this.#C=s,this.#_=t,this.#x=e}static create(e,t,n,s){const a=new yt(e,t,n,s);return a.#S(),a}#S(){this.#I()}#I(){this.#T()}#T(){this.#_.Runtime.on("consoleAPICalled",(async e=>{const t=vt.getRealm({cdpSessionId:this.#g,executionContextId:e.executionContextId}),n=await Promise.all(e.args.map((async e=>t.serializeCdpObject(e,"none"))));await this.#C.sendMessage(new rt.LogEntryAddedEvent({level:yt.#k(e.type),source:{realm:e.executionContextId.toString(),context:this.#x},text:ht(n,!0),timestamp:Math.round(e.timestamp),stackTrace:yt.#O(e.stackTrace),type:"console",method:"warning"===e.type?"warn":e.type,args:n}))})),this.#_.Runtime.on("exceptionThrown",(async e=>{const t=(()=>{if(void 0!==e.exceptionDetails.executionContextId)return vt.getRealm({cdpSessionId:this.#g,executionContextId:e.exceptionDetails.executionContextId})})(),n=await(async()=>e.exceptionDetails.exception?void 0===t?JSON.stringify(e.exceptionDetails.exception):await t.stringifyObject(e.exceptionDetails.exception,t):e.exceptionDetails.text)();await this.#C.sendMessage(new rt.LogEntryAddedEvent({level:"error",source:{realm:t?.realmId??"UNKNOWN",context:t?.browsingContextId??"UNKNOWN"},text:n,timestamp:Math.round(e.timestamp),stackTrace:yt.#O(e.exceptionDetails.stackTrace),type:"javascript"}))}))}static#k(e){return["assert","error"].includes(e)?"error":["debug","trace"].includes(e)?"debug":["warn","warning"].includes(e)?"warning":"info"}static#O(e){const t=e?.callFrames.map((e=>({columnNumber:e.columnNumber,functionName:e.functionName,lineNumber:e.lineNumber,url:e.url})));return t?{callFrames:t}:void 0}}var bt=at.LoadEvent;class wt{#E={documentInitialized:new ct,targetUnblocked:new ct,Page:{navigatedWithinDocument:new ct,lifecycleEvent:{DOMContentLoaded:new ct,load:new ct}}};#x;#P;#D="about:blank";#N=null;#g;#_;#C;#R;#j=new Map;#M;get#A(){if(void 0===this.#M)throw new Error(`No default realm for browsing context ${this.#x}`);return this.#M}constructor(e,t,n,s,a,r){this.#x=e,this.#P=t,this.#_=n,this.#R=r,this.#g=a,this.#C=s,this.#L(),gt.addContext(this)}static async createFrameContext(e,t,n,s,a,r){const i=new wt(e,t,n,s,a,r);i.#E.targetUnblocked.resolve(),await r.sendEvent(new at.ContextCreatedEvent(i.serializeToBidiValue()),i.contextId)}static async createTargetContext(e,t,n,s,a,r){const i=new wt(e,t,n,s,a,r);i.#Z(),await r.sendEvent(new at.ContextCreatedEvent(i.serializeToBidiValue()),i.contextId)}convertFrameToTargetContext(e,t){this.#B(e,t),this.#Z()}async delete(){if(await this.#F(),null!==this.parentId){gt.getKnownContext(this.parentId).#j.delete(this.contextId)}await this.#R.sendEvent(new at.ContextDestroyedEvent(this.serializeToBidiValue()),this.contextId),gt.removeContext(this.contextId)}async#F(){await Promise.all(this.children.map((e=>e.delete())))}#B(e,t){this.#E.targetUnblocked.isFinished||this.#E.targetUnblocked.reject("OOPiF"),this.#E.targetUnblocked=new ct,this.#_=e,this.#g=t,this.#L()}async#Z(){yt.create(this.#x,this.#_,this.#g,this.#C),await this.#_.Runtime.enable(),await this.#_.Page.enable(),await this.#_.Page.setLifecycleEventsEnabled({enabled:!0}),await this.#_.Target.setAutoAttach({autoAttach:!0,waitForDebuggerOnStart:!0,flatten:!0}),await this.#_.Runtime.runIfWaitingForDebugger(),this.#E.targetUnblocked.resolve()}get contextId(){return this.#x}get parentId(){return this.#P}get cdpSessionId(){return this.#g}get children(){return Array.from(this.#j.values())}get url(){return this.#D}addChild(e){this.#j.set(e.contextId,e)}async awaitLoaded(){await this.#E.Page.lifecycleEvent.load}async awaitUnblocked(){await this.#E.targetUnblocked}serializeToBidiValue(e=0,t=!0){return{context:this.#x,url:this.url,children:e>0?this.children.map((t=>t.serializeToBidiValue(e-1,!1))):null,...t?{parent:this.#P}:{}}}#L(){this.#_.Target.on("targetInfoChanged",(e=>{this.contextId===e.targetInfo.targetId&&(this.#D=e.targetInfo.url)})),this.#_.Page.on("frameNavigated",(async e=>{this.contextId===e.frame.id&&(this.#D=e.frame.url+(e.frame.urlFragment??""),await this.#F(),vt.clearBrowsingContext(this.contextId))})),this.#_.Page.on("navigatedWithinDocument",(e=>{this.contextId===e.frameId&&(this.#D=e.url,this.#E.Page.navigatedWithinDocument.resolve(e))})),this.#_.Page.on("lifecycleEvent",(async e=>{if(this.contextId===e.frameId)if("init"===e.name&&(this.#z(e.loaderId),this.#E.documentInitialized.resolve()),"commit"!==e.name){if(e.loaderId===this.#N)switch(e.name){case"DOMContentLoaded":this.#E.Page.lifecycleEvent.DOMContentLoaded.resolve(e),await this.#R.sendEvent(new at.DomContentLoadedEvent({context:this.contextId,navigation:this.#N,url:this.#D}),this.contextId);break;case"load":this.#E.Page.lifecycleEvent.load.resolve(e),await this.#R.sendEvent(new bt({context:this.contextId,navigation:this.#N,url:this.#D}),this.contextId)}}else this.#N=e.loaderId})),this.#_.Runtime.on("executionContextCreated",(e=>{if(e.context.auxData.frameId!==this.contextId)return;if(!["default","isolated"].includes(e.context.auxData.type))return;const t=vt.create(e.context.uniqueId,this.contextId,e.context.id,this.#V(e),ft.window,"isolated"===e.context.auxData.type?e.context.name:void 0,this.#g,this.#_);e.context.auxData.isDefault&&(this.#M=t)})),this.#_.Runtime.on("executionContextDestroyed",(e=>{vt.findRealms({cdpSessionId:this.#g,executionContextId:e.executionContextId}).map((e=>e.delete()))}))}#V(e){return"isolated"===e.context.auxData.type?this.#A.origin:["://",""].includes(e.context.origin)?"null":e.context.origin}#z(e){this.#N!==e&&(this.#E.documentInitialized.isFinished||this.#E.documentInitialized.reject("Document changed"),this.#E.documentInitialized=new ct,this.#E.Page.navigatedWithinDocument.isFinished||this.#E.Page.navigatedWithinDocument.reject("Document changed"),this.#E.Page.navigatedWithinDocument=new ct,this.#E.Page.lifecycleEvent.DOMContentLoaded.isFinished||this.#E.Page.lifecycleEvent.DOMContentLoaded.reject("Document changed"),this.#E.Page.lifecycleEvent.DOMContentLoaded=new ct,this.#E.Page.lifecycleEvent.load.isFinished||this.#E.Page.lifecycleEvent.load.reject("Document changed"),this.#E.Page.lifecycleEvent.load=new ct,this.#N=e)}async navigate(e,t){await this.#E.targetUnblocked;const s=await this.#_.Page.navigate({url:e,frameId:this.contextId});if(s.errorText)throw new n(s.errorText);switch(void 0!==s.loaderId&&s.loaderId!==this.#N&&this.#z(s.loaderId),t){case"none":break;case"interactive":void 0===s.loaderId?await this.#E.Page.navigatedWithinDocument:await this.#E.Page.lifecycleEvent.DOMContentLoaded;break;case"complete":void 0===s.loaderId?await this.#E.Page.navigatedWithinDocument:await this.#E.Page.lifecycleEvent.load;break;default:throw new Error(`Not implemented wait '${t}'`)}return{result:{navigation:s.loaderId||null,url:e}}}async findElement(e){await this.#E.targetUnblocked;const t=String((e=>document.querySelector(e))),n=[{type:"string",value:e}];return await this.#A.callFunction(t,{type:"undefined"},n,!0,"root")}async getOrCreateSandbox(e){if(void 0===e||""===e)return this.#A;let t=vt.findRealms({browsingContextId:this.contextId,sandbox:e});if(0==t.length&&(await this.#_.Page.createIsolatedWorld({frameId:this.contextId,worldName:e}),t=vt.findRealms({browsingContextId:this.contextId,sandbox:e})),1!==t.length)throw Error(`Sandbox ${e} wasn't created.`);return t[0]}}const _t=e("context");class xt{sessions=new Set;#$;#U;#C;#R;constructor(e,t,n,s){this.#$=e,this.#U=t,this.#C=n,this.#R=s,this.#W(this.#$.browserClient())}#W(e){this.#K(e)}#K(e){e.Target.on("attachedToTarget",(async t=>{await this.#H(t,e)})),e.Target.on("detachedFromTarget",(async e=>{await xt.#J(e)}))}#q(e){if(this.sessions.has(e))return;this.sessions.add(e);const t=this.#$.getCdpClient(e);this.#K(t),t.on("event",(async(t,n)=>{await this.#R.sendEvent({method:"PROTO.cdp.eventReceived",params:{cdpMethod:t,cdpParams:n,cdpSession:e}},null)})),t.Page.on("frameAttached",(async n=>{await wt.createFrameContext(n.frameId,n.parentFrameId,t,this.#C,e,this.#R)}))}async#H(e,t){_t("AttachedToTarget event received: "+JSON.stringify(e));const{sessionId:n,targetInfo:s}=e;let a=this.#$.getCdpClient(n);if(!this.#G(s))return await a.Runtime.runIfWaitingForDebugger(),void await t.Target.detachFromTarget(e);this.#q(n),gt.hasKnownContext(s.targetId)?gt.getKnownContext(s.targetId).convertFrameToTargetContext(a,n):await wt.createTargetContext(s.targetId,null,a,this.#C,n,this.#R)}static async#J(e){const t=e.targetId;await(gt.findContext(t)?.delete())}async process_browsingContext_getTree(e){return{result:{contexts:(void 0===e.root?gt.getTopLevelContexts():[gt.getKnownContext(e.root)]).map((t=>t.serializeToBidiValue(e.maxDepth??Number.MAX_VALUE)))}}}async process_browsingContext_create(e){const t=this.#$.browserClient(),n=(await t.Target.createTarget({url:"about:blank",newWindow:"window"===e.type})).targetId,s=gt.getKnownContext(n);return await s.awaitLoaded(),{result:s.serializeToBidiValue(1)}}async process_browsingContext_navigate(e){const t=gt.getKnownContext(e.context);return await t.navigate(e.url,void 0!==e.wait?e.wait:"none")}static async#X(e){if("realm"in e)return vt.getRealm({realmId:e.realm});const t=gt.getKnownContext(e.context);return await t.getOrCreateSandbox(e.sandbox)}async process_script_evaluate(e){const t=await xt.#X(e.target);return await t.scriptEvaluate(e.expression,e.awaitPromise,e.resultOwnership??"none")}process_script_getRealms(e){void 0!==e.context&>.getKnownContext(e.context);return{result:{realms:vt.findRealms({browsingContextId:e.context,type:e.type}).map((e=>e.toBiDi()))}}}async process_script_callFunction(e){const t=await xt.#X(e.target);return await t.callFunction(e.functionDeclaration,e.this||{type:"undefined"},e.arguments||[],e.awaitPromise,e.resultOwnership??"none")}async process_script_disown(e){const t=await xt.#X(e.target);return await Promise.all(e.handles.map((async e=>await t.disown(e)))),{result:{}}}async process_PROTO_browsingContext_findElement(e){const t=gt.getKnownContext(e.context);return await t.findElement(e.selector)}async process_browsingContext_close(e){const t=this.#$.browserClient();if(null!==gt.getKnownContext(e.context).parentId)throw new a("Not a top-level browsing context cannot be closed.");const n=new Promise((async n=>{const s=a=>{a.targetId===e.context&&(t.Target.removeListener("detachedFromTarget",s),n())};t.Target.on("detachedFromTarget",s)}));return await this.#$.browserClient().Target.closeTarget({targetId:e.context}),await n,{result:{}}}#G(e){return e.targetId!==this.#U&&["page","iframe"].includes(e.type)}async process_PROTO_cdp_sendCommand(e){return{result:await this.#$.sendCommand(e.cdpMethod,e.cdpParams,e.cdpSession??null),cdpSession:e.cdpSession}}async process_PROTO_cdp_getSession(e){const t=e.context,n=gt.getKnownContext(t).cdpSessionId;return void 0===n?{result:{cdpSession:null}}:{result:{cdpSession:n}}}}class Ct{#Q;#C;#R;static run(e,t,n,s){new Ct(e,t,n,s).#Y()}constructor(e,t,n,s){this.#R=n,this.#C=t,this.#Q=new xt(e,s,t,n)}#Y(){this.#C.on("message",(e=>this.#ee(e)))}async#te(){return{result:{ready:!1,message:"already connected"}}}async#ne(e){return await this.#R.subscribe(e.events,e.contexts??null),{result:{}}}async#se(e){return await this.#R.unsubscribe(e.events,e.contexts??null),{result:{}}}async#ae(e){switch(e.method){case"session.status":return await this.#te();case"session.subscribe":return await this.#ne(ot.parseSubscribeParams(e.params));case"session.unsubscribe":return await this.#se(ot.parseSubscribeParams(e.params));case"browsingContext.create":return await this.#Q.process_browsingContext_create(at.parseCreateParams(e.params));case"browsingContext.close":return await this.#Q.process_browsingContext_close(at.parseCloseParams(e.params));case"browsingContext.getTree":return await this.#Q.process_browsingContext_getTree(at.parseGetTreeParams(e.params));case"browsingContext.navigate":return await this.#Q.process_browsingContext_navigate(at.parseNavigateParams(e.params));case"script.getRealms":return this.#Q.process_script_getRealms(st.parseGetRealmsParams(e.params));case"script.callFunction":return await this.#Q.process_script_callFunction(st.parseCallFunctionParams(e.params));case"script.evaluate":return await this.#Q.process_script_evaluate(st.parseEvaluateParams(e.params));case"script.disown":return await this.#Q.process_script_disown(st.parseDisownParams(e.params));case"PROTO.browsingContext.findElement":return await this.#Q.process_PROTO_browsingContext_findElement(at.PROTO.parseFindElementParams(e.params));case"PROTO.cdp.sendCommand":return await this.#Q.process_PROTO_cdp_sendCommand(it.PROTO.parseSendCommandParams(e.params));case"PROTO.cdp.getSession":return await this.#Q.process_PROTO_cdp_getSession(it.PROTO.parseGetSessionParams(e.params));default:throw new s(`Unknown command '${e.method}'.`)}}#ee=async e=>{try{const t=await this.#ae(e),n={id:e.id,...t};await this.#C.sendMessage(n)}catch(s){if(s instanceof t){const t=s;await this.#C.sendMessage(t.toErrorResponse(e.id))}else{const t=s;console.error(t),await this.#C.sendMessage(new n(t.message).toErrorResponse(e.id))}}}}function St(){}function It(){It.init.call(this)}function Tt(e){return void 0===e._maxListeners?It.defaultMaxListeners:e._maxListeners}function kt(e,t,n){if(t)e.call(n);else for(var s=e.length,a=Mt(e,s),r=0;r<s;++r)a[r].call(n)}function Ot(e,t,n,s){if(t)e.call(n,s);else for(var a=e.length,r=Mt(e,a),i=0;i<a;++i)r[i].call(n,s)}function Et(e,t,n,s,a){if(t)e.call(n,s,a);else for(var r=e.length,i=Mt(e,r),o=0;o<r;++o)i[o].call(n,s,a)}function Pt(e,t,n,s,a,r){if(t)e.call(n,s,a,r);else for(var i=e.length,o=Mt(e,i),c=0;c<i;++c)o[c].call(n,s,a,r)}function Dt(e,t,n,s){if(t)e.apply(n,s);else for(var a=e.length,r=Mt(e,a),i=0;i<a;++i)r[i].apply(n,s)}function Nt(e,t,n,s){var a,r,i,o;if("function"!=typeof n)throw new TypeError('"listener" argument must be a function');if((r=e._events)?(r.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),r=e._events),i=r[t]):(r=e._events=new St,e._eventsCount=0),i){if("function"==typeof i?i=r[t]=s?[n,i]:[i,n]:s?i.unshift(n):i.push(n),!i.warned&&(a=Tt(e))&&a>0&&i.length>a){i.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+i.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=i.length,o=c,"function"==typeof console.warn?console.warn(o):console.log(o)}}else i=r[t]=n,++e._eventsCount;return e}function Rt(e,t,n){var s=!1;function a(){e.removeListener(t,a),s||(s=!0,n.apply(e,arguments))}return a.listener=n,a}function jt(e){var t=this._events;if(t){var n=t[e];if("function"==typeof n)return 1;if(n)return n.length}return 0}function Mt(e,t){for(var n=new Array(t);t--;)n[t]=e[t];return n}St.prototype=Object.create(null),It.EventEmitter=It,It.usingDomains=!1,It.prototype.domain=void 0,It.prototype._events=void 0,It.prototype._maxListeners=void 0,It.defaultMaxListeners=10,It.init=function(){this.domain=null,It.usingDomains&&undefined.active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new St,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},It.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},It.prototype.getMaxListeners=function(){return Tt(this)},It.prototype.emit=function(e){var t,n,s,a,r,i,o,c="error"===e;if(i=this._events)c=c&&null==i.error;else if(!c)return!1;if(o=this.domain,c){if(t=arguments[1],!o){if(t instanceof Error)throw t;var d=new Error('Uncaught, unspecified "error" event. ('+t+")");throw d.context=t,d}return t||(t=new Error('Uncaught, unspecified "error" event')),t.domainEmitter=this,t.domain=o,t.domainThrown=!1,o.emit("error",t),!1}if(!(n=i[e]))return!1;var l="function"==typeof n;switch(s=arguments.length){case 1:kt(n,l,this);break;case 2:Ot(n,l,this,arguments[1]);break;case 3:Et(n,l,this,arguments[1],arguments[2]);break;case 4:Pt(n,l,this,arguments[1],arguments[2],arguments[3]);break;default:for(a=new Array(s-1),r=1;r<s;r++)a[r-1]=arguments[r];Dt(n,l,this,a)}return!0},It.prototype.addListener=function(e,t){return Nt(this,e,t,!1)},It.prototype.on=It.prototype.addListener,It.prototype.prependListener=function(e,t){return Nt(this,e,t,!0)},It.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,Rt(this,e,t)),this},It.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,Rt(this,e,t)),this},It.prototype.removeListener=function(e,t){var n,s,a,r,i;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(s=this._events))return this;if(!(n=s[e]))return this;if(n===t||n.listener&&n.listener===t)0==--this._eventsCount?this._events=new St:(delete s[e],s.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(a=-1,r=n.length;r-- >0;)if(n[r]===t||n[r].listener&&n[r].listener===t){i=n[r].listener,a=r;break}if(a<0)return this;if(1===n.length){if(n[0]=void 0,0==--this._eventsCount)return this._events=new St,this;delete s[e]}else!function(e,t){for(var n=t,s=n+1,a=e.length;s<a;n+=1,s+=1)e[n]=e[s];e.pop()}(n,a);s.removeListener&&this.emit("removeListener",e,i||t)}return this},It.prototype.removeAllListeners=function(e){var t,n;if(!(n=this._events))return this;if(!n.removeListener)return 0===arguments.length?(this._events=new St,this._eventsCount=0):n[e]&&(0==--this._eventsCount?this._events=new St:delete n[e]),this;if(0===arguments.length){for(var s,a=Object.keys(n),r=0;r<a.length;++r)"removeListener"!==(s=a[r])&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=new St,this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(t)do{this.removeListener(e,t[t.length-1])}while(t[0]);return this},It.prototype.listeners=function(e){var t,n=this._events;return n&&(t=n[e])?"function"==typeof t?[t.listener||t]:function(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(t):[]},It.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):jt.call(e,t)},It.prototype.listenerCount=jt,It.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};const At=[{domain:"Accessibility",commands:["disable","enable","getPartialAXTree","getFullAXTree","getRootAXNode","getAXNodeAndAncestors","getChildAXNodes","queryAXTree"]},{domain:"Animation",commands:["disable","enable","getCurrentTime","getPlaybackRate","releaseAnimations","resolveAnimation","seekAnimations","setPaused","setPlaybackRate","setTiming"]},{domain:"Audits",commands:["getEncodedResponse","disable","enable","checkContrast"]},{domain:"BackgroundService",commands:["startObserving","stopObserving","setRecording","clearEvents"]},{domain:"Browser",commands:["setPermission","grantPermissions","resetPermissions","setDownloadBehavior","cancelDownload","close","crash","crashGpuProcess","getVersion","getBrowserCommandLine","getHistograms","getHistogram","getWindowBounds","getWindowForTarget","setWindowBounds","setDockTile","executeBrowserCommand"]},{domain:"CSS",commands:["addRule","collectClassNames","createStyleSheet","disable","enable","forcePseudoState","getBackgroundColors","getComputedStyleForNode","getInlineStylesForNode","getMatchedStylesForNode","getMediaQueries","getPlatformFontsForNode","getStyleSheetText","getLayersForNode","trackComputedStyleUpdates","takeComputedStyleUpdates","setEffectivePropertyValueForNode","setKeyframeKey","setMediaText","setContainerQueryText","setSupportsText","setRuleSelector","setStyleSheetText","setStyleTexts","startRuleUsageTracking","stopRuleUsageTracking","takeCoverageDelta","setLocalFontsEnabled"]},{domain:"CacheStorage",commands:["deleteCache","deleteEntry","requestCacheNames","requestCachedResponse","requestEntries"]},{domain:"Cast",commands:["enable","disable","setSinkToUse","startDesktopMirroring","startTabMirroring","stopCasting"]},{domain:"DOM",commands:["collectClassNamesFromSubtree","copyTo","describeNode","scrollIntoViewIfNeeded","disable","discardSearchResults","enable","focus","getAttributes","getBoxModel","getContentQuads","getDocument","getFlattenedDocument","getNodesForSubtreeByStyle","getNodeForLocation","getOuterHTML","getRelayoutBoundary","getSearchResults","hideHighlight","highlightNode","highlightRect","markUndoableState","moveTo","performSearch","pushNodeByPathToFrontend","pushNodesByBackendIdsToFrontend","querySelector","querySelectorAll","redo","removeAttribute","removeNode","requestChildNodes","requestNode","resolveNode","setAttributeValue","setAttributesAsText","setFileInputFiles","setNodeStackTracesEnabled","getNodeStackTraces","getFileInfo","setInspectedNode","setNodeName","setNodeValue","setOuterHTML","undo","getFrameOwner","getContainerForNode","getQueryingDescendantsForContainer"]},{domain:"DOMDebugger",commands:["getEventListeners","removeDOMBreakpoint","removeEventListenerBreakpoint","removeInstrumentationBreakpoint","removeXHRBreakpoint","setBreakOnCSPViolation","setDOMBreakpoint","setEventListenerBreakpoint","setInstrumentationBreakpoint","setXHRBreakpoint"]},{domain:"EventBreakpoints",commands:["setInstrumentationBreakpoint","removeInstrumentationBreakpoint"]},{domain:"DOMSnapshot",commands:["disable","enable","getSnapshot","captureSnapshot"]},{domain:"DOMStorage",commands:["clear","disable","enable","getDOMStorageItems","removeDOMStorageItem","setDOMStorageItem"]},{domain:"Database",commands:["disable","enable","executeSQL","getDatabaseTableNames"]},{domain:"DeviceOrientation",commands:["clearDeviceOrientationOverride","setDeviceOrientationOverride"]},{domain:"Emulation",commands:["canEmulate","clearDeviceMetricsOverride","clearGeolocationOverride","resetPageScaleFactor","setFocusEmulationEnabled","setAutoDarkModeOverride","setCPUThrottlingRate","setDefaultBackgroundColorOverride","setDeviceMetricsOverride","setScrollbarsHidden","setDocumentCookieDisabled","setEmitTouchEventsForMouse","setEmulatedMedia","setEmulatedVisionDeficiency","setGeolocationOverride","setIdleOverride","clearIdleOverride","setNavigatorOverrides","setPageScaleFactor","setScriptExecutionDisabled","setTouchEmulationEnabled","setVirtualTimePolicy","setLocaleOverride","setTimezoneOverride","setVisibleSize","setDisabledImageTypes","setHardwareConcurrencyOverride","setUserAgentOverride","setAutomationOverride"]},{domain:"HeadlessExperimental",commands:["beginFrame","disable","enable"]},{domain:"IO",commands:["close","read","resolveBlob"]},{domain:"IndexedDB",commands:["clearObjectStore","deleteDatabase","deleteObjectStoreEntries","disable","enable","requestData","getMetadata","requestDatabase","requestDatabaseNames"]},{domain:"Input",commands:["dispatchDragEvent","dispatchKeyEvent","insertText","imeSetComposition","dispatchMouseEvent","dispatchTouchEvent","emulateTouchFromMouseEvent","setIgnoreInputEvents","setInterceptDrags","synthesizePinchGesture","synthesizeScrollGesture","synthesizeTapGesture"]},{domain:"Inspector",commands:["disable","enable"]},{domain:"LayerTree",commands:["compositingReasons","disable","enable","loadSnapshot","makeSnapshot","profileSnapshot","releaseSnapshot","replaySnapshot","snapshotCommandLog"]},{domain:"Log",commands:["clear","disable","enable","startViolationsReport","stopViolationsReport"]},{domain:"Memory",commands:["getDOMCounters","prepareForLeakDetection","forciblyPurgeJavaScriptMemory","setPressureNotificationsSuppressed","simulatePressureNotification","startSampling","stopSampling","getAllTimeSamplingProfile","getBrowserSamplingProfile","getSamplingProfile"]},{domain:"Network",commands:["setAcceptedEncodings","clearAcceptedEncodingsOverride","canClearBrowserCache","canClearBrowserCookies","canEmulateNetworkConditions","clearBrowserCache","clearBrowserCookies","continueInterceptedRequest","deleteCookies","disable","emulateNetworkConditions","enable","getAllCookies","getCertificate","getCookies","getResponseBody","getRequestPostData","getResponseBodyForInterception","takeResponseBodyForInterceptionAsStream","replayXHR","searchInResponseBody","setBlockedURLs","setBypassServiceWorker","setCacheDisabled","setCookie","setCookies","setExtraHTTPHeaders","setAttachDebugStack","setRequestInterception","setUserAgentOverride","getSecurityIsolationStatus","enableReportingApi","loadNetworkResource"]},{domain:"Overlay",commands:["disable","enable","getHighlightObjectForTest","getGridHighlightObjectsForTest","getSourceOrderHighlightObjectForTest","hideHighlight","highlightFrame","highlightNode","highlightQuad","highlightRect","highlightSourceOrder","setInspectMode","setShowAdHighlights","setPausedInDebuggerMessage","setShowDebugBorders","setShowFPSCounter","setShowGridOverlays","setShowFlexOverlays","setShowScrollSnapOverlays","setShowContainerQueryOverlays","setShowPaintRects","setShowLayoutShiftRegions","setShowScrollBottleneckRects","setShowHitTestBorders","setShowWebVitals","setShowViewportSizeOnResize","setShowHinge","setShowIsolatedElements"]},{domain:"Page",commands:["addScriptToEvaluateOnLoad","addScriptToEvaluateOnNewDocument","bringToFront","captureScreenshot","captureSnapshot","clearDeviceMetricsOverride","clearDeviceOrientationOverride","clearGeolocationOverride","createIsolatedWorld","deleteCookie","disable","enable","getAppManifest","getInstallabilityErrors","getManifestIcons","getAppId","getCookies","getFrameTree","getLayoutMetrics","getNavigationHistory","resetNavigationHistory","getResourceContent","getResourceTree","handleJavaScriptDialog","navigate","navigateToHistoryEntry","printToPDF","reload","removeScriptToEvaluateOnLoad","removeScriptToEvaluateOnNewDocument","screencastFrameAck","searchInResource","setAdBlockingEnabled","setBypassCSP","getPermissionsPolicyState","getOriginTrials","setDeviceMetricsOverride","setDeviceOrientationOverride","setFontFamilies","setFontSizes","setDocumentContent","setDownloadBehavior","setGeolocationOverride","setLifecycleEventsEnabled","setTouchEmulationEnabled","startScreencast","stopLoading","crash","close","setWebLifecycleState","stopScreencast","produceCompilationCache","addCompilationCache","clearCompilationCache","setSPCTransactionMode","generateTestReport","waitForDebugger","setInterceptFileChooserDialog"]},{domain:"Performance",commands:["disable","enable","setTimeDomain","getMetrics"]},{domain:"PerformanceTimeline",commands:["enable"]},{domain:"Security",commands:["disable","enable","setIgnoreCertificateErrors","handleCertificateError","setOverrideCertificateErrors"]},{domain:"ServiceWorker",commands:["deliverPushMessage","disable","dispatchSyncEvent","dispatchPeriodicSyncEvent","enable","inspectWorker","setForceUpdateOnPageLoad","skipWaiting","startWorker","stopAllWorkers","stopWorker","unregister","updateRegistration"]},{domain:"Storage",commands:["getStorageKeyForFrame","clearDataForOrigin","getCookies","setCookies","clearCookies","getUsageAndQuota","overrideQuotaForOrigin","trackCacheStorageForOrigin","trackIndexedDBForOrigin","untrackCacheStorageForOrigin","untrackIndexedDBForOrigin","getTrustTokens","clearTrustTokens","getInterestGroupDetails","setInterestGroupTracking"]},{domain:"SystemInfo",commands:["getInfo","getProcessInfo"]},{domain:"Target",commands:["activateTarget","attachToTarget","attachToBrowserTarget","closeTarget","exposeDevToolsProtocol","createBrowserContext","getBrowserContexts","createTarget","detachFromTarget","disposeBrowserContext","getTargetInfo","getTargets","sendMessageToTarget","setAutoAttach","autoAttachRelated","setDiscoverTargets","setRemoteLocations"]},{domain:"Tethering",commands:["bind","unbind"]},{domain:"Tracing",commands:["end","getCategories","recordClockSyncMarker","requestMemoryDump","start"]},{domain:"Fetch",commands:["disable","enable","failRequest","fulfillRequest","continueRequest","continueWithAuth","continueResponse","getResponseBody","takeResponseBodyAsStream"]},{domain:"WebAudio",commands:["enable","disable","getRealtimeData"]},{domain:"WebAuthn",commands:["enable","disable","addVirtualAuthenticator","removeVirtualAuthenticator","addCredential","getCredential","getCredentials","removeCredential","clearCredentials","setUserVerified","setAutomaticPresenceSimulation"]},{domain:"Media",commands:["enable","disable"]},{domain:"Console",commands:["clearMessages","disable","enable"]},{domain:"Debugger",commands:["continueToLocation","disable","enable","evaluateOnCallFrame","getPossibleBreakpoints","getScriptSource","getWasmBytecode","getStackTrace","pause","pauseOnAsyncCall","removeBreakpoint","restartFrame","resume","searchInContent","setAsyncCallStackDepth","setBlackboxPatterns","setBlackboxedRanges","setBreakpoint","setInstrumentationBreakpoint","setBreakpointByUrl","setBreakpointOnFunctionCall","setBreakpointsActive","setPauseOnExceptions","setReturnValue","setScriptSource","setSkipAllPauses","setVariableValue","stepInto","stepOut","stepOver"]},{domain:"HeapProfiler",commands:["addInspectedHeapObject","collectGarbage","disable","enable","getHeapObjectId","getObjectByHeapObjectId","getSamplingProfile","startSampling","startTrackingHeapObjects","stopSampling","stopTrackingHeapObjects","takeHeapSnapshot"]},{domain:"Profiler",commands:["disable","enable","getBestEffortCoverage","setSamplingInterval","start","startPreciseCoverage","startTypeProfile","stop","stopPreciseCoverage","stopTypeProfile","takePreciseCoverage","takeTypeProfile"]},{domain:"Runtime",commands:["awaitPromise","callFunctionOn","compileScript","disable","discardConsoleEntries","enable","evaluate","getIsolateId","getHeapUsage","getProperties","globalLexicalScopeNames","queryObjects","releaseObject","releaseObjectGroup","runIfWaitingForDebugger","runScript","setAsyncCallStackDepth","setCustomObjectFormatterEnabled","setMaxCallStackSizeToCapture","terminateExecution","addBinding","removeBinding","getExceptionDetails"]},{domain:"Schema",commands:["getDomains"]}],Lt=new Map;class Zt extends It{_client;constructor(e){super(),this._client=e}}for(let e of At){class t extends Zt{constructor(e){super(e)}}for(let n of e.commands)Object.defineProperty(t.prototype,n,{value:async function(t){return await this._client.sendCommand(`${e.domain}.${n}`,t)}});Lt.set(e.domain,t)}class Bt extends It{_cdpConnection;_sessionId;_domains;constructor(e,t){super(),this._cdpConnection=e,this._sessionId=t,this._domains=new Map;for(const[e,t]of Lt.entries())this._domains.set(e,new t(this)),Object.defineProperty(this,e,{get(){return this._domains.get(e)}})}sendCommand(e,t){return this._cdpConnection.sendCommand(e,t,this._sessionId)}_onCdpEvent(e,t){this.emit("event",e,t);const[n,s]=e.split("."),a=this._domains.get(n);a&&a.emit(s,t)}}function Ft(e,t){return new Bt(e,t)}const zt=e("cdp");class Vt{_transport;_browserCdpClient;_sessionCdpClients=new Map;_commandCallbacks=new Map;_nextId;constructor(e){this._transport=e,this._nextId=0,this._transport.setOnMessage(this._onMessage),this._browserCdpClient=Ft(this,null)}close(){this._transport.close();for(const[e,{reject:t}]of this._commandCallbacks)t(new Error("Disconnected"));this._commandCallbacks.clear(),this._sessionCdpClients.clear()}browserClient(){return this._browserCdpClient}getCdpClient(e){const t=this._sessionCdpClients.get(e);if(!t)throw new Error("Unknown CDP session ID");return t}sendCommand(e,t,n){return new Promise(((s,a)=>{const r=this._nextId++;this._commandCallbacks.set(r,{resolve:s,reject:a});let i={id:r,method:e,params:t};n&&(i.sessionId=n);const o=JSON.stringify(i);this._transport.sendMessage(o),zt("sent > "+o)}))}_onMessage=async e=>{zt("received < "+e);const t=JSON.parse(e);if("Target.attachedToTarget"===t.method){const{sessionId:e}=t.params;this._sessionCdpClients.set(e,Ft(this,e))}else if("Target.detachedFromTarget"===t.method){const{sessionId:e}=t.params;this._sessionCdpClients.get(e)&&this._sessionCdpClients.delete(e)}if(void 0!==t.id){const e=this._commandCallbacks.get(t.id);e&&(t.result?e.resolve(t.result):t.error&&e.reject(t.error))}else if(t.method){const e=t.sessionId?this._sessionCdpClients.get(t.sessionId):this._browserCdpClient;e&&e._onCdpEvent(t.method,t.params||{})}}}const $t=e("bidi");class Ut extends It{_transport;constructor(e){super(),this._transport=e,this._transport.setOnMessage(this._onBidiMessage)}async sendMessage(e){const t=JSON.stringify(e);$t("sent > "+t),this._transport.sendMessage(t)}close(){this._transport.close()}_onBidiMessage=async e=>{let t;$t("received < "+e);try{t=this._parseBidiMessage(e)}catch(t){return void this._respondWithError(e,"invalid argument",t.message)}this.emit("message",t)};_respondWithError(e,t,n){const s=this._getErrorResponse(e,t,n);this.sendMessage(s)}_getJsonType(e){return null===e?"null":Array.isArray(e)?"array":typeof e}_getErrorResponse(e,t,n){let s;try{const t=JSON.parse(e);"object"===this._getJsonType(t)&&"id"in t&&(s=t.id)}catch{}return{id:s,error:t,message:n}}_parseBidiMessage(e){let t;try{t=JSON.parse(e)}catch{throw new Error("Cannot parse data as JSON")}const n=this._getJsonType(t);if("object"!==n)throw new Error(`Expected JSON object but got ${n}`);const{id:s,method:a,params:r}=t,i=this._getJsonType(s);if("number"!==i||!Number.isInteger(s)||s<0)throw new Error(`Expected unsigned integer but got ${i}`);const o=this._getJsonType(a);if("string"!==o)throw new Error(`Expected string method but got ${o}`);const c=this._getJsonType(r);if("object"!==c)throw new Error(`Expected object params but got ${c}`);return{id:s,method:a,params:r}}}class Wt{#re=new Map;#C;constructor(e){this.#C=e}async sendEvent(e,t){(this.#ie(e.method,null)||null!==t&&this.#ie(e.method,t))&&await this.#C.sendMessage(e)}#ie(e,t){return this.#re.has(t)&&this.#re.get(t).has(e)}async subscribe(e,t){for(let n of e)if(null===t)this.#oe(n,null);else for(let e of t)this.#oe(n,e)}#oe(e,t){this.#re.has(t)||this.#re.set(t,new Set),this.#re.get(t).add(e)}async unsubscribe(e,t){for(let n of e)if(null===t)this.#ce(n,null);else for(let e of t)this.#ce(n,e)}#ce(e,t){const n=this.#re.get(t);n?.delete(e),0===n?.size&&this.#re.delete(t)}} /** * Copyright 2021 Google LLC. * Copyright (c) Microsoft Corporation. @@ -16,5 +16,5 @@ * limitations under the License. * * @license - */const Kt=e("system"),Ht=async function(){return await new Promise((e=>{window.setSelfTargetId=function(t){Kt("current target ID: "+t),e(t)}}))}();(async()=>{window.document.documentElement.innerHTML="<h1>Bidi mapper runs here!</h1><h2>Don't close.</h2>",window.document.title="BiDi Mapper";const e=function(){class e{_onMessage=null;constructor(){window.cdp.onmessage=e=>{this._onMessage&&this._onMessage.call(null,e)}}setOnMessage(e){this._onMessage=e}async sendMessage(e){window.cdp.send(e)}close(){this._onMessage=null,window.cdp.onmessage=null}}return new Vt(new e)}(),t=e.browserClient(),n=function(){class e{_onMessage=null;constructor(){window.onBidiMessage=e=>{this._onMessage&&this._onMessage.call(null,e)}}setOnMessage(e){this._onMessage=e}async sendMessage(e){window.sendBidiResponse(e)}close(){this._onMessage=null,window.onBidiMessage=null}}return new Ut(new e)}(),s=new Wt(n),r=await Ht;Ct.run(e,n,s,r),await async function(e){await e.Target.setDiscoverTargets({discover:!0}),await e.Target.setAutoAttach({autoAttach:!0,waitForDebuggerOnStart:!0,flatten:!0}),await Promise.all(gt.getTopLevelContexts().map((e=>e.awaitLoaded())))}(t),Kt("launched"),n.sendMessage({launched:!0})})()}(); + */const Kt=e("system"),Ht=async function(){return await new Promise((e=>{window.setSelfTargetId=function(t){Kt("current target ID: "+t),e(t)}}))}();(async()=>{window.document.documentElement.innerHTML="<h1>Bidi mapper runs here!</h1><h2>Don't close.</h2>",window.document.title="BiDi Mapper";const e=function(){class e{_onMessage=null;constructor(){window.cdp.onmessage=e=>{this._onMessage&&this._onMessage.call(null,e)}}setOnMessage(e){this._onMessage=e}async sendMessage(e){window.cdp.send(e)}close(){this._onMessage=null,window.cdp.onmessage=null}}return new Vt(new e)}(),t=e.browserClient(),n=function(){class e{_onMessage=null;constructor(){window.onBidiMessage=e=>{this._onMessage&&this._onMessage.call(null,e)}}setOnMessage(e){this._onMessage=e}async sendMessage(e){window.sendBidiResponse(e)}close(){this._onMessage=null,window.onBidiMessage=null}}return new Ut(new e)}(),s=new Wt(n),a=await Ht;Ct.run(e,n,s,a),await async function(e){await e.Target.setDiscoverTargets({discover:!0}),await e.Target.setAutoAttach({autoAttach:!0,waitForDebuggerOnStart:!0,flatten:!0}),await Promise.all(gt.getTopLevelContexts().map((e=>e.awaitLoaded())))}(t),Kt("launched"),n.sendMessage({launched:!0})})()}(); //# sourceMappingURL=mapper.js.map
diff --git a/third_party/blink/common/features.cc b/third_party/blink/common/features.cc index e129cc3..998a1b0 100644 --- a/third_party/blink/common/features.cc +++ b/third_party/blink/common/features.cc
@@ -1637,7 +1637,7 @@ BASE_FEATURE(kWildcardSubdomainsInPermissionsPolicy, "WildcardSubdomainsInPermissionsPolicy", - base::FEATURE_DISABLED_BY_DEFAULT); + base::FEATURE_ENABLED_BY_DEFAULT); BASE_FEATURE(kDocumentEventNodePathCaching, "DocumentEventNodePathCaching",
diff --git a/third_party/blink/public/mojom/file_system_access/file_system_access_directory_handle.mojom b/third_party/blink/public/mojom/file_system_access/file_system_access_directory_handle.mojom index 88c36c5e..ef7dbc3 100644 --- a/third_party/blink/public/mojom/file_system_access/file_system_access_directory_handle.mojom +++ b/third_party/blink/public/mojom/file_system_access/file_system_access_directory_handle.mojom
@@ -102,4 +102,8 @@ // a reference to this directory to other methods, for example to copy or move // the directory, or when transferring the handle over postMessage. Transfer(pending_receiver<FileSystemAccessTransferToken> token); + + // Returns a uniquely identifying string for the handle. + // `id` must be in GUID version 4 format. + GetUniqueId() => (string id); };
diff --git a/third_party/blink/public/mojom/file_system_access/file_system_access_file_handle.mojom b/third_party/blink/public/mojom/file_system_access/file_system_access_file_handle.mojom index ad11ad4..739cd6c 100644 --- a/third_party/blink/public/mojom/file_system_access/file_system_access_file_handle.mojom +++ b/third_party/blink/public/mojom/file_system_access/file_system_access_file_handle.mojom
@@ -98,4 +98,8 @@ // a reference to this directory to other methods, for example to copy or move // the file, or when transferring the handle over postMessage. Transfer(pending_receiver<FileSystemAccessTransferToken> token); + + // Returns a uniquely identifying string for the handle. + // `id` must be in GUID version 4 format. + GetUniqueId() => (string id); };
diff --git a/third_party/blink/public/web/blink.h b/third_party/blink/public/web/blink.h index a7aac13..a8a1ea6 100644 --- a/third_party/blink/public/web/blink.h +++ b/third_party/blink/public/web/blink.h
@@ -121,7 +121,6 @@ // agents, not both. // This is called at most once. This is called earlier than any frame commit. BLINK_EXPORT void SetIsCrossOriginIsolated(bool value); -BLINK_EXPORT bool IsCrossOriginIsolated(); // Set whether this renderer process has the "isolated application" isolation // level. Similarly to the `SetIsCrossOriginIsolated()` method above, this @@ -130,7 +129,7 @@ // // TODO(mkwst): We need a specification for this restriction. BLINK_EXPORT void SetIsIsolatedApplication(bool value); -BLINK_EXPORT bool IsIsolatedApplication(); + } // namespace blink #endif // THIRD_PARTY_BLINK_PUBLIC_WEB_BLINK_H_
diff --git a/third_party/blink/renderer/controller/blink_initializer.cc b/third_party/blink/renderer/controller/blink_initializer.cc index db8db249..c9803571 100644 --- a/third_party/blink/renderer/controller/blink_initializer.cc +++ b/third_party/blink/renderer/controller/blink_initializer.cc
@@ -219,20 +219,10 @@ } // Function defined in third_party/blink/public/web/blink.h. -bool IsCrossOriginIsolated() { - return Agent::IsCrossOriginIsolated(); -} - -// Function defined in third_party/blink/public/web/blink.h. void SetIsIsolatedApplication(bool value) { Agent::SetIsIsolatedApplication(value); } -// Function defined in third_party/blink/public/web/blink.h. -bool IsIsolatedApplication() { - return Agent::IsIsolatedApplication(); -} - void BlinkInitializer::RegisterInterfaces(mojo::BinderMap& binders) { ModulesInitializer::RegisterInterfaces(binders); Thread* main_thread = Thread::MainThread();
diff --git a/third_party/blink/renderer/core/css/parser/css_parser_impl.cc b/third_party/blink/renderer/core/css/parser/css_parser_impl.cc index 6b1ff14..f12c6e4 100644 --- a/third_party/blink/renderer/core/css/parser/css_parser_impl.cc +++ b/third_party/blink/renderer/core/css/parser/css_parser_impl.cc
@@ -1382,6 +1382,9 @@ case kSemicolonToken: stream.UncheckedConsume(); break; + case kAtKeywordToken: + ConsumeErroneousAtRule(stream); + break; case kIdentToken: { { CSSParserTokenStream::Boundary boundary(stream, kSemicolonToken);
diff --git a/third_party/blink/renderer/core/exported/web_view_impl.cc b/third_party/blink/renderer/core/exported/web_view_impl.cc index 26d75d9..5e007a9 100644 --- a/third_party/blink/renderer/core/exported/web_view_impl.cc +++ b/third_party/blink/renderer/core/exported/web_view_impl.cc
@@ -2587,15 +2587,6 @@ } void WebViewImpl::DispatchPersistedPageshow(base::TimeTicks navigation_start) { - // Reset NotRestoredReasons for successful back/forward cache restore here, - // so that we set a new value for NotRestoredReasons every time main-frame - // history navigation is completed. For history navigation that is not - // restored from back/forward cache, we set a new value in - // |CommitNavigationWithParams()|. - if (MainFrame()->IsWebLocalFrame() && MainFrame()->IsOutermostMainFrame()) { - MainFrame()->ToWebLocalFrame()->SetNotRestoredReasons(nullptr); - } - for (Frame* frame = GetPage()->MainFrame(); frame; frame = frame->Tree().TraverseNext()) { auto* local_frame = DynamicTo<LocalFrame>(frame);
diff --git a/third_party/blink/renderer/core/layout/layout_box.cc b/third_party/blink/renderer/core/layout/layout_box.cc index d1e4c49..ad16233 100644 --- a/third_party/blink/renderer/core/layout/layout_box.cc +++ b/third_party/blink/renderer/core/layout/layout_box.cc
@@ -1105,6 +1105,28 @@ } } +LayoutUnit LayoutBox::ClientWidthFrom(LayoutUnit width) const { + NOT_DESTROYED(); + if (CanSkipComputeScrollbars()) { + return (width - BorderLeft() - BorderRight()).ClampNegativeToZero(); + } else { + return (width - BorderLeft() - BorderRight() - + ComputeScrollbarsInternal(kClampToContentBox).HorizontalSum()) + .ClampNegativeToZero(); + } +} + +LayoutUnit LayoutBox::ClientHeightFrom(LayoutUnit height) const { + NOT_DESTROYED(); + if (CanSkipComputeScrollbars()) { + return (height - BorderTop() - BorderBottom()).ClampNegativeToZero(); + } else { + return (height - BorderTop() - BorderBottom() - + ComputeScrollbarsInternal(kClampToContentBox).VerticalSum()) + .ClampNegativeToZero(); + } +} + int LayoutBox::PixelSnappedClientWidth() const { NOT_DESTROYED(); return SnapSizeToPixel(ClientWidth(), Location().X() + ClientLeft());
diff --git a/third_party/blink/renderer/core/layout/layout_box.h b/third_party/blink/renderer/core/layout/layout_box.h index e7f15cb..47adbb9e 100644 --- a/third_party/blink/renderer/core/layout/layout_box.h +++ b/third_party/blink/renderer/core/layout/layout_box.h
@@ -856,8 +856,14 @@ else return BorderTop() + ComputeScrollbarsInternal(kClampToContentBox).top; } + + // Size without borders and scrollbars. LayoutUnit ClientWidth() const; LayoutUnit ClientHeight() const; + // Similar to ClientWidth() and ClientHeight(), but based on the specified + // border-box size. + LayoutUnit ClientWidthFrom(LayoutUnit width) const; + LayoutUnit ClientHeightFrom(LayoutUnit height) const; DISABLE_CFI_PERF LayoutUnit ClientLogicalWidth() const { NOT_DESTROYED(); return IsHorizontalWritingMode() ? ClientWidth() : ClientHeight();
diff --git a/third_party/blink/renderer/core/layout/ng/ng_block_node.cc b/third_party/blink/renderer/core/layout/ng/ng_block_node.cc index 06ceea2c..631c530 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_block_node.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_block_node.cc
@@ -2150,7 +2150,9 @@ void NGBlockNode::StoreColumnInlineSize(LayoutUnit inline_size) { LayoutMultiColumnFlowThread* flow_thread = To<LayoutBlockFlow>(box_.Get())->MultiColumnFlowThread(); - flow_thread->SetLogicalWidth(inline_size); + // We have no chance to unregister the inline size for the + // LayoutMultiColumnFlowThread. + TextAutosizer::MaybeRegisterInlineSize(*flow_thread, inline_size); flow_thread->ClearNeedsLayout(); }
diff --git a/third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.cc b/third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.cc index 489b5da..14315236 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.cc
@@ -542,20 +542,26 @@ break_token_ = NGBlockBreakToken::Create(this); } - OverflowClipAxes block_axis = - GetWritingDirection().IsHorizontal() ? kOverflowClipY : kOverflowClipX; - if ((To<NGBlockNode>(node_).GetOverflowClipAxes() & block_axis) || - is_block_size_for_fragmentation_clamped_) { - // If block-axis overflow is clipped, ignore child overflow and just use - // the border-box size of the fragment itself. Also do this if the node - // was forced to stay in the current fragmentainer. We'll ignore overflow - // in such cases, because children are allowed to overflow without - // affecting fragmentation then. - block_size_for_fragmentation_ = FragmentBlockSize(); - } else { - // Include the border-box size of the fragment itself. - block_size_for_fragmentation_ = - std::max(block_size_for_fragmentation_, FragmentBlockSize()); + // Make some final adjustments to block-size for fragmentation, unless this + // is a fragmentainer (so that we only include the block-size propagated + // from children in that case). + if (!NGPhysicalFragment::IsFragmentainerBoxType(box_type_)) { + OverflowClipAxes block_axis = GetWritingDirection().IsHorizontal() + ? kOverflowClipY + : kOverflowClipX; + if ((To<NGBlockNode>(node_).GetOverflowClipAxes() & block_axis) || + is_block_size_for_fragmentation_clamped_) { + // If block-axis overflow is clipped, ignore child overflow and just use + // the border-box size of the fragment itself. Also do this if the node + // was forced to stay in the current fragmentainer. We'll ignore + // overflow in such cases, because children are allowed to overflow + // without affecting fragmentation then. + block_size_for_fragmentation_ = FragmentBlockSize(); + } else { + // Include the border-box size of the fragment itself. + block_size_for_fragmentation_ = + std::max(block_size_for_fragmentation_, FragmentBlockSize()); + } } }
diff --git a/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm.cc b/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm.cc index dcad987..86dc678 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm.cc
@@ -652,6 +652,8 @@ may_resume_in_next_outer_fragmentainer = true; } + bool shrink_to_fit_column_block_size = false; + // We balance if block-size is unconstrained, or when we're explicitly told // to. Note that the block-size may be constrained by outer fragmentation // contexts, not just by a block-size specified on this multicol container. @@ -667,8 +669,17 @@ // don't take up more space than there's room for in the outer fragmentation // context. if (column_size.block_size > available_outer_space || - column_size.block_size == kIndefiniteSize) + column_size.block_size == kIndefiniteSize) { + // If the block-size of the inner multicol is unconstrained, we'll let the + // outer fragmentainer context constrain it. However, if the inner + // multicol only has content for one column (in the current row), and only + // fills it partially, we need to shrink its block-size, to make room for + // any content that follows the inner multicol, rather than eating the + // entire fragmentainer. + if (column_size.block_size == kIndefiniteSize) + shrink_to_fit_column_block_size = true; column_size.block_size = available_outer_space; + } } DCHECK_GE(column_size.block_size, LayoutUnit()); @@ -700,6 +711,7 @@ const NGLayoutResult* result = nullptr; absl::optional<NGBreakAppeal> min_break_appeal; + LayoutUnit intrinsic_block_size_contribution; do { const NGBlockBreakToken* column_break_token = next_column_token; @@ -720,6 +732,7 @@ LayoutUnit minimal_space_shortage = kIndefiniteSize; min_break_appeal = absl::nullopt; + intrinsic_block_size_contribution = LayoutUnit(); do { // Lay out one column. Each column will become a fragment. @@ -740,6 +753,29 @@ result = child_algorithm.Layout(); const auto& column = To<NGPhysicalBoxFragment>(result->PhysicalFragment()); + intrinsic_block_size_contribution = column_size.block_size; + if (shrink_to_fit_column_block_size) { + // Shrink-to-fit the row block-size contribution from the first column + // if we're nested inside another fragmentation context. The column + // block-size that we use in auto-filled (non-balanced) inner multicol + // containers with unconstrained block-size is set to the available + // block-size in the outer fragmentation context. If we end up with just + // one inner column in this row, we should shrink the inner multicol + // container fragment, so that it doesn't take up the entire outer + // fragmentainer needlessly. So clamp it to the total block-size of the + // contents in the column (including overflow). + // + // TODO(layout-dev): It would be slightly nicer if we actually shrunk + // the block-size of the column fragment (in + // FinishFragmentationForFragmentainer()) instead of just cropping the + // block-size of the multicol container here, but that would cause + // trouble for out-of-flow positioned descendants that extend past the + // end of in-flow content, which benefit from "full" column block-size. + intrinsic_block_size_contribution = + std::min(intrinsic_block_size_contribution, + result->BlockSizeForFragmentation()); + shrink_to_fit_column_block_size = false; + } if (!has_oof_fragmentainer_descendants && balance_columns && NGFragmentedOutOfFlowData:: @@ -973,7 +1009,7 @@ // (which will also be used as layout position for subsequent content), and // reset the margin strut (it has already been incorporated into the // offset). - intrinsic_block_size_ = row_offset + column_size.block_size; + intrinsic_block_size_ = row_offset + intrinsic_block_size_contribution; *margin_strut = NGMarginStrut(); }
diff --git a/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm_test.cc b/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm_test.cc index 6e70c83..f407d45 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm_test.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm_test.cc
@@ -4213,7 +4213,7 @@ offset:0,0 size:45x20 offset:0,20 size:45x20 offset:110,0 size:100x50 - offset:0,0 size:100x50 + offset:0,0 size:100x40 offset:0,0 size:45x50 offset:0,0 size:45x20 offset:0,20 size:45x20
diff --git a/third_party/blink/renderer/core/layout/ng/ng_physical_fragment.h b/third_party/blink/renderer/core/layout/ng/ng_physical_fragment.h index 8004025..040a24c 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_physical_fragment.h +++ b/third_party/blink/renderer/core/layout/ng/ng_physical_fragment.h
@@ -115,7 +115,12 @@ return IsBox() && BoxType() == NGBoxType::kColumnBox; } bool IsPageBox() const { return IsBox() && BoxType() == NGBoxType::kPageBox; } - bool IsFragmentainerBox() const { return IsColumnBox() || IsPageBox(); } + static bool IsFragmentainerBoxType(NGBoxType type) { + return type == NGBoxType::kColumnBox || type == NGBoxType::kPageBox; + } + bool IsFragmentainerBox() const { + return IsBox() && IsFragmentainerBoxType(BoxType()); + } bool IsColumnSpanAll() const { if (const auto* box = DynamicTo<LayoutBox>(GetLayoutObject())) return box->IsColumnSpanAll();
diff --git a/third_party/blink/renderer/core/layout/svg/layout_svg_block.cc b/third_party/blink/renderer/core/layout/svg/layout_svg_block.cc index c412ab65..0762145 100644 --- a/third_party/blink/renderer/core/layout/svg/layout_svg_block.cc +++ b/third_party/blink/renderer/core/layout/svg/layout_svg_block.cc
@@ -126,7 +126,7 @@ SetNeedsTransformUpdate(); } - SVGResources::UpdateEffects(*this, old_style); + SVGResources::UpdateEffects(*this, diff, old_style); if (!Parent()) return;
diff --git a/third_party/blink/renderer/core/layout/svg/layout_svg_inline.cc b/third_party/blink/renderer/core/layout/svg/layout_svg_inline.cc index c6d125f..61d8246 100644 --- a/third_party/blink/renderer/core/layout/svg/layout_svg_inline.cc +++ b/third_party/blink/renderer/core/layout/svg/layout_svg_inline.cc
@@ -202,7 +202,7 @@ if (diff.NeedsFullLayout()) SetNeedsBoundariesUpdate(); - SVGResources::UpdateEffects(*this, old_style); + SVGResources::UpdateEffects(*this, diff, old_style); SVGResources::UpdatePaints(*this, old_style, StyleRef()); if (!Parent())
diff --git a/third_party/blink/renderer/core/layout/svg/layout_svg_model_object.cc b/third_party/blink/renderer/core/layout/svg/layout_svg_model_object.cc index e9ae60f..b8ee789 100644 --- a/third_party/blink/renderer/core/layout/svg/layout_svg_model_object.cc +++ b/third_party/blink/renderer/core/layout/svg/layout_svg_model_object.cc
@@ -144,7 +144,7 @@ SetHasTransformRelatedProperty( StyleRef().HasTransformRelatedPropertyForSVG()); - SVGResources::UpdateEffects(*this, old_style); + SVGResources::UpdateEffects(*this, diff, old_style); if (!Parent()) return;
diff --git a/third_party/blink/renderer/core/layout/svg/layout_svg_root.cc b/third_party/blink/renderer/core/layout/svg/layout_svg_root.cc index c120237f..020e83e8 100644 --- a/third_party/blink/renderer/core/layout/svg/layout_svg_root.cc +++ b/third_party/blink/renderer/core/layout/svg/layout_svg_root.cc
@@ -364,7 +364,7 @@ if (old_style && StyleChangeAffectsIntrinsicSize(*old_style)) IntrinsicSizingInfoChanged(); - SVGResources::UpdateEffects(*this, old_style); + SVGResources::UpdateEffects(*this, diff, old_style); if (diff.TransformChanged()) { for (auto& svg_text : text_set_) {
diff --git a/third_party/blink/renderer/core/layout/svg/svg_resources.cc b/third_party/blink/renderer/core/layout/svg/svg_resources.cc index a3a84cc6..24659f2 100644 --- a/third_party/blink/renderer/core/layout/svg/svg_resources.cc +++ b/third_party/blink/renderer/core/layout/svg/svg_resources.cc
@@ -68,6 +68,7 @@ } void SVGResources::UpdateEffects(LayoutObject& object, + StyleDifference diff, const ComputedStyle* old_style) { const bool had_client = GetClient(object); const ComputedStyle& style = object.StyleRef(); @@ -75,14 +76,16 @@ DynamicTo<ReferenceClipPathOperation>(style.ClipPath())) { reference_clip->AddClient(EnsureClient(object)); } - if (style.HasFilter()) { - SVGElementResourceClient& client = EnsureClient(object); - style.Filter().AddClient(client); - object.SetNeedsPaintPropertyUpdate(); - client.MarkFilterDataDirty(); - } + if (style.HasFilter()) + style.Filter().AddClient(EnsureClient(object)); if (StyleSVGResource* masker_resource = style.MaskerResource()) masker_resource->AddClient(EnsureClient(object)); + if (diff.FilterChanged()) { + // We either created one above, or had one already. + DCHECK(GetClient(object)); + object.SetNeedsPaintPropertyUpdate(); + GetClient(object)->MarkFilterDataDirty(); + } if (!old_style || !had_client) return; SVGElementResourceClient* client = GetClient(object); @@ -90,10 +93,8 @@ DynamicTo<ReferenceClipPathOperation>(old_style->ClipPath())) { old_reference_clip->RemoveClient(*client); } - if (old_style->HasFilter()) { + if (old_style->HasFilter()) old_style->Filter().RemoveClient(*client); - client->InvalidateFilterData(); - } if (StyleSVGResource* masker_resource = old_style->MaskerResource()) masker_resource->RemoveClient(*client); }
diff --git a/third_party/blink/renderer/core/layout/svg/svg_resources.h b/third_party/blink/renderer/core/layout/svg/svg_resources.h index 030bdf01..39863af5 100644 --- a/third_party/blink/renderer/core/layout/svg/svg_resources.h +++ b/third_party/blink/renderer/core/layout/svg/svg_resources.h
@@ -20,6 +20,7 @@ #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_SVG_SVG_RESOURCES_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_SVG_SVG_RESOURCES_H_ +#include "third_party/blink/renderer/core/style/style_difference.h" #include "third_party/blink/renderer/core/svg/svg_resource_client.h" #include "third_party/blink/renderer/platform/heap/garbage_collected.h" #include "third_party/blink/renderer/platform/heap/member.h" @@ -47,7 +48,9 @@ static SVGElementResourceClient* GetClient(const LayoutObject&); static gfx::RectF ReferenceBoxForEffects(const LayoutObject&); - static void UpdateEffects(LayoutObject&, const ComputedStyle* old_style); + static void UpdateEffects(LayoutObject&, + StyleDifference, + const ComputedStyle* old_style); static void ClearEffects(const LayoutObject&); static void UpdatePaints(const LayoutObject&, const ComputedStyle* old_style,
diff --git a/third_party/blink/renderer/core/layout/text_autosizer.cc b/third_party/blink/renderer/core/layout/text_autosizer.cc index 5152d50..93b782a 100644 --- a/third_party/blink/renderer/core/layout/text_autosizer.cc +++ b/third_party/blink/renderer/core/layout/text_autosizer.cc
@@ -1036,7 +1036,7 @@ if (!(block->IsTable() || block->IsTableCell() || block->IsListItemIncludingNG())) - return block->ContentLogicalWidth().ToFloat(); + return ContentInlineSize(block); if (!block->ContainingBlock()) return 0; @@ -1054,13 +1054,12 @@ return width; } if (specified_width.IsPercentOrCalc()) { - if (float container_width = - block->ContainingBlock()->ContentLogicalWidth().ToFloat()) { + if (float container_width = ContentInlineSize(block->ContainingBlock())) { if ((width = FloatValueForLength(specified_width, container_width)) > 0) return width; } } - if ((width = block->ContentLogicalWidth().ToFloat()) > 0) + if ((width = ContentInlineSize(block)) > 0) return width; } return 0; @@ -1289,9 +1288,9 @@ #endif float content_width = - DeepestBlockContainingAllText(cluster)->ContentLogicalWidth().ToFloat(); + ContentInlineSize(DeepestBlockContainingAllText(cluster)); float cluster_text_width = - parent_deepest_block_containing_all_text->ContentLogicalWidth().ToFloat(); + ContentInlineSize(parent_deepest_block_containing_all_text); // Clusters with a root that is wider than the deepestBlockContainingAllText // of their parent autosize independently of their parent. @@ -1460,6 +1459,15 @@ } } +// static +void TextAutosizer::MaybeRegisterInlineSize(const LayoutBlock& ng_block, + LayoutUnit inline_size) { + if (auto* text_autosizer = ng_block.GetDocument().GetTextAutosizer()) { + if (text_autosizer->ShouldHandleLayout()) + text_autosizer->RegisterInlineSize(ng_block, inline_size); + } +} + TextAutosizer::NGLayoutScope::NGLayoutScope(LayoutBox* box, LayoutUnit inline_size) : text_autosizer_(box->GetDocument().GetTextAutosizer()), @@ -1478,17 +1486,19 @@ } // In order for the text autosizer to do anything useful at all, it needs to - // know the inline size of the block. So set it. LayoutNG normally writes back - // to the legacy tree *after* layout, but this one must be set before, at - // least if the autosizer is enabled. - block_->SetLogicalWidth(inline_size); + // know the inline size of the block. So register it. LayoutNG normally + // writes back to the legacy tree *after* layout, but this one must be ready + // before, at least if the autosizer is enabled. + text_autosizer_->RegisterInlineSize(*block_, inline_size); text_autosizer_->BeginLayout(block_, nullptr); } TextAutosizer::NGLayoutScope::~NGLayoutScope() { - if (text_autosizer_) + if (text_autosizer_) { text_autosizer_->EndLayout(block_); + text_autosizer_->UnregisterInlineSize(*block_); + } } TextAutosizer::DeferUpdatePageInfo::~DeferUpdatePageInfo() { @@ -1569,9 +1579,36 @@ potentially_inconsistent_superclusters.clear(); } +float TextAutosizer::ContentInlineSize(const LayoutBlock* block) const { + if (!block->IsLayoutNGObject()) + return block->ContentLogicalWidth().ToFloat(); + auto iter = inline_size_map_.find(block); + if (iter == inline_size_map_.end()) + return block->ContentLogicalWidth().ToFloat(); + LayoutUnit size = iter.Get()->value; + if (block->IsHorizontalWritingMode()) { + size = block->ClientWidthFrom(size) - block->PaddingLeft() - + block->PaddingRight(); + } else { + size = block->ClientHeightFrom(size) - block->PaddingTop() - + block->PaddingBottom(); + } + return size.ClampNegativeToZero().ToFloat(); +} + +void TextAutosizer::RegisterInlineSize(const LayoutBlock& ng_block, + LayoutUnit inline_size) { + inline_size_map_.insert(&ng_block, inline_size); +} + +void TextAutosizer::UnregisterInlineSize(const LayoutBlock& ng_block) { + inline_size_map_.erase(&ng_block); +} + void TextAutosizer::Trace(Visitor* visitor) const { visitor->Trace(document_); visitor->Trace(first_block_to_begin_layout_); + visitor->Trace(inline_size_map_); #if DCHECK_IS_ON() visitor->Trace(blocks_that_have_begun_layout_); #endif
diff --git a/third_party/blink/renderer/core/layout/text_autosizer.h b/third_party/blink/renderer/core/layout/text_autosizer.h index 8af76e3c..1d1c530 100644 --- a/third_party/blink/renderer/core/layout/text_autosizer.h +++ b/third_party/blink/renderer/core/layout/text_autosizer.h
@@ -98,6 +98,11 @@ bool PageNeedsAutosizing() const; + // Register the specified |inline_size| for |ng_block| if the document has + // a TextAutosizer instance and it should handle layout. + static void MaybeRegisterInlineSize(const LayoutBlock& ng_block, + LayoutUnit inline_size); + void Trace(Visitor*) const; class LayoutScope { @@ -309,6 +314,8 @@ void BeginLayout(LayoutBlock*, SubtreeLayoutScope*); void EndLayout(LayoutBlock*); + void RegisterInlineSize(const LayoutBlock& ng_block, LayoutUnit inline_size); + void UnregisterInlineSize(const LayoutBlock& ng_block); void InflateAutoTable(LayoutNGTableInterface*); float Inflate(LayoutObject*, SubtreeLayoutScope*, @@ -371,8 +378,14 @@ void ReportIfCrossSiteFrame(); + float ContentInlineSize(const LayoutBlock* block) const; + Member<const Document> document_; Member<const LayoutBlock> first_block_to_begin_layout_; + // WeakMember because we don't call UnregisterInlineSize() for + // LayoutMultiColumnFlowThread. + HeapHashMap<WeakMember<const LayoutBlock>, LayoutUnit> inline_size_map_; + #if DCHECK_IS_ON() // Used to ensure we don't compute properties of a block before beginLayout() // is called on it.
diff --git a/third_party/blink/renderer/core/loader/build.gni b/third_party/blink/renderer/core/loader/build.gni index 647f2c4..ae4a5977 100644 --- a/third_party/blink/renderer/core/loader/build.gni +++ b/third_party/blink/renderer/core/loader/build.gni
@@ -119,12 +119,12 @@ "resource/image_resource_observer.h", "resource/link_prefetch_resource.cc", "resource/link_prefetch_resource.h", - "resource/speculation_rules_resource.cc", - "resource/speculation_rules_resource.h", "resource/multipart_image_resource_parser.cc", "resource/multipart_image_resource_parser.h", "resource/script_resource.cc", "resource/script_resource.h", + "resource/speculation_rules_resource.cc", + "resource/speculation_rules_resource.h", "resource/text_resource.cc", "resource/text_resource.h", "resource/xsl_style_sheet_resource.cc",
diff --git a/third_party/blink/renderer/core/loader/document_loader.cc b/third_party/blink/renderer/core/loader/document_loader.cc index 2b9911e..cf10288 100644 --- a/third_party/blink/renderer/core/loader/document_loader.cc +++ b/third_party/blink/renderer/core/loader/document_loader.cc
@@ -2294,9 +2294,7 @@ // trials to be initialized. // TODO(iclelland): Add Permissions-Policy-Report-Only to Origin Policy. security_init.ApplyPermissionsPolicy( - *frame_.Get(), response_, frame_policy_, - Agent::IsIsolatedApplication() ? initial_permissions_policy_ - : absl::nullopt); + *frame_.Get(), response_, frame_policy_, initial_permissions_policy_); // |document_policy_| is parsed in document loader because it is // compared with |frame_policy.required_document_policy| to decide @@ -2505,8 +2503,7 @@ auto& speculation_rules_header = response_.HttpHeaderField(http_names::kSpeculationRules); PreloadHelper::LoadSpeculationRuleLinkFromHeader( - speculation_rules_header, response_.CurrentRequestUrl(), - GetFrame()->GetDocument(), *GetFrame()); + speculation_rules_header, GetFrame()->GetDocument(), *GetFrame()); } // DidObserveLoadingBehavior() must be called after DispatchDidCommitLoad() is
diff --git a/third_party/blink/renderer/core/loader/preload_helper.cc b/third_party/blink/renderer/core/loader/preload_helper.cc index 72a9f23..e5928ef3 100644 --- a/third_party/blink/renderer/core/loader/preload_helper.cc +++ b/third_party/blink/renderer/core/loader/preload_helper.cc
@@ -636,7 +636,6 @@ void PreloadHelper::LoadSpeculationRuleLinkFromHeader( const String& header_value, - const KURL& base_url, Document* document, LocalFrame& frame) { DCHECK(document); @@ -655,9 +654,16 @@ } for (auto const& parsed_item : parsed_header.value()) { - // to make sure not a nested list + // Only strings are valid list members. if (parsed_item.member.size() != 1u || !parsed_item.member[0].item.is_string()) { + SendMessageToConsoleForPossiblyNullDocument( + MakeGarbageCollected<ConsoleMessage>( + mojom::blink::ConsoleMessageSource::kOther, + mojom::blink::ConsoleMessageLevel::kWarning, + String("Only strings are valid in Speculation-Rules header value " + "and inner lists are ignored.")), + document, &frame); continue; } const auto& url_str = String(parsed_item.member[0].item.GetString());
diff --git a/third_party/blink/renderer/core/loader/preload_helper.h b/third_party/blink/renderer/core/loader/preload_helper.h index 5d8379f..2908470 100644 --- a/third_party/blink/renderer/core/loader/preload_helper.h +++ b/third_party/blink/renderer/core/loader/preload_helper.h
@@ -35,7 +35,6 @@ enum MediaPreloadPolicy { kLoadAll, kOnlyLoadNonMedia, kOnlyLoadMedia }; static void LoadSpeculationRuleLinkFromHeader(const String& header_value, - const KURL& base_url, Document* document, LocalFrame& frame);
diff --git a/third_party/blink/renderer/core/loader/resource/speculation_rules_resource.h b/third_party/blink/renderer/core/loader/resource/speculation_rules_resource.h index 6d3aa87..796b7bc5 100644 --- a/third_party/blink/renderer/core/loader/resource/speculation_rules_resource.h +++ b/third_party/blink/renderer/core/loader/resource/speculation_rules_resource.h
@@ -12,7 +12,7 @@ class FetchParameters; class ResourceFetcher; -// This is the implementation of Resource for in Speculation-Rules header. +// This is the implementation of Resource for the Speculation-Rules header. class SpeculationRulesResource final : public TextResource { public: static SpeculationRulesResource* Fetch(FetchParameters&, ResourceFetcher*);
diff --git a/third_party/blink/renderer/core/loader/speculation_rule_loader.cc b/third_party/blink/renderer/core/loader/speculation_rule_loader.cc index 734f783..3a3792f 100644 --- a/third_party/blink/renderer/core/loader/speculation_rule_loader.cc +++ b/third_party/blink/renderer/core/loader/speculation_rule_loader.cc
@@ -69,7 +69,6 @@ String parse_error; if (auto* rule_set = SpeculationRuleSet::Parse(source_text, base_url_, &parse_error)) { - speculation_rule_set_ = rule_set; DocumentSpeculationRules::From(*document_).AddRuleSet(rule_set); } if (!parse_error.IsNull()) { @@ -88,7 +87,6 @@ void SpeculationRuleLoader::Trace(Visitor* visitor) const { visitor->Trace(document_); visitor->Trace(resource_); - visitor->Trace(speculation_rule_set_); ResourceFinishObserver::Trace(visitor); }
diff --git a/third_party/blink/renderer/core/loader/speculation_rule_loader.h b/third_party/blink/renderer/core/loader/speculation_rule_loader.h index 6d6c95c..6d5b636 100644 --- a/third_party/blink/renderer/core/loader/speculation_rule_loader.h +++ b/third_party/blink/renderer/core/loader/speculation_rule_loader.h
@@ -15,8 +15,8 @@ class Document; class SpeculationRulesResource; -class SpeculationRuleSet; +// This is used for Speculation-Rules header class CORE_EXPORT SpeculationRuleLoader final : public ResourceFinishObserver, public NameClient { public: @@ -37,7 +37,6 @@ KURL base_url_; Member<Document> document_; Member<SpeculationRulesResource> resource_; - Member<SpeculationRuleSet> speculation_rule_set_; }; } // namespace blink
diff --git a/third_party/blink/renderer/core/page/print_context_test.cc b/third_party/blink/renderer/core/page/print_context_test.cc index c354551..36df50f3 100644 --- a/third_party/blink/renderer/core/page/print_context_test.cc +++ b/third_party/blink/renderer/core/page/print_context_test.cc
@@ -1036,4 +1036,43 @@ EXPECT_EQ(target->OffsetWidth(), 800); } +TEST_P(PrintContextTest, + TransparentRootBackgroundWithShouldPrintBackgroundDisabled) { + MockPageContextCanvas canvas; + SetBodyInnerHTML(""); + + GetDocument().GetSettings()->SetShouldPrintBackgrounds(false); + EXPECT_CALL(canvas, onDrawRect(_, _)).Times(0); + PrintSinglePage(canvas); +} + +TEST_P(PrintContextTest, + TransparentRootBackgroundWithShouldPrintBackgroundEnabled) { + MockPageContextCanvas canvas; + SetBodyInnerHTML(""); + + GetDocument().GetSettings()->SetShouldPrintBackgrounds(true); + EXPECT_CALL(canvas, onDrawRect(_, _)).Times(0); + PrintSinglePage(canvas); +} + +TEST_P(PrintContextTest, WhiteRootBackgroundWithShouldPrintBackgroundDisabled) { + MockPageContextCanvas canvas; + SetBodyInnerHTML("<style>body { background: white; }</style>"); + + GetDocument().GetSettings()->SetShouldPrintBackgrounds(false); + EXPECT_CALL(canvas, onDrawRect(_, _)).Times(0); + PrintSinglePage(canvas); +} + +TEST_P(PrintContextTest, WhiteRootBackgroundWithShouldPrintBackgroundEnabled) { + MockPageContextCanvas canvas; + SetBodyInnerHTML("<style>body { background: white; }</style>"); + + GetDocument().GetSettings()->SetShouldPrintBackgrounds(true); + // We should paint the specified white background. + EXPECT_CALL(canvas, onDrawRect(_, _)).Times(1); + PrintSinglePage(canvas); +} + } // namespace blink
diff --git a/third_party/blink/renderer/core/paint/paint_and_raster_invalidation_test.cc b/third_party/blink/renderer/core/paint/paint_and_raster_invalidation_test.cc index c461500b..2b592ab 100644 --- a/third_party/blink/renderer/core/paint/paint_and_raster_invalidation_test.cc +++ b/third_party/blink/renderer/core/paint/paint_and_raster_invalidation_test.cc
@@ -828,6 +828,23 @@ GetDocument().View()->SetTracksRasterInvalidations(false); } +TEST_P(PaintAndRasterInvalidationTest, SVGWithFilterNoOpStyleUpdate) { + SetBodyInnerHTML(R"HTML( + <svg> + <filter id="f"> + <feGaussianBlur stdDeviation="5"/> + </filter> + <rect width="100" height="100" style="filter: url(#f)"/> + </svg> + )HTML"); + + GetDocument().View()->SetTracksRasterInvalidations(true); + GetDocument().body()->setAttribute(html_names::kStyleAttr, "--x: 42"); + UpdateAllLifecyclePhasesForTest(); + EXPECT_FALSE(GetRasterInvalidationTracking()->HasInvalidations()); + GetDocument().View()->SetTracksRasterInvalidations(false); +} + TEST_P(PaintAndRasterInvalidationTest, PaintPropertyChange) { SetUpHTML(*this); Element* target = GetDocument().getElementById("target");
diff --git a/third_party/blink/renderer/core/paint/paint_layer.cc b/third_party/blink/renderer/core/paint/paint_layer.cc index 2bfba0c2e6..9a607fd 100644 --- a/third_party/blink/renderer/core/paint/paint_layer.cc +++ b/third_party/blink/renderer/core/paint/paint_layer.cc
@@ -2603,6 +2603,13 @@ return *rare_data.resource_info; } +void PaintLayer::SetNeedsReorderOverlayOverflowControls(bool b) { + if (b != needs_reorder_overlay_overflow_controls_) { + SetNeedsRepaint(); + needs_reorder_overlay_overflow_controls_ = b; + } +} + gfx::RectF PaintLayer::MapRectForFilter(const gfx::RectF& rect) const { if (!HasFilterThatMovesPixels()) return rect;
diff --git a/third_party/blink/renderer/core/paint/paint_layer.h b/third_party/blink/renderer/core/paint/paint_layer.h index a09e2d8..f2c576c3 100644 --- a/third_party/blink/renderer/core/paint/paint_layer.h +++ b/third_party/blink/renderer/core/paint/paint_layer.h
@@ -776,9 +776,7 @@ // PaintLayerPaintOrderIterator. PaintLayerStackingNode* StackingNode() const { return stacking_node_; } - void SetNeedsReorderOverlayOverflowControls(bool b) { - needs_reorder_overlay_overflow_controls_ = b; - } + void SetNeedsReorderOverlayOverflowControls(bool); bool ComputeHasFilterThatMovesPixels() const;
diff --git a/third_party/blink/renderer/core/paint/paint_layer_stacking_node.h b/third_party/blink/renderer/core/paint/paint_layer_stacking_node.h index 3cdf8c27..e859891 100644 --- a/third_party/blink/renderer/core/paint/paint_layer_stacking_node.h +++ b/third_party/blink/renderer/core/paint/paint_layer_stacking_node.h
@@ -143,11 +143,6 @@ // Holds descendants within our stacking context with negative z-indices. PaintLayers neg_z_order_list_; - // All PaintLayers (just in current stacking context, child stacking contexts - // will have their own list) that have overlay overflow controls that should - // paint reordered. For the above example, this has one entry {target}. - PaintLayers overlay_overflow_controls_reordered_list_; - // Overlay overflow controls(scrollbar or resizer) need to be painted above // all child contents, even if the contents are stacked in a stacking context // which is an ancestor of the scrolling or resizing layer, for example: @@ -192,6 +187,11 @@ HeapHashMap<Member<const PaintLayer>, Member<PaintLayers>> layer_to_overlay_overflow_controls_painting_after_; + // All PaintLayers (just in current stacking context, child stacking contexts + // will have their own list) that have overlay overflow controls that should + // paint reordered. For the above example, this has one entry {target}. + PaintLayers overlay_overflow_controls_reordered_list_; + Member<PaintLayer> layer_; // Indicates whether the z-order lists above are dirty.
diff --git a/third_party/blink/renderer/core/paint/paint_layer_test.cc b/third_party/blink/renderer/core/paint/paint_layer_test.cc index 369c3b1..1caa44e 100644 --- a/third_party/blink/renderer/core/paint/paint_layer_test.cc +++ b/third_party/blink/renderer/core/paint/paint_layer_test.cc
@@ -264,10 +264,11 @@ class ReorderOverlayOverflowControlsTest : public testing::WithParamInterface<OverlayType>, - public RenderingTest { + public PaintControllerPaintTestBase { public: ReorderOverlayOverflowControlsTest() - : RenderingTest(MakeGarbageCollected<SingleChildLocalFrameClient>()) {} + : PaintControllerPaintTestBase( + MakeGarbageCollected<SingleChildLocalFrameClient>()) {} ~ReorderOverlayOverflowControlsTest() override { // Must destruct all objects before toggling back feature flags. WebHeap::CollectAllGarbageForTesting(); @@ -288,11 +289,6 @@ "overflow: visible"); UpdateAllLifecyclePhasesForTest(); } - - void SetUp() override { - EnableCompositing(); - RenderingTest::SetUp(); - } }; INSTANTIATE_TEST_SUITE_P(All, @@ -862,6 +858,49 @@ EXPECT_FALSE(LayersPaintingOverlayOverflowControlsAfter(child)); } +TEST_P(ReorderOverlayOverflowControlsTest, AddRemoveStackedChild) { + SetBodyInnerHTML(R"HTML( + <style> + #parent { + position: relative; + width: 100px; + height: 100px; + } + #child { + position: absolute; + width: 200px; + height: 200px; + display: none; + } + </style> + <div id='parent'> + <div id='child'></div> + </div> + )HTML"); + + InitOverflowStyle("parent"); + auto* parent = GetPaintLayerByElementId("parent"); + EXPECT_FALSE(parent->NeedsReorderOverlayOverflowControls()); + + auto* child_element = GetDocument().getElementById("child"); + child_element->setAttribute(html_names::kStyleAttr, "display: block"); + UpdateAllLifecyclePhasesExceptPaint(); + EXPECT_TRUE(parent->NeedsReorderOverlayOverflowControls()); + EXPECT_THAT(LayersPaintingOverlayOverflowControlsAfter( + GetPaintLayerByElementId("child")), + Pointee(ElementsAre(parent))); + EXPECT_TRUE(parent->SelfNeedsRepaint()); + UpdateAllLifecyclePhasesForTest(); + EXPECT_FALSE(parent->SelfNeedsRepaint()); + + child_element->setAttribute(html_names::kStyleAttr, ""); + UpdateAllLifecyclePhasesExceptPaint(); + EXPECT_FALSE(parent->NeedsReorderOverlayOverflowControls()); + EXPECT_TRUE(parent->SelfNeedsRepaint()); + UpdateAllLifecyclePhasesForTest(); + EXPECT_FALSE(parent->SelfNeedsRepaint()); +} + TEST_P(PaintLayerTest, SubsequenceCachingStackedLayers) { SetBodyInnerHTML(R"HTML( <div id='parent' style='position:relative'>
diff --git a/third_party/blink/renderer/core/paint/paint_timing.cc b/third_party/blink/renderer/core/paint/paint_timing.cc index c991418..c4b4fd96 100644 --- a/third_party/blink/renderer/core/paint/paint_timing.cc +++ b/third_party/blink/renderer/core/paint/paint_timing.cc
@@ -336,9 +336,12 @@ "GlobalFirstContentfulPaint", TRACE_EVENT_SCOPE_GLOBAL, stamp); first_contentful_paint_presentation_ = stamp; + bool is_soft_navigation_fcp = false; if (first_contentful_paint_presentation_ignoring_soft_navigations_ .is_null()) { first_contentful_paint_presentation_ignoring_soft_navigations_ = stamp; + } else { + is_soft_navigation_fcp = true; } probe::PaintTiming( GetSupplementable(), "firstContentfulPaint", @@ -348,6 +351,11 @@ performance->AddFirstContentfulPaintTiming( first_contentful_paint_presentation_); } + // For soft navigations, we just want to report a performance entry, but not + // trigger any of the other FCP observers. + if (is_soft_navigation_fcp) { + return; + } if (GetFrame()) GetFrame()->Loader().Progress().DidFirstContentfulPaint(); NotifyPaintTimingChanged();
diff --git a/third_party/blink/renderer/core/paint/view_painter.cc b/third_party/blink/renderer/core/paint/view_painter.cc index 97e16b72..3546d729 100644 --- a/third_party/blink/renderer/core/paint/view_painter.cc +++ b/third_party/blink/renderer/core/paint/view_painter.cc
@@ -262,9 +262,18 @@ (frame_view.BaseBackgroundColor().Alpha() > 0); Color base_background_color = paints_base_background ? frame_view.BaseBackgroundColor() : Color(); + if (document.Printing() && base_background_color == Color::kWhite) { + // Leave a transparent background, assuming the paper or the PDF viewer + // background is white by default. This allows further customization of the + // background, e.g. in the case of https://crbug.com/498892. + base_background_color = Color(); + paints_base_background = false; + } + Color root_element_background_color = layout_view_.StyleRef().VisitedDependentColor( GetCSSPropertyBackgroundColor()); + const LayoutObject* root_object = document.documentElement() ? document.documentElement()->GetLayoutObject() : nullptr; @@ -348,8 +357,7 @@ should_draw_background_in_separate_buffer = true; } else { // If the root background color is opaque, isolation group can be skipped - // because the canvas - // will be cleared by root background color. + // because the canvas will be cleared by root background color. if (!root_element_background_color.HasAlpha()) should_draw_background_in_separate_buffer = false;
diff --git a/third_party/blink/renderer/core/permissions_policy/dom_feature_policy.cc b/third_party/blink/renderer/core/permissions_policy/dom_feature_policy.cc index c7aecea..8c1247a 100644 --- a/third_party/blink/renderer/core/permissions_policy/dom_feature_policy.cc +++ b/third_party/blink/renderer/core/permissions_policy/dom_feature_policy.cc
@@ -123,10 +123,16 @@ } Vector<String> result; for (const auto& origin_with_possible_wildcards : allowed_origins) { - // TODO(crbug.com/1345994): Support wildcard matching. if (!origin_with_possible_wildcards.has_subdomain_wildcard) { result.push_back(WTF::String::FromUTF8( origin_with_possible_wildcards.origin.Serialize())); + } else { + // Restore the missing wildcard from the front so this permissions + // policy element is inspectable. This looks different from when the + // wildcard wasn't supported as a %2A will be used instead of a *. + result.push_back(WTF::String::FromUTF8( + origin_with_possible_wildcards.origin.Serialize()) + .Replace("://", "://*.")); } } return result;
diff --git a/third_party/blink/renderer/core/permissions_policy/permissions_policy_attr_fuzzer.cc b/third_party/blink/renderer/core/permissions_policy/permissions_policy_attr_fuzzer.cc index f351da7e..6a4950d 100644 --- a/third_party/blink/renderer/core/permissions_policy/permissions_policy_attr_fuzzer.cc +++ b/third_party/blink/renderer/core/permissions_policy/permissions_policy_attr_fuzzer.cc
@@ -13,10 +13,10 @@ #include "third_party/blink/renderer/platform/wtf/vector.h" extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { + // TODO(crbug.com/1345994): Add seed corpus w/ wildcards. static blink::BlinkFuzzerTestSupport test_support = blink::BlinkFuzzerTestSupport(); blink::PolicyParserMessageBuffer logger; - // TODO(csharrison): Be smarter about parsing these origins for performance. scoped_refptr<const blink::SecurityOrigin> parent_origin = blink::SecurityOrigin::CreateFromString("https://example.com/"); scoped_refptr<const blink::SecurityOrigin> child_origin =
diff --git a/third_party/blink/renderer/core/permissions_policy/permissions_policy_fuzzer.cc b/third_party/blink/renderer/core/permissions_policy/permissions_policy_fuzzer.cc index 8ce5275..8c92154 100644 --- a/third_party/blink/renderer/core/permissions_policy/permissions_policy_fuzzer.cc +++ b/third_party/blink/renderer/core/permissions_policy/permissions_policy_fuzzer.cc
@@ -14,6 +14,7 @@ #include "third_party/blink/renderer/platform/wtf/vector.h" extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { + // TODO(crbug.com/1345994): Add seed corpus w/ wildcards. static blink::BlinkFuzzerTestSupport test_support = blink::BlinkFuzzerTestSupport(); blink::PolicyParserMessageBuffer logger;
diff --git a/third_party/blink/renderer/core/permissions_policy/permissions_policy_parser.cc b/third_party/blink/renderer/core/permissions_policy/permissions_policy_parser.cc index 3f5f07c..75bb228e 100644 --- a/third_party/blink/renderer/core/permissions_policy/permissions_policy_parser.cc +++ b/third_party/blink/renderer/core/permissions_policy/permissions_policy_parser.cc
@@ -7,8 +7,10 @@ #include <utility> #include "base/containers/contains.h" +#include "base/feature_list.h" #include "base/metrics/histogram_macros.h" #include "net/http/structured_headers.h" +#include "third_party/blink/public/common/features.h" #include "third_party/blink/public/common/permissions_policy/origin_with_possible_wildcards.h" #include "third_party/blink/public/mojom/permissions_policy/permissions_policy.mojom-blink.h" #include "third_party/blink/renderer/core/execution_context/execution_context.h" @@ -109,7 +111,8 @@ static constexpr wtf_size_t MAX_LENGTH_PARSE = 1 << 16; absl::optional<ParsedPermissionsPolicyDeclaration> ParseFeature( - const PermissionsPolicyParser::Declaration&); + const PermissionsPolicyParser::Declaration& declaration_node, + const PermissionsPolicyParser::NodeType type); struct ParsedAllowlist { std::vector<blink::OriginWithPossibleWildcards> allowed_origins; @@ -123,7 +126,8 @@ const String& feature_name); // Parse allowlist for feature. - ParsedAllowlist ParseAllowlist(const Vector<String>& origin_strings); + ParsedAllowlist ParseAllowlist(const Vector<String>& origin_strings, + const PermissionsPolicyParser::NodeType type); void ReportFeatureUsage(mojom::blink::PermissionsPolicyFeature feature); void ReportFeatureUsageLegacy(mojom::blink::PermissionsPolicyFeature feature); @@ -275,7 +279,11 @@ } ParsingContext::ParsedAllowlist ParsingContext::ParseAllowlist( - const Vector<String>& origin_strings) { + const Vector<String>& origin_strings, + const PermissionsPolicyParser::NodeType type) { + // The source of the PermissionsPolicyParser::Node must have an explicit + // source so that we know which wildcards can be enabled. + DCHECK_NE(PermissionsPolicyParser::NodeType::kUnknown, type); ParsedAllowlist allowlist; if (origin_strings.empty()) { // If a policy entry has no listed origins (e.g. "feature_name1" in @@ -309,6 +317,11 @@ // attribute.) url::Origin target_origin; + // Determine if there is a wildcard subdomain in the target origin + // (e.g., https://*.google.com). + bool has_subdomain_wildcard = false; + wtf_size_t wildcard_pos = kNotFound; + // If the iframe will have an opaque origin (for example, if it is // sandboxed, or has a data: URL), then 'src' needs to refer to the // opaque origin of the frame, which is not known yet. In this case, @@ -339,6 +352,30 @@ allowlist_includes_star_ = true; target_is_all = true; } + // If there's a subdomain wildcard in the `origin_string` of a permissions + // policy, then we can parse it out and update `has_subdomain_wildcard`. + // We know there's a subdomain wildcard because there is a exactly one `*` + // and it's after the scheme and before the rest of the host. + else if (base::FeatureList::IsEnabled( + features::kWildcardSubdomainsInPermissionsPolicy) && + type == PermissionsPolicyParser::NodeType::kHeader && + (wildcard_pos = origin_string.Find("://*.")) != kNotFound && + origin_string.find('*') == origin_string.ReverseFind('*')) { + // We need a copy as Remove modifies the original. + String origin_string_copy(origin_string); + origin_string_copy.Remove(wildcard_pos + 3, 2); + scoped_refptr<SecurityOrigin> parsed_origin = + SecurityOrigin::CreateFromString(origin_string_copy); + if (!parsed_origin->IsOpaque()) { + target_origin = parsed_origin->ToUrlOrigin(); + has_subdomain_wildcard = true; + allowlist_includes_origin_ = true; + } else { + logger_.Warn("Unrecognized origin with subdomain wildcard: '" + + origin_string + "'."); + continue; + } + } // Otherwise, parse the origin string and verify that the result is // valid. Invalid strings will produce an opaque origin, which will // result in an error message. @@ -360,10 +397,8 @@ } else if (target_is_opaque) { allowlist.matches_opaque_src = true; } else { - // TODO(crbug.com/1345994): Support wildcard matching. - allowlist.allowed_origins.emplace_back( - target_origin, - /*has_subdomain_wildcard=*/false); + allowlist.allowed_origins.emplace_back(target_origin, + has_subdomain_wildcard); } } } @@ -381,13 +416,15 @@ } absl::optional<ParsedPermissionsPolicyDeclaration> ParsingContext::ParseFeature( - const PermissionsPolicyParser::Declaration& declaration_node) { + const PermissionsPolicyParser::Declaration& declaration_node, + const PermissionsPolicyParser::NodeType type) { absl::optional<mojom::blink::PermissionsPolicyFeature> feature = ParseFeatureName(declaration_node.feature_name); if (!feature) return absl::nullopt; - ParsedAllowlist parsed_allowlist = ParseAllowlist(declaration_node.allowlist); + ParsedAllowlist parsed_allowlist = + ParseAllowlist(declaration_node.allowlist, type); // If same feature appeared more than once, only the first one counts. if (feature_observer_.FeatureObserved(*feature)) @@ -414,9 +451,10 @@ ParsedPermissionsPolicy ParsingContext::ParsePolicyFromNode( const PermissionsPolicyParser::Node& root) { ParsedPermissionsPolicy parsed_policy; - for (const PermissionsPolicyParser::Declaration& declaration_node : root) { + for (const PermissionsPolicyParser::Declaration& declaration_node : + root.declarations) { absl::optional<ParsedPermissionsPolicyDeclaration> parsed_feature = - ParseFeature(declaration_node); + ParseFeature(declaration_node, root.type); if (parsed_feature) { ReportFeatureUsage(parsed_feature->feature); ReportFeatureUsageLegacy(parsed_feature->feature); @@ -429,7 +467,8 @@ PermissionsPolicyParser::Node ParsingContext::ParseFeaturePolicyToIR( const String& policy) { - PermissionsPolicyParser::Node root; + PermissionsPolicyParser::Node root{ + PermissionsPolicyParser::NodeType::kAttribute}; if (policy.length() > MAX_LENGTH_PARSE) { logger_.Error("Feature policy declaration exceeds size limit(" + @@ -485,7 +524,7 @@ declaration_node.feature_name = std::move(tokens.front()); tokens.erase(tokens.begin()); declaration_node.allowlist = std::move(tokens); - root.push_back(declaration_node); + root.declarations.push_back(declaration_node); } } @@ -509,7 +548,8 @@ return {}; } - PermissionsPolicyParser::Node ir_root; + PermissionsPolicyParser::Node ir_root{ + PermissionsPolicyParser::NodeType::kHeader}; for (const auto& feature_entry : root.value()) { const auto& key = feature_entry.first; const char* feature_name = key.c_str(); @@ -560,7 +600,7 @@ if (allowlist.empty()) allowlist.push_back("'none'"); - ir_root.push_back( + ir_root.declarations.push_back( PermissionsPolicyParser::Declaration{feature_name, allowlist}); }
diff --git a/third_party/blink/renderer/core/permissions_policy/permissions_policy_parser.h b/third_party/blink/renderer/core/permissions_policy/permissions_policy_parser.h index b6f6739..873b1eea2 100644 --- a/third_party/blink/renderer/core/permissions_policy/permissions_policy_parser.h +++ b/third_party/blink/renderer/core/permissions_policy/permissions_policy_parser.h
@@ -56,7 +56,13 @@ String feature_name; Vector<String> allowlist; }; - using Node = Vector<Declaration>; + enum NodeType { kHeader, kAttribute, kUnknown }; + // We need to keep track of the source of the list of declarations as + // different features (e.g., wildcards) might be active per-context. + struct Node { + NodeType type{kUnknown}; + Vector<Declaration> declarations; + }; // Converts a header policy string into a vector of allowlists, one for each // feature specified. Unrecognized features are filtered out. The optional
diff --git a/third_party/blink/renderer/core/permissions_policy/permissions_policy_test.cc b/third_party/blink/renderer/core/permissions_policy/permissions_policy_test.cc index f5c999d..b0091d25 100644 --- a/third_party/blink/renderer/core/permissions_policy/permissions_policy_test.cc +++ b/third_party/blink/renderer/core/permissions_policy/permissions_policy_test.cc
@@ -8,7 +8,9 @@ #include <string> #include "base/ranges/algorithm.h" +#include "base/test/scoped_feature_list.h" #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/public/common/features.h" #include "third_party/blink/public/common/permissions_policy/origin_with_possible_wildcards.h" #include "third_party/blink/public/mojom/permissions_policy/permissions_policy.mojom-blink.h" #include "third_party/blink/renderer/core/frame/local_dom_window.h" @@ -22,6 +24,8 @@ // Origin strings used for tests #define ORIGIN_A "https://example.com/" +#define ORIGIN_A_SUBDOMAIN_WILDCARD "https://*.example.com/" +#define ORIGIN_A_SUBDOMAIN_ESCAPED "https://%2A.example.com/" #define ORIGIN_B "https://example.net/" #define ORIGIN_C "https://example.org/" #define OPAQUE_ORIGIN "" @@ -114,11 +118,16 @@ } }; +struct OriginWithPossibleWildcardsForTest { + const char* origin; + bool has_subdomain_wildcard; +}; + struct ParsedPolicyDeclarationForTest { mojom::blink::PermissionsPolicyFeature feature; bool matches_all_origins; bool matches_opaque_src; - std::vector<const char*> origins; + std::vector<OriginWithPossibleWildcardsForTest> allowed_origins; }; using ParsedPolicyForTest = std::vector<ParsedPolicyDeclarationForTest>; @@ -131,6 +140,7 @@ const char* permissions_policy_string; const char* self_origin; const char* src_origin; + const bool subdomain_wildcards; // Test expectation. ParsedPolicyForTest expected_parse_result; @@ -190,11 +200,15 @@ expected_declaration.matches_opaque_src); ASSERT_EQ(actual_declaration.allowed_origins.size(), - expected_declaration.origins.size()); + expected_declaration.allowed_origins.size()); for (size_t j = 0; j < actual_declaration.allowed_origins.size(); ++j) { EXPECT_TRUE( actual_declaration.allowed_origins[j].origin.IsSameOriginWith( - url::Origin::Create(GURL(expected_declaration.origins[j])))); + url::Origin::Create( + GURL(expected_declaration.allowed_origins[j].origin)))); + EXPECT_EQ( + actual_declaration.allowed_origins[j].has_subdomain_wildcard, + expected_declaration.allowed_origins[j].has_subdomain_wildcard); } } } @@ -208,6 +222,8 @@ } } + base::test::ScopedFeatureList scoped_feature_list_; + public: static const PermissionsPolicyParserTestCase kCases[]; }; @@ -220,6 +236,7 @@ /* permissions_policy_string */ "", /* self_origin */ ORIGIN_A, /* src_origin */ ORIGIN_B, + /* subdomain_wildcards */ false, /* expected_parse_result */ {}, }, { @@ -228,13 +245,14 @@ /* permissions_policy_string */ "geolocation=self", /* self_origin */ ORIGIN_A, /* src_origin */ ORIGIN_B, + /* subdomain_wildcards */ false, /* expected_parse_result */ { { mojom::blink::PermissionsPolicyFeature::kGeolocation, /* matches_all_origins */ false, /* matches_opaque_src */ false, - {ORIGIN_A}, + {{ORIGIN_A, /*has_subdomain_wildcard=*/false}}, }, }, }, @@ -244,13 +262,14 @@ /* permissions_policy_string */ "geolocation=(self)", /* self_origin */ ORIGIN_A, /* src_origin */ ORIGIN_B, + /* subdomain_wildcards */ false, /* expected_parse_result */ { { mojom::blink::PermissionsPolicyFeature::kGeolocation, /* matches_all_origins */ false, /* matches_opaque_src */ false, - {ORIGIN_A}, + {{ORIGIN_A, /*has_subdomain_wildcard=*/false}}, }, }, }, @@ -260,6 +279,7 @@ /* permissions_policy_string */ "geolocation=*", /* self_origin */ ORIGIN_A, /* src_origin */ ORIGIN_B, + /* subdomain_wildcards */ false, /* expected_parse_result */ { { @@ -282,6 +302,7 @@ "payment=self", /* self_origin */ ORIGIN_A, /* src_origin */ ORIGIN_B, + /* subdomain_wildcards */ false, /* expected_parse_result */ { { @@ -294,13 +315,14 @@ mojom::blink::PermissionsPolicyFeature::kFullscreen, /* matches_all_origins */ false, /* matches_opaque_src */ false, - {ORIGIN_B, ORIGIN_C}, + {{ORIGIN_B, /*has_subdomain_wildcard=*/false}, + {ORIGIN_C, /*has_subdomain_wildcard=*/false}}, }, { mojom::blink::PermissionsPolicyFeature::kPayment, /* matches_all_origins */ false, /* matches_opaque_src */ false, - {ORIGIN_A}, + {{ORIGIN_A, /*has_subdomain_wildcard=*/false}}, }, }, }, @@ -316,6 +338,7 @@ "payment=(self \"badorigin\")", /* self_origin */ ORIGIN_A, /* src_origin */ ORIGIN_B, + /* subdomain_wildcards */ false, /* expected_parse_result */ { { @@ -328,13 +351,14 @@ mojom::blink::PermissionsPolicyFeature::kFullscreen, /* matches_all_origins */ false, /* matches_opaque_src */ false, - {ORIGIN_B, ORIGIN_C}, + {{ORIGIN_B, /*has_subdomain_wildcard=*/false}, + {ORIGIN_C, /*has_subdomain_wildcard=*/false}}, }, { mojom::blink::PermissionsPolicyFeature::kPayment, /* matches_all_origins */ false, /* matches_opaque_src */ false, - {ORIGIN_A}, + {{ORIGIN_A, /*has_subdomain_wildcard=*/false}}, }, }, }, @@ -348,25 +372,26 @@ "geolocation=self,fullscreen=self,payment=self", /* self_origin */ ORIGIN_A, /* src_origin */ nullptr, + /* subdomain_wildcards */ false, /* expected_parse_result */ { { mojom::blink::PermissionsPolicyFeature::kGeolocation, /* matches_all_origins */ false, /* matches_opaque_src */ false, - {ORIGIN_A}, + {{ORIGIN_A, /*has_subdomain_wildcard=*/false}}, }, { mojom::blink::PermissionsPolicyFeature::kFullscreen, /* matches_all_origins */ false, /* matches_opaque_src */ false, - {ORIGIN_A}, + {{ORIGIN_A, /*has_subdomain_wildcard=*/false}}, }, { mojom::blink::PermissionsPolicyFeature::kPayment, /* matches_all_origins */ false, /* matches_opaque_src */ false, - {ORIGIN_A}, + {{ORIGIN_A, /*has_subdomain_wildcard=*/false}}, }, }, }, @@ -376,6 +401,7 @@ /* permissions_policy_string */ "", /* self_origin */ ORIGIN_A, /* src_origin */ OPAQUE_ORIGIN, + /* subdomain_wildcards */ false, /* expected_parse_result */ {}, }, { @@ -384,6 +410,7 @@ /* permissions_policy_string */ NOT_APPLICABLE, /* self_origin */ ORIGIN_A, /* src_origin */ OPAQUE_ORIGIN, + /* subdomain_wildcards */ false, /* expected_parse_result */ { { @@ -400,6 +427,7 @@ /* permissions_policy_string */ NOT_APPLICABLE, /* self_origin */ ORIGIN_A, /* src_origin */ OPAQUE_ORIGIN, + /* subdomain_wildcards */ false, /* expected_parse_result */ { { @@ -416,6 +444,7 @@ /* permissions_policy_string */ "geolocation=*", /* self_origin */ ORIGIN_A, /* src_origin */ OPAQUE_ORIGIN, + /* subdomain_wildcards */ false, /* expected_parse_result */ { { @@ -433,13 +462,15 @@ "geolocation=(\"" ORIGIN_B "\" \"" ORIGIN_C "\")", /* self_origin */ ORIGIN_A, /* src_origin */ OPAQUE_ORIGIN, + /* subdomain_wildcards */ false, /* expected_parse_result */ { { mojom::blink::PermissionsPolicyFeature::kGeolocation, /* matches_all_origins */ false, /* matches_opaque_src */ false, - {ORIGIN_B, ORIGIN_C}, + {{ORIGIN_B, /*has_subdomain_wildcard=*/false}, + {ORIGIN_C, /*has_subdomain_wildcard=*/false}}, }, }, }, @@ -450,13 +481,14 @@ /* permissions_policy_string */ NOT_APPLICABLE, /* self_origin */ ORIGIN_A, /* src_origin */ OPAQUE_ORIGIN, + /* subdomain_wildcards */ false, /* expected_parse_result */ { { mojom::blink::PermissionsPolicyFeature::kGeolocation, /* matches_all_origins */ false, /* matches_opaque_src */ true, - {ORIGIN_B}, + {{ORIGIN_B, /*has_subdomain_wildcard=*/false}}, }, }, }, @@ -467,6 +499,7 @@ /* permissions_policy_string */ "geolocation=9", /* self_origin */ ORIGIN_A, /* src_origin */ nullptr, + /* subdomain_wildcards */ false, /* expected_parse_result */ { { @@ -484,6 +517,7 @@ /* permissions_policy_string */ "geolocation=1.1", /* self_origin */ ORIGIN_A, /* src_origin */ nullptr, + /* subdomain_wildcards */ false, /* expected_parse_result */ { { @@ -501,6 +535,7 @@ /* permissions_policy_string */ "geolocation=?0", /* self_origin */ ORIGIN_A, /* src_origin */ nullptr, + /* subdomain_wildcards */ false, /* expected_parse_result */ { { @@ -517,6 +552,7 @@ /* permissions_policy_string */ "geolocation=\"\"", /* self_origin */ ORIGIN_A, /* src_origin */ nullptr, + /* subdomain_wildcards */ false, /* expected_parse_result */ { { @@ -527,6 +563,114 @@ }, }, }, + { + /* test_name */ "ProperWildcardIncludedWhileFeatureDisabled", + /* feature_policy_string */ + "fullscreen " ORIGIN_A_SUBDOMAIN_WILDCARD, + /* permissions_policy_string */ + "fullscreen=(\"" ORIGIN_A_SUBDOMAIN_WILDCARD "\")", + /* self_origin */ ORIGIN_A, + /* src_origin */ ORIGIN_B, + /* subdomain_wildcards */ false, + /* expected_parse_result */ + { + { + mojom::blink::PermissionsPolicyFeature::kFullscreen, + /* matches_all_origins */ false, + /* matches_opaque_src */ false, + {{ORIGIN_A_SUBDOMAIN_ESCAPED, + /*has_subdomain_wildcard=*/false}}, + }, + }, + }, + { + /* test_name */ "ProperWildcardIncludedWhileFeatureEnabledForFeatur" + "ePolicy", + /* feature_policy_string */ + "fullscreen " ORIGIN_A_SUBDOMAIN_WILDCARD, + /* permissions_policy_string */ NOT_APPLICABLE, + /* self_origin */ ORIGIN_A, + /* src_origin */ ORIGIN_B, + /* subdomain_wildcards */ true, + /* expected_parse_result */ + { + { + mojom::blink::PermissionsPolicyFeature::kFullscreen, + /* matches_all_origins */ false, + /* matches_opaque_src */ false, + {{ORIGIN_A_SUBDOMAIN_ESCAPED, + /*has_subdomain_wildcard=*/false}}, + }, + }, + }, + { + /* test_name */ "ProperWildcardIncludedWhileFeatureEnabledForPermis" + "sionsPolicy", + /* feature_policy_string */ NOT_APPLICABLE, + /* permissions_policy_string */ + "fullscreen=(\"" ORIGIN_A_SUBDOMAIN_WILDCARD "\")", + /* self_origin */ ORIGIN_A, + /* src_origin */ ORIGIN_B, + /* subdomain_wildcards */ true, + /* expected_parse_result */ + { + { + mojom::blink::PermissionsPolicyFeature::kFullscreen, + /* matches_all_origins */ false, + /* matches_opaque_src */ false, + {{ORIGIN_A, + /*has_subdomain_wildcard=*/true}}, + }, + }, + }, + { + /* test_name */ "ImproperWildcardsIncludedWhileFeatureDisabled", + /* feature_policy_string */ + "fullscreen *://example.com https://foo.*.example.com " + "https://*.*.example.com https://example.com:*", + /* permissions_policy_string */ + "fullscreen=(\"*://example.com\" \"https://foo.*.example.com\" " + "\"https://*.*.example.com\" \"https://example.com:*\")", + /* self_origin */ ORIGIN_A, + /* src_origin */ ORIGIN_B, + /* subdomain_wildcards */ false, + /* expected_parse_result */ + { + { + mojom::blink::PermissionsPolicyFeature::kFullscreen, + /* matches_all_origins */ false, + /* matches_opaque_src */ false, + {{"https://%2A.%2A.example.com", + /*has_subdomain_wildcard=*/false}, + {"https://foo.%2A.example.com", + /*has_subdomain_wildcard=*/false}}, + }, + }, + }, + { + /* test_name */ "ImproperWildcardsIncludedWhileFeatureEnabled", + /* feature_policy_string */ + "fullscreen *://example.com https://foo.*.example.com " + "https://*.*.example.com https://example.com:*", + /* permissions_policy_string */ + "fullscreen=(\"*://example.com\" \"https://foo.*.example.com\" " + "\"https://*.*.example.com\" \"https://example.com:*\")", + /* self_origin */ ORIGIN_A, + /* src_origin */ ORIGIN_B, + /* subdomain_wildcards */ true, + /* expected_parse_result */ + { + { + mojom::blink::PermissionsPolicyFeature::kFullscreen, + /* matches_all_origins */ false, + /* matches_opaque_src */ false, + {{"https://%2A.%2A.example.com", + /*has_subdomain_wildcard=*/false}, + {"https://foo.%2A.example.com", + /*has_subdomain_wildcard=*/false}}, + }, + }, + }, }; INSTANTIATE_TEST_SUITE_P( @@ -543,7 +687,9 @@ return; ASSERT_NE(test_case.self_origin, nullptr); - + scoped_feature_list_.InitWithFeatureState( + features::kWildcardSubdomainsInPermissionsPolicy, + test_case.subdomain_wildcards); CheckParsedPolicy( ParseFeaturePolicy(test_case.feature_policy_string, test_case.self_origin, test_case.src_origin, logger, test_feature_name_map), @@ -557,6 +703,9 @@ return; ASSERT_NE(test_case.self_origin, nullptr); + scoped_feature_list_.InitWithFeatureState( + features::kWildcardSubdomainsInPermissionsPolicy, + test_case.subdomain_wildcards); CheckParsedPolicy( ParsePermissionsPolicy(test_case.permissions_policy_string, test_case.self_origin, test_case.src_origin, @@ -603,7 +752,7 @@ mojom::blink::PermissionsPolicyFeature::kGeolocation, /* matches_all_origins */ false, /* matches_opaque_src */ false, - {ORIGIN_A}, + {{ORIGIN_A, /*has_subdomain_wildcard=*/false}}, }, }); @@ -629,7 +778,7 @@ mojom::blink::PermissionsPolicyFeature::kGeolocation, /* matches_all_origins */ false, /* matches_opaque_src */ false, - {ORIGIN_A}, + {{ORIGIN_A, /*has_subdomain_wildcard=*/false}}, }, { mojom::blink::PermissionsPolicyFeature::kPayment, @@ -641,7 +790,7 @@ mojom::blink::PermissionsPolicyFeature::kFullscreen, /* matches_all_origins */ false, /* matches_opaque_src */ false, - {ORIGIN_A}, + {{ORIGIN_A, /*has_subdomain_wildcard=*/false}}, }, }); } @@ -741,7 +890,7 @@ mojom::blink::PermissionsPolicyFeature::kGeolocation, /* matches_all_origins */ false, /* matches_opaque_src */ false, - {ORIGIN_A}, + {{ORIGIN_A, /*has_subdomain_wildcard=*/false}}, }, });
diff --git a/third_party/blink/renderer/core/permissions_policy/policy_test.cc b/third_party/blink/renderer/core/permissions_policy/policy_test.cc index 400bfca..f9a14993 100644 --- a/third_party/blink/renderer/core/permissions_policy/policy_test.cc +++ b/third_party/blink/renderer/core/permissions_policy/policy_test.cc
@@ -2,8 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "base/test/scoped_feature_list.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/public/common/features.h" #include "third_party/blink/renderer/core/frame/local_dom_window.h" #include "third_party/blink/renderer/core/frame/local_frame.h" #include "third_party/blink/renderer/core/permissions_policy/dom_feature_policy.h" @@ -17,25 +19,30 @@ namespace { constexpr char kSelfOrigin[] = "https://selforigin.com"; constexpr char kOriginA[] = "https://example.com"; +constexpr char kOriginASubdomain[] = "https://sub.example.com"; constexpr char kOriginB[] = "https://example.net"; +constexpr char kOriginBSubdomain[] = "https://sub.example.net"; } // namespace using testing::UnorderedElementsAre; -class PolicyTest : public testing::Test { +class PolicyTest : public testing::TestWithParam<bool> { public: void SetUp() override { + scoped_feature_list_.InitWithFeatureState( + features::kWildcardSubdomainsInPermissionsPolicy, + HasWildcardSubdomainsInPermissionsPolicy()); page_holder_ = std::make_unique<DummyPageHolder>(); auto origin = SecurityOrigin::CreateFromString(kSelfOrigin); auto permissions_policy = PermissionsPolicy::CreateFromParentPolicy( - nullptr, ParsedPermissionsPolicy(), origin->ToUrlOrigin()); + nullptr, {}, origin->ToUrlOrigin()); auto header = PermissionsPolicyParser::ParseHeader( "fullscreen *; payment 'self'; midi 'none'; camera 'self' " "https://example.com https://example.net", - /* permissions_policy_header */ g_empty_string, origin.get(), - dummy_logger_, dummy_logger_); + "gyroscope=(self \"https://*.example.com\" \"https://example.net\")", + origin.get(), dummy_logger_, dummy_logger_); permissions_policy->SetHeaderPolicy(header); auto& security_context = @@ -46,12 +53,15 @@ DOMFeaturePolicy* GetPolicy() const { return policy_; } + bool HasWildcardSubdomainsInPermissionsPolicy() { return GetParam(); } + PolicyParserMessageBuffer dummy_logger_ = PolicyParserMessageBuffer("", true /* discard_message */); protected: std::unique_ptr<DummyPageHolder> page_holder_; Persistent<DOMFeaturePolicy> policy_; + base::test::ScopedFeatureList scoped_feature_list_; }; class DOMFeaturePolicyTest : public PolicyTest { @@ -63,6 +73,8 @@ } }; +INSTANTIATE_TEST_SUITE_P(All, DOMFeaturePolicyTest, testing::Bool()); + class IFramePolicyTest : public PolicyTest { public: void SetUp() override { @@ -73,7 +85,9 @@ } }; -TEST_F(DOMFeaturePolicyTest, TestAllowsFeature) { +INSTANTIATE_TEST_SUITE_P(All, IFramePolicyTest, testing::Bool()); + +TEST_P(DOMFeaturePolicyTest, TestAllowsFeature) { EXPECT_FALSE(GetPolicy()->allowsFeature(nullptr, "badfeature")); EXPECT_FALSE(GetPolicy()->allowsFeature(nullptr, "midi")); EXPECT_FALSE(GetPolicy()->allowsFeature(nullptr, "midi", kSelfOrigin)); @@ -90,9 +104,17 @@ EXPECT_TRUE(GetPolicy()->allowsFeature(nullptr, "geolocation", kSelfOrigin)); EXPECT_TRUE(GetPolicy()->allowsFeature(nullptr, "sync-xhr")); EXPECT_TRUE(GetPolicy()->allowsFeature(nullptr, "sync-xhr", kOriginA)); + EXPECT_TRUE(GetPolicy()->allowsFeature(nullptr, "gyroscope")); + EXPECT_FALSE(GetPolicy()->allowsFeature(nullptr, "gyroscope", kOriginA)); + EXPECT_EQ( + HasWildcardSubdomainsInPermissionsPolicy(), + GetPolicy()->allowsFeature(nullptr, "gyroscope", kOriginASubdomain)); + EXPECT_TRUE(GetPolicy()->allowsFeature(nullptr, "gyroscope", kOriginB)); + EXPECT_FALSE( + GetPolicy()->allowsFeature(nullptr, "gyroscope", kOriginBSubdomain)); } -TEST_F(DOMFeaturePolicyTest, TestGetAllowList) { +TEST_P(DOMFeaturePolicyTest, TestGetAllowList) { EXPECT_THAT(GetPolicy()->getAllowlistForFeature(nullptr, "camera"), UnorderedElementsAre(kSelfOrigin, kOriginA, kOriginB)); EXPECT_THAT(GetPolicy()->getAllowlistForFeature(nullptr, "payment"), @@ -106,13 +128,19 @@ EXPECT_TRUE(GetPolicy()->getAllowlistForFeature(nullptr, "midi").empty()); EXPECT_THAT(GetPolicy()->getAllowlistForFeature(nullptr, "sync-xhr"), UnorderedElementsAre("*")); + EXPECT_THAT(GetPolicy()->getAllowlistForFeature(nullptr, "gyroscope"), + UnorderedElementsAre(kSelfOrigin, kOriginB, + HasWildcardSubdomainsInPermissionsPolicy() + ? "https://*.example.com" + : "https://%2A.example.com")); } -TEST_F(DOMFeaturePolicyTest, TestAllowedFeatures) { +TEST_P(DOMFeaturePolicyTest, TestAllowedFeatures) { Vector<String> allowed_features = GetPolicy()->allowedFeatures(nullptr); EXPECT_TRUE(allowed_features.Contains("fullscreen")); EXPECT_TRUE(allowed_features.Contains("payment")); EXPECT_TRUE(allowed_features.Contains("camera")); + EXPECT_TRUE(allowed_features.Contains("gyroscope")); // "geolocation" has default policy as allowed on self origin. EXPECT_TRUE(allowed_features.Contains("geolocation")); EXPECT_FALSE(allowed_features.Contains("badfeature")); @@ -121,7 +149,7 @@ EXPECT_TRUE(allowed_features.Contains("sync-xhr")); } -TEST_F(IFramePolicyTest, TestAllowsFeature) { +TEST_P(IFramePolicyTest, TestAllowsFeature) { EXPECT_FALSE(GetPolicy()->allowsFeature(nullptr, "badfeature")); EXPECT_FALSE(GetPolicy()->allowsFeature(nullptr, "midi")); EXPECT_FALSE(GetPolicy()->allowsFeature(nullptr, "midi", kSelfOrigin)); @@ -139,9 +167,16 @@ EXPECT_TRUE(GetPolicy()->allowsFeature(nullptr, "geolocation", kSelfOrigin)); EXPECT_TRUE(GetPolicy()->allowsFeature(nullptr, "sync-xhr")); EXPECT_TRUE(GetPolicy()->allowsFeature(nullptr, "sync-xhr", kOriginA)); + EXPECT_TRUE(GetPolicy()->allowsFeature(nullptr, "gyroscope")); + EXPECT_FALSE(GetPolicy()->allowsFeature(nullptr, "gyroscope", kOriginA)); + EXPECT_FALSE( + GetPolicy()->allowsFeature(nullptr, "gyroscope", kOriginASubdomain)); + EXPECT_FALSE(GetPolicy()->allowsFeature(nullptr, "gyroscope", kOriginB)); + EXPECT_FALSE( + GetPolicy()->allowsFeature(nullptr, "gyroscope", kOriginBSubdomain)); } -TEST_F(IFramePolicyTest, TestGetAllowList) { +TEST_P(IFramePolicyTest, TestGetAllowList) { EXPECT_THAT(GetPolicy()->getAllowlistForFeature(nullptr, "camera"), UnorderedElementsAre(kSelfOrigin)); EXPECT_THAT(GetPolicy()->getAllowlistForFeature(nullptr, "payment"), @@ -155,9 +190,11 @@ EXPECT_TRUE(GetPolicy()->getAllowlistForFeature(nullptr, "midi").empty()); EXPECT_THAT(GetPolicy()->getAllowlistForFeature(nullptr, "sync-xhr"), UnorderedElementsAre("*")); + EXPECT_THAT(GetPolicy()->getAllowlistForFeature(nullptr, "gyroscope"), + UnorderedElementsAre(kSelfOrigin)); } -TEST_F(IFramePolicyTest, TestSameOriginAllowedFeatures) { +TEST_P(IFramePolicyTest, TestSameOriginAllowedFeatures) { Vector<String> allowed_features = GetPolicy()->allowedFeatures(nullptr); // These features are allowed in a same origin context, and not restricted by // the parent document's policy. @@ -165,6 +202,7 @@ EXPECT_TRUE(allowed_features.Contains("payment")); EXPECT_TRUE(allowed_features.Contains("camera")); EXPECT_TRUE(allowed_features.Contains("geolocation")); + EXPECT_TRUE(allowed_features.Contains("gyroscope")); // "midi" is restricted by the parent document's policy. EXPECT_FALSE(allowed_features.Contains("midi")); // "sync-xhr" is allowed on all origins. @@ -173,7 +211,7 @@ EXPECT_FALSE(allowed_features.Contains("badfeature")); } -TEST_F(IFramePolicyTest, TestCrossOriginAllowedFeatures) { +TEST_P(IFramePolicyTest, TestCrossOriginAllowedFeatures) { // Update the iframe's policy, given a new origin. GetPolicy()->UpdateContainerPolicy( ParsedPermissionsPolicy(), SecurityOrigin::CreateFromString(kOriginA)); @@ -184,16 +222,18 @@ EXPECT_FALSE(allowed_features.Contains("camera")); EXPECT_FALSE(allowed_features.Contains("geolocation")); EXPECT_FALSE(allowed_features.Contains("midi")); + EXPECT_FALSE(allowed_features.Contains("gyroscope")); // "sync-xhr" is allowed on all origins. EXPECT_TRUE(allowed_features.Contains("sync-xhr")); // This feature does not exist, so should not be advertised as allowed. EXPECT_FALSE(allowed_features.Contains("badfeature")); } -TEST_F(IFramePolicyTest, TestCombinedPolicy) { +TEST_P(IFramePolicyTest, TestCombinedPolicyOnOriginA) { ParsedPermissionsPolicy container_policy = PermissionsPolicyParser::ParseAttribute( - "geolocation 'src'; payment 'none'; midi; camera 'src'", + "geolocation 'src'; payment 'none'; midi; camera 'src'; gyroscope " + "'src'", SecurityOrigin::CreateFromString(kSelfOrigin), SecurityOrigin::CreateFromString(kOriginA), dummy_logger_); GetPolicy()->UpdateContainerPolicy( @@ -202,6 +242,7 @@ // These features are not explicitly allowed. EXPECT_FALSE(allowed_features.Contains("fullscreen")); EXPECT_FALSE(allowed_features.Contains("payment")); + EXPECT_FALSE(allowed_features.Contains("gyroscope")); // These features are explicitly allowed. EXPECT_TRUE(allowed_features.Contains("geolocation")); EXPECT_TRUE(allowed_features.Contains("camera")); @@ -214,4 +255,81 @@ EXPECT_FALSE(allowed_features.Contains("badfeature")); } +TEST_P(IFramePolicyTest, TestCombinedPolicyOnOriginASubdomain) { + ParsedPermissionsPolicy container_policy = + PermissionsPolicyParser::ParseAttribute( + "geolocation 'src'; payment 'none'; midi; camera 'src'; gyroscope " + "'src'", + SecurityOrigin::CreateFromString(kSelfOrigin), + SecurityOrigin::CreateFromString(kOriginASubdomain), dummy_logger_); + GetPolicy()->UpdateContainerPolicy( + container_policy, SecurityOrigin::CreateFromString(kOriginASubdomain)); + Vector<String> allowed_features = GetPolicy()->allowedFeatures(nullptr); + // These features are not explicitly allowed. + EXPECT_FALSE(allowed_features.Contains("fullscreen")); + EXPECT_FALSE(allowed_features.Contains("payment")); + // These features are explicitly allowed. + EXPECT_TRUE(allowed_features.Contains("geolocation")); + // These are allowed by the attribute, but still blocked by the parent policy. + EXPECT_FALSE(allowed_features.Contains("midi")); + EXPECT_FALSE(allowed_features.Contains("camera")); + // These features are allowed if subdomain wildcard matching is on. + EXPECT_EQ(HasWildcardSubdomainsInPermissionsPolicy(), + allowed_features.Contains("gyroscope")); + // "sync-xhr" is still implicitly allowed on all origins. + EXPECT_TRUE(allowed_features.Contains("sync-xhr")); + // This feature does not exist, so should not be advertised as allowed. + EXPECT_FALSE(allowed_features.Contains("badfeature")); +} + +TEST_P(IFramePolicyTest, TestCombinedPolicyOnOriginB) { + ParsedPermissionsPolicy container_policy = + PermissionsPolicyParser::ParseAttribute( + "geolocation 'src'; payment 'none'; midi; camera 'src'; gyroscope " + "'src'", + SecurityOrigin::CreateFromString(kSelfOrigin), + SecurityOrigin::CreateFromString(kOriginB), dummy_logger_); + GetPolicy()->UpdateContainerPolicy( + container_policy, SecurityOrigin::CreateFromString(kOriginB)); + Vector<String> allowed_features = GetPolicy()->allowedFeatures(nullptr); + // These features are not explicitly allowed. + EXPECT_FALSE(allowed_features.Contains("fullscreen")); + EXPECT_FALSE(allowed_features.Contains("payment")); + // These features are explicitly allowed. + EXPECT_TRUE(allowed_features.Contains("geolocation")); + EXPECT_TRUE(allowed_features.Contains("camera")); + EXPECT_TRUE(allowed_features.Contains("gyroscope")); + // These are allowed by the attribute, but still blocked by the parent policy. + EXPECT_FALSE(allowed_features.Contains("midi")); + // "sync-xhr" is still implicitly allowed on all origins. + EXPECT_TRUE(allowed_features.Contains("sync-xhr")); + // This feature does not exist, so should not be advertised as allowed. + EXPECT_FALSE(allowed_features.Contains("badfeature")); +} + +TEST_P(IFramePolicyTest, TestCombinedPolicyOnOriginBSubdomain) { + ParsedPermissionsPolicy container_policy = + PermissionsPolicyParser::ParseAttribute( + "geolocation 'src'; payment 'none'; midi; camera 'src'; gyroscope " + "'src'", + SecurityOrigin::CreateFromString(kSelfOrigin), + SecurityOrigin::CreateFromString(kOriginBSubdomain), dummy_logger_); + GetPolicy()->UpdateContainerPolicy( + container_policy, SecurityOrigin::CreateFromString(kOriginBSubdomain)); + Vector<String> allowed_features = GetPolicy()->allowedFeatures(nullptr); + // These features are not explicitly allowed. + EXPECT_FALSE(allowed_features.Contains("fullscreen")); + EXPECT_FALSE(allowed_features.Contains("payment")); + EXPECT_FALSE(allowed_features.Contains("gyroscope")); + // These features are explicitly allowed. + EXPECT_TRUE(allowed_features.Contains("geolocation")); + // These are allowed by the attribute, but still blocked by the parent policy. + EXPECT_FALSE(allowed_features.Contains("midi")); + EXPECT_FALSE(allowed_features.Contains("camera")); + // "sync-xhr" is still implicitly allowed on all origins. + EXPECT_TRUE(allowed_features.Contains("sync-xhr")); + // This feature does not exist, so should not be advertised as allowed. + EXPECT_FALSE(allowed_features.Contains("badfeature")); +} + } // namespace blink
diff --git a/third_party/blink/renderer/modules/file_system_access/file_system_directory_handle.cc b/third_party/blink/renderer/modules/file_system_access/file_system_directory_handle.cc index 042d0d4..c712db0 100644 --- a/third_party/blink/renderer/modules/file_system_access/file_system_directory_handle.cc +++ b/third_party/blink/renderer/modules/file_system_access/file_system_directory_handle.cc
@@ -321,4 +321,13 @@ std::move(callback))); } +void FileSystemDirectoryHandle::GetUniqueIdImpl( + base::OnceCallback<void(const WTF::String&)> callback) { + if (!mojo_ptr_.is_bound()) { + std::move(callback).Run(""); + return; + } + mojo_ptr_->GetUniqueId(std::move(callback)); +} + } // namespace blink
diff --git a/third_party/blink/renderer/modules/file_system_access/file_system_directory_handle.h b/third_party/blink/renderer/modules/file_system_access/file_system_directory_handle.h index 3bcb1c5..2b05ce3 100644 --- a/third_party/blink/renderer/modules/file_system_access/file_system_directory_handle.h +++ b/third_party/blink/renderer/modules/file_system_access/file_system_directory_handle.h
@@ -82,6 +82,7 @@ mojo::PendingRemote<mojom::blink::FileSystemAccessTransferToken> other, base::OnceCallback<void(mojom::blink::FileSystemAccessErrorPtr, bool)>) override; + void GetUniqueIdImpl(base::OnceCallback<void(const WTF::String&)>) override; HeapMojoRemote<mojom::blink::FileSystemAccessDirectoryHandle> mojo_ptr_; };
diff --git a/third_party/blink/renderer/modules/file_system_access/file_system_file_handle.cc b/third_party/blink/renderer/modules/file_system_access/file_system_file_handle.cc index e1b0102e..35fba0ba 100644 --- a/third_party/blink/renderer/modules/file_system_access/file_system_file_handle.cc +++ b/third_party/blink/renderer/modules/file_system_access/file_system_file_handle.cc
@@ -248,4 +248,13 @@ mojo_ptr_->IsSameEntry(std::move(other), std::move(callback)); } +void FileSystemFileHandle::GetUniqueIdImpl( + base::OnceCallback<void(const WTF::String&)> callback) { + if (!mojo_ptr_.is_bound()) { + std::move(callback).Run(""); + return; + } + mojo_ptr_->GetUniqueId(std::move(callback)); +} + } // namespace blink
diff --git a/third_party/blink/renderer/modules/file_system_access/file_system_file_handle.h b/third_party/blink/renderer/modules/file_system_access/file_system_file_handle.h index 8b9c567..9b0c03b 100644 --- a/third_party/blink/renderer/modules/file_system_access/file_system_file_handle.h +++ b/third_party/blink/renderer/modules/file_system_access/file_system_file_handle.h
@@ -63,6 +63,7 @@ mojo::PendingRemote<mojom::blink::FileSystemAccessTransferToken> other, base::OnceCallback<void(mojom::blink::FileSystemAccessErrorPtr, bool)>) override; + void GetUniqueIdImpl(base::OnceCallback<void(const WTF::String&)>) override; HeapMojoRemote<mojom::blink::FileSystemAccessFileHandle> mojo_ptr_; };
diff --git a/third_party/blink/renderer/modules/file_system_access/file_system_handle.cc b/third_party/blink/renderer/modules/file_system_access/file_system_handle.cc index 832127b..922a431 100644 --- a/third_party/blink/renderer/modules/file_system_access/file_system_handle.cc +++ b/third_party/blink/renderer/modules/file_system_access/file_system_handle.cc
@@ -200,6 +200,21 @@ return result; } +ScriptPromise FileSystemHandle::getUniqueId(ScriptState* script_state) { + auto* resolver = MakeGarbageCollected<ScriptPromiseResolver>(script_state); + ScriptPromise result = resolver->Promise(); + + GetUniqueIdImpl(WTF::BindOnce( + [](FileSystemHandle*, ScriptPromiseResolver* resolver, + const WTF::String& id) { + // Keep `this` alive so the handle will not be garbage-collected + // before the promise is resolved. + resolver->Resolve(std::move(id)); + }, + WrapPersistent(this), WrapPersistent(resolver))); + return result; +} + void FileSystemHandle::Trace(Visitor* visitor) const { ScriptWrappable::Trace(visitor); ExecutionContextClient::Trace(visitor);
diff --git a/third_party/blink/renderer/modules/file_system_access/file_system_handle.h b/third_party/blink/renderer/modules/file_system_access/file_system_handle.h index 481ed600..48115cda 100644 --- a/third_party/blink/renderer/modules/file_system_access/file_system_handle.h +++ b/third_party/blink/renderer/modules/file_system_access/file_system_handle.h
@@ -51,6 +51,7 @@ ScriptPromise remove(ScriptState*, const FileSystemRemoveOptions* options); ScriptPromise isSameEntry(ScriptState*, FileSystemHandle* other); + ScriptPromise getUniqueId(ScriptState*); // Grab a handle to a transfer token. This may return an invalid PendingRemote // if the context is already destroyed. @@ -78,6 +79,8 @@ mojo::PendingRemote<mojom::blink::FileSystemAccessTransferToken> other, base::OnceCallback<void(mojom::blink::FileSystemAccessErrorPtr, bool)>) = 0; + virtual void GetUniqueIdImpl( + base::OnceCallback<void(const WTF::String&)>) = 0; String name_; };
diff --git a/third_party/blink/renderer/modules/file_system_access/file_system_handle.idl b/third_party/blink/renderer/modules/file_system_access/file_system_handle.idl index 5f8c942..1c563cc 100644 --- a/third_party/blink/renderer/modules/file_system_access/file_system_handle.idl +++ b/third_party/blink/renderer/modules/file_system_access/file_system_handle.idl
@@ -47,4 +47,9 @@ [CallWith=ScriptState, Measure] Promise<boolean> isSameEntry(FileSystemHandle other); + + [ + CallWith=ScriptState, + RuntimeEnabled=FileSystemAccessAPIExperimental + ] Promise<USVString> getUniqueId(); };
diff --git a/third_party/blink/renderer/modules/manifest/manifest_parser.cc b/third_party/blink/renderer/modules/manifest/manifest_parser.cc index b86d30a..7587c233 100644 --- a/third_party/blink/renderer/modules/manifest/manifest_parser.cc +++ b/third_party/blink/renderer/modules/manifest/manifest_parser.cc
@@ -1612,7 +1612,8 @@ Vector<blink::ParsedPermissionsPolicyDeclaration> ManifestParser::ParseIsolatedAppPermissions(const JSONObject* object) { - PermissionsPolicyParser::Node policy; + PermissionsPolicyParser::Node policy{ + PermissionsPolicyParser::NodeType::kHeader}; JSONValue* json_value = object->Get("permissions_policy"); if (!json_value) @@ -1649,7 +1650,7 @@ String wrapped_origin = (origin == "*" ? origin : "'" + origin + "'"); new_policy.allowlist.push_back(wrapped_origin); } - policy.push_back(new_policy); + policy.declarations.push_back(new_policy); } PolicyParserMessageBuffer logger(
diff --git a/third_party/blink/renderer/modules/webgpu/gpu.cc b/third_party/blink/renderer/modules/webgpu/gpu.cc index ccb07d8..b427a048 100644 --- a/third_party/blink/renderer/modules/webgpu/gpu.cc +++ b/third_party/blink/renderer/modules/webgpu/gpu.cc
@@ -139,6 +139,29 @@ return dawn_options; } +// Returns the execution context token given the context. Currently returning +// the WebGPU specific execution context token. +// TODO(dawn:549) Might be able to use ExecutionContextToken instead of WebGPU +// specific execution context token if/when DocumentToken becomes a part of +// ExecutionContextToken. +WebGPUExecutionContextToken GetExecutionContextToken( + const ExecutionContext* execution_context) { + auto execution_context_token = execution_context->GetExecutionContextToken(); + + // TODO(dawn:549) Implement passing real DocumentToken when ready. + // WebGPU only supports 2 types of context tokens, DocumentTokens and + // DedicatedWorkerTokens. We are currently passing a placeholder + // DocumentToken (by default construction), and a real DedicatedWorkerToken. + // The token is sent to the GPU process so that it can be cross-referenced + // against the browser process to get an isolation key for caching purposes. + WebGPUExecutionContextToken webgpu_execution_context_token; + if (execution_context_token.Is<DedicatedWorkerToken>()) { + webgpu_execution_context_token = + execution_context_token.GetAs<DedicatedWorkerToken>(); + } + return webgpu_execution_context_token; +} + } // anonymous namespace // static @@ -281,11 +304,8 @@ resolver->Resolve(v8::Null(script_state->GetIsolate())); return promise; } else { - // Get an identifying token from the execution context to be sent to the - // GPU process so that it can be cross-referenced against the browser - // process to get an isolation key for caching purposes. - context_provider->WebGPUInterface()->SetExecutionContextToken( - execution_context->GetExecutionContextToken()); + context_provider->WebGPUInterface()->SetWebGPUExecutionContextToken( + GetExecutionContextToken(execution_context)); // Make a new DawnControlClientHolder with the context provider we just // made and set the lost context callback
diff --git a/third_party/blink/renderer/platform/image-decoders/jpeg/jpeg_image_decoder.cc b/third_party/blink/renderer/platform/image-decoders/jpeg/jpeg_image_decoder.cc index a37da977..55802bc3 100644 --- a/third_party/blink/renderer/platform/image-decoders/jpeg/jpeg_image_decoder.cc +++ b/third_party/blink/renderer/platform/image-decoders/jpeg/jpeg_image_decoder.cc
@@ -307,8 +307,7 @@ } static void ReadExifDirectory(JOCTET* dir_start, - JOCTET* tiff_start, - JOCTET* root_dir_start, + JOCTET* data_start, JOCTET* data_end, bool is_big_endian, DecodedImageMetaData& metadata, @@ -347,9 +346,9 @@ // EXIF stores the value with an offset if it's bigger than 4 bytes, e.g. for rational values. if (type == kUnsignedRationalType) { value_ptr = - ReadPointerOffset(value_ptr, tiff_start, data_end, is_big_endian); + ReadPointerOffset(value_ptr, data_start, data_end, is_big_endian); // Make sure offset points to a valid location. - if (!value_ptr || value_ptr < ifd || value_ptr > data_end - 16) + if (!value_ptr || value_ptr > data_end - 16) continue; } @@ -406,12 +405,12 @@ case ExifTags::kExifOffsetTag: if (type == kUnsignedLongType && count == 1 && is_root) { - JOCTET* subdir = ReadPointerOffset(value_ptr, root_dir_start, - data_end, is_big_endian); + JOCTET* subdir = + ReadPointerOffset(value_ptr, data_start, data_end, is_big_endian); if (subdir) { - ReadExifDirectory(subdir, tiff_start, root_dir_start, data_end, - is_big_endian, metadata, false); + ReadExifDirectory(subdir, data_start, data_end, is_big_endian, + metadata, false); } } break; @@ -440,11 +439,10 @@ // When touching this code, it's useful to look at the tiff spec: // http://partners.adobe.com/public/developer/en/tiff/TIFF6.pdf JOCTET* data_end = marker->data + marker->data_length; - JOCTET* root_start = marker->data + kOffsetToTiffData; - JOCTET* tiff_start = marker->data + ifd_offset - 2; - JOCTET* ifd0 = root_start + ifd_offset; + JOCTET* data_start = marker->data + kOffsetToTiffData; + JOCTET* ifd0 = data_start + ifd_offset; - ReadExifDirectory(ifd0, tiff_start, root_start, data_end, is_big_endian, metadata); + ReadExifDirectory(ifd0, data_start, data_end, is_big_endian, metadata); } }
diff --git a/third_party/blink/renderer/platform/image-decoders/jpeg/jpeg_image_decoder_test.cc b/third_party/blink/renderer/platform/image-decoders/jpeg/jpeg_image_decoder_test.cc index 1e839961..69c9c34 100644 --- a/third_party/blink/renderer/platform/image-decoders/jpeg/jpeg_image_decoder_test.cc +++ b/third_party/blink/renderer/platform/image-decoders/jpeg/jpeg_image_decoder_test.cc
@@ -275,6 +275,24 @@ EXPECT_TRUE(test_decoder->Failed()); } +// Decode a JPEG with EXIF data that defines a density corrected size. The EXIF +// data has the initial IFD at the end of the data blob, and out-of-line data +// defined just after the header. +// The order of the EXIF data is: +// <header> <out-of-line data> <Exif IFD> <0th IFD> +TEST(JPEGImageDecoderTest, exifWithInitialIfdLast) { + scoped_refptr<SharedBuffer> test_data = + ReadFile(kDecodersTestingDir, "green-exif-ifd-last.jpg"); + ASSERT_TRUE(test_data.get()); + + std::unique_ptr<ImageDecoder> test_decoder = CreateJPEGDecoder(); + test_decoder->SetData(test_data.get(), true); + EXPECT_EQ(1u, test_decoder->FrameCount()); + ASSERT_TRUE(test_decoder->DecodeFrameBufferAtIndex(0)); + EXPECT_EQ(test_decoder->Orientation(), ImageOrientationEnum::kOriginTopRight); + EXPECT_EQ(test_decoder->DensityCorrectedSize(), gfx::Size(32, 32)); +} + TEST(JPEGImageDecoderTest, SupportedSizesSquare) { const char* jpeg_file = "/images/resources/gracehopper.jpg"; // 256x256 scoped_refptr<SharedBuffer> data = ReadFile(jpeg_file);
diff --git a/third_party/blink/renderer/platform/image-decoders/testing/green-exif-ifd-last.jpg b/third_party/blink/renderer/platform/image-decoders/testing/green-exif-ifd-last.jpg new file mode 100644 index 0000000..7aaf730 --- /dev/null +++ b/third_party/blink/renderer/platform/image-decoders/testing/green-exif-ifd-last.jpg Binary files differ
diff --git a/third_party/blink/web_tests/FlagExpectations/disable-layout-ng b/third_party/blink/web_tests/FlagExpectations/disable-layout-ng index d647e652..5ca6f774e 100644 --- a/third_party/blink/web_tests/FlagExpectations/disable-layout-ng +++ b/third_party/blink/web_tests/FlagExpectations/disable-layout-ng
@@ -771,6 +771,7 @@ ### external/wpt/css/css-multicol/ crbug.com/829028 external/wpt/css/css-multicol/abspos-containing-block-outside-spanner.html [ Failure ] +crbug.com/829028 external/wpt/css/css-multicol/auto-fill-auto-size-002-print.html [ Failure ] crbug.com/829028 external/wpt/css/css-multicol/balance-break-avoidance-001.html [ Failure ] crbug.com/829028 external/wpt/css/css-multicol/balance-break-avoidance-002.html [ Failure ] crbug.com/829028 external/wpt/css/css-multicol/balance-orphans-widows-000.html [ Failure ] @@ -802,6 +803,7 @@ crbug.com/829028 external/wpt/css/css-multicol/multicol-nested-018.html [ Failure ] crbug.com/829028 external/wpt/css/css-multicol/multicol-nested-022.html [ Failure ] crbug.com/829028 external/wpt/css/css-multicol/multicol-nested-023.html [ Failure ] +crbug.com/829028 external/wpt/css/css-multicol/multicol-nested-026.html [ Failure ] crbug.com/1246602 external/wpt/css/css-multicol/multicol-oof-inline-cb-001.html [ Failure ] crbug.com/1246602 external/wpt/css/css-multicol/multicol-oof-inline-cb-002.html [ Failure ] crbug.com/990240 external/wpt/css/css-multicol/multicol-rule-nested-balancing-004.html [ Failure ]
diff --git a/third_party/blink/web_tests/MSANExpectations b/third_party/blink/web_tests/MSANExpectations index 9fbc3cbe..7d8b1595 100644 --- a/third_party/blink/web_tests/MSANExpectations +++ b/third_party/blink/web_tests/MSANExpectations
@@ -124,3 +124,6 @@ crbug.com/887140 [ Linux ] virtual/hdr/color-jpeg-with-color-profile.html [ Skip ] crbug.com/887140 [ Linux ] virtual/hdr/color-profile-video.html [ Skip ] crbug.com/887140 [ Linux ] virtual/hdr/video-canvas-alpha.html [ Skip ] + +# Sheriff 2022-10-06, use-of-uninitialized-value +crbug.com/1372356 [ Linux ] virtual/oopr-canvas2d/fast/canvas/* [ Skip ]
diff --git a/third_party/blink/web_tests/SmokeTests/Mac.txt b/third_party/blink/web_tests/SmokeTests/Mac.txt index d33f06e..ce950c5 100644 --- a/third_party/blink/web_tests/SmokeTests/Mac.txt +++ b/third_party/blink/web_tests/SmokeTests/Mac.txt
@@ -1000,7 +1000,6 @@ http/tests/security/cross-origin-shared-worker-allowed.html http/tests/security/frameNavigation/xss-ALLOWED-parent-navigation-change-async.html http/tests/security/offscreencanvas-placeholder-read-blocked-no-crossorigin.html -http/tests/security/opened-document-security-origin-resets-on-navigation.html ietestcenter/css3/bordersbackgrounds/background-attachment-local-scrolling.htm images/color-profile-image-filter-all.html images/color-profile-svg-foreign-object.html
diff --git a/third_party/blink/web_tests/TestExpectations b/third_party/blink/web_tests/TestExpectations index 067f8ff1..68568baf 100644 --- a/third_party/blink/web_tests/TestExpectations +++ b/third_party/blink/web_tests/TestExpectations
@@ -3345,7 +3345,21 @@ crbug.com/626703 [ Win ] virtual/partitioned-cookies/http/tests/inspector-protocol/network/disabled-cache-navigation.js [ Failure ] # ====== New tests from wpt-importer added here ====== -crbug.com/1371978 [ Mac12-arm64 ] external/wpt/fetch/api/abort/serviceworker-intercepted.https.html [ Crash ] +crbug.com/626703 external/wpt/css/css-transforms/transform-background-007.html [ Failure ] +crbug.com/626703 external/wpt/css/css-transforms/transform-background-008.html [ Failure ] +crbug.com/626703 external/wpt/css/css-transforms/transform-root-bg-001.html [ Failure ] +crbug.com/626703 external/wpt/css/css-transforms/transform-root-bg-002.html [ Failure ] +crbug.com/626703 external/wpt/css/css-transforms/transform-root-bg-003.html [ Failure ] +crbug.com/626703 external/wpt/css/css-transforms/transform-translate-background-001.html [ Failure ] +crbug.com/626703 external/wpt/css/css-transforms/transform-translate-background-002.html [ Failure ] +crbug.com/626703 [ Mac12-arm64 ] external/wpt/fetch/api/abort/serviceworker-intercepted.https.html [ Timeout ] +crbug.com/626703 virtual/backface-visibility-interop/external/wpt/css/css-transforms/transform-background-007.html [ Failure ] +crbug.com/626703 virtual/backface-visibility-interop/external/wpt/css/css-transforms/transform-background-008.html [ Failure ] +crbug.com/626703 virtual/backface-visibility-interop/external/wpt/css/css-transforms/transform-root-bg-001.html [ Failure ] +crbug.com/626703 virtual/backface-visibility-interop/external/wpt/css/css-transforms/transform-root-bg-002.html [ Failure ] +crbug.com/626703 virtual/backface-visibility-interop/external/wpt/css/css-transforms/transform-root-bg-003.html [ Failure ] +crbug.com/626703 virtual/backface-visibility-interop/external/wpt/css/css-transforms/transform-translate-background-001.html [ Failure ] +crbug.com/626703 virtual/backface-visibility-interop/external/wpt/css/css-transforms/transform-translate-background-002.html [ Failure ] crbug.com/626703 [ Linux ] external/wpt/fetch/api/abort/serviceworker-intercepted.https.html [ Timeout ] crbug.com/626703 [ Mac10.15 ] external/wpt/fetch/api/abort/serviceworker-intercepted.https.html [ Timeout ] crbug.com/626703 [ Mac11 ] external/wpt/fetch/api/abort/serviceworker-intercepted.https.html [ Timeout ] @@ -5148,7 +5162,7 @@ crbug.com/1279648 virtual/threaded/external/wpt/scroll-animations/css/scroll-timeline-frame-size-changed.html [ Failure ] crbug.com/1279648 virtual/threaded/external/wpt/scroll-animations/css/scroll-timeline-inline-orientation.html [ Failure ] crbug.com/1279648 [ Mac12 ] virtual/threaded/external/wpt/scroll-animations/css/scroll-timeline-default-iframe.html [ Failure ] -crbug.com/1279648 virtual/threaded/external/wpt/scroll-animations/css/view-timeline-inset-animation.html [ Pass Failure Timeout ] +crbug.com/1279648 virtual/threaded/external/wpt/scroll-animations/css/view-timeline-inset-animation.html [ Failure Pass Timeout ] crbug.com/1071189 [ Debug ] editing/selection/programmatic-selection-on-mac-is-directionless.html [ Pass Timeout ] @@ -5206,6 +5220,9 @@ crbug.com/1365858 http/tests/devtools/console/console-functions.js [ Failure Pass ] crbug.com/1365858 http/tests/devtools/sources/debugger/properties-special.js [ Failure Pass ] +# Temporarily disabled to land the V8 CL https://crrev.com/c/3929037 +crbug.com/1371072 http/tests/devtools/tracing/timeline-js/timeline-microtasks.js [ Failure Pass ] + crbug.com/1093445 http/tests/loading/pdf-commit-load-callbacks.html [ Failure Pass ] crbug.com/1093497 http/tests/history/client-redirect-after-push-state.html [ Failure Pass ] @@ -6224,9 +6241,6 @@ crbug.com/1249176 [ Mac12-arm64 ] http/tests/devtools/elements/styles-2/nested-pseudo-elements.js [ Failure Pass ] crbug.com/1249176 [ Mac11-arm64 ] http/tests/devtools/elements/styles-2/nested-pseudo-elements.js [ Failure Pass ] -# mac-arm CI 10-01-2021 -crbug.com/1249176 [ Mac11-arm64 ] http/tests/security/opened-document-security-origin-resets-on-navigation.html [ Timeout ] - # mac-arm CI 10-05-2021 crbug.com/1249176 [ Mac11-arm64 ] virtual/no-alloc-direct-call/fast/canvas/canvas-lost-gpu-context.html [ Failure ] crbug.com/1249176 [ Mac11-arm64 ] virtual/gpu-rasterization/images/directly-composited-image-orientation.html [ Failure Pass ] @@ -7227,3 +7241,6 @@ # Temporarily disable tests to land cache storage changes crbug.com/1363138 http/tests/inspector-protocol/cachestorage/read-cached-response.js [ Skip ] + +# Investigate the flake +crbug.com/1371395 virtual/not-restored-reasons/external/wpt/performance-timeline/not-restored-reasons/performance-navigation-timing-same-origin-bfcache.window.html [ Failure Pass ] \ No newline at end of file
diff --git a/third_party/blink/web_tests/VirtualTestSuites b/third_party/blink/web_tests/VirtualTestSuites index 02cb85d..e77786c 100644 --- a/third_party/blink/web_tests/VirtualTestSuites +++ b/third_party/blink/web_tests/VirtualTestSuites
@@ -698,6 +698,12 @@ "args": ["--disable-features=PrefersReducedMotionClientHintHeader"] }, { + "prefix": "disable-wildcard-subdomains-in-permissions-policy", + "platforms": ["Linux", "Mac", "Win"], + "bases": ["external/wpt/permissions-policy/"], + "args": ["--disable-features=WildcardSubdomainsInPermissionsPolicy"] + }, + { "prefix": "storage-access-api", "platforms": ["Linux", "Mac", "Win"], "bases": [ "external/wpt/storage-access-api" ],
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 062cd4b..17a16ee 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
@@ -980,6 +980,13 @@ {} ] ], + "chrome-layout-root-crash.html": [ + "e3e709a240bd870250b2747c94fe96880bdf52e3", + [ + null, + {} + ] + ], "chrome-quotes-crash.html": [ "363f96fd02e1bc63d70ccda56dff2b9f935448ed", [ @@ -4977,6 +4984,13 @@ {} ] ], + "chrome-bug-1371700.html": [ + "e1a13305c4319505af0ebab2ae6f497f81b14b46", + [ + null, + {} + ] + ], "firefox-bug-1688293.html": [ "9ab1a88312683a66798cb52693c2ba4389222ff4", [ @@ -191698,61 +191712,29 @@ ] ], "transform-background-007.html": [ - "55214ae65567b37210df76fe8d7fb0131018fc5f", + "787c593fb093a74f5c0bbc07a511acae37ec929b", [ null, [ [ - "/css/css-transforms/transform-background-ref-2.html", + "/css/css-transforms/transform-root-bg-001-ref.html", "==" ] ], - { - "fuzzy": [ - [ - null, - [ - [ - 0, - 1 - ], - [ - 0, - 4800 - ] - ] - ] - ] - } + {} ] ], "transform-background-008.html": [ - "9f96582de05c850c0784d302b73545d754657f7d", + "c1565bf1c2799e8c7ee3f8557165b2a62271e060", [ null, [ [ - "/css/css-transforms/transform-background-ref-2.html", + "/css/css-transforms/transform-root-bg-001-ref.html", "==" ] ], - { - "fuzzy": [ - [ - null, - [ - [ - 0, - 1 - ], - [ - 0, - 4800 - ] - ] - ] - ] - } + {} ] ], "transform-box": { @@ -194925,7 +194907,7 @@ ] ], "transform-root-bg-001.html": [ - "c750fbaaf94a7b7373c72c466b3dbad12e35a5e0", + "e3d7ff3807ea42e72b8b99ea1db73fc69a728d85", [ null, [ @@ -194951,12 +194933,12 @@ ] ], "transform-root-bg-003.html": [ - "db51c88ad64aa2d5b5755cf7694283f0b140adfd", + "377847fc5abaef1d481d431fc9e71e34e21a8a5c", [ null, [ [ - "/css/css-transforms/transform-root-bg-003-ref.html", + "/css/css-transforms/transform-root-bg-001-ref.html", "==" ] ], @@ -195835,7 +195817,7 @@ ] ], "transform-translate-background-001.html": [ - "72011e37bce073ce79bc65ad75dcaf4f55cce55a", + "bd14ebc25ee89612c4816e03005aa88310c8fff7", [ null, [ @@ -195848,7 +195830,7 @@ ] ], "transform-translate-background-002.html": [ - "b1be52774007c1f7886c18fd18f2acea279ef554", + "d714af2d07b37e6bb86c1996520aa9fadccb378f", [ null, [ @@ -296647,10 +296629,6 @@ "cd0e7013ba16436994dd750a0efacc0490499fba", [] ], - "transform-triangle-left-small.svg": [ - "b86047b627efe5f752026539dc5aef9bbea18d33", - [] - ], "transform-triangle-left.svg": [ "e0bf2665687dbd56cde5c7d4a6b837e03bd5233e", [] @@ -296985,11 +296963,7 @@ [] ], "transform-root-bg-001-ref.html": [ - "cf4f1c1bbf2ca0e9d071afa87762967014e3e4d4", - [] - ], - "transform-root-bg-003-ref.html": [ - "b5bb182b2249f31652c1c749dab374e22a311802", + "811172e43385fbfc9b5db56e61ae0310cdd7f219", [] ], "transform-root-bg-004-ref.html": [ @@ -309802,7 +309776,7 @@ [] ], "general.any.serviceworker-expected.txt": [ - "7a1b5a41a93f460ec4b77ac7cab653906ce133be", + "39cdb155476490139f70745441d679135fcb70a7", [] ], "general.any.sharedworker-expected.txt": [ @@ -313003,6 +312977,10 @@ "8b99a0140dbfcc1293c19105437d37577fd373db", [] ], + "idlharness.https.any.worker-expected.txt": [ + "8c0f17ec553a619e630a8c9f12903f95a223c6b5", + [] + ], "opaque-origin.https.window-expected.txt": [ "a4f8b49db924c9948f821ab077cf58f3dcb0348b", [] @@ -331402,7 +331380,7 @@ [] ], "fs.idl": [ - "9263ca7dbeec000792315c51d4b1b980777d23a2", + "0bda456e2d2d57c604dd12496fd827d0a427b406", [] ], "fullscreen.idl": [ @@ -331746,7 +331724,7 @@ [] ], "screen-capture.idl": [ - "06b1ae6706350dc192823f99ff8ab0275ffae513", + "908fce2c6baa25b637a4a0d200a6d7423a1674ba", [] ], "screen-orientation.idl": [ @@ -331918,7 +331896,7 @@ [] ], "webcodecs.idl": [ - "669add6162b02554c64c741ff64f318abf979ae3", + "4854d9698b0144218684fbcc1b83804d496350c8", [] ], "webcrypto-secure-curves.idl": [ @@ -331938,7 +331916,7 @@ [] ], "webgpu.idl": [ - "a6c00023c73eac30532f08062c156b32b8ee55c1", + "f2e038c2047d142fbad56312704e3ea5947988b2", [] ], "webhid.idl": [ @@ -331958,7 +331936,7 @@ [] ], "webrtc-encoded-transform.idl": [ - "b905ab84bbc288d9c70ab7eba822222b13ff25b1", + "e6ebf7f714be9464825616dab38ed6523842e4ae", [] ], "webrtc-ice.idl": [ @@ -331974,7 +331952,7 @@ [] ], "webrtc-stats.idl": [ - "ea300a2407af86469f58304fb17a6a92e7b53830", + "ec8044955741c6e4fb4d36e5a09129846815ab21", [] ], "webrtc-svc.idl": [ @@ -331982,7 +331960,7 @@ [] ], "webrtc.idl": [ - "5b53441ba39271358e858e052d407a47f790c68c", + "7bf168c48e27193a0ad9adde3ee8609652cc0e20", [] ], "websockets.idl": [ @@ -339731,6 +339709,10 @@ "4cdf6f2574d11071332d57eef4113c77b312ee9d", [] ], + "idlharness.https.window-expected.txt": [ + "4605eb29fe6fe1f326bec5abf4c5f14e22a31bb6", + [] + ], "permissions-policy-audio.https.sub-expected.txt": [ "0e8322924f443bffcae91b32da1742d34be3582c", [] @@ -341048,6 +341030,10 @@ "3d82496870edb6921cc927be315fb6db78bc5ad4", [] ], + "cache-add.https.any.js.ini": [ + "4fcea8d5b1ffbd72d8d75cb707ad795a976676f3", + [] + ], "cache-add.https.any.serviceworker-expected.txt": [ "3d82496870edb6921cc927be315fb6db78bc5ad4", [] @@ -341064,10 +341050,18 @@ "452fa9f031ea6bd368b357cf30629498c633399b", [] ], + "cache-keys-attributes-for-service-worker.https.html.ini": [ + "3c36c91ba49762cd9c998bcec46d1d6ee4c30fe1", + [] + ], "cache-keys.https.any-expected.txt": [ "cfd4098aa4635d68e8550034a6c40582de362909", [] ], + "cache-keys.https.any.js.ini": [ + "aaddf08f338cd97a52ebc296fc58568fb8e75a6d", + [] + ], "cache-keys.https.any.serviceworker-expected.txt": [ "cfd4098aa4635d68e8550034a6c40582de362909", [] @@ -341084,6 +341078,10 @@ "07557f11a9c0fe2abaf363c568c8b2a81349c8be", [] ], + "cache-match.https.any.js.ini": [ + "867ff274789038ea49a32428e3fac9b8c8c6aaee", + [] + ], "cache-match.https.any.serviceworker-expected.txt": [ "07557f11a9c0fe2abaf363c568c8b2a81349c8be", [] @@ -341100,6 +341098,10 @@ "391a706b5bda0b78cc4cab483f5f70a719fc1f94", [] ], + "cache-matchAll.https.any.js.ini": [ + "3e4636f1fa64151d975e77dc007f3eafffeb7c7a", + [] + ], "cache-matchAll.https.any.serviceworker-expected.txt": [ "391a706b5bda0b78cc4cab483f5f70a719fc1f94", [] @@ -341116,6 +341118,10 @@ "d1c62496bacf4b31a2cf5671693042fba8abfef4", [] ], + "cache-storage.https.any.js.ini": [ + "914e96adbf514f0980b300d4d4f82aab84b5afa2", + [] + ], "cache-storage.https.any.serviceworker-expected.txt": [ "d1c62496bacf4b31a2cf5671693042fba8abfef4", [] @@ -341128,10 +341134,20 @@ "d1c62496bacf4b31a2cf5671693042fba8abfef4", [] ], + "crashtests": { + "cache-response-clone.https.html.ini": [ + "e81716f7992070b16028f6d9f28932556470eb20", + [] + ] + }, "cross-partition.https.tentative-expected.txt": [ "e32cd4678b8dec940c9ab885b91a75df9490fb35", [] ], + "cross-partition.https.tentative.html.ini": [ + "e7cbac810cc872377163714bc1d2e55cda874aab", + [] + ], "resources": { "blank.html": [ "a3c3a4689a62b45b1e429f6b7a94690e556a1259", @@ -341178,68 +341194,10 @@ "a0a646099cfa729b63cc3bd1f56bfb4dedd94b46", [] ], - "serviceworker": { - "cache-keys-attributes-for-service-worker.https-expected.txt": [ - "452fa9f031ea6bd368b357cf30629498c633399b", - [] - ], - "cache-keys.https-expected.txt": [ - "23df4e7bb8e22708e1ed6ac17867240c706ee308", - [] - ], - "cache-match.https-expected.txt": [ - "18aa19d47954308397a66a493a268a40d9a17af6", - [] - ], - "cache-matchAll.https-expected.txt": [ - "fef44702529ce973a8b720e34b9636792f1db77d", - [] - ], - "cache-storage.https-expected.txt": [ - "22932f43a888a46f2cbf02e6d34ca93d4953ea0d", - [] - ] - }, - "window": { - "cache-keys.https-expected.txt": [ - "cfd4098aa4635d68e8550034a6c40582de362909", - [] - ], - "cache-match.https-expected.txt": [ - "07557f11a9c0fe2abaf363c568c8b2a81349c8be", - [] - ], - "cache-matchAll.https-expected.txt": [ - "391a706b5bda0b78cc4cab483f5f70a719fc1f94", - [] - ], - "cache-storage.https-expected.txt": [ - "d1c62496bacf4b31a2cf5671693042fba8abfef4", - [] - ], - "sandboxed-iframes.https-expected.txt": [ - "a0a646099cfa729b63cc3bd1f56bfb4dedd94b46", - [] - ] - }, - "worker": { - "cache-keys.https-expected.txt": [ - "cfd4098aa4635d68e8550034a6c40582de362909", - [] - ], - "cache-match.https-expected.txt": [ - "07557f11a9c0fe2abaf363c568c8b2a81349c8be", - [] - ], - "cache-matchAll.https-expected.txt": [ - "391a706b5bda0b78cc4cab483f5f70a719fc1f94", - [] - ], - "cache-storage.https-expected.txt": [ - "d1c62496bacf4b31a2cf5671693042fba8abfef4", - [] - ] - } + "sandboxed-iframes.https.html.ini": [ + "1c63c803fa2b5f7a1fc7b65cb3383284b68d90b2", + [] + ] }, "idlharness.https.any.serviceworker-expected.txt": [ "cc464f51a494ffa581d445bdf9aeb8fe718d17de", @@ -348573,6 +348531,10 @@ "985da71a2b6ea4da09f38642752d10e888e2c756", [] ], + "videoFrame-construction.crossOriginSource.sub-expected.txt": [ + "9a418e806dab6fb7991a593f18a783c5c7020c2f", + [] + ], "videoFrame-copyTo.crossOriginIsolated.https.any.js.headers": [ "5f8621ef83660c66f0d037ea28fafefb558140f1", [] @@ -421374,7 +421336,7 @@ ] ], "scrollend-event-fired-after-sequence-of-scrolls.tentative.html": [ - "ae3c26f2afa9c4b68635793506418e4be6177553", + "77bf029ced58c5591c46364af0cd5ddeab054da7", [ null, { @@ -421383,7 +421345,7 @@ ] ], "scrollend-event-fired-after-snap.html": [ - "ef1b495791cad1079063180619861bfbb0d5e682", + "03079ddc6cad8c82da74725206b39ca0924b0615", [ null, { @@ -421392,7 +421354,7 @@ ] ], "scrollend-event-fired-for-programmatic-scroll.html": [ - "79b5f5f0186871b7c139c551faf5cf1ef15f77b9", + "c6569e0bebbd9f8bc0fe91415acdbbae482b82dd", [ null, { @@ -421402,7 +421364,7 @@ ] ], "scrollend-event-fired-for-scrollIntoView.html": [ - "63e1c3e22eaafcb84b98f542778787b7ae397ca4", + "8782b1dfee623741dd2830d538684ecffe767f18", [ null, { @@ -421412,7 +421374,7 @@ ] ], "scrollend-event-fired-to-document.html": [ - "99c1c6930fab0be920c1d6a3fdddac64251cc851", + "3090455388343563d3bfe844ba24b7f2dcb1e288", [ null, { @@ -421421,7 +421383,7 @@ ] ], "scrollend-event-fired-to-element-with-overscroll-behavior.html": [ - "0269c66fdde1922ca9d997a3189831136ba59b13", + "fd9418eb7037bfe2c55df804c0ee8ac961661d8a", [ null, { @@ -421430,7 +421392,7 @@ ] ], "scrollend-event-fired-to-scrolled-element.html": [ - "87cad79df7c2af1835db2fc7fe92198ceeef83ea", + "734339694220ccca6158b1494b4ffe08c2311765", [ null, { @@ -421439,7 +421401,7 @@ ] ], "scrollend-event-fired-to-window.html": [ - "f9510e6e23161515d4856e298b223b08c44a33b3", + "ef72f56d2ba9d62237646dc946fcd0be86dde97e", [ null, { @@ -421448,7 +421410,7 @@ ] ], "scrollend-event-for-user-scroll.html": [ - "30f16571cd83201e039fd9e682e0cca6b8569d76", + "e203482d57907f65c7a3f8484dd8ad0717b74094", [ null, { @@ -421457,7 +421419,7 @@ ] ], "scrollend-event-not-fired-after-removing-scroller.tentative.html": [ - "575a5ac19a51deb46a516544091917031ee62108", + "95447fbd12ea2a0c149d196a3ef0fe681ea03131", [ null, { @@ -542259,7 +542221,7 @@ ] ], "view-timeline-inset-animation.html": [ - "82bfb93eeaae24493499e23caf1525612c97dc18", + "1f33c6642fa0eb830cfe76ac5d642bb0a042b38a", [ null, {} @@ -573989,7 +573951,7 @@ ] ], "videoFrame-construction.any.js": [ - "9a8ae03327b752f22f5d733846d25ed998001735", + "07df649e66870604d767c714a00ff4ed8c298519", [ "webcodecs/videoFrame-construction.any.html", { @@ -574070,6 +574032,13 @@ } ] ], + "videoFrame-construction.crossOriginSource.sub.html": [ + "9238dc0ebdabbe0c95dd033dc31d8743d9e9c1ae", + [ + null, + {} + ] + ], "videoFrame-construction.window.js": [ "02f84215522aed4e3ede029342838119bd92fba2", [ @@ -574085,7 +574054,7 @@ ] ], "videoFrame-copyTo.any.js": [ - "a64603c5ec9fd55028097cb37c4302fc598ca6db", + "d2d04c57d32776796028d554714f84961b771682", [ "webcodecs/videoFrame-copyTo.any.html", {
diff --git a/third_party/blink/web_tests/external/wpt/ambient-light/AmbientLightSensor.https.html b/third_party/blink/web_tests/external/wpt/ambient-light/AmbientLightSensor.https.html index 7d23896..a8c65e4d 100644 --- a/third_party/blink/web_tests/external/wpt/ambient-light/AmbientLightSensor.https.html +++ b/third_party/blink/web_tests/external/wpt/ambient-light/AmbientLightSensor.https.html
@@ -14,10 +14,43 @@ const kReadings = { readings: [ - [3.1415] + // Readings are selected so that illuminance significance check causes + // the following to happen: + // 1. First two values test situation when two values would be rounded + // to same value. As the second value would be rounded to same value + // as first it won't trigger reading event. + // 2. New value is set to 24. And test checks it is correctly rounded to + // 0. + // 3. New reading is attempted to set to 35. + // 4. Value is read from sensor and compared new reading. But as new + // reading was not significantly different compared to initial, for + // privacy reasons, service returns the initial value. + // 5. New value is set to 49. And test checks it is correctly rounded to + // 50. New value is allowed as it is significantly different compared + // to old value (24). + // 6. New reading is attempted to set to 35. + // 7. Value is read from sensor and compared new reading. But as new + // reading was not significantly different compared to initial, for + // privacy reasons, service returns the initial value. + // 8. New value is set to 23. And test checks it is correctly rounded to + // 0. New value is allowed as it is significantly different compared + // to old value (49). + // + // Note: Readings and expectedReadings wraps around correctly as next + // value would be 150 (output from 127). + [127], + [165], + [24], + [35], + [49], + [35], + [23] ], expectedReadings: [ - [3.1415] + [150], // output from 127 + [0], // output from 24 + [50], // output from 49 + [0] // output from 23 ] };
diff --git a/third_party/blink/web_tests/external/wpt/common/dispatcher/README.md b/third_party/blink/web_tests/external/wpt/common/dispatcher/README.md index 3bb2900c..cfaafb6 100644 --- a/third_party/blink/web_tests/external/wpt/common/dispatcher/README.md +++ b/third_party/blink/web_tests/external/wpt/common/dispatcher/README.md
@@ -39,8 +39,9 @@ and [executor.html](../../html/browsers/browsing-the-web/back-forward-cache/resources/executor.html) in back-forward cache tests. -Note that executor files under `/common/dispatcher/` are NOT for -`RemoteContext.execute_script()`. + +Note that `executor*` files under `/common/dispatcher/` are NOT for +`RemoteContext.execute_script()`. Use `remote-executor.html` instead. This is universal and avoids introducing many specific `XXX-helper.html` resources.
diff --git a/third_party/blink/web_tests/external/wpt/common/dispatcher/remote-executor.html b/third_party/blink/web_tests/external/wpt/common/dispatcher/remote-executor.html new file mode 100644 index 0000000..8b00303 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/common/dispatcher/remote-executor.html
@@ -0,0 +1,12 @@ +<!DOCTYPE html> +<html> +<meta charset="utf-8"> +<body> +</body> +<script src="./dispatcher.js"></script> +<script> + const params = new URLSearchParams(window.location.search); + const uuid = params.get('uuid'); + const executor = new Executor(uuid); // `execute()` is called in constructor. +</script> +</html>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-multicol/auto-fill-auto-size-001-print-ref.html b/third_party/blink/web_tests/external/wpt/css/css-multicol/auto-fill-auto-size-001-print-ref.html new file mode 100644 index 0000000..fcd9b7d --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-multicol/auto-fill-auto-size-001-print-ref.html
@@ -0,0 +1,3 @@ +<!DOCTYPE html> +<link rel="author" title="Morten Stenshorne" href="mailto:mstensho@chromium.org"> +On the first page
diff --git a/third_party/blink/web_tests/external/wpt/css/css-multicol/auto-fill-auto-size-001-print.html b/third_party/blink/web_tests/external/wpt/css/css-multicol/auto-fill-auto-size-001-print.html new file mode 100644 index 0000000..6652fe1 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-multicol/auto-fill-auto-size-001-print.html
@@ -0,0 +1,6 @@ +<!DOCTYPE html> +<link rel="author" title="Morten Stenshorne" href="mailto:mstensho@chromium.org"> +<link rel="help" href="https://bugs.chromium.org/p/chromium/issues/detail?id=1339963"> +<link rel="match" href="auto-fill-auto-size-001-print-ref.html"> +<div style="columns:2; column-fill:auto; border:10px solid red; border-top:none; border-bottom:none;"></div> +On the first page
diff --git a/third_party/blink/web_tests/external/wpt/css/css-multicol/auto-fill-auto-size-002-print-ref.html b/third_party/blink/web_tests/external/wpt/css/css-multicol/auto-fill-auto-size-002-print-ref.html new file mode 100644 index 0000000..2ae0778 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-multicol/auto-fill-auto-size-002-print-ref.html
@@ -0,0 +1,7 @@ +<!DOCTYPE html> +<link rel="author" title="Morten Stenshorne" href="mailto:mstensho@chromium.org"> +<style> + body { margin: 0; } +</style> +<div style="height:150vh;"></div> +Middle of second page
diff --git a/third_party/blink/web_tests/external/wpt/css/css-multicol/auto-fill-auto-size-002-print.html b/third_party/blink/web_tests/external/wpt/css/css-multicol/auto-fill-auto-size-002-print.html new file mode 100644 index 0000000..4e024321 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-multicol/auto-fill-auto-size-002-print.html
@@ -0,0 +1,11 @@ +<!DOCTYPE html> +<link rel="author" title="Morten Stenshorne" href="mailto:mstensho@chromium.org"> +<link rel="help" href="https://bugs.chromium.org/p/chromium/issues/detail?id=1339963"> +<link rel="match" href="auto-fill-auto-size-002-print-ref.html"> +<style> + body { margin: 0; } +</style> +<div style="columns:2; column-fill:auto;"> + <div style="height:250vh;"></div> +</div> +Middle of second page
diff --git a/third_party/blink/web_tests/external/wpt/css/css-multicol/multicol-nested-025.html b/third_party/blink/web_tests/external/wpt/css/css-multicol/multicol-nested-025.html new file mode 100644 index 0000000..badc91e0 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-multicol/multicol-nested-025.html
@@ -0,0 +1,8 @@ +<!DOCTYPE html> +<link rel="author" title="Morten Stenshorne" href="mailto:mstensho@chromium.org"> +<link rel="help" href="https://bugs.chromium.org/p/chromium/issues/detail?id=1339963"> +<link rel="match" href="../reference/nothing.html"> +<p>There should be nothing below.</p> +<div style="columns:2; column-fill:auto; height:100px;"> + <div style="columns:2; column-fill:auto; background:red;"></div> +</div>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-multicol/multicol-nested-026.html b/third_party/blink/web_tests/external/wpt/css/css-multicol/multicol-nested-026.html new file mode 100644 index 0000000..25371b7 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-multicol/multicol-nested-026.html
@@ -0,0 +1,14 @@ +<!DOCTYPE html> +<link rel="author" title="Morten Stenshorne" href="mailto:mstensho@chromium.org"> +<link rel="help" href="https://bugs.chromium.org/p/chromium/issues/detail?id=1339963"> +<link rel="match" href="../reference/ref-filled-green-100px-square.xht"> +<p>Test passes if there is a filled green square and <strong>no red</strong>.</p> +<div style="columns:2; gap:0; column-fill:auto; width:100px; height:100px;"> + <div style="columns:2; gap:0; column-fill:auto; background:red;"> + <div style="height:150px;"> + <div style="height:150px; background:green;"></div> + <div style="width:200%; height:100px; background:green;"></div> + </div> + </div> + <div style="height:50px; background:green;"></div> +</div>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-multicol/multicol-nested-027.html b/third_party/blink/web_tests/external/wpt/css/css-multicol/multicol-nested-027.html new file mode 100644 index 0000000..02590d39 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-multicol/multicol-nested-027.html
@@ -0,0 +1,12 @@ +<!DOCTYPE html> +<link rel="author" title="Morten Stenshorne" href="mailto:mstensho@chromium.org"> +<link rel="help" href="https://bugs.chromium.org/p/chromium/issues/detail?id=1339963"> +<link rel="match" href="../reference/ref-filled-green-100px-square.xht"> +<p>Test passes if there is a filled green square and <strong>no red</strong>.</p> +<div style="columns:2; gap:0; column-fill:auto; width:100px; height:100px; background:red;"> + <div style="columns:2; gap:0; column-fill:auto; min-height:75px; background:green;"> + <div style="height:50px;"></div> + </div> + <div style="height:25px; background:green;"></div> + <div style="break-inside:avoid; height:100px; background:green;"></div> +</div>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-multicol/multicol-nested-028.html b/third_party/blink/web_tests/external/wpt/css/css-multicol/multicol-nested-028.html new file mode 100644 index 0000000..cfd164f1 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-multicol/multicol-nested-028.html
@@ -0,0 +1,12 @@ +<!DOCTYPE html> +<link rel="author" title="Morten Stenshorne" href="mailto:mstensho@chromium.org"> +<link rel="help" href="https://bugs.chromium.org/p/chromium/issues/detail?id=1339963"> +<link rel="match" href="../reference/ref-filled-green-100px-square.xht"> +<p>Test passes if there is a filled green square and <strong>no red</strong>.</p> +<div style="columns:4; gap:0; column-fill:auto; width:100px; height:100px; background:red;"> + <div style="columns:2; gap:0; column-fill:auto; min-height:125px; background:green;"> + <div style="height:205px;"></div> + </div> + <div style="break-inside:avoid; height:75px; background:green;"></div> + <div style="break-inside:avoid; height:200px; background:green;"></div> +</div>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-syntax/at-rule-in-declaration-list.html b/third_party/blink/web_tests/external/wpt/css/css-syntax/at-rule-in-declaration-list.html new file mode 100644 index 0000000..f40975d --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-syntax/at-rule-in-declaration-list.html
@@ -0,0 +1,76 @@ +<!doctype html> +<title>CSS Syntax Test: handle at-rules in declaration lists</title> +<link rel="help" href="https://drafts.csswg.org/css-syntax/#consume-list-of-declarations"> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<style id="test_sheet"> +</style> +<script> + function parseRule(rule_text) { + let sheet = test_sheet.sheet; + if (sheet.cssRules.length != 0) + sheet.deleteRule(0); + sheet.insertRule(rule_text); + return sheet.cssRules[0]; + } + + test(() => { + let rule = parseRule(` + div { + @at {} + color: green; + } + `); + assert_equals(rule.style.color, "green"); + }, "Allow @-rule with block inside style rule"); + + test(() => { + let rule = parseRule(` + div { + @at at; + color: green; + } + `); + assert_equals(rule.style.color, "green"); + }, "Allow @-rule with semi-colon inside style rule"); + + test(() => { + let rule = parseRule(` + @page { + @at {} + margin-top: 20px; + } + `); + assert_equals(rule.style.marginTop, "20px"); + }, "Allow @-rule with block inside page rule"); + + test(() => { + let rule = parseRule(` + @page { + @at at; + margin-top: 20px; + } + `); + assert_equals(rule.style.marginTop, "20px"); + }, "Allow @-rule with semi-colon inside page rule"); + + test(() => { + let rule = parseRule(` + @font-face { + @at {} + font-family: myfont; + } + `); + assert_equals(rule.style.fontFamily, "myfont"); + }, "Allow @-rule with block inside font-face rule"); + + test(() => { + let rule = parseRule(` + @font-face { + @at at; + font-family: myfont; + } + `); + assert_equals(rule.style.fontFamily, "myfont"); + }, "Allow @-rule with semi-colon inside font-face rule"); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-transforms/support/transform-triangle-left-small.svg b/third_party/blink/web_tests/external/wpt/css/css-transforms/support/transform-triangle-left-small.svg deleted file mode 100644 index b86047b6..0000000 --- a/third_party/blink/web_tests/external/wpt/css/css-transforms/support/transform-triangle-left-small.svg +++ /dev/null
@@ -1,4 +0,0 @@ -<svg height="50px" width="50px" viewBox="0 0 50 50" -xmlns="http://www.w3.org/2000/svg"> -<polygon fill="blue" points="0,25 50,50 50,0" /> -</svg>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-background-007.html b/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-background-007.html index 55214ae6..787c593 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-background-007.html +++ b/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-background-007.html
@@ -5,23 +5,10 @@ <link rel="author" title="Aryeh Gregor" href="mailto:ayg@aryeh.name"> <link rel="help" href="http://www.w3.org/TR/css-transforms-1/#transform-rendering"> <link rel="reviewer" title="Apple Inc." href="http://www.apple.com"> - <meta name="assert" content='"If the root element is transformed, the - transformation applies to the entire canvas, including any background - specified for the root element. Since the background painting area for the - root element is the entire canvas, which is infinite, the transformation - might cause parts of the background that were originally off-screen to - appear. For example, if the root element's background were repeating - dots, and a transformation of 'scale(0.5)' were specified on the - root element, the dots would shrink to half their size, but there will be - twice as many, so they still cover the whole viewport." In this case, the - background is specified on the body but propagates to the root element. - The transform is on the root element, so it needs to affect the background. - The rotation 90 degrees clockwise means that most of the screen will be - filled with triangles that were originally above the top of the viewport; - the original top row of triangles will now be on the left.'> + <meta name="assert" content='"If the root element is transformed, the transformation should not apply to + any background specified for the root element.'> <meta name="flags" content="svg"> - <link rel="match" href="transform-background-ref-2.html"> - <meta name="fuzzy" content="maxDifference=0-1;totalPixels=0-4800"> + <link rel="match" href="transform-root-bg-001-ref.html"> <style> html { overflow: hidden;
diff --git a/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-background-008.html b/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-background-008.html index 9f96582..c1565bf 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-background-008.html +++ b/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-background-008.html
@@ -10,8 +10,7 @@ root element instead of being specified on the body and propagating to the root.'> <meta name="flags" content="svg"> - <link rel="match" href="transform-background-ref-2.html"> - <meta name="fuzzy" content="maxDifference=0-1;totalPixels=0-4800"> + <link rel="match" href="transform-root-bg-001-ref.html"> <style> html { background: url(support/transform-triangle-left.svg);
diff --git a/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-root-bg-001-ref.html b/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-root-bg-001-ref.html index cf4f1c1b..811172e 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-root-bg-001-ref.html +++ b/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-root-bg-001-ref.html
@@ -5,7 +5,7 @@ <link rel="author" title="Aryeh Gregor" href="mailto:ayg@aryeh.name"> <style> html { - background: url(support/transform-triangle-right.svg) top right; + background: url(support/transform-triangle-left.svg) top left; } body { /* The default 8px margin makes the background not line up exactly */
diff --git a/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-root-bg-001.html b/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-root-bg-001.html index c750fba..e3d7ff3 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-root-bg-001.html +++ b/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-root-bg-001.html
@@ -5,15 +5,10 @@ <link rel="author" title="Aryeh Gregor" href="mailto:ayg@aryeh.name"> <link rel="help" href="http://www.w3.org/TR/css-transforms-1/#transform-rendering"> <meta name="assert" content="The background here extends to the whole - canvas, and a transform on the root element must transform the whole - canvas, background included. Thus the entire tiled background of - left-pointing triangles needs to be rotated 180 degrees (same as scale(-1)) - around the top center of the viewport, which is the default - transform-origin of 50% 50% in this case. An implementation that doesn't - draw the background on parts of the canvas outside the viewport might - incorrectly display nothing, because the part of the background that's - supposed to be rotated into view was initially above the visible part of - the canvas."> + canvas, and a transform on the root element should not transform the + canvas background. Thus the entire tiled background of left-pointing triangles + should not be rotated. An implementation that doesn't draw the background + correctly may rotate the background, or incorrectly clip it."> <link rel="match" href="transform-root-bg-001-ref.html"> <style> html {
diff --git a/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-root-bg-003-ref.html b/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-root-bg-003-ref.html deleted file mode 100644 index b5bb182..0000000 --- a/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-root-bg-003-ref.html +++ /dev/null
@@ -1,16 +0,0 @@ -<!DOCTYPE html> -<html> - <head> - <title>CSS Reftest Reference</title> - <link rel="author" title="Aryeh Gregor" href="mailto:ayg@aryeh.name"> - <style> - html { - background: url(support/transform-triangle-left-small.svg); - } - body { - margin: 0; - } - </head> - <body> - </body> -</html>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-root-bg-003.html b/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-root-bg-003.html index db51c88a..377847f 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-root-bg-003.html +++ b/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-root-bg-003.html
@@ -8,7 +8,7 @@ transform-root-bg-001.html, except that it uses scale(0.5) instead of scale(-1). It also specifies a transform-origin, because the default of 50% 50% wouldn't work well with the way the reference image is constructed."> - <link rel="match" href="transform-root-bg-003-ref.html"> + <link rel="match" href="transform-root-bg-001-ref.html"> <style> html { background: url(support/transform-triangle-left.svg);
diff --git a/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-translate-background-001.html b/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-translate-background-001.html index 72011e37..bd14ebc2 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-translate-background-001.html +++ b/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-translate-background-001.html
@@ -6,10 +6,10 @@ <link rel="help" href="https://drafts.csswg.org/css-transforms/#transform-rendering"> <link rel="help" href="https://bugs.chromium.org/p/chromium/issues/detail?id=988446"> <link rel="match" href="transform-translate-background-001-ref.html"> -<meta name="assert" content="Checks that the linear gradient is modified when you vertically translate the root element. The test passes if you see only green."> +<meta name="assert" content="Checks that the linear gradient is not modified when you vertically translate the root element. The test passes if you see only green."> <style> html { - background: linear-gradient(to bottom, red 0%, red 50%, green 50%, green 100%); + background: linear-gradient(to bottom, green 0%, green 50%, red 50%, red 100%); transform: translate(0, -250vh); } </style>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-translate-background-002.html b/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-translate-background-002.html index b1be527..d714af2d 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-translate-background-002.html +++ b/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-translate-background-002.html
@@ -6,11 +6,11 @@ <link rel="help" href="https://drafts.csswg.org/css-transforms/#transform-rendering"> <link rel="help" href="https://bugs.chromium.org/p/chromium/issues/detail?id=988446"> <link rel="match" href="transform-translate-background-001-ref.html"> -<meta name="assert" content="Checks that the linear gradient is modified when you dynamically translate the root element. The test passes if you see only green."> +<meta name="assert" content="Checks that the linear gradient is not modified when you dynamically translate the root element. The test passes if you see only green."> <script src="/common/reftest-wait.js"></script> <style> html { - background: linear-gradient(to bottom, red 0%, red 50%, green 50%, green 100%); + background: linear-gradient(to bottom, green 0%, green 50%, red 50%, red 100%); } </style> <div style="height: 400vh;"></div>
diff --git a/third_party/blink/web_tests/external/wpt/dom/events/scrolling/scrollend-event-fired-after-sequence-of-scrolls.tentative.html b/third_party/blink/web_tests/external/wpt/dom/events/scrolling/scrollend-event-fired-after-sequence-of-scrolls.tentative.html index ae3c26f..77bf029c 100644 --- a/third_party/blink/web_tests/external/wpt/dom/events/scrolling/scrollend-event-fired-after-sequence-of-scrolls.tentative.html +++ b/third_party/blink/web_tests/external/wpt/dom/events/scrolling/scrollend-event-fired-after-sequence-of-scrolls.tentative.html
@@ -1,4 +1,5 @@ <!DOCTYPE HTML> +<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/resources/testdriver.js"></script>
diff --git a/third_party/blink/web_tests/external/wpt/dom/events/scrolling/scrollend-event-fired-after-snap.html b/third_party/blink/web_tests/external/wpt/dom/events/scrolling/scrollend-event-fired-after-snap.html index ef1b495..03079dd 100644 --- a/third_party/blink/web_tests/external/wpt/dom/events/scrolling/scrollend-event-fired-after-snap.html +++ b/third_party/blink/web_tests/external/wpt/dom/events/scrolling/scrollend-event-fired-after-snap.html
@@ -1,4 +1,5 @@ <!DOCTYPE html> +<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/resources/testdriver.js"></script>
diff --git a/third_party/blink/web_tests/external/wpt/dom/events/scrolling/scrollend-event-fired-for-programmatic-scroll.html b/third_party/blink/web_tests/external/wpt/dom/events/scrolling/scrollend-event-fired-for-programmatic-scroll.html index 79b5f5f..c6569e0 100644 --- a/third_party/blink/web_tests/external/wpt/dom/events/scrolling/scrollend-event-fired-for-programmatic-scroll.html +++ b/third_party/blink/web_tests/external/wpt/dom/events/scrolling/scrollend-event-fired-for-programmatic-scroll.html
@@ -1,5 +1,6 @@ <!DOCTYPE HTML> <meta name="timeout" content="long"> +<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/resources/testdriver.js"></script>
diff --git a/third_party/blink/web_tests/external/wpt/dom/events/scrolling/scrollend-event-fired-for-scrollIntoView.html b/third_party/blink/web_tests/external/wpt/dom/events/scrolling/scrollend-event-fired-for-scrollIntoView.html index 63e1c3e..8782b1df 100644 --- a/third_party/blink/web_tests/external/wpt/dom/events/scrolling/scrollend-event-fired-for-scrollIntoView.html +++ b/third_party/blink/web_tests/external/wpt/dom/events/scrolling/scrollend-event-fired-for-scrollIntoView.html
@@ -1,5 +1,6 @@ <!DOCTYPE HTML> <meta name="timeout" content="long"> +<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/resources/testdriver.js"></script>
diff --git a/third_party/blink/web_tests/external/wpt/dom/events/scrolling/scrollend-event-fired-to-document.html b/third_party/blink/web_tests/external/wpt/dom/events/scrolling/scrollend-event-fired-to-document.html index 99c1c69..3090455 100644 --- a/third_party/blink/web_tests/external/wpt/dom/events/scrolling/scrollend-event-fired-to-document.html +++ b/third_party/blink/web_tests/external/wpt/dom/events/scrolling/scrollend-event-fired-to-document.html
@@ -1,4 +1,5 @@ <!DOCTYPE HTML> +<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/resources/testdriver.js"></script>
diff --git a/third_party/blink/web_tests/external/wpt/dom/events/scrolling/scrollend-event-fired-to-element-with-overscroll-behavior.html b/third_party/blink/web_tests/external/wpt/dom/events/scrolling/scrollend-event-fired-to-element-with-overscroll-behavior.html index 0269c66..fd9418eb 100644 --- a/third_party/blink/web_tests/external/wpt/dom/events/scrolling/scrollend-event-fired-to-element-with-overscroll-behavior.html +++ b/third_party/blink/web_tests/external/wpt/dom/events/scrolling/scrollend-event-fired-to-element-with-overscroll-behavior.html
@@ -1,4 +1,5 @@ <!DOCTYPE HTML> +<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/resources/testdriver.js"></script>
diff --git a/third_party/blink/web_tests/external/wpt/dom/events/scrolling/scrollend-event-fired-to-scrolled-element.html b/third_party/blink/web_tests/external/wpt/dom/events/scrolling/scrollend-event-fired-to-scrolled-element.html index 87cad79..7343396 100644 --- a/third_party/blink/web_tests/external/wpt/dom/events/scrolling/scrollend-event-fired-to-scrolled-element.html +++ b/third_party/blink/web_tests/external/wpt/dom/events/scrolling/scrollend-event-fired-to-scrolled-element.html
@@ -1,4 +1,5 @@ <!DOCTYPE HTML> +<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/resources/testdriver.js"></script>
diff --git a/third_party/blink/web_tests/external/wpt/dom/events/scrolling/scrollend-event-fired-to-window.html b/third_party/blink/web_tests/external/wpt/dom/events/scrolling/scrollend-event-fired-to-window.html index f9510e6e..ef72f56 100644 --- a/third_party/blink/web_tests/external/wpt/dom/events/scrolling/scrollend-event-fired-to-window.html +++ b/third_party/blink/web_tests/external/wpt/dom/events/scrolling/scrollend-event-fired-to-window.html
@@ -1,4 +1,5 @@ <!DOCTYPE HTML> +<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/resources/testdriver.js"></script>
diff --git a/third_party/blink/web_tests/external/wpt/dom/events/scrolling/scrollend-event-for-user-scroll.html b/third_party/blink/web_tests/external/wpt/dom/events/scrolling/scrollend-event-for-user-scroll.html index 30f1657..e203482d 100644 --- a/third_party/blink/web_tests/external/wpt/dom/events/scrolling/scrollend-event-for-user-scroll.html +++ b/third_party/blink/web_tests/external/wpt/dom/events/scrolling/scrollend-event-for-user-scroll.html
@@ -1,6 +1,7 @@ <!DOCTYPE html> <html> <head> + <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/resources/testdriver.js"></script>
diff --git a/third_party/blink/web_tests/external/wpt/dom/events/scrolling/scrollend-event-not-fired-after-removing-scroller.tentative.html b/third_party/blink/web_tests/external/wpt/dom/events/scrolling/scrollend-event-not-fired-after-removing-scroller.tentative.html index 575a5ac..95447fbd 100644 --- a/third_party/blink/web_tests/external/wpt/dom/events/scrolling/scrollend-event-not-fired-after-removing-scroller.tentative.html +++ b/third_party/blink/web_tests/external/wpt/dom/events/scrolling/scrollend-event-not-fired-after-removing-scroller.tentative.html
@@ -1,4 +1,5 @@ <!DOCTYPE HTML> +<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/resources/testdriver.js"></script>
diff --git a/third_party/blink/web_tests/external/wpt/fetch/api/abort/general.any.serviceworker-expected.txt b/third_party/blink/web_tests/external/wpt/fetch/api/abort/general.any.serviceworker-expected.txt index 7a1b5a4..39cdb15 100644 --- a/third_party/blink/web_tests/external/wpt/fetch/api/abort/general.any.serviceworker-expected.txt +++ b/third_party/blink/web_tests/external/wpt/fetch/api/abort/general.any.serviceworker-expected.txt
@@ -1,5 +1,7 @@ This is a testharness.js-based test. +Found 51 tests; 48 PASS, 3 FAIL, 0 TIMEOUT, 0 NOTRUN. PASS Aborting rejects with AbortError +FAIL Aborting rejects with abort reason promise_rejects_exactly: fetch() should reject with abort reason function "function() { throw e }" threw object "AbortError: Failed to execute 'fetch' on 'WorkerGlobalScope': The user aborted a request." but we expected it to throw object "error1: error1" PASS Aborting rejects with AbortError - no-cors PASS TypeError from request constructor takes priority - RequestInit's window is not null PASS TypeError from request constructor takes priority - Input URL is not valid @@ -19,6 +21,7 @@ PASS TypeError from request constructor takes priority - Bad redirect init parameter value PASS Request objects have a signal property PASS Signal on request object +FAIL Signal on request object should also have abort reason promise_rejects_exactly: fetch() should reject with abort reason function "function() { throw e }" threw object "AbortError: Failed to execute 'fetch' on 'WorkerGlobalScope': The user aborted a request." but we expected it to throw object "error1: error1" PASS Signal on request object created from request object PASS Signal on request object created from request object, with signal on second request PASS Signal on request object created from request object, with signal on second request overriding another
diff --git a/third_party/blink/web_tests/external/wpt/file-system-access/local_FileSystemBaseHandle-getUniqueId-manual.https.html b/third_party/blink/web_tests/external/wpt/file-system-access/local_FileSystemBaseHandle-getUniqueId-manual.https.html new file mode 100644 index 0000000..32fc5ea1 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/file-system-access/local_FileSystemBaseHandle-getUniqueId-manual.https.html
@@ -0,0 +1,10 @@ +<!doctype html> +<meta charset=utf-8> + +<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/test-helpers.js"></script> +<script src="resources/local-fs-test-helpers.js"></script> +<script src="../fs/script-tests/FileSystemBaseHandle-getUniqueId.js"></script>
diff --git a/third_party/blink/web_tests/external/wpt/fs/FileSystemBaseHandle-getUniqueId.https.any.js b/third_party/blink/web_tests/external/wpt/fs/FileSystemBaseHandle-getUniqueId.https.any.js new file mode 100644 index 0000000..24ea202 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/fs/FileSystemBaseHandle-getUniqueId.https.any.js
@@ -0,0 +1,3 @@ +// META: script=resources/test-helpers.js +// META: script=resources/sandboxed-fs-test-helpers.js +// META: script=script-tests/FileSystemBaseHandle-getUniqueId.js
diff --git a/third_party/blink/web_tests/external/wpt/fs/idlharness.https.any.worker-expected.txt b/third_party/blink/web_tests/external/wpt/fs/idlharness.https.any.worker-expected.txt new file mode 100644 index 0000000..8c0f17e --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/fs/idlharness.https.any.worker-expected.txt
@@ -0,0 +1,59 @@ +This is a testharness.js-based test. +Found 55 tests; 51 PASS, 4 FAIL, 0 TIMEOUT, 0 NOTRUN. +PASS idl_test setup +PASS idl_test validation +PASS Partial interface StorageManager: original interface defined +PASS Partial interface StorageManager: member names are unique +PASS FileSystemHandle interface: existence and properties of interface object +PASS FileSystemHandle interface object length +PASS FileSystemHandle interface object name +PASS FileSystemHandle interface: existence and properties of interface prototype object +PASS FileSystemHandle interface: existence and properties of interface prototype object's "constructor" property +PASS FileSystemHandle interface: existence and properties of interface prototype object's @@unscopables property +PASS FileSystemHandle interface: attribute kind +PASS FileSystemHandle interface: attribute name +PASS FileSystemHandle interface: operation isSameEntry(FileSystemHandle) +PASS FileSystemFileHandle interface: existence and properties of interface object +PASS FileSystemFileHandle interface object length +PASS FileSystemFileHandle interface object name +PASS FileSystemFileHandle interface: existence and properties of interface prototype object +PASS FileSystemFileHandle interface: existence and properties of interface prototype object's "constructor" property +PASS FileSystemFileHandle interface: existence and properties of interface prototype object's @@unscopables property +PASS FileSystemFileHandle interface: operation getFile() +PASS FileSystemFileHandle interface: operation createWritable(optional FileSystemCreateWritableOptions) +PASS FileSystemFileHandle interface: operation createSyncAccessHandle() +PASS FileSystemDirectoryHandle interface: existence and properties of interface object +PASS FileSystemDirectoryHandle interface object length +PASS FileSystemDirectoryHandle interface object name +PASS FileSystemDirectoryHandle interface: existence and properties of interface prototype object +PASS FileSystemDirectoryHandle interface: existence and properties of interface prototype object's "constructor" property +PASS FileSystemDirectoryHandle interface: existence and properties of interface prototype object's @@unscopables property +PASS FileSystemDirectoryHandle interface: async iterable<USVString, FileSystemHandle> +PASS FileSystemDirectoryHandle interface: operation getFileHandle(USVString, optional FileSystemGetFileOptions) +PASS FileSystemDirectoryHandle interface: operation getDirectoryHandle(USVString, optional FileSystemGetDirectoryOptions) +PASS FileSystemDirectoryHandle interface: operation removeEntry(USVString, optional FileSystemRemoveOptions) +PASS FileSystemDirectoryHandle interface: operation resolve(FileSystemHandle) +PASS FileSystemWritableFileStream interface: existence and properties of interface object +PASS FileSystemWritableFileStream interface object length +PASS FileSystemWritableFileStream interface object name +PASS FileSystemWritableFileStream interface: existence and properties of interface prototype object +PASS FileSystemWritableFileStream interface: existence and properties of interface prototype object's "constructor" property +PASS FileSystemWritableFileStream interface: existence and properties of interface prototype object's @@unscopables property +PASS FileSystemWritableFileStream interface: operation write(FileSystemWriteChunkType) +PASS FileSystemWritableFileStream interface: operation seek(unsigned long long) +PASS FileSystemWritableFileStream interface: operation truncate(unsigned long long) +PASS FileSystemSyncAccessHandle interface: existence and properties of interface object +PASS FileSystemSyncAccessHandle interface object length +PASS FileSystemSyncAccessHandle interface object name +PASS FileSystemSyncAccessHandle interface: existence and properties of interface prototype object +PASS FileSystemSyncAccessHandle interface: existence and properties of interface prototype object's "constructor" property +PASS FileSystemSyncAccessHandle interface: existence and properties of interface prototype object's @@unscopables property +PASS FileSystemSyncAccessHandle interface: operation read(BufferSource, optional FileSystemReadWriteOptions) +PASS FileSystemSyncAccessHandle interface: operation write(BufferSource, optional FileSystemReadWriteOptions) +FAIL FileSystemSyncAccessHandle interface: operation truncate(unsigned long long) assert_unreached: Throws "TypeError: Illegal invocation" instead of rejecting promise Reached unreachable code +FAIL FileSystemSyncAccessHandle interface: operation getSize() assert_unreached: Throws "TypeError: Illegal invocation" instead of rejecting promise Reached unreachable code +FAIL FileSystemSyncAccessHandle interface: operation flush() assert_unreached: Throws "TypeError: Illegal invocation" instead of rejecting promise Reached unreachable code +FAIL FileSystemSyncAccessHandle interface: operation close() assert_unreached: Throws "TypeError: Illegal invocation" instead of rejecting promise Reached unreachable code +PASS StorageManager interface: operation getDirectory() +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/fs/script-tests/FileSystemBaseHandle-getUniqueId.js b/third_party/blink/web_tests/external/wpt/fs/script-tests/FileSystemBaseHandle-getUniqueId.js new file mode 100644 index 0000000..d1240d8 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/fs/script-tests/FileSystemBaseHandle-getUniqueId.js
@@ -0,0 +1,89 @@ +'use strict'; + +directory_test(async (t, root_dir) => { + assert_equals(await root_dir.getUniqueId(), await root_dir.getUniqueId()); + + const subdir = await createDirectory(t, 'subdir-name', root_dir); + assert_equals(await subdir.getUniqueId(), await subdir.getUniqueId()); +}, 'identical directory handles return the same ID'); + +directory_test(async (t, root_dir) => { + const subdir = await createDirectory(t, 'subdir-name', root_dir); + + assert_not_equals(await root_dir.getUniqueId(), await subdir.getUniqueId()); +}, 'different directories return different IDs'); + +directory_test(async (t, root_dir) => { + const subdir = await createDirectory(t, 'subdir-name', root_dir); + const subdir2 = await root_dir.getDirectoryHandle('subdir-name'); + + assert_equals(await subdir.getUniqueId(), await subdir2.getUniqueId()); +}, 'different handles for the same directory return the same ID'); + +directory_test(async (t, root_dir) => { + const handle = await createEmptyFile(t, 'foo.txt', root_dir); + + assert_equals(await handle.getUniqueId(), await handle.getUniqueId()); +}, 'identical file handles return the same unique ID'); + +directory_test(async (t, root_dir) => { + const handle1 = await createEmptyFile(t, 'foo.txt', root_dir); + const handle2 = await createEmptyFile(t, 'bar.txt', root_dir); + + assert_not_equals(await handle1.getUniqueId(), await handle2.getUniqueId()); +}, 'different files return different IDs'); + +directory_test(async (t, root_dir) => { + const handle1 = await createEmptyFile(t, 'foo.txt', root_dir); + const handle2 = await root_dir.getFileHandle('foo.txt'); + + assert_equals(await handle1.getUniqueId(), await handle2.getUniqueId()); +}, 'different handles for the same file return the same ID'); + +directory_test(async (t, root_dir) => { + const handle1 = await createEmptyFile(t, 'foo.txt', root_dir); + const subdir = await createDirectory(t, 'subdir-name', root_dir); + const handle2 = await createEmptyFile(t, 'foo.txt', subdir); + + assert_not_equals(await handle1.getUniqueId(), await handle2.getUniqueId()); +}, 'two files of the same name in different directories return different IDs'); + +directory_test(async (t, root_dir) => { + const handle1 = await createEmptyFile(t, 'foo.txt', root_dir); + const handle2 = await createDirectory(t, 'subdir-name', root_dir); + + assert_not_equals(await handle1.getUniqueId(), await handle2.getUniqueId()); +}, 'a file and a directory return different IDs'); + +directory_test(async (t, root_dir) => { + const file_handle = await createEmptyFile(t, 'foo', root_dir); + const file_id = await file_handle.getUniqueId(); + + // Remove the file. + await root_dir.removeEntry('foo'); + + // Create a directory of the same name and path. + const dir_handle = await createDirectory(t, 'foo', root_dir); + assert_not_equals(await dir_handle.getUniqueId(), file_id); +}, 'a file and a directory of the same path return different IDs'); + +directory_test(async (t, root_dir) => { + const handle = await createEmptyFile(t, 'foo.txt', root_dir); + const id_before = await handle.getUniqueId(); + + // Write to the file. The unique ID should not change. + const writable = await handle.createWritable(); + await writable.write("blah"); + await writable.close(); + + assert_equals(await handle.getUniqueId(), id_before); +}, 'unique ID of a file handle does not change after writes'); + +directory_test(async (t, root_dir) => { + const subdir = await createDirectory(t, 'subdir-name', root_dir); + + const UUIDRegex = + /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/ + assert_true(UUIDRegex.test(await root_dir.getUniqueId())); + assert_true(UUIDRegex.test(await subdir.getUniqueId())); +}, 'unique ID is in GUID version 4 format');
diff --git a/third_party/blink/web_tests/external/wpt/generic-sensor/generic-sensor-tests.js b/third_party/blink/web_tests/external/wpt/generic-sensor/generic-sensor-tests.js index da55e741b..2f910806 100644 --- a/third_party/blink/web_tests/external/wpt/generic-sensor/generic-sensor-tests.js +++ b/third_party/blink/web_tests/external/wpt/generic-sensor/generic-sensor-tests.js
@@ -33,10 +33,9 @@ throw new TypeError('readingData.expectedReadings must be an array of ' + 'arrays.'); } - if (readings.length != expectedReadings.length) { - throw new TypeError('readingData.readings and ' + - 'readingData.expectedReadings must have the same ' + - 'length.'); + if (readings.length < expectedReadings.length) { + throw new TypeError('readingData.readings\' length must be bigger than ' + + 'or equal to readingData.expectedReadings\' length.'); } if (expectedRemappedReadings && !validateReadingFormat(expectedRemappedReadings)) { @@ -44,8 +43,8 @@ 'array of arrays.'); } if (expectedRemappedReadings && - readings.length != expectedRemappedReadings.length) { - throw new TypeError('readingData.readings and ' + + expectedReadings.length != expectedRemappedReadings.length) { + throw new TypeError('readingData.expectedReadings and ' + 'readingData.expectedRemappedReadings must have the same ' + 'length.'); } @@ -248,6 +247,28 @@ assert_true(verificationFunction(expected, sensor2, /*isNull=*/true)); }, `${sensorName}: sensor reading is correct.`); + // Tests that readings maps to expectedReadings correctly. Due to threshold + // check and rounding some values might be discarded or changed. + sensor_test(async (t, sensorProvider) => { + assert_implements(sensorName in self, `${sensorName} is not supported.`); + const sensor = new sensorType(); + const sensorWatcher = new EventWatcher(t, sensor, ["reading", "error"]); + sensor.start(); + + const mockSensor = await sensorProvider.getCreatedSensor(sensorName); + await mockSensor.setSensorReading(readings); + + for (let expectedReading of expectedReadings) { + await sensorWatcher.wait_for("reading"); + assert_true(sensor.hasReading, "hasReading"); + assert_true(verificationFunction(expectedReading, sensor), + "verification"); + } + + sensor.stop(); + }, `${sensorName}: Test that readings are all mapped to expectedReadings\ + correctly.`); + sensor_test(async (t, sensorProvider) => { assert_implements(sensorName in self, `${sensorName} is not supported.`); const sensor = new sensorType();
diff --git a/third_party/blink/web_tests/external/wpt/geolocation-sensor/GeolocationSensor.https-expected.txt b/third_party/blink/web_tests/external/wpt/geolocation-sensor/GeolocationSensor.https-expected.txt index 11f9fa8c..20cd8a1c 100644 --- a/third_party/blink/web_tests/external/wpt/geolocation-sensor/GeolocationSensor.https-expected.txt +++ b/third_party/blink/web_tests/external/wpt/geolocation-sensor/GeolocationSensor.https-expected.txt
@@ -9,6 +9,7 @@ FAIL GeolocationSensor: Test that sensor can be constructed within an iframe allowed to use feature policy. assert_implements: GeolocationSensor is not supported. undefined FAIL GeolocationSensor: Test that 'onreading' is called and sensor reading is valid. assert_implements: GeolocationSensor is not supported. undefined FAIL GeolocationSensor: sensor reading is correct. assert_implements: GeolocationSensor is not supported. undefined +FAIL GeolocationSensor: Test that readings are all mapped to expectedReadings correctly. assert_implements: GeolocationSensor is not supported. undefined FAIL GeolocationSensor: sensor timestamp is updated when time passes. assert_implements: GeolocationSensor is not supported. undefined FAIL GeolocationSensor: Test that sensor can be successfully created and its states are correct. assert_implements: GeolocationSensor is not supported. undefined FAIL GeolocationSensor: no exception is thrown when calling start() on already started sensor. assert_implements: GeolocationSensor is not supported. undefined
diff --git a/third_party/blink/web_tests/external/wpt/html/browsers/browsing-the-web/remote-context-helper-tests/resources/test-helper.js b/third_party/blink/web_tests/external/wpt/html/browsers/browsing-the-web/remote-context-helper-tests/resources/test-helper.js index 5f8e0771..71cd87e 100644 --- a/third_party/blink/web_tests/external/wpt/html/browsers/browsing-the-web/remote-context-helper-tests/resources/test-helper.js +++ b/third_party/blink/web_tests/external/wpt/html/browsers/browsing-the-web/remote-context-helper-tests/resources/test-helper.js
@@ -45,41 +45,4 @@ const res = await fetch(location); return res.headers.get(headerName); }, [headerName]), 'header is set'); -} - -async function assertNotRestoredReasonsEquals( - remoteContextHelper, blocked, url, src, id, name, reasons, children) { - let result = await remoteContextHelper.executeScript(() => { - return performance.getEntriesByType('navigation')[0].notRestoredReasons; - }); - assertReasonsStructEquals(result, blocked, url, src, id, name, reasons, children); -} - -function assertReasonsStructEquals(result, blocked, url, src, id, name, reasons, children) { - assert_equals(result.blocked, blocked); - assert_equals(result.url, url); - assert_equals(result.src, src); - assert_equals(result.id, id); - assert_equals(result.name, name); - // Reasons should match. - assert_equals(result.reasons.length, reasons.length); - reasons.sort(); - result.reasons.sort(); - for (let i=0; i<reasons.length; i++) { - assert_equals(result.reasons[i], reasons[i]); - } - // Children should match. - assert_equals(result.children.length, children.length); - children.sort(); - result.children.sort(); - for (let j=0; j<children.length; j++) { - assertReasonsStructEquals(result.children[0], - children[0].blocked, - children[0].url, - children[0].src, - children[0].id, - children[0].name, - children[0].reasons, - children[0].children); - } } \ No newline at end of file
diff --git a/third_party/blink/web_tests/external/wpt/html/webappapis/dynamic-markup-insertion/opening-the-input-stream/crbug-583445-regression.window.js b/third_party/blink/web_tests/external/wpt/html/webappapis/dynamic-markup-insertion/opening-the-input-stream/crbug-583445-regression.window.js new file mode 100644 index 0000000..0332483 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/webappapis/dynamic-markup-insertion/opening-the-input-stream/crbug-583445-regression.window.js
@@ -0,0 +1,139 @@ +// META: script=/common/get-host-info.sub.js +// META: script=/common/utils.js +// META: script=/common/dispatcher/dispatcher.js +// +// This is a regression test for crbug.com/583445. It checks an obscure bug in +// Chromium's handling of `document.open()` whereby the URL change would affect +// the document's origin after a javascript navigation. +// +// See also dcheng@'s comments on the original code review in which he +// introduced the precursor to this test: +// https://codereview.chromium.org/1675473002. + +function executorUrl(uuid, options) { + const url = + new URL("/common/dispatcher/remote-executor.html", window.location); + url.searchParams.set("uuid", uuid); + + if (options?.host) { + url.host = options.host; + } + + return url; +} + +function nextMessage() { + return new Promise((resolve) => { + window.addEventListener("message", (e) => { resolve(e.data); }, { + once: true + }); + }); +} + +promise_test(async (t) => { + // Embed a cross-origin frame A and set up remote code execution. + const iframeA = document.body.appendChild(document.createElement("iframe")); + t.add_cleanup(() => { iframeA.remove(); }); + + const uuidA = token(); + iframeA.src = executorUrl(uuidA, { host: get_host_info().REMOTE_HOST }); + const ctxA = new RemoteContext(uuidA); + + // Frame A embeds a cross-origin frame B, which is same-origin with the + // top-level frame. Frame B is the center of this test: it is where we will + // verify that a bug does not grant it UXSS in frame A. + // + // Though we could reach into `iframeA.frames[0]` to get a proxy to frame B + // and use `setTimeout()` like below to execute code inside it, we set up + // remote code execution using `dispatcher.js` for better ergonomics. + const uuidB = token(); + await ctxA.execute_script((url) => { + const iframeB = document.createElement("iframe"); + iframeB.src = url; + document.body.appendChild(iframeB); + }, [executorUrl(uuidB).href]); + + // Start listening for a message, which will come as a result of executing + // the code below in frame B. + const message = nextMessage(); + + const ctxB = new RemoteContext(uuidB); + await ctxB.execute_script(() => { + // Frame B embeds an `about:blank` frame C. + const iframeC = document.body.appendChild(document.createElement("iframe")); + + // We wish to execute code inside frame C, but it is important to this test + // that its URL remain `about:blank`, so we cannot use `dispatcher.js`. + // Instead we rely on `setTimeout()`. + // + // We use `setTimeout(string, ...)` instead of `setTimeout(function, ...)` + // as the given script executes against the target window's global object + // and does not capture any local variables. + // + // In order to have nice syntax highlighting and avoid quote-escaping hell, + // we use a trick employed by `dispatcher.js`. We rely on the fact that + // functions in JS have a stringifier that returns their source code. Thus + // `"(" + func + ")()"` is a string that executes `func()` when evaluated. + iframeC.contentWindow.setTimeout("(" + (() => { + // This executes in frame C. + + // Frame C calls `document.open()` on its parent, which results in B's + // URL being set to `about:blank` (C's URL). + // + // However, just before `document.open()` is called, B schedules a + // self-navigation to a `javascript:` URL. This will occur after + // `document.open()`, so the document will navigate from `about:blank` to + // the new URL. + // + // This should not result in B's origin changing, so B should remain + // same-origin with the top-level frame. + // + // Due to crbug.com/583445, this used to behave wrongly in Chromium. The + // navigation code incorrectly assumed that B's origin should be inherited + // from its parent A because B's URL was `about:blank`. + // + // It is important to schedule this from within the child, as this + // guarantees that `document.open()` will be called before the navigation. + // A previous version of this test scheduled this from within frame B + // right after scheduling the call to `document.open()`, but that ran the + // risk of races depending on which timeout fired first. + parent.window.setTimeout("(" + (() => { + // This executes in frame B. + + location = "javascript:(" + (() => { + /* This also executes in frame B. + * + * Note that because this whole function gets stuffed in a JS URL, + * single-line comments do not work, as they affect the following + * lines. */ + + let error; + try { + /* This will fail with a `SecurityError` if frame B is no longer + * same-origin with the top-level frame. */ + top.window.testSameOrigin = true; + } catch (e) { + error = e; + } + + top.postMessage({ + error: error?.toString(), + }, "*"); + + }) + ")()"; + + }) + ")()", 0); + + // This executes in frame C. + parent.document.open(); + + }) + ")()", 0); + }); + + // Await the message from frame B after its navigation. + const { error } = await message; + assert_equals(error, undefined, "error accessing top frame from frame B"); + assert_true(window.testSameOrigin, "top frame testSameOrigin is mutated"); + +}, "Regression test for crbug.com/583445"); +
diff --git a/third_party/blink/web_tests/external/wpt/interfaces/fs.idl b/third_party/blink/web_tests/external/wpt/interfaces/fs.idl index 9263ca7..0bda456 100644 --- a/third_party/blink/web_tests/external/wpt/interfaces/fs.idl +++ b/third_party/blink/web_tests/external/wpt/interfaces/fs.idl
@@ -24,6 +24,8 @@ interface FileSystemFileHandle : FileSystemHandle { Promise<File> getFile(); Promise<FileSystemWritableFileStream> createWritable(optional FileSystemCreateWritableOptions options = {}); + [Exposed=DedicatedWorker] + Promise<FileSystemSyncAccessHandle> createSyncAccessHandle(); }; dictionary FileSystemGetFileOptions { @@ -72,6 +74,23 @@ Promise<undefined> truncate(unsigned long long size); }; +dictionary FileSystemReadWriteOptions { + [EnforceRange] required unsigned long long at; +}; + +[Exposed=DedicatedWorker, SecureContext] +interface FileSystemSyncAccessHandle { + unsigned long long read([AllowShared] BufferSource buffer, + optional FileSystemReadWriteOptions options = {}); + unsigned long long write([AllowShared] BufferSource buffer, + optional FileSystemReadWriteOptions options = {}); + + Promise<undefined> truncate([EnforceRange] unsigned long long newSize); + Promise<unsigned long long> getSize(); + Promise<undefined> flush(); + Promise<undefined> close(); +}; + [SecureContext] partial interface StorageManager { Promise<FileSystemDirectoryHandle> getDirectory();
diff --git a/third_party/blink/web_tests/external/wpt/interfaces/screen-capture.idl b/third_party/blink/web_tests/external/wpt/interfaces/screen-capture.idl index 06b1ae67..908fce2 100644 --- a/third_party/blink/web_tests/external/wpt/interfaces/screen-capture.idl +++ b/third_party/blink/web_tests/external/wpt/interfaces/screen-capture.idl
@@ -7,6 +7,12 @@ Promise<MediaStream> getDisplayMedia(optional DisplayMediaStreamOptions options = {}); }; +[Exposed=Window, SecureContext] +interface CaptureController { + constructor(); + // TODO: Add setFocusBehavior() in a separate PR. +}; + enum SelfCapturePreferenceEnum { "include", "exclude" @@ -25,6 +31,7 @@ dictionary DisplayMediaStreamOptions { (boolean or MediaTrackConstraints) video = true; (boolean or MediaTrackConstraints) audio = false; + CaptureController controller = null; SelfCapturePreferenceEnum selfBrowserSurface; SystemAudioPreferenceEnum systemAudio; SurfaceSwitchingPreferenceEnum surfaceSwitching;
diff --git a/third_party/blink/web_tests/external/wpt/interfaces/webcodecs.idl b/third_party/blink/web_tests/external/wpt/interfaces/webcodecs.idl index 669add6..4854d96 100644 --- a/third_party/blink/web_tests/external/wpt/interfaces/webcodecs.idl +++ b/third_party/blink/web_tests/external/wpt/interfaces/webcodecs.idl
@@ -170,7 +170,7 @@ [EnforceRange] unsigned long displayWidth; [EnforceRange] unsigned long displayHeight; [EnforceRange] unsigned long long bitrate; - [EnforceRange] double framerate; + double framerate; HardwareAcceleration hardwareAcceleration = "no-preference"; AlphaOption alpha = "discard"; DOMString scalabilityMode;
diff --git a/third_party/blink/web_tests/external/wpt/interfaces/webgpu.idl b/third_party/blink/web_tests/external/wpt/interfaces/webgpu.idl index a6c00023..f2e038c2 100644 --- a/third_party/blink/web_tests/external/wpt/interfaces/webgpu.idl +++ b/third_party/blink/web_tests/external/wpt/interfaces/webgpu.idl
@@ -37,7 +37,7 @@ readonly attribute unsigned long maxInterStageShaderComponents; readonly attribute unsigned long maxInterStageShaderVariables; readonly attribute unsigned long maxColorAttachments; - readonly attribute unsigned long maxColorAttachmentBytesPerPixel; + readonly attribute unsigned long maxColorAttachmentBytesPerSample; readonly attribute unsigned long maxComputeWorkgroupStorageSize; readonly attribute unsigned long maxComputeInvocationsPerWorkgroup; readonly attribute unsigned long maxComputeWorkgroupSizeX; @@ -1028,7 +1028,7 @@ "discard" }; -dictionary GPURenderPassLayout: GPUObjectDescriptorBase { +dictionary GPURenderPassLayout : GPUObjectDescriptorBase { required sequence<GPUTextureFormat?> colorFormats; GPUTextureFormat depthStencilFormat; GPUSize32 sampleCount = 1;
diff --git a/third_party/blink/web_tests/external/wpt/interfaces/webrtc-encoded-transform.idl b/third_party/blink/web_tests/external/wpt/interfaces/webrtc-encoded-transform.idl index b905ab84..e6ebf7f7 100644 --- a/third_party/blink/web_tests/external/wpt/interfaces/webrtc-encoded-transform.idl +++ b/third_party/blink/web_tests/external/wpt/interfaces/webrtc-encoded-transform.idl
@@ -3,12 +3,6 @@ // (https://github.com/w3c/webref) // Source: WebRTC Encoded Transform (https://w3c.github.io/webrtc-encoded-transform/) -// New dictionary -dictionary RTCInsertableStreams { - ReadableStream readable; - WritableStream writable; -}; - typedef (SFrameTransform or RTCRtpScriptTransform) RTCRtpTransform; // New methods for RTCRtpSender and RTCRtpReceiver @@ -76,9 +70,9 @@ unsigned short height; long spatialIndex; long temporalIndex; - long synchronizationSource; + unsigned long synchronizationSource; octet payloadType; - sequence<long> contributingSources; + sequence<unsigned long> contributingSources; }; // New interfaces to define encoded video and audio frames. Will eventually @@ -92,9 +86,9 @@ }; dictionary RTCEncodedAudioFrameMetadata { - long synchronizationSource; + unsigned long synchronizationSource; octet payloadType; - sequence<long> contributingSources; + sequence<unsigned long> contributingSources; }; [Exposed=(Window,DedicatedWorker)]
diff --git a/third_party/blink/web_tests/external/wpt/interfaces/webrtc-stats.idl b/third_party/blink/web_tests/external/wpt/interfaces/webrtc-stats.idl index ea300a24..ec80449 100644 --- a/third_party/blink/web_tests/external/wpt/interfaces/webrtc-stats.idl +++ b/third_party/blink/web_tests/external/wpt/interfaces/webrtc-stats.idl
@@ -230,7 +230,7 @@ required RTCIceCandidateType candidateType; long priority; DOMString url; - DOMString relayProtocol; + RTCIceServerTransportProtocol relayProtocol; }; dictionary RTCIceCandidatePairStats : RTCStats {
diff --git a/third_party/blink/web_tests/external/wpt/interfaces/webrtc.idl b/third_party/blink/web_tests/external/wpt/interfaces/webrtc.idl index 5b53441..7bf168c 100644 --- a/third_party/blink/web_tests/external/wpt/interfaces/webrtc.idl +++ b/third_party/blink/web_tests/external/wpt/interfaces/webrtc.idl
@@ -51,29 +51,29 @@ }; enum RTCIceGatheringState { - "new", - "gathering", - "complete" -}; +"new", +"gathering", +"complete" + }; enum RTCPeerConnectionState { - "closed", - "failed", - "disconnected", - "new", - "connecting", - "connected" -}; +"closed", +"failed", +"disconnected", +"new", +"connecting", +"connected" + }; enum RTCIceConnectionState { - "closed", - "failed", - "disconnected", - "new", - "checking", - "completed", - "connected" -}; +"closed", +"failed", +"disconnected", +"new", +"checking", +"completed", +"connected" + }; [Exposed=Window] interface RTCPeerConnection : EventTarget {
diff --git a/third_party/blink/web_tests/external/wpt/lint.ignore b/third_party/blink/web_tests/external/wpt/lint.ignore index 46f50d0..8b1b703 100644 --- a/third_party/blink/web_tests/external/wpt/lint.ignore +++ b/third_party/blink/web_tests/external/wpt/lint.ignore
@@ -333,6 +333,7 @@ SET TIMEOUT: html/cross-origin-opener-policy/navigate-to-aboutblank.https.html SET TIMEOUT: html/cross-origin-opener-policy/navigate-top-to-aboutblank.https.html SET TIMEOUT: html/dom/documents/dom-tree-accessors/Document.currentScript.html +SET TIMEOUT: html/webappapis/dynamic-markup-insertion/opening-the-input-stream/crbug-583445-regression.window.js SET TIMEOUT: html/webappapis/timers/* SET TIMEOUT: orientation-event/resources/orientation-event-helpers.js SET TIMEOUT: portals/history/resources/portal-harness.js
diff --git a/third_party/blink/web_tests/external/wpt/magnetometer/Magnetometer.https-expected.txt b/third_party/blink/web_tests/external/wpt/magnetometer/Magnetometer.https-expected.txt index 7ec2483..fd4f820 100644 --- a/third_party/blink/web_tests/external/wpt/magnetometer/Magnetometer.https-expected.txt +++ b/third_party/blink/web_tests/external/wpt/magnetometer/Magnetometer.https-expected.txt
@@ -9,6 +9,7 @@ PASS Magnetometer: Test that sensor can be constructed within an iframe allowed to use feature policy. PASS Magnetometer: Test that 'onreading' is called and sensor reading is valid. PASS Magnetometer: sensor reading is correct. +PASS Magnetometer: Test that readings are all mapped to expectedReadings correctly. PASS Magnetometer: sensor timestamp is updated when time passes. PASS Magnetometer: Test that sensor can be successfully created and its states are correct. PASS Magnetometer: no exception is thrown when calling start() on already started sensor. @@ -29,6 +30,7 @@ FAIL UncalibratedMagnetometer: Test that sensor can be constructed within an iframe allowed to use feature policy. assert_implements: UncalibratedMagnetometer is not supported. undefined FAIL UncalibratedMagnetometer: Test that 'onreading' is called and sensor reading is valid. assert_implements: UncalibratedMagnetometer is not supported. undefined FAIL UncalibratedMagnetometer: sensor reading is correct. assert_implements: UncalibratedMagnetometer is not supported. undefined +FAIL UncalibratedMagnetometer: Test that readings are all mapped to expectedReadings correctly. assert_implements: UncalibratedMagnetometer is not supported. undefined FAIL UncalibratedMagnetometer: sensor timestamp is updated when time passes. assert_implements: UncalibratedMagnetometer is not supported. undefined FAIL UncalibratedMagnetometer: Test that sensor can be successfully created and its states are correct. assert_implements: UncalibratedMagnetometer is not supported. undefined FAIL UncalibratedMagnetometer: no exception is thrown when calling start() on already started sensor. assert_implements: UncalibratedMagnetometer is not supported. undefined
diff --git a/third_party/blink/web_tests/external/wpt/performance-timeline/not-restored-reasons/performance-navigation-timing-bfcache-reasons-stay.window.js b/third_party/blink/web_tests/external/wpt/performance-timeline/not-restored-reasons/performance-navigation-timing-bfcache-reasons-stay.window.js new file mode 100644 index 0000000..47d965f --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/performance-timeline/not-restored-reasons/performance-navigation-timing-bfcache-reasons-stay.window.js
@@ -0,0 +1,56 @@ +// META: title=RemoteContextHelper navigation using BFCache +// META: script=./test-helper.js +// META: script=/common/dispatcher/dispatcher.js +// META: script=/common/get-host-info.sub.js +// META: script=/common/utils.js +// META: script=/html/browsers/browsing-the-web/remote-context-helper/resources/remote-context-helper.js +// META: script=/websockets/constants.sub.js + +'use strict'; + +// Ensure that notRestoredReasons are only updated after non BFCache navigation. +promise_test(async t => { + const rcHelper = new RemoteContextHelper(); + // Open a window with noopener so that BFCache will work. + const rc1 = await rcHelper.addWindow( + /*config=*/ null, /*options=*/ {features: 'noopener'}); + // Use WebSocket to block BFCache. + await useWebSocket(rc1); + const rc1_url = await rc1.executeScript(() => { + return location.href; + }); + prepareForBFCache(rc1); + + // Navigate away. + const rc2 = await rc1.navigateToNew(); + // Navigate back. + await rc2.historyBack(); + assert_not_bfcached(rc1); + + // Check the reported reasons. + await assertNotRestoredReasonsEquals( + rc1, + /*blocked=*/ true, + /*url=*/ rc1_url, + /*src=*/ '', + /*id=*/ '', + /*name=*/ '', + /*reasons=*/['WebSocket'], + /*children=*/[]); + prepareForBFCache(rc1); + + await rc1.historyForward(); + await rc2.historyBack(); + // This time no blocking feature is used, so the page is restored + // from BFCache. Ensure that the previous reasons stay there. + assert_implements_bfcache(rc1); + await assertNotRestoredReasonsEquals( + rc1, + /*blocked=*/ true, + /*url=*/ rc1_url, + /*src=*/ '', + /*id=*/ '', + /*name=*/ '', + /*reasons=*/['WebSocket'], + /*children=*/[]); +});
diff --git a/third_party/blink/web_tests/external/wpt/performance-timeline/not-restored-reasons/performance-navigation-timing-bfcache.window.js b/third_party/blink/web_tests/external/wpt/performance-timeline/not-restored-reasons/performance-navigation-timing-bfcache.window.js index a5646f4..1e7f6d88 100644 --- a/third_party/blink/web_tests/external/wpt/performance-timeline/not-restored-reasons/performance-navigation-timing-bfcache.window.js +++ b/third_party/blink/web_tests/external/wpt/performance-timeline/not-restored-reasons/performance-navigation-timing-bfcache.window.js
@@ -1,9 +1,9 @@ // META: title=RemoteContextHelper navigation using BFCache +// META: script=./test-helper.js // META: script=/common/dispatcher/dispatcher.js // META: script=/common/get-host-info.sub.js // META: script=/common/utils.js // META: script=/html/browsers/browsing-the-web/remote-context-helper/resources/remote-context-helper.js -// META: script=/html/browsers/browsing-the-web/remote-context-helper-tests/resources/test-helper.js 'use strict'; @@ -14,16 +14,19 @@ // Open a window with noopener so that BFCache will work. const rc1 = await rcHelper.addWindow( /*config=*/ null, /*options=*/ {features: 'noopener'}); + prepareForBFCache(rc1); // Navigate away. const rc2 = await rc1.navigateToNew(); // Navigate back. await rc2.historyBack(); + assert_implements_bfcache(rc1); // Verify that no reasons are recorded for successful restore. assert_true(await rc1.executeScript(() => { - let reasons = performance.getEntriesByType('navigation')[0].notRestoredReasons; + let reasons = + performance.getEntriesByType('navigation')[0].notRestoredReasons; return reasons == null; })); }); \ No newline at end of file
diff --git a/third_party/blink/web_tests/external/wpt/performance-timeline/not-restored-reasons/performance-navigation-timing-cross-origin-bfcache.window.js b/third_party/blink/web_tests/external/wpt/performance-timeline/not-restored-reasons/performance-navigation-timing-cross-origin-bfcache.window.js index d49e137..c3ad649 100644 --- a/third_party/blink/web_tests/external/wpt/performance-timeline/not-restored-reasons/performance-navigation-timing-cross-origin-bfcache.window.js +++ b/third_party/blink/web_tests/external/wpt/performance-timeline/not-restored-reasons/performance-navigation-timing-cross-origin-bfcache.window.js
@@ -1,14 +1,15 @@ // META: title=RemoteContextHelper navigation using BFCache +// META: script=./test-helper.js // META: script=/common/dispatcher/dispatcher.js // META: script=/common/get-host-info.sub.js // META: script=/common/utils.js // META: script=/html/browsers/browsing-the-web/remote-context-helper/resources/remote-context-helper.js -// META: script=/html/browsers/browsing-the-web/remote-context-helper-tests/resources/test-helper.js // META: script=/websockets/constants.sub.js 'use strict'; -// Ensure that cross-origin subtree's reasons are not exposed to notRestoredReasons. +// Ensure that cross-origin subtree's reasons are not exposed to +// notRestoredReasons. promise_test(async t => { const rcHelper = new RemoteContextHelper(); // Open a window with noopener so that BFCache will work. @@ -19,18 +20,15 @@ }); // Add a cross-origin iframe and use BroadcastChannel. const rc1_child = await rc1.addIframe( - /*extraConfig=*/ { - origin: 'HTTP_REMOTE_ORIGIN', - scripts: [], - headers: [], - }, - /*attributes=*/ {id: 'test-id'}, + /*extraConfig=*/ { + origin: 'HTTP_REMOTE_ORIGIN', + scripts: [], + headers: [], + }, + /*attributes=*/ {id: 'test-id'}, ); - - const domainPort = SCHEME_DOMAIN_PORT; - await rc1_child.executeScript((domain) => { - var ws = new WebSocket(domain + '/echo'); - }, [domainPort]); + // Use WebSocket to block BFCache. + await useWebSocket(rc1_child); const rc1_child_url = await rc1_child.executeScript(() => { return location.href; @@ -40,29 +38,29 @@ const rc1_grand_child_url = await rc1_grand_child.executeScript(() => { return location.href; }); - + prepareForBFCache(rc1); // Navigate away. const rc2 = await rc1.navigateToNew(); // Navigate back. await rc2.historyBack(); - + assert_not_bfcached(rc1); // Check the reported reasons. await assertNotRestoredReasonsEquals( - rc1, - /*blocked=*/false, - /*url=*/rc1_url, - /*src=*/ "", - /*id=*/"", - /*name=*/"", - /*reasons=*/[], - /*children=*/[{ - "blocked": true, - "url": "", - "src": "", - "id": "", - "name": "", - "reasons": [], - "children": [] - }]); + rc1, + /*blocked=*/ false, + /*url=*/ rc1_url, + /*src=*/ '', + /*id=*/ '', + /*name=*/ '', + /*reasons=*/[], + /*children=*/[{ + 'blocked': true, + 'url': '', + 'src': '', + 'id': '', + 'name': '', + 'reasons': [], + 'children': [] + }]); }); \ No newline at end of file
diff --git a/third_party/blink/web_tests/external/wpt/performance-timeline/not-restored-reasons/performance-navigation-timing-not-bfcached.window.js b/third_party/blink/web_tests/external/wpt/performance-timeline/not-restored-reasons/performance-navigation-timing-not-bfcached.window.js index 12e02f2c..32542591 100644 --- a/third_party/blink/web_tests/external/wpt/performance-timeline/not-restored-reasons/performance-navigation-timing-not-bfcached.window.js +++ b/third_party/blink/web_tests/external/wpt/performance-timeline/not-restored-reasons/performance-navigation-timing-not-bfcached.window.js
@@ -1,9 +1,9 @@ // META: title=RemoteContextHelper navigation using BFCache +// META: script=./test-helper.js // META: script=/common/dispatcher/dispatcher.js // META: script=/common/get-host-info.sub.js // META: script=/common/utils.js // META: script=/html/browsers/browsing-the-web/remote-context-helper/resources/remote-context-helper.js -// META: script=/html/browsers/browsing-the-web/remote-context-helper-tests/resources/test-helper.js // META: script=/websockets/constants.sub.js 'use strict'; @@ -14,29 +14,28 @@ // Open a window with noopener so that BFCache will work. const rc1 = await rcHelper.addWindow( /*config=*/ null, /*options=*/ {features: 'noopener'}); - - const domainPort = SCHEME_DOMAIN_PORT; - await rc1.executeScript((domain) => { - var ws = new WebSocket(domain + '/echo'); - }, [domainPort]); + // Use WebSocket to block BFCache. + await useWebSocket(rc1); const rc1_url = await rc1.executeScript(() => { return location.href; }); + prepareForBFCache(rc1); // Navigate away. const rc2 = await rc1.navigateToNew(); // Navigate back. await rc2.historyBack(); + assert_not_bfcached(rc1); // Check the reported reasons. await assertNotRestoredReasonsEquals( - rc1, - /*blocked=*/true, - /*url=*/rc1_url, - /*src=*/ "", - /*id=*/"", - /*name=*/"", - /*reasons=*/["WebSocket"], - /*children=*/[]); + rc1, + /*blocked=*/ true, + /*url=*/ rc1_url, + /*src=*/ '', + /*id=*/ '', + /*name=*/ '', + /*reasons=*/['WebSocket'], + /*children=*/[]); }); \ No newline at end of file
diff --git a/third_party/blink/web_tests/external/wpt/performance-timeline/not-restored-reasons/performance-navigation-timing-same-origin-bfcache.window.js b/third_party/blink/web_tests/external/wpt/performance-timeline/not-restored-reasons/performance-navigation-timing-same-origin-bfcache.window.js index 6d1413f..108fc9d 100644 --- a/third_party/blink/web_tests/external/wpt/performance-timeline/not-restored-reasons/performance-navigation-timing-same-origin-bfcache.window.js +++ b/third_party/blink/web_tests/external/wpt/performance-timeline/not-restored-reasons/performance-navigation-timing-same-origin-bfcache.window.js
@@ -1,9 +1,9 @@ // META: title=RemoteContextHelper navigation using BFCache +// META: script=./test-helper.js // META: script=/common/dispatcher/dispatcher.js // META: script=/common/get-host-info.sub.js // META: script=/common/utils.js // META: script=/html/browsers/browsing-the-web/remote-context-helper/resources/remote-context-helper.js -// META: script=/html/browsers/browsing-the-web/remote-context-helper-tests/resources/test-helper.js // META: script=/websockets/constants.sub.js 'use strict'; @@ -18,12 +18,9 @@ return location.href; }); // Add a same-origin iframe and use WebSocket. - const rc1_child = await rc1.addIframe(/*extra_config=*/{}, /*attributes=*/ {id: 'test-id'}); - - const domainPort = SCHEME_DOMAIN_PORT; - await rc1_child.executeScript((domain) => { - var ws = new WebSocket(domain + '/echo'); - }, [domainPort]); + const rc1_child = await rc1.addIframe( + /*extra_config=*/ {}, /*attributes=*/ {id: 'test-id'}); + await useWebSocket(rc1_child); const rc1_child_url = await rc1_child.executeScript(() => { return location.href; @@ -33,39 +30,38 @@ const rc1_grand_child_url = await rc1_grand_child.executeScript(() => { return location.href; }); + prepareForBFCache(rc1); // Navigate away. const rc2 = await rc1.navigateToNew(); // Navigate back. await rc2.historyBack(); - + assert_not_bfcached(rc1); // Check the reported reasons. await assertNotRestoredReasonsEquals( - rc1, - /*blocked=*/false, - /*url=*/rc1_url, - /*src=*/ "", - /*id=*/"", - /*name=*/"", - /*reasons=*/[], - /*children=*/[{ - "blocked": true, - "url": rc1_child_url, - "src": rc1_child_url, - "id": "test-id", - "name": "", - "reasons": ["WebSocket"], - "children": [ - { - "blocked": false, - "url": rc1_grand_child_url, - "src": rc1_grand_child_url, - "id": "", - "name": "", - "reasons": [], - "children": [] - } - ] - }]); + rc1, + /*blocked=*/ false, + /*url=*/ rc1_url, + /*src=*/ '', + /*id=*/ '', + /*name=*/ '', + /*reasons=*/[], + /*children=*/[{ + 'blocked': true, + 'url': rc1_child_url, + 'src': rc1_child_url, + 'id': 'test-id', + 'name': '', + 'reasons': ['WebSocket'], + 'children': [{ + 'blocked': false, + 'url': rc1_grand_child_url, + 'src': rc1_grand_child_url, + 'id': '', + 'name': '', + 'reasons': [], + 'children': [] + }] + }]); }); \ No newline at end of file
diff --git a/third_party/blink/web_tests/external/wpt/performance-timeline/not-restored-reasons/test-helper.js b/third_party/blink/web_tests/external/wpt/performance-timeline/not-restored-reasons/test-helper.js new file mode 100644 index 0000000..26d2a3c --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/performance-timeline/not-restored-reasons/test-helper.js
@@ -0,0 +1,75 @@ +async function assertNotRestoredReasonsEquals( + remoteContextHelper, blocked, url, src, id, name, reasons, children) { + let result = await remoteContextHelper.executeScript(() => { + return performance.getEntriesByType('navigation')[0].notRestoredReasons; + }); + assertReasonsStructEquals( + result, blocked, url, src, id, name, reasons, children); +} + +function assertReasonsStructEquals( + result, blocked, url, src, id, name, reasons, children) { + assert_equals(result.blocked, blocked); + assert_equals(result.url, url); + assert_equals(result.src, src); + assert_equals(result.id, id); + assert_equals(result.name, name); + // Reasons should match. + assert_equals(result.reasons.length, reasons.length); + reasons.sort(); + result.reasons.sort(); + for (let i = 0; i < reasons.length; i++) { + assert_equals(result.reasons[i], reasons[i]); + } + // Children should match. + assert_equals(result.children.length, children.length); + children.sort(); + result.children.sort(); + for (let j = 0; j < children.length; j++) { + assertReasonsStructEquals( + result.children[0], children[0].blocked, children[0].url, + children[0].src, children[0].id, children[0].name, children[0].reasons, + children[0].children); + } +} + +// Requires: +// - /websockets/constants.sub.js in the test file and pass the domainPort +// constant here. +async function useWebSocket(remoteContextHelper) { + await remoteContextHelper.executeScript((domain) => { + var webSocketInNotRestoredReasonsTests = new WebSocket(domain + '/echo'); + }, [SCHEME_DOMAIN_PORT]); +} + +// Call |prepareForBFCache()| before navigating away from the page. This simply +// sets a variable in window. +async function prepareForBFCache(remoteContextHelper) { + await remoteContextHelper.executeScript(() => { + window.beforeBFCache = true; + }); +} + +// Call |getBeforeCache| after navigating back to the page. This returns the +// value in window. +async function getBeforeBFCache(remoteContextHelper) { + return await remoteContextHelper.executeScript(() => { + return window.beforeBFCache; + }); +} + +// If the value in window is set to true, this means that the page was reloaded, +// i.e., the page was restored from BFCache. +// Call |prepareForBFCache()| before navigating away to call this function. +async function assert_implements_bfcache(remoteContextHelper) { + var beforeBFCache = await getBeforeBFCache(remoteContextHelper); + assert_implements_optional(beforeBFCache == true, 'BFCache not supported.'); +} + +// If the value in window is undefined, this means that the page was reloaded, +// i.e., the page was not restored from BFCache. +// Call |prepareForBFCache()| before navigating away to call this function. +async function assert_not_bfcached(remoteContextHelper) { + var beforeBFCache = await getBeforeBFCache(remoteContextHelper); + assert_equals(beforeBFCache, undefined); +}
diff --git a/third_party/blink/web_tests/external/wpt/permissions-policy/permissions-policy-header-policy-allowed-for-malformed-wildcard.https.sub.html b/third_party/blink/web_tests/external/wpt/permissions-policy/permissions-policy-header-policy-allowed-for-malformed-wildcard.https.sub.html new file mode 100644 index 0000000..daa47ef --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/permissions-policy/permissions-policy-header-policy-allowed-for-malformed-wildcard.https.sub.html
@@ -0,0 +1,55 @@ +<!DOCTYPE html> +<body> + <script src=/resources/testharness.js></script> + <script src=/resources/testharnessreport.js></script> + <script src=/permissions-policy/resources/permissions-policy.js></script> + <!-- Permissions-Policy: fullscreen=$MALFORMED_WILDCARD_ORIGINS self; --> + <script> + 'use strict'; + var same_origin = 'https://{{domains[]}}:{{ports[https][0]}}'; + var cross_origin = 'https://{{domains[www]}}:{{ports[https][0]}}'; + var cross_origin1 = 'https://{{domains[www1]}}:{{ports[https][0]}}'; + var same_origin_src = '/permissions-policy/resources/permissions-policy-allowedfeatures.html'; + var cross_origin_src = cross_origin + same_origin_src; + var cross_origin_src1 = cross_origin1 + same_origin_src; + var header_policy = `Permissions-Policy: fullscreen=("$MALFORMED_WILDCARD_ORIGINS self")`; + + // Test that fullscreen's allowlist lists all the malformed wildcards and self. + test(function() { + assert_array_equals( + document.featurePolicy.getAllowlistForFeature('fullscreen').sort(), + ["https://%2A.%2A.{{domains[]}}:{{ports[https][0]}}", "https://example.%2A.{{domains[]}}:{{ports[https][0]}}", "https://{{domains[]}}:{{ports[https][0]}}"].sort()); + }, header_policy + ' -- test allowlist lists all the malformed wildcards and self.'); + + // Test that fullscreen is allowed on same-origin subframes with or without an allow attribute. + test_allowed_feature_for_subframe( + header_policy + ' -- test fullscreen is allowed on same-origin subframe', + 'fullscreen', + same_origin_src); + test_allowed_feature_for_subframe( + header_policy + ' -- test fullscreen is allowed on same-origin subframe with allow attribute', + 'fullscreen', + same_origin_src, + "fullscreen " + same_origin); + + // Test that fullscreen is disallowed on cross-origin subframes without an allow attribute. + test_disallowed_feature_for_subframe( + header_policy + ' -- test fullscreen is disallowed on cross-origin subframe', + 'fullscreen', + cross_origin_src); + test_disallowed_feature_for_subframe( + header_policy + ' -- test fullscreen is disallowed on cross-origin subframe allow attribute', + 'fullscreen', + cross_origin_src, + "fullscreen " + cross_origin); + test_disallowed_feature_for_subframe( + header_policy + ' -- test fullscreen is disallowed on another cross-origin subframe', + 'fullscreen', + cross_origin_src1); + test_disallowed_feature_for_subframe( + header_policy + ' -- test fullscreen is disallowed on another cross-origin subframe allow attribute', + 'fullscreen', + cross_origin_src1, + "fullscreen " + cross_origin1); + </script> +</body>
diff --git a/third_party/blink/web_tests/external/wpt/permissions-policy/permissions-policy-header-policy-allowed-for-malformed-wildcard.https.sub.html.sub.headers b/third_party/blink/web_tests/external/wpt/permissions-policy/permissions-policy-header-policy-allowed-for-malformed-wildcard.https.sub.html.sub.headers new file mode 100644 index 0000000..cfb0f3f --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/permissions-policy/permissions-policy-header-policy-allowed-for-malformed-wildcard.https.sub.html.sub.headers
@@ -0,0 +1 @@ +Permissions-Policy: fullscreen=("*://{{domains[]}}:{{ports[https][0]}}" "https://{{domains[]}}:*" "https://*.*.{{domains[]}}:{{ports[https][0]}}" "https://example.*.{{domains[]}}:{{ports[https][0]}}" self)
diff --git a/third_party/blink/web_tests/external/wpt/permissions-policy/permissions-policy-header-policy-allowed-for-wildcard.https.sub.html b/third_party/blink/web_tests/external/wpt/permissions-policy/permissions-policy-header-policy-allowed-for-wildcard.https.sub.html new file mode 100644 index 0000000..713d697 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/permissions-policy/permissions-policy-header-policy-allowed-for-wildcard.https.sub.html
@@ -0,0 +1,68 @@ +<!DOCTYPE html> +<body> + <script src=/resources/testharness.js></script> + <script src=/resources/testharnessreport.js></script> + <script src=/permissions-policy/resources/permissions-policy.js></script> + <!-- Permissions-Policy: fullscreen=self wildcard_origin; --> + <script> + 'use strict'; + var same_origin = 'https://{{domains[]}}:{{ports[https][0]}}'; + var wildcard_origin = 'https://*.{{domains[]}}:{{ports[https][0]}}'; + var cross_origin = 'https://{{domains[www]}}:{{ports[https][0]}}'; + var cross_origin1 = 'https://{{domains[www1]}}:{{ports[https][0]}}'; + var same_origin_src = '/permissions-policy/resources/permissions-policy-allowedfeatures.html'; + var cross_origin_src = cross_origin + same_origin_src; + var cross_origin_src1 = cross_origin1 + same_origin_src; + var header_policy = `Permissions-Policy: fullscreen=("${wildcard_origin}")`; + + // Test that fullscreen's allowlist is [self wildcard_origin]. + test(function() { + assert_array_equals( + document.featurePolicy.getAllowlistForFeature('fullscreen').sort(), + [wildcard_origin, same_origin].sort()); + }, header_policy + ' -- test allowlist is [self wildcard_origin].'); + + // Test that fullscreen is allowed on same-origin subframes with or without an allow attribute. + test_allowed_feature_for_subframe( + header_policy + ' -- test fullscreen is allowed on same-origin subframe', + 'fullscreen', + same_origin_src); + test_allowed_feature_for_subframe( + header_policy + ' -- test fullscreen is allowed on same-origin subframe even with allow attribute', + 'fullscreen', + same_origin_src, + "fullscreen " + same_origin); + + // Test that fullscreen is disallowed on cross-origin subframes without an allow attribute. + test_disallowed_feature_for_subframe( + header_policy + ' -- test fullscreen is disallowed on cross-origin subframe', + 'fullscreen', + cross_origin_src); + test_allowed_feature_for_subframe( + header_policy + ' -- test fullscreen is allowed on cross-origin subframe allow attribute', + 'fullscreen', + cross_origin_src, + "fullscreen " + cross_origin); + test_disallowed_feature_for_subframe( + header_policy + ' -- test fullscreen is disallowed on another cross-origin subframe', + 'fullscreen', + cross_origin_src1); + test_allowed_feature_for_subframe( + header_policy + ' -- test fullscreen is allowed on another cross-origin subframe allow attribute', + 'fullscreen', + cross_origin_src1, + "fullscreen " + cross_origin1); + + // Test that wildcard allow attribute isn't supported. + test_disallowed_feature_for_subframe( + header_policy + ' -- test fullscreen is disallowed on cross-origin subframe with wildcard allow attribute', + 'fullscreen', + cross_origin_src, + "fullscreen " + wildcard_origin); + test_disallowed_feature_for_subframe( + header_policy + ' -- test fullscreen is disallowed on another cross-origin subframe with wildcard allow attribute', + 'fullscreen', + cross_origin_src1, + "fullscreen " + wildcard_origin); + </script> +</body>
diff --git a/third_party/blink/web_tests/external/wpt/permissions-policy/permissions-policy-header-policy-allowed-for-wildcard.https.sub.html.sub.headers b/third_party/blink/web_tests/external/wpt/permissions-policy/permissions-policy-header-policy-allowed-for-wildcard.https.sub.html.sub.headers new file mode 100644 index 0000000..cc492ecc --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/permissions-policy/permissions-policy-header-policy-allowed-for-wildcard.https.sub.html.sub.headers
@@ -0,0 +1 @@ +Permissions-Policy: fullscreen=(self "https://*.{{domains[]}}:{{ports[https][0]}}")
diff --git a/third_party/blink/web_tests/external/wpt/resources/chromium/generic_sensor_mocks.js b/third_party/blink/web_tests/external/wpt/resources/chromium/generic_sensor_mocks.js index 86904d1..bbc3973b 100644 --- a/third_party/blink/web_tests/external/wpt/resources/chromium/generic_sensor_mocks.js +++ b/third_party/blink/web_tests/external/wpt/resources/chromium/generic_sensor_mocks.js
@@ -31,6 +31,58 @@ } }; +class DefaultSensorTraits { + // https://w3c.github.io/sensors/#threshold-check-algorithm + static isSignificantlyDifferent(reading1, reading2) { + return true; + } + + // https://w3c.github.io/sensors/#reading-quantization-algorithm + static roundToMultiple(reading) { + return reading; + } + + // https://w3c.github.io/ambient-light/#ambient-light-threshold-check-algorithm + static areReadingsEqual(reading1, reading2) { + return false; + } +} + +class AmbientLightSensorTraits extends DefaultSensorTraits { + // https://w3c.github.io/ambient-light/#reduce-sensor-accuracy + static #ROUNDING_MULTIPLE = 50; + static #SIGNIFICANCE_THRESHOLD = 25; + + // https://w3c.github.io/ambient-light/#ambient-light-threshold-check-algorithm + static isSignificantlyDifferent([illuminance1], [illuminance2]) { + return Math.abs(illuminance1 - illuminance2) >= + this.#SIGNIFICANCE_THRESHOLD; + } + + // https://w3c.github.io/ambient-light/#ambient-light-reading-quantization-algorithm + static roundToMultiple(reading) { + const illuminance = reading[0]; + const scaledValue = + illuminance / AmbientLightSensorTraits.#ROUNDING_MULTIPLE; + let roundedReading = reading.splice(); + + if (illuminance < 0.0) { + roundedReading[0] = -AmbientLightSensorTraits.#ROUNDING_MULTIPLE * + Math.floor(-scaledValue + 0.5); + } else { + roundedReading[0] = AmbientLightSensorTraits.#ROUNDING_MULTIPLE * + Math.floor(scaledValue + 0.5); + } + + return roundedReading; + } + + // https://w3c.github.io/ambient-light/#ambient-light-threshold-check-algorithm + static areReadingsEqual([illuminance1], [illuminance2]) { + return illuminance1 === illuminance2; + } +} + self.GenericSensorTest = (() => { // Default sensor frequency in default configurations. const DEFAULT_FREQUENCY = 5; @@ -41,11 +93,12 @@ static #BUFFER_OFFSET_TIMESTAMP = 1; static #BUFFER_OFFSET_READINGS = 2; - constructor(sensorRequest, buffer, reportingMode) { + constructor(sensorRequest, buffer, reportingMode, sensorType) { this.client_ = null; this.startShouldFail_ = false; this.notifyOnReadingChange_ = true; this.reportingMode_ = reportingMode; + this.sensorType_ = sensorType; this.sensorReadingTimerId_ = null; this.readingData_ = null; this.requestedFrequencies_ = []; @@ -71,6 +124,14 @@ this.buffer_.fill(0); this.receiver_ = new SensorReceiver(this); this.receiver_.$.bindHandle(sensorRequest.handle); + this.lastRawReading_ = null; + this.lastRoundedReading_ = null; + + if (sensorType == SensorType.AMBIENT_LIGHT) { + this.sensorTraits = AmbientLightSensorTraits; + } else { + this.sensorTraits = DefaultSensorTraits; + } } // Returns default configuration. @@ -131,6 +192,8 @@ this.readingData_ = null; this.buffer_.fill(0); this.receiver_.$.close(); + this.lastRawReading_ = null; + this.lastRoundedReading_ = null; } // Sets fake data that is used to deliver sensor reading updates. @@ -169,8 +232,31 @@ throw new TypeError("startReading(): The readings passed to " + "setSensorReading() must be arrays"); } - this.buffer_.set(reading, MockSensor.#BUFFER_OFFSET_READINGS); + + if (this.reportingMode_ == ReportingMode.ON_CHANGE && + this.lastRawReading_ !== null && + !this.sensorTraits.isSignificantlyDifferent( + this.lastRawReading_, reading)) { + // In case new value is not significantly different compared to + // old value, new value is not sent. + return; + } + + this.lastRawReading_ = reading.slice(); + const roundedReading = this.sensorTraits.roundToMultiple(reading); + + if (this.reportingMode_ == ReportingMode.ON_CHANGE && + this.lastRoundedReading_ !== null && + this.sensorTraits.areReadingsEqual( + roundedReading, this.lastRoundedReading_)) { + // In case new rounded value is not different compared to old + // value, new value is not sent. + return; + } + this.buffer_.set(roundedReading, MockSensor.#BUFFER_OFFSET_READINGS); + this.lastRoundedReading_ = roundedReading; } + // For all tests sensor reading should have monotonically // increasing timestamp. this.buffer_[MockSensor.#BUFFER_OFFSET_TIMESTAMP] = this.timestamp_++; @@ -278,7 +364,8 @@ this.shmemArrayBuffer_, offset, this.readingSizeInBytes_ / Float64Array.BYTES_PER_ELEMENT); const mockSensor = new MockSensor( - sensor.$.bindNewPipeAndPassReceiver(), shmemView, reportingMode); + sensor.$.bindNewPipeAndPassReceiver(), shmemView, reportingMode, + type); this.activeSensors_.set(type, mockSensor); this.activeSensors_.get(type).client_ = new SensorClientRemote(); } @@ -296,19 +383,6 @@ this.maxFrequency_ = Math.min(10, this.maxFrequency_); } - // Chromium applies some rounding and other privacy-related measures that - // can cause ALS not to report a reading when it has not changed beyond a - // certain threshold compared to the previous illuminance value. Make - // each reading return a different value that is significantly different - // from the previous one when setSensorReading() is not called by client - // code (e.g. run_generic_sensor_iframe_tests()). - if (type == SensorType.AMBIENT_LIGHT) { - this.activeSensors_.get(type).setSensorReading([ - [window.performance.now() * 100], - [(window.performance.now() + 50) * 100] - ]); - } - const client = this.activeSensors_.get(type).client_; const initParams = { sensor,
diff --git a/third_party/blink/web_tests/external/wpt/screen-capture/idlharness.https.window-expected.txt b/third_party/blink/web_tests/external/wpt/screen-capture/idlharness.https.window-expected.txt new file mode 100644 index 0000000..4605eb2 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/screen-capture/idlharness.https.window-expected.txt
@@ -0,0 +1,25 @@ +This is a testharness.js-based test. +PASS idl_test setup +PASS idl_test validation +PASS Partial interface MediaDevices: original interface defined +PASS Partial interface MediaDevices: member names are unique +PASS Partial dictionary MediaTrackSupportedConstraints: original dictionary defined +PASS Partial dictionary MediaTrackSupportedConstraints: member names are unique +PASS Partial dictionary MediaTrackConstraintSet: original dictionary defined +PASS Partial dictionary MediaTrackConstraintSet: member names are unique +PASS Partial dictionary MediaTrackSettings: original dictionary defined +PASS Partial dictionary MediaTrackSettings: member names are unique +PASS Partial dictionary MediaTrackCapabilities: original dictionary defined +PASS Partial dictionary MediaTrackCapabilities: member names are unique +PASS Partial interface MediaDevices[2]: member names are unique +FAIL CaptureController interface: existence and properties of interface object assert_own_property: self does not have own property "CaptureController" expected property "CaptureController" missing +FAIL CaptureController interface object length assert_own_property: self does not have own property "CaptureController" expected property "CaptureController" missing +FAIL CaptureController interface object name assert_own_property: self does not have own property "CaptureController" expected property "CaptureController" missing +FAIL CaptureController interface: existence and properties of interface prototype object assert_own_property: self does not have own property "CaptureController" expected property "CaptureController" missing +FAIL CaptureController interface: existence and properties of interface prototype object's "constructor" property assert_own_property: self does not have own property "CaptureController" expected property "CaptureController" missing +FAIL CaptureController interface: existence and properties of interface prototype object's @@unscopables property assert_own_property: self does not have own property "CaptureController" expected property "CaptureController" missing +PASS MediaDevices interface: operation getDisplayMedia(optional DisplayMediaStreamOptions) +PASS MediaDevices interface: navigator.mediaDevices must inherit property "getDisplayMedia(optional DisplayMediaStreamOptions)" with the proper type +PASS MediaDevices interface: calling getDisplayMedia(optional DisplayMediaStreamOptions) on navigator.mediaDevices with too few arguments must throw TypeError +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/speculation-rules/prefetch/out-of-document-rule-set.https.html b/third_party/blink/web_tests/external/wpt/speculation-rules/prefetch/out-of-document-rule-set.https.html index 6b437fa..9f2c311 100644 --- a/third_party/blink/web_tests/external/wpt/speculation-rules/prefetch/out-of-document-rule-set.https.html +++ b/third_party/blink/web_tests/external/wpt/speculation-rules/prefetch/out-of-document-rule-set.https.html
@@ -13,6 +13,7 @@ <meta name="variant" content="?include=UseNonUTF8EncodingForSpeculationRulesSet"> <meta name="variant" content="?include=FailCORS"> <meta name="variant" content="?include=FailToParseSpeculationRulesHeader"> +<meta name="variant" content="?include=InnerListInSpeculationRulesHeader"> <meta name="variant" content="?include=EmptyRuleSet"> <meta name="variant" content="?include=FailToParseRuleSet"> <meta name="variant" content="?include=InvalidUrlForSpeculationRulesSet"> @@ -39,6 +40,8 @@ failCors: false, // Whether to use a valid SpeculationRules header format. useValidSpeculationRulesHeaderValue: true, + // Whether to use an inner list of URLS in SpeculationRules header. + useInnerListInSpeculationRulesHeaderValue: false, // Whether to return an empty response. useEmptySpeculationRulesSet: false, // Wheter to return a rule set with valid JSON format @@ -67,7 +70,14 @@ speculation_rule_set_url = "http://:80/"; } - let speculation_rules_header = options.useValidSpeculationRulesHeaderValue ? `header(Speculation-Rules,"${speculation_rule_set_url}")` : `header(Speculation-Rules, x y z)`; + let speculation_rules_header = `header(Speculation-Rules,"${speculation_rule_set_url}")`; + if (!options.useValidSpeculationRulesHeaderValue) { + speculation_rules_header = `header(Speculation-Rules, x y z)`; + } + else if (options.useInnerListInSpeculationRulesHeaderValue) { + speculation_rules_header = `header(Speculation-Rules, \\("${speculation_rule_set_url}" "xyz.com/rule-set.json"\\))`; + } + let agent = await spawnWindow(t, {pipe: speculation_rules_header}, uuid); await new Promise(resolve => t.step_timeout(resolve, 2000)); // Passing non-ascii character '÷' as part of the next URL to check if we always decode the speculation rules set using utf-8 or not. This character is encoded differently in utf-8 and windows-1250 @@ -109,7 +119,11 @@ subsetTestByKey('FailToParseSpeculationRulesHeader', promise_test, async t => { return runSpeculationRulesFetchTest(t, {useValidSpeculationRulesHeaderValue: false, shouldPrefetch: false}); - }, "It should reject the speculation rules set if it fails to parse the SpecultionRules header."); + }, "It should reject the speculation rules set if it fails to parse the SpeculationRules header."); + + subsetTestByKey('InnerListInSpeculationRulesHeader', promise_test, async t => { + return runSpeculationRulesFetchTest(t, {useInnerListInSpeculationRulesHeaderValue: true, shouldPrefetch: false}); + }, "It should reject the speculation rules passed as inner list in the SpeculationRules header."); subsetTestByKey('EmptyRuleSet', promise_test, async t => { return runSpeculationRulesFetchTest(t, {useEmptySpeculationRulesSet: true, shouldPrefetch: false});
diff --git a/third_party/blink/web_tests/external/wpt/webcodecs/videoFrame-construction.any.js b/third_party/blink/web_tests/external/wpt/webcodecs/videoFrame-construction.any.js index 9a8ae033..07df649e 100644 --- a/third_party/blink/web_tests/external/wpt/webcodecs/videoFrame-construction.any.js +++ b/third_party/blink/web_tests/external/wpt/webcodecs/videoFrame-construction.any.js
@@ -93,6 +93,30 @@ }) }, 'Test constructing w/ unusable image argument throws: HAVE_NOTHING <video>.'); +promise_test(async t => { + // Test only valid for Window contexts. + if (!('document' in self)) + return; + + let video = document.createElement('video'); + video.src = 'av1.mp4'; + video.autoplay = true; + video.controls = false; + video.muted = false; + document.body.appendChild(video); + + const loadVideo = new Promise((resolve) => { + video.onloadeddata = () => resolve(); + }); + await loadVideo; + + let frame = new VideoFrame(video, {timestamp: 10}); + assert_equals(frame.codedWidth, 320, 'codedWidth'); + assert_equals(frame.codedHeight, 240, 'codedHeight'); + assert_equals(frame.timestamp, 10, 'timestamp'); + frame.close(); +}, 'Test we can construct a VideoFrame from a <video>.'); + test(t => { let canvas = new OffscreenCanvas(0, 0);
diff --git a/third_party/blink/web_tests/external/wpt/webcodecs/videoFrame-construction.crossOriginSource.sub-expected.txt b/third_party/blink/web_tests/external/wpt/webcodecs/videoFrame-construction.crossOriginSource.sub-expected.txt new file mode 100644 index 0000000..9a418e8 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/webcodecs/videoFrame-construction.crossOriginSource.sub-expected.txt
@@ -0,0 +1,15 @@ +This is a testharness.js-based test. +PASS Test creating a VideoFrame with a same-origin HTMLImageElement +PASS Test creating a VideoFrame with a cross-origin HTMLImageElement +PASS Test creating a VideoFrame with a CORS enabled cross-origin HTMLImageElement without setting crossorigin +PASS Test creating a VideoFrame with a CORS enabled cross-origin HTMLImageElement with crossorigin="anonymous" +PASS Test creating a VideoFrame with a same-origin SVGImageElement +PASS Test creating a VideoFrame with a cross-origin SVGImageElement +PASS Test creating a VideoFrame with a CORS enabled cross-origin SVGImageElement without setting crossorigin +FAIL Test creating a VideoFrame with a CORS enabled cross-origin SVGImageElement with crossorigin="anonymous" promise_test: Unhandled rejection with value: object "SecurityError: Failed to construct 'VideoFrame': VideoFrames can't be created from tainted sources." +FAIL Test creating a VideoFrame with a same-origin HTMLVideoElement promise_test: Unhandled rejection with value: object "InvalidStateError: Failed to construct 'VideoFrame': Invalid source state" +PASS Test creating a VideoFrame with a cross-origin HTMLVideoElement +PASS Test creating a VideoFrame with a CORS enabled cross-origin HTMLVideoElement without setting crossorigin +FAIL Test creating a VideoFrame with a CORS enabled cross-origin HTMLVideoElement with crossorigin="anonymous" promise_test: Unhandled rejection with value: object "InvalidStateError: Failed to construct 'VideoFrame': Invalid source state" +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/webcodecs/videoFrame-construction.crossOriginSource.sub.html b/third_party/blink/web_tests/external/wpt/webcodecs/videoFrame-construction.crossOriginSource.sub.html new file mode 100644 index 0000000..9238dc0 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/webcodecs/videoFrame-construction.crossOriginSource.sub.html
@@ -0,0 +1,187 @@ + +<!DOCTYPE html> +<html> +<head> + <script src='/resources/testharness.js'></script> + <script src='/resources/testharnessreport.js'></script> +</head> +<body> +<script> +const SAMEORIGIN_BASE = '{{location[scheme]}}://{{location[host]}}'; +const CROSSORIGIN_BASE = 'http://{{hosts[][www]}}:{{ports[http][0]}}'; +const NO_CORS = undefined; + +const TESTS = [ + // HTMLImageElement + { + title: 'Test creating a VideoFrame with a same-origin HTMLImageElement', + factory: () => { + return new Promise((resolve, reject) => { + const image = new Image(); + image.onload = () => resolve(image); + image.onerror = reject; + image.src = SAMEORIGIN_BASE + '/webcodecs/four-colors.jpg'; + }); + }, + should_throw: false, + }, + { + title: 'Test creating a VideoFrame with a cross-origin HTMLImageElement', + factory: () => { + return new Promise((resolve, reject) => { + const image = new Image(); + image.onload = () => resolve(image); + image.onerror = reject; + image.src = CROSSORIGIN_BASE + '/webcodecs/four-colors.jpg'; + }); + }, + should_throw: true, + }, + { + title: 'Test creating a VideoFrame with a CORS enabled cross-origin HTMLImageElement without setting crossorigin', + factory: () => { + return new Promise((resolve, reject) => { + const image = new Image(); + image.onload = () => resolve(image); + image.onerror = reject; + image.src = CROSSORIGIN_BASE + '/webcodecs/four-colors.jpg?pipe=header(Access-Control-Allow-Origin,*)'; + }); + }, + should_throw: true, + }, + { + title: 'Test creating a VideoFrame with a CORS enabled cross-origin HTMLImageElement with crossorigin="anonymous"', + factory: () => { + return new Promise((resolve, reject) => { + const image = new Image(); + image.onload = () => resolve(image); + image.onerror = reject; + image.crossOrigin = 'anonymous'; + image.src = CROSSORIGIN_BASE + '/webcodecs/four-colors.jpg?pipe=header(Access-Control-Allow-Origin,*)'; + }); + }, + should_throw: false, + }, + // SVGImageElement + { + title: 'Test creating a VideoFrame with a same-origin SVGImageElement', + factory: () => { + return new Promise((resolve, reject) => { + const image = document.createElementNS('http://www.w3.org/2000/svg','image'); + image.onload = () => resolve(image); + image.onerror = reject; + image.setAttribute('href', SAMEORIGIN_BASE + '/webcodecs/four-colors.jpg'); + }); + }, + should_throw: false, + }, + { + title: 'Test creating a VideoFrame with a cross-origin SVGImageElement', + factory: () => { + return new Promise((resolve, reject) => { + const image = document.createElementNS('http://www.w3.org/2000/svg','image'); + image.onload = () => resolve(image); + image.onerror = reject; + image.setAttribute('href', CROSSORIGIN_BASE + '/webcodecs/four-colors.jpg'); + }); + }, + should_throw: true, + }, + { + title: 'Test creating a VideoFrame with a CORS enabled cross-origin SVGImageElement without setting crossorigin', + factory: () => { + return new Promise((resolve, reject) => { + const image = document.createElementNS('http://www.w3.org/2000/svg','image'); + image.onload = () => resolve(image); + image.onerror = reject; + image.setAttribute('href', CROSSORIGIN_BASE + '/webcodecs/four-colors.jpg?pipe=header(Access-Control-Allow-Origin,*)'); + }); + }, + should_throw: true, + }, + { + title: 'Test creating a VideoFrame with a CORS enabled cross-origin SVGImageElement with crossorigin="anonymous"', + factory: () => { + return new Promise((resolve, reject) => { + const image = document.createElementNS('http://www.w3.org/2000/svg','image'); + image.onload = () => resolve(image); + image.onerror = reject; + image.crossOrigin = 'anonymous'; + image.setAttribute('href', CROSSORIGIN_BASE + '/webcodecs/four-colors.jpg?pipe=header(Access-Control-Allow-Origin,*)'); + }); + }, + should_throw: false, + }, + // HTMLVideoElement + { + title: 'Test creating a VideoFrame with a same-origin HTMLVideoElement', + factory: () => { + return new Promise((resolve, reject) => { + const video = document.createElement('video'); + video.onloadeddata = () => resolve(video); + video.onerror = reject; + video.src = SAMEORIGIN_BASE + '/webcodecs/av1.mp4'; + }); + }, + should_throw: false, + }, + { + title: 'Test creating a VideoFrame with a cross-origin HTMLVideoElement', + factory: () => { + return new Promise((resolve, reject) => { + const video = document.createElement('video'); + video.onloadeddata = () => resolve(video); + video.onerror = reject; + video.src = CROSSORIGIN_BASE + '/webcodecs/av1.mp4'; + }); + }, + should_throw: true, + }, + { + title: 'Test creating a VideoFrame with a CORS enabled cross-origin HTMLVideoElement without setting crossorigin', + factory: () => { + return new Promise((resolve, reject) => { + const video = document.createElement('video'); + video.onloadeddata = () => resolve(video); + video.onerror = reject; + video.src = CROSSORIGIN_BASE + '/webcodecs/av1.mp4?pipe=header(Access-Control-Allow-Origin,*)'; + }); + }, + should_throw: true, + }, + { + title: 'Test creating a VideoFrame with a CORS enabled cross-origin HTMLVideoElement with crossorigin="anonymous"', + factory: () => { + return new Promise((resolve, reject) => { + const video = document.createElement('video'); + video.onloadeddata = () => resolve(video); + video.onerror = reject; + video.crossOrigin = 'anonymous'; + video.src = CROSSORIGIN_BASE + '/webcodecs/av1.mp4?pipe=header(Access-Control-Allow-Origin,*)'; + }); + }, + should_throw: false, + }, +]; + +TESTS.forEach(test => run_test(test)); + +function run_test(test) { + promise_test(async t => { + const source = await test.factory(); + if (test.should_throw) { + assert_throws_dom('SecurityError', () => { create_frame(source); }); + } else { + create_frame(source); + } + }, test.title); +} + +function create_frame(img) { + let frame = new VideoFrame(img, {timestamp: 0}); + frame.close(); +} + +</script> +</body> +</html>
diff --git a/third_party/blink/web_tests/external/wpt/webcodecs/videoFrame-copyTo.any.js b/third_party/blink/web_tests/external/wpt/webcodecs/videoFrame-copyTo.any.js index a64603c5..d2d04c5 100644 --- a/third_party/blink/web_tests/external/wpt/webcodecs/videoFrame-copyTo.any.js +++ b/third_party/blink/web_tests/external/wpt/webcodecs/videoFrame-copyTo.any.js
@@ -87,7 +87,7 @@ const layout = await frame.copyTo(data, options); assert_layout_equals(layout, options.layout); assert_buffer_equals(data, expectedData); -}, 'Test stride and offset work.'); +}, 'Test I420 stride and offset work.'); promise_test(async t => { const frame = makeI420_4x2(); @@ -112,7 +112,77 @@ const layout = await frame.copyTo(data, options); assert_layout_equals(layout, options.layout); assert_buffer_equals(data, expectedData); -}, 'Test stride and offset with padding.'); +}, 'Test I420 stride and offset with padding.'); + +promise_test(async t => { + const init = { + format: 'I420A', + timestamp: 0, + codedWidth: 4, + codedHeight: 2, + }; + const buf = new Uint8Array([ + 1, 2, 3, 4, // y + 5, 6, 7, 8, + 9, 10, // u + 11, 12, // v + 13, 14, 15, 16, // a + 17, 18, 19, 20, + ]); + const frame = new VideoFrame(buf, init); + const options = { + layout: [ + {offset: 12, stride: 4}, + {offset: 8, stride: 2}, + {offset: 10, stride: 2}, + {offset: 0, stride: 4}, + ], + }; + const expectedData = new Uint8Array([ + 13, 14, 15, 16, // a + 17, 18, 19, 20, + 9, 10, // u + 11, 12, // v + 1, 2, 3, 4, // y + 5, 6, 7, 8, + ]); + assert_equals(frame.allocationSize(options), expectedData.length, 'allocationSize()'); + const data = new Uint8Array(expectedData.length); + const layout = await frame.copyTo(data, options); + assert_layout_equals(layout, options.layout); + assert_buffer_equals(data, expectedData); +}, 'Test I420A stride and offset work.'); + +promise_test(async t => { + const init = { + format: 'NV12', + timestamp: 0, + codedWidth: 4, + codedHeight: 2, + }; + const buf = new Uint8Array([ + 1, 2, 3, 4, // y + 5, 6, 7, 8, + 9, 10, 11, 12 // uv + ]); + const frame = new VideoFrame(buf, init); + const options = { + layout: [ + {offset: 4, stride: 4}, + {offset: 0, stride: 4}, + ], + }; + const expectedData = new Uint8Array([ + 9, 10, 11, 12, // uv + 1, 2, 3, 4, // y + 5, 6, 7, 8 + ]); + assert_equals(frame.allocationSize(options), expectedData.length, 'allocationSize()'); + const data = new Uint8Array(expectedData.length); + const layout = await frame.copyTo(data, options); + assert_layout_equals(layout, options.layout); + assert_buffer_equals(data, expectedData); +}, 'Test NV12 stride and offset work.'); promise_test(async t => { const frame = makeI420_4x2();
diff --git a/third_party/blink/web_tests/http/tests/security/opened-document-security-origin-resets-on-navigation.html b/third_party/blink/web_tests/http/tests/security/opened-document-security-origin-resets-on-navigation.html deleted file mode 100644 index c03e0ad..0000000 --- a/third_party/blink/web_tests/http/tests/security/opened-document-security-origin-resets-on-navigation.html +++ /dev/null
@@ -1,25 +0,0 @@ -<!DOCTYPE html> -<html> -<head> -<script src="/js-test-resources/js-test.js"></script> -<script> -var jsTestIsAsync = true; -function runTest() { - var frame = document.body.appendChild(document.createElement("iframe")); - frame.src = "http://localhost:8000/security/resources/opened-document-security-origin-resets-on-navigation-frame.html"; - frame.onload = function () { - frame.onload = null; - var blob = new Blob(["<script>(" + function () { - frame = document.documentElement.appendChild(document.createElement("iframe")); - frame.contentWindow.setTimeout("parent.document.open()", 0); - setTimeout(function () { - location = "javascript:'<script>setTimeout(top.finishJSTest, 0); parent.eval(\"alert(location)\"); top.testFailed(\"context security origin was not updated!\");</scr" + "ipt>'" }, 0); - } + "())</sc" + "ript>"], {type: "text/html"}); - frame.contentWindow[0].location = URL.createObjectURL(blob); - } -} -</script> -</head> -<body onload="runTest()"> -</body> -</html>
diff --git a/third_party/blink/web_tests/http/tests/serviceworker/webexposed/global-interface-listing-service-worker-expected.txt b/third_party/blink/web_tests/http/tests/serviceworker/webexposed/global-interface-listing-service-worker-expected.txt index 4d8d83dc..26631f49 100644 --- a/third_party/blink/web_tests/http/tests/serviceworker/webexposed/global-interface-listing-service-worker-expected.txt +++ b/third_party/blink/web_tests/http/tests/serviceworker/webexposed/global-interface-listing-service-worker-expected.txt
@@ -553,6 +553,7 @@ getter kind getter name method constructor + method getUniqueId method isSameEntry method move method queryPermission
diff --git a/third_party/blink/web_tests/platform/linux/external/wpt/fetch/api/abort/general.any.serviceworker-expected.txt b/third_party/blink/web_tests/platform/linux/external/wpt/fetch/api/abort/general.any.serviceworker-expected.txt deleted file mode 100644 index 39cdb15..0000000 --- a/third_party/blink/web_tests/platform/linux/external/wpt/fetch/api/abort/general.any.serviceworker-expected.txt +++ /dev/null
@@ -1,55 +0,0 @@ -This is a testharness.js-based test. -Found 51 tests; 48 PASS, 3 FAIL, 0 TIMEOUT, 0 NOTRUN. -PASS Aborting rejects with AbortError -FAIL Aborting rejects with abort reason promise_rejects_exactly: fetch() should reject with abort reason function "function() { throw e }" threw object "AbortError: Failed to execute 'fetch' on 'WorkerGlobalScope': The user aborted a request." but we expected it to throw object "error1: error1" -PASS Aborting rejects with AbortError - no-cors -PASS TypeError from request constructor takes priority - RequestInit's window is not null -PASS TypeError from request constructor takes priority - Input URL is not valid -PASS TypeError from request constructor takes priority - Input URL has credentials -PASS TypeError from request constructor takes priority - RequestInit's mode is navigate -PASS TypeError from request constructor takes priority - RequestInit's referrer is invalid -PASS TypeError from request constructor takes priority - RequestInit's method is invalid -PASS TypeError from request constructor takes priority - RequestInit's method is forbidden -PASS TypeError from request constructor takes priority - RequestInit's mode is no-cors and method is not simple -PASS TypeError from request constructor takes priority - RequestInit's cache mode is only-if-cached and mode is not same-origin -PASS TypeError from request constructor takes priority - Request with cache mode: only-if-cached and fetch mode cors -PASS TypeError from request constructor takes priority - Request with cache mode: only-if-cached and fetch mode no-cors -PASS TypeError from request constructor takes priority - Bad referrerPolicy init parameter value -PASS TypeError from request constructor takes priority - Bad mode init parameter value -PASS TypeError from request constructor takes priority - Bad credentials init parameter value -PASS TypeError from request constructor takes priority - Bad cache init parameter value -PASS TypeError from request constructor takes priority - Bad redirect init parameter value -PASS Request objects have a signal property -PASS Signal on request object -FAIL Signal on request object should also have abort reason promise_rejects_exactly: fetch() should reject with abort reason function "function() { throw e }" threw object "AbortError: Failed to execute 'fetch' on 'WorkerGlobalScope': The user aborted a request." but we expected it to throw object "error1: error1" -PASS Signal on request object created from request object -PASS Signal on request object created from request object, with signal on second request -PASS Signal on request object created from request object, with signal on second request overriding another -PASS Signal retained after unrelated properties are overridden by fetch -PASS Signal removed by setting to null -PASS Already aborted signal rejects immediately -PASS Request is still 'used' if signal is aborted before fetching -PASS response.arrayBuffer() rejects if already aborted -PASS response.blob() rejects if already aborted -PASS response.formData() rejects if already aborted -PASS response.json() rejects if already aborted -PASS response.text() rejects if already aborted -PASS Call text() twice on aborted response -PASS Already aborted signal does not make request -PASS Already aborted signal can be used for many fetches -PASS Signal can be used to abort other fetches, even if another fetch succeeded before aborting -PASS Underlying connection is closed when aborting after receiving response -PASS Underlying connection is closed when aborting after receiving response - no-cors -PASS Fetch aborted & connection closed when aborted after calling response.arrayBuffer() -PASS Fetch aborted & connection closed when aborted after calling response.blob() -PASS Fetch aborted & connection closed when aborted after calling response.formData() -PASS Fetch aborted & connection closed when aborted after calling response.json() -PASS Fetch aborted & connection closed when aborted after calling response.text() -PASS Stream errors once aborted. Underlying connection closed. -PASS Stream errors once aborted, after reading. Underlying connection closed. -PASS Stream will not error if body is empty. It's closed with an empty queue before it errors. -FAIL Readable stream synchronously cancels with AbortError if aborted before reading assert_true: Cancel called sync expected true got false -PASS Signal state is cloned -PASS Clone aborts with original controller -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/platform/mac/external/wpt/fetch/api/abort/general.any.serviceworker-expected.txt b/third_party/blink/web_tests/platform/mac/external/wpt/fetch/api/abort/general.any.serviceworker-expected.txt deleted file mode 100644 index 39cdb15..0000000 --- a/third_party/blink/web_tests/platform/mac/external/wpt/fetch/api/abort/general.any.serviceworker-expected.txt +++ /dev/null
@@ -1,55 +0,0 @@ -This is a testharness.js-based test. -Found 51 tests; 48 PASS, 3 FAIL, 0 TIMEOUT, 0 NOTRUN. -PASS Aborting rejects with AbortError -FAIL Aborting rejects with abort reason promise_rejects_exactly: fetch() should reject with abort reason function "function() { throw e }" threw object "AbortError: Failed to execute 'fetch' on 'WorkerGlobalScope': The user aborted a request." but we expected it to throw object "error1: error1" -PASS Aborting rejects with AbortError - no-cors -PASS TypeError from request constructor takes priority - RequestInit's window is not null -PASS TypeError from request constructor takes priority - Input URL is not valid -PASS TypeError from request constructor takes priority - Input URL has credentials -PASS TypeError from request constructor takes priority - RequestInit's mode is navigate -PASS TypeError from request constructor takes priority - RequestInit's referrer is invalid -PASS TypeError from request constructor takes priority - RequestInit's method is invalid -PASS TypeError from request constructor takes priority - RequestInit's method is forbidden -PASS TypeError from request constructor takes priority - RequestInit's mode is no-cors and method is not simple -PASS TypeError from request constructor takes priority - RequestInit's cache mode is only-if-cached and mode is not same-origin -PASS TypeError from request constructor takes priority - Request with cache mode: only-if-cached and fetch mode cors -PASS TypeError from request constructor takes priority - Request with cache mode: only-if-cached and fetch mode no-cors -PASS TypeError from request constructor takes priority - Bad referrerPolicy init parameter value -PASS TypeError from request constructor takes priority - Bad mode init parameter value -PASS TypeError from request constructor takes priority - Bad credentials init parameter value -PASS TypeError from request constructor takes priority - Bad cache init parameter value -PASS TypeError from request constructor takes priority - Bad redirect init parameter value -PASS Request objects have a signal property -PASS Signal on request object -FAIL Signal on request object should also have abort reason promise_rejects_exactly: fetch() should reject with abort reason function "function() { throw e }" threw object "AbortError: Failed to execute 'fetch' on 'WorkerGlobalScope': The user aborted a request." but we expected it to throw object "error1: error1" -PASS Signal on request object created from request object -PASS Signal on request object created from request object, with signal on second request -PASS Signal on request object created from request object, with signal on second request overriding another -PASS Signal retained after unrelated properties are overridden by fetch -PASS Signal removed by setting to null -PASS Already aborted signal rejects immediately -PASS Request is still 'used' if signal is aborted before fetching -PASS response.arrayBuffer() rejects if already aborted -PASS response.blob() rejects if already aborted -PASS response.formData() rejects if already aborted -PASS response.json() rejects if already aborted -PASS response.text() rejects if already aborted -PASS Call text() twice on aborted response -PASS Already aborted signal does not make request -PASS Already aborted signal can be used for many fetches -PASS Signal can be used to abort other fetches, even if another fetch succeeded before aborting -PASS Underlying connection is closed when aborting after receiving response -PASS Underlying connection is closed when aborting after receiving response - no-cors -PASS Fetch aborted & connection closed when aborted after calling response.arrayBuffer() -PASS Fetch aborted & connection closed when aborted after calling response.blob() -PASS Fetch aborted & connection closed when aborted after calling response.formData() -PASS Fetch aborted & connection closed when aborted after calling response.json() -PASS Fetch aborted & connection closed when aborted after calling response.text() -PASS Stream errors once aborted. Underlying connection closed. -PASS Stream errors once aborted, after reading. Underlying connection closed. -PASS Stream will not error if body is empty. It's closed with an empty queue before it errors. -FAIL Readable stream synchronously cancels with AbortError if aborted before reading assert_true: Cancel called sync expected true got false -PASS Signal state is cloned -PASS Clone aborts with original controller -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/platform/win10/external/wpt/fetch/api/abort/general.any.serviceworker-expected.txt b/third_party/blink/web_tests/platform/win10/external/wpt/fetch/api/abort/general.any.serviceworker-expected.txt deleted file mode 100644 index 39cdb15..0000000 --- a/third_party/blink/web_tests/platform/win10/external/wpt/fetch/api/abort/general.any.serviceworker-expected.txt +++ /dev/null
@@ -1,55 +0,0 @@ -This is a testharness.js-based test. -Found 51 tests; 48 PASS, 3 FAIL, 0 TIMEOUT, 0 NOTRUN. -PASS Aborting rejects with AbortError -FAIL Aborting rejects with abort reason promise_rejects_exactly: fetch() should reject with abort reason function "function() { throw e }" threw object "AbortError: Failed to execute 'fetch' on 'WorkerGlobalScope': The user aborted a request." but we expected it to throw object "error1: error1" -PASS Aborting rejects with AbortError - no-cors -PASS TypeError from request constructor takes priority - RequestInit's window is not null -PASS TypeError from request constructor takes priority - Input URL is not valid -PASS TypeError from request constructor takes priority - Input URL has credentials -PASS TypeError from request constructor takes priority - RequestInit's mode is navigate -PASS TypeError from request constructor takes priority - RequestInit's referrer is invalid -PASS TypeError from request constructor takes priority - RequestInit's method is invalid -PASS TypeError from request constructor takes priority - RequestInit's method is forbidden -PASS TypeError from request constructor takes priority - RequestInit's mode is no-cors and method is not simple -PASS TypeError from request constructor takes priority - RequestInit's cache mode is only-if-cached and mode is not same-origin -PASS TypeError from request constructor takes priority - Request with cache mode: only-if-cached and fetch mode cors -PASS TypeError from request constructor takes priority - Request with cache mode: only-if-cached and fetch mode no-cors -PASS TypeError from request constructor takes priority - Bad referrerPolicy init parameter value -PASS TypeError from request constructor takes priority - Bad mode init parameter value -PASS TypeError from request constructor takes priority - Bad credentials init parameter value -PASS TypeError from request constructor takes priority - Bad cache init parameter value -PASS TypeError from request constructor takes priority - Bad redirect init parameter value -PASS Request objects have a signal property -PASS Signal on request object -FAIL Signal on request object should also have abort reason promise_rejects_exactly: fetch() should reject with abort reason function "function() { throw e }" threw object "AbortError: Failed to execute 'fetch' on 'WorkerGlobalScope': The user aborted a request." but we expected it to throw object "error1: error1" -PASS Signal on request object created from request object -PASS Signal on request object created from request object, with signal on second request -PASS Signal on request object created from request object, with signal on second request overriding another -PASS Signal retained after unrelated properties are overridden by fetch -PASS Signal removed by setting to null -PASS Already aborted signal rejects immediately -PASS Request is still 'used' if signal is aborted before fetching -PASS response.arrayBuffer() rejects if already aborted -PASS response.blob() rejects if already aborted -PASS response.formData() rejects if already aborted -PASS response.json() rejects if already aborted -PASS response.text() rejects if already aborted -PASS Call text() twice on aborted response -PASS Already aborted signal does not make request -PASS Already aborted signal can be used for many fetches -PASS Signal can be used to abort other fetches, even if another fetch succeeded before aborting -PASS Underlying connection is closed when aborting after receiving response -PASS Underlying connection is closed when aborting after receiving response - no-cors -PASS Fetch aborted & connection closed when aborted after calling response.arrayBuffer() -PASS Fetch aborted & connection closed when aborted after calling response.blob() -PASS Fetch aborted & connection closed when aborted after calling response.formData() -PASS Fetch aborted & connection closed when aborted after calling response.json() -PASS Fetch aborted & connection closed when aborted after calling response.text() -PASS Stream errors once aborted. Underlying connection closed. -PASS Stream errors once aborted, after reading. Underlying connection closed. -PASS Stream will not error if body is empty. It's closed with an empty queue before it errors. -FAIL Readable stream synchronously cancels with AbortError if aborted before reading assert_true: Cancel called sync expected true got false -PASS Signal state is cloned -PASS Clone aborts with original controller -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/virtual/disable-wildcard-subdomains-in-permissions-policy/README.md b/third_party/blink/web_tests/virtual/disable-wildcard-subdomains-in-permissions-policy/README.md new file mode 100644 index 0000000..31860a83 --- /dev/null +++ b/third_party/blink/web_tests/virtual/disable-wildcard-subdomains-in-permissions-policy/README.md
@@ -0,0 +1 @@ +Tests with WildcardSubdomainsInPermissionsPolicy enabled.
diff --git a/third_party/blink/web_tests/virtual/disable-wildcard-subdomains-in-permissions-policy/external/wpt/permissions-policy/README.txt b/third_party/blink/web_tests/virtual/disable-wildcard-subdomains-in-permissions-policy/external/wpt/permissions-policy/README.txt new file mode 100644 index 0000000..31860a83 --- /dev/null +++ b/third_party/blink/web_tests/virtual/disable-wildcard-subdomains-in-permissions-policy/external/wpt/permissions-policy/README.txt
@@ -0,0 +1 @@ +Tests with WildcardSubdomainsInPermissionsPolicy enabled.
diff --git a/third_party/blink/web_tests/virtual/disable-wildcard-subdomains-in-permissions-policy/external/wpt/permissions-policy/permissions-policy-header-policy-allowed-for-wildcard.https.sub-expected.txt b/third_party/blink/web_tests/virtual/disable-wildcard-subdomains-in-permissions-policy/external/wpt/permissions-policy/permissions-policy-header-policy-allowed-for-wildcard.https.sub-expected.txt new file mode 100644 index 0000000..23dbddc --- /dev/null +++ b/third_party/blink/web_tests/virtual/disable-wildcard-subdomains-in-permissions-policy/external/wpt/permissions-policy/permissions-policy-header-policy-allowed-for-wildcard.https.sub-expected.txt
@@ -0,0 +1,12 @@ +This is a testharness.js-based test. +FAIL Permissions-Policy: fullscreen=("https://*.web-platform.test:8444") -- test allowlist is [self wildcard_origin]. assert_array_equals: expected property 0 to be "https://*.web-platform.test:8444" but got "https://%2A.web-platform.test:8444" (expected array ["https://*.web-platform.test:8444", "https://web-platform.test:8444"] got ["https://%2A.web-platform.test:8444", "https://web-platform.test:8444"]) +PASS Permissions-Policy: fullscreen=("https://*.web-platform.test:8444") -- test fullscreen is allowed on same-origin subframe +PASS Permissions-Policy: fullscreen=("https://*.web-platform.test:8444") -- test fullscreen is allowed on same-origin subframe even with allow attribute +PASS Permissions-Policy: fullscreen=("https://*.web-platform.test:8444") -- test fullscreen is disallowed on cross-origin subframe +FAIL Permissions-Policy: fullscreen=("https://*.web-platform.test:8444") -- test fullscreen is allowed on cross-origin subframe allow attribute assert_true: fullscreen expected true got false +PASS Permissions-Policy: fullscreen=("https://*.web-platform.test:8444") -- test fullscreen is disallowed on another cross-origin subframe +FAIL Permissions-Policy: fullscreen=("https://*.web-platform.test:8444") -- test fullscreen is allowed on another cross-origin subframe allow attribute assert_true: fullscreen expected true got false +PASS Permissions-Policy: fullscreen=("https://*.web-platform.test:8444") -- test fullscreen is disallowed on cross-origin subframe with wildcard allow attribute +PASS Permissions-Policy: fullscreen=("https://*.web-platform.test:8444") -- test fullscreen is disallowed on another cross-origin subframe with wildcard allow attribute +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/webexposed/global-interface-listing-dedicated-worker-expected.txt b/third_party/blink/web_tests/webexposed/global-interface-listing-dedicated-worker-expected.txt index 7fd13c9..dc18eb6f 100644 --- a/third_party/blink/web_tests/webexposed/global-interface-listing-dedicated-worker-expected.txt +++ b/third_party/blink/web_tests/webexposed/global-interface-listing-dedicated-worker-expected.txt
@@ -546,6 +546,7 @@ [Worker] getter kind [Worker] getter name [Worker] method constructor +[Worker] method getUniqueId [Worker] method isSameEntry [Worker] method move [Worker] method queryPermission
diff --git a/third_party/blink/web_tests/webexposed/global-interface-listing-expected.txt b/third_party/blink/web_tests/webexposed/global-interface-listing-expected.txt index 0b2a77af..4d92f6fc 100644 --- a/third_party/blink/web_tests/webexposed/global-interface-listing-expected.txt +++ b/third_party/blink/web_tests/webexposed/global-interface-listing-expected.txt
@@ -2717,6 +2717,7 @@ getter kind getter name method constructor + method getUniqueId method isSameEntry method move method queryPermission
diff --git a/third_party/blink/web_tests/webexposed/global-interface-listing-shared-worker-expected.txt b/third_party/blink/web_tests/webexposed/global-interface-listing-shared-worker-expected.txt index 8fb310f..d9db42ec 100644 --- a/third_party/blink/web_tests/webexposed/global-interface-listing-shared-worker-expected.txt +++ b/third_party/blink/web_tests/webexposed/global-interface-listing-shared-worker-expected.txt
@@ -485,6 +485,7 @@ [Worker] getter kind [Worker] getter name [Worker] method constructor +[Worker] method getUniqueId [Worker] method isSameEntry [Worker] method move [Worker] method queryPermission
diff --git a/third_party/closure_compiler/externs/file_manager_private.js b/third_party/closure_compiler/externs/file_manager_private.js index 536e6ab..9915867 100644 --- a/third_party/closure_compiler/externs/file_manager_private.js +++ b/third_party/closure_compiler/externs/file_manager_private.js
@@ -96,6 +96,7 @@ ERROR_NEED_PASSWORD: 'error_need_password', ERROR_IN_PROGRESS: 'error_in_progress', ERROR_CANCELLED: 'error_cancelled', + ERROR_BUSY: 'error_busy', }; /** @enum {string} */
diff --git a/third_party/closure_compiler/externs/input_method_private.js b/third_party/closure_compiler/externs/input_method_private.js index 567eaf88..8a0e69d 100644 --- a/third_party/closure_compiler/externs/input_method_private.js +++ b/third_party/closure_compiler/externs/input_method_private.js
@@ -124,6 +124,7 @@ * enableSoundOnKeypress: (boolean|undefined), * physicalKeyboardAutoCorrectionLevel: (number|undefined), * physicalKeyboardEnableCapitalization: (boolean|undefined), + * physicalKeyboardEnableDiacriticsOnLongpress: (boolean|undefined), * virtualKeyboardAutoCorrectionLevel: (number|undefined), * virtualKeyboardEnableCapitalization: (boolean|undefined), * xkbLayout: (string|undefined), @@ -443,6 +444,12 @@ chrome.inputMethodPrivate.getTextFieldBounds = function(parameters, callback) {}; /** + * Notifies Chrome that the current input method is ready to accept key events + * from Tast. + */ +chrome.inputMethodPrivate.notifyInputMethodReadyForTesting = function() {}; + +/** * Fired when the caret bounds change. * @type {!ChromeEvent} */
diff --git a/third_party/shell-encryption/BUILD.gn b/third_party/shell-encryption/BUILD.gn index 4cf4c7e..c9125440 100644 --- a/third_party/shell-encryption/BUILD.gn +++ b/third_party/shell-encryption/BUILD.gn
@@ -6,15 +6,7 @@ import("//testing/test.gni") import("//third_party/protobuf/proto_library.gni") -config("shell_encryption_config1") { - # TODO(crbug.com/1095122) Reenable the warning for unused functions and typedef. - cflags = [ - "-Wno-unused-local-typedef", - "-Wno-unused-function", - "-Wno-sign-compare", - "-Wno-ignored-qualifiers", - ] - +config("shell_encryption_internal_config") { defines = [] if (is_component_build) { defines = [ @@ -25,7 +17,9 @@ "SHELL_ENCRYPTION_ENABLE_SYMBOL_EXPORT", ] } +} +config("shell_encryption_config") { include_dirs = [ # Allow includes to be prefixed with shell-encryption/src/ in case it is not an # immediate subdirectory of the top-level. @@ -68,9 +62,12 @@ # SHELL lib. if (is_chromeos_ash) { component("shell_encryption") { - public_configs = [ ":shell_encryption_config1" ] + public_configs = [ ":shell_encryption_config" ] configs -= [ "//build/config/compiler:chromium_code" ] - configs += [ "//build/config/compiler:no_chromium_code" ] + configs += [ + ":shell_encryption_internal_config", + "//build/config/compiler:no_chromium_code", + ] public = [ "base/shell_encryption_export.h", "base/shell_encryption_export_template.h", @@ -120,9 +117,12 @@ if (is_chromeos_ash) { source_set("shell_encryption_test_library") { testonly = true - public_configs = [ ":shell_encryption_config1" ] + public_configs = [ ":shell_encryption_config" ] configs -= [ "//build/config/compiler:chromium_code" ] - configs += [ "//build/config/compiler:no_chromium_code" ] + configs += [ + ":shell_encryption_internal_config", + "//build/config/compiler:no_chromium_code", + ] public = [ "src/prng/integral_prng_testing_types.h", "src/testing/coefficient_polynomial.h", @@ -145,9 +145,11 @@ test("shell_encryption_unittests") { testonly = true - public_configs = [ ":shell_encryption_config1" ] configs -= [ "//build/config/compiler:chromium_code" ] - configs += [ "//build/config/compiler:no_chromium_code" ] + configs += [ + ":shell_encryption_internal_config", + "//build/config/compiler:no_chromium_code", + ] sources = [ "src/bits_util_test.cc", "src/context_test.cc",
diff --git a/third_party/shell-encryption/patches/0007-Fix-Wunused-function-Wunused-local-typedef.patch b/third_party/shell-encryption/patches/0007-Fix-Wunused-function-Wunused-local-typedef.patch new file mode 100644 index 0000000..8cf2156 --- /dev/null +++ b/third_party/shell-encryption/patches/0007-Fix-Wunused-function-Wunused-local-typedef.patch
@@ -0,0 +1,25 @@ +diff --git a/montgomery_test.cc b/montgomery_test.cc +index 97444fc6c15c2..d5078fdcc86df 100644 +--- a/montgomery_test.cc ++++ b/montgomery_test.cc +@@ -59,12 +59,6 @@ absl::uint128 GenerateRandom(unsigned int* seed) { + Uint64 lo = GenerateRandom<Uint64>(seed); + return absl::MakeUint128(hi, lo); + } +-template <> +-uint256 GenerateRandom(unsigned int* seed) { +- absl::uint128 hi = GenerateRandom<absl::uint128>(seed); +- absl::uint128 lo = GenerateRandom<absl::uint128>(seed); +- return uint256(hi, lo); +-} + + template <typename T> + class EXPORT_TEMPLATE_DECLARE(SHELL_ENCRYPTION_EXPORT) MontgomeryTest : public ::testing::Test {}; +@@ -728,7 +722,6 @@ TYPED_TEST(MontgomeryTest, ImportRandomWithPrngWithDifferentKeys) { + // Verifies that Barrett reductions functions properly. + TYPED_TEST(MontgomeryTest, VerifyBarrett) { + using Int = typename TypeParam::Int; +- using BigInt = typename internal::BigInt<Int>::value_type; + + for (const auto& params : + rlwe::testing::ContextParameters<TypeParam>::Value()) {
diff --git a/third_party/shell-encryption/patches/0008-Fix-Wsign-compare.patch b/third_party/shell-encryption/patches/0008-Fix-Wsign-compare.patch new file mode 100644 index 0000000..87a569a --- /dev/null +++ b/third_party/shell-encryption/patches/0008-Fix-Wsign-compare.patch
@@ -0,0 +1,61 @@ +diff --git a/ntt_parameters.h b/ntt_parameters.h +index eba9579ab87ca..dc56ab62dd666 100644 +--- a/ntt_parameters.h ++++ b/ntt_parameters.h +@@ -34,7 +34,7 @@ template <typename ModularInt> + void FillWithEveryPower(const ModularInt& base, unsigned int n, + std::vector<ModularInt>* row, + const typename ModularInt::Params* params) { +- for (int i = 0; i < n; i++) { ++ for (unsigned int i = 0; i < n; i++) { + (*row)[i].AddInPlace(base.ModExp(i, params), params); + } + } +@@ -183,7 +183,7 @@ rlwe::StatusOr<NttParameters<ModularInt>> InitializeNttParameters( + // Abort if log_n is non-positive. + if (log_n <= 0) { + return absl::InvalidArgumentError("log_n must be positive"); +- } else if (log_n > kMaxLogNumCoeffs) { ++ } else if (static_cast<Uint64>(log_n) > kMaxLogNumCoeffs) { + return absl::InvalidArgumentError(absl::StrCat( + "log_n, ", log_n, ", must be less than ", kMaxLogNumCoeffs, ".")); + } +diff --git a/sample_error.h b/sample_error.h +index 7d570c5cd2e7a..b1f19eb952551 100644 +--- a/sample_error.h ++++ b/sample_error.h +@@ -57,7 +57,7 @@ static rlwe::StatusOr<std::vector<ModularInt>> SampleFromErrorDistribution( + Uint64 k; + typename ModularInt::Int coefficient; + +- for (int i = 0; i < num_coeffs; i++) { ++ for (unsigned int i = 0; i < num_coeffs; i++) { + coefficient = modulus_params->modulus; + k = variance << 1; + +diff --git a/symmetric_encryption.h b/symmetric_encryption.h +index 987e86f7a9823..06dabb89502d4 100644 +--- a/symmetric_encryption.h ++++ b/symmetric_encryption.h +@@ -630,9 +630,9 @@ class SymmetricRlweKey { + const typename ModularInt::Params* ModulusParams() const { + return modulus_params_; + } +- const unsigned int BitsPerCoeff() const { return log_t_; } +- const Uint64 Variance() const { return variance_; } +- const unsigned int LogT() const { return log_t_; } ++ unsigned int BitsPerCoeff() const { return log_t_; } ++ Uint64 Variance() const { return variance_; } ++ unsigned int LogT() const { return log_t_; } + const ModularInt& PlaintextModulus() const { return t_mod_; } + const typename ModularInt::Params* PlaintextModulusParams() const { + return plaintext_modulus_params_; +@@ -941,7 +941,7 @@ rlwe::StatusOr<std::vector<typename ModularInt::Int>> Decrypt( + Polynomial<ModularInt> key_powers = key.Key(); + unsigned int ciphertext_len = ciphertext.Len(); + +- for (int i = 0; i < ciphertext_len; i++) { ++ for (unsigned int i = 0; i < ciphertext_len; i++) { + // Extract component i. + RLWE_ASSIGN_OR_RETURN(Polynomial<ModularInt> ci, ciphertext.Component(i)); +
diff --git a/third_party/shell-encryption/src/montgomery_test.cc b/third_party/shell-encryption/src/montgomery_test.cc index 97444fc..d5078fd 100644 --- a/third_party/shell-encryption/src/montgomery_test.cc +++ b/third_party/shell-encryption/src/montgomery_test.cc
@@ -59,12 +59,6 @@ Uint64 lo = GenerateRandom<Uint64>(seed); return absl::MakeUint128(hi, lo); } -template <> -uint256 GenerateRandom(unsigned int* seed) { - absl::uint128 hi = GenerateRandom<absl::uint128>(seed); - absl::uint128 lo = GenerateRandom<absl::uint128>(seed); - return uint256(hi, lo); -} template <typename T> class EXPORT_TEMPLATE_DECLARE(SHELL_ENCRYPTION_EXPORT) MontgomeryTest : public ::testing::Test {}; @@ -728,7 +722,6 @@ // Verifies that Barrett reductions functions properly. TYPED_TEST(MontgomeryTest, VerifyBarrett) { using Int = typename TypeParam::Int; - using BigInt = typename internal::BigInt<Int>::value_type; for (const auto& params : rlwe::testing::ContextParameters<TypeParam>::Value()) {
diff --git a/third_party/shell-encryption/src/ntt_parameters.h b/third_party/shell-encryption/src/ntt_parameters.h index eba9579..dc56ab62 100644 --- a/third_party/shell-encryption/src/ntt_parameters.h +++ b/third_party/shell-encryption/src/ntt_parameters.h
@@ -34,7 +34,7 @@ void FillWithEveryPower(const ModularInt& base, unsigned int n, std::vector<ModularInt>* row, const typename ModularInt::Params* params) { - for (int i = 0; i < n; i++) { + for (unsigned int i = 0; i < n; i++) { (*row)[i].AddInPlace(base.ModExp(i, params), params); } } @@ -183,7 +183,7 @@ // Abort if log_n is non-positive. if (log_n <= 0) { return absl::InvalidArgumentError("log_n must be positive"); - } else if (log_n > kMaxLogNumCoeffs) { + } else if (static_cast<Uint64>(log_n) > kMaxLogNumCoeffs) { return absl::InvalidArgumentError(absl::StrCat( "log_n, ", log_n, ", must be less than ", kMaxLogNumCoeffs, ".")); }
diff --git a/third_party/shell-encryption/src/sample_error.h b/third_party/shell-encryption/src/sample_error.h index 7d570c5..b1f19eb 100644 --- a/third_party/shell-encryption/src/sample_error.h +++ b/third_party/shell-encryption/src/sample_error.h
@@ -57,7 +57,7 @@ Uint64 k; typename ModularInt::Int coefficient; - for (int i = 0; i < num_coeffs; i++) { + for (unsigned int i = 0; i < num_coeffs; i++) { coefficient = modulus_params->modulus; k = variance << 1;
diff --git a/third_party/shell-encryption/src/symmetric_encryption.h b/third_party/shell-encryption/src/symmetric_encryption.h index 987e86f7..06dabb89 100644 --- a/third_party/shell-encryption/src/symmetric_encryption.h +++ b/third_party/shell-encryption/src/symmetric_encryption.h
@@ -630,9 +630,9 @@ const typename ModularInt::Params* ModulusParams() const { return modulus_params_; } - const unsigned int BitsPerCoeff() const { return log_t_; } - const Uint64 Variance() const { return variance_; } - const unsigned int LogT() const { return log_t_; } + unsigned int BitsPerCoeff() const { return log_t_; } + Uint64 Variance() const { return variance_; } + unsigned int LogT() const { return log_t_; } const ModularInt& PlaintextModulus() const { return t_mod_; } const typename ModularInt::Params* PlaintextModulusParams() const { return plaintext_modulus_params_; @@ -941,7 +941,7 @@ Polynomial<ModularInt> key_powers = key.Key(); unsigned int ciphertext_len = ciphertext.Len(); - for (int i = 0; i < ciphertext_len; i++) { + for (unsigned int i = 0; i < ciphertext_len; i++) { // Extract component i. RLWE_ASSIGN_OR_RETURN(Polynomial<ModularInt> ci, ciphertext.Component(i));
diff --git a/tools/clang/scripts/build.py b/tools/clang/scripts/build.py index 8201cb6..4b44cd26 100755 --- a/tools/clang/scripts/build.py +++ b/tools/clang/scripts/build.py
@@ -323,15 +323,15 @@ '-DLIBXML2_WITH_MEM_DEBUG=OFF', '-DLIBXML2_WITH_MODULES=OFF', '-DLIBXML2_WITH_OUTPUT=ON', - '-DLIBXML2_WITH_PATTERN=OFF', + '-DLIBXML2_WITH_PATTERN=ON', '-DLIBXML2_WITH_PROGRAMS=OFF', '-DLIBXML2_WITH_PUSH=OFF', '-DLIBXML2_WITH_PYTHON=OFF', '-DLIBXML2_WITH_READER=OFF', - '-DLIBXML2_WITH_REGEXPS=OFF', + '-DLIBXML2_WITH_REGEXPS=ON', '-DLIBXML2_WITH_RUN_DEBUG=OFF', - '-DLIBXML2_WITH_SAX1=OFF', - '-DLIBXML2_WITH_SCHEMAS=OFF', + '-DLIBXML2_WITH_SAX1=ON', + '-DLIBXML2_WITH_SCHEMAS=ON', '-DLIBXML2_WITH_SCHEMATRON=OFF', '-DLIBXML2_WITH_TESTS=OFF', '-DLIBXML2_WITH_THREADS=ON', @@ -357,6 +357,7 @@ '-DLLVM_ENABLE_LIBXML2=FORCE_ON', '-DLIBXML2_INCLUDE_DIR=' + libxml2_include_dir.replace('\\', '/'), '-DLIBXML2_LIBRARIES=' + libxml2_lib.replace('\\', '/'), + '-DLIBXML2_LIBRARY=' + libxml2_lib.replace('\\', '/'), ] extra_cflags = ['-DLIBXML_STATIC']
diff --git a/tools/clang/scripts/update.py b/tools/clang/scripts/update.py index 2e56c78..24d1aff8 100755 --- a/tools/clang/scripts/update.py +++ b/tools/clang/scripts/update.py
@@ -36,7 +36,7 @@ # Reverting problematic clang rolls is safe, though. # This is the output of `git describe` and is usable as a commit-ish. CLANG_REVISION = 'llvmorg-16-init-6578-g0d30e92f' -CLANG_SUB_REVISION = 1 +CLANG_SUB_REVISION = 2 PACKAGE_VERSION = '%s-%s' % (CLANG_REVISION, CLANG_SUB_REVISION) RELEASE_VERSION = '16.0.0'
diff --git a/tools/mb/mb_config.pyl b/tools/mb/mb_config.pyl index aa5788c..086ac24a 100644 --- a/tools/mb/mb_config.pyl +++ b/tools/mb/mb_config.pyl
@@ -1050,7 +1050,6 @@ 'android_n5x_swarming_dbg': 'android_debug_trybot_arm64', 'android_optional_gpu_tests_rel': 'gpu_tests_android_release_trybot', 'android_unswarmed_pixel_aosp': 'android_debug_trybot_arm64', - 'cast_shell_android': 'android_cast_debug_static_bot_compile_only', 'gpu-fyi-try-android-l-nexus-5-32': 'gpu_tests_android_release_trybot', 'gpu-fyi-try-android-m-nexus-5x-64': 'gpu_tests_android_release_trybot_arm64', 'gpu-fyi-try-android-nvidia-shield-tv': 'gpu_tests_android_release_trybot', @@ -1164,10 +1163,6 @@ 'tryserver.chromium.linux': { 'cast-binary-size': 'cast_binary_size', - 'cast_shell_audio_linux': 'cast_audio_release_trybot', - 'cast_shell_linux': 'cast_release_trybot', - 'cast_shell_linux_arm64': 'cast_arm64_release_bot', - 'cast_shell_linux_dbg': 'cast_debug_bot', 'chromium_presubmit': 'presubmit', 'gpu-fyi-try-lacros-amd-rel': 'gpu_tests_ozone_linux_non_x11_release_trybot', 'gpu-fyi-try-lacros-intel-rel': 'gpu_tests_ozone_linux_non_x11_release_trybot',
diff --git a/tools/mb/mb_config_expectations/tryserver.chromium.android.json b/tools/mb/mb_config_expectations/tryserver.chromium.android.json index c0bb0ae0..1f5e53d 100644 --- a/tools/mb/mb_config_expectations/tryserver.chromium.android.json +++ b/tools/mb/mb_config_expectations/tryserver.chromium.android.json
@@ -1251,21 +1251,6 @@ "use_goma": true } }, - "cast_shell_android": { - "gn_args": { - "debuggable_apks": false, - "enable_cast_receiver": true, - "ffmpeg_branding": "Chrome", - "is_cast_android": true, - "is_clang": true, - "is_component_build": false, - "is_debug": true, - "proprietary_codecs": true, - "symbol_level": 0, - "target_os": "android", - "use_goma": true - } - }, "gpu-fyi-try-android-l-nexus-5-32": { "gn_args": { "dcheck_always_on": true,
diff --git a/tools/mb/mb_config_expectations/tryserver.chromium.linux.json b/tools/mb/mb_config_expectations/tryserver.chromium.linux.json index 1f25ddfe..39134879 100644 --- a/tools/mb/mb_config_expectations/tryserver.chromium.linux.json +++ b/tools/mb/mb_config_expectations/tryserver.chromium.linux.json
@@ -10,51 +10,6 @@ "use_goma": true } }, - "cast_shell_audio_linux": { - "gn_args": { - "dcheck_always_on": true, - "enable_cast_receiver": true, - "is_cast_audio_only": true, - "is_castos": true, - "is_component_build": false, - "is_debug": false, - "symbol_level": 0, - "use_goma": true - } - }, - "cast_shell_linux": { - "gn_args": { - "dcheck_always_on": true, - "enable_cast_receiver": true, - "is_castos": true, - "is_component_build": false, - "is_debug": false, - "symbol_level": 0, - "use_goma": true - } - }, - "cast_shell_linux_arm64": { - "gn_args": { - "dcheck_always_on": false, - "enable_cast_receiver": true, - "is_castos": true, - "is_component_build": false, - "is_debug": false, - "symbol_level": 1, - "target_cpu": "arm64", - "use_goma": true - } - }, - "cast_shell_linux_dbg": { - "gn_args": { - "enable_cast_receiver": true, - "is_castos": true, - "is_component_build": true, - "is_debug": true, - "symbol_level": 1, - "use_goma": true - } - }, "gpu-fyi-try-lacros-amd-rel": { "gn_args": { "dcheck_always_on": true,
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index 0d1b51ab..3e1a174 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -21749,6 +21749,7 @@ <int value="17" label="Need password">MountError::kNeedPassword</int> <int value="18" label="In progress">MountError::kInProgress</int> <int value="19" label="Cancelled">MountError::kCancelled</int> + <int value="20" label="Busy">MountError::kBusy</int> </enum> <enum name="CrosDisksDeviceMediaType"> @@ -21835,6 +21836,9 @@ <int value="19" label="Invalid - Cancelled"> 100 * MountType::kInvalid + MountError::kCancelled </int> + <int value="20" label="Invalid - Busy"> + 100 * MountType::kInvalid + MountError::kBusy + </int> <int value="100" label="Device - Success"> 100 * MountType::kDevice + MountError::kNone </int> @@ -21895,6 +21899,9 @@ <int value="119" label="Device - Cancelled"> 100 * MountType::kDevice + MountError::kCancelled </int> + <int value="120" label="Device - Busy"> + 100 * MountType::kDevice + MountError::kBusy + </int> <int value="200" label="Archive - Success"> 100 * MountType::kArchive + MountError::kNone </int> @@ -21955,6 +21962,9 @@ <int value="219" label="Archive - Cancelled"> 100 * MountType::kArchive + MountError::kCancelled </int> + <int value="220" label="Archive - Busy"> + 100 * MountType::kArchive + MountError::kBusy + </int> <int value="300" label="Network - Success"> 100 * MountType::kNetworkStorage + MountError::kNone </int> @@ -22015,6 +22025,9 @@ <int value="319" label="Network - Cancelled"> 100 * MountType::kNetworkStorage + MountError::kCancelled </int> + <int value="320" label="Network - Busy"> + 100 * MountType::kNetworkStorage + MountError::kBusy + </int> </enum> <enum name="CrosEnableDriveOfflineOutcome"> @@ -35681,6 +35694,8 @@ <int value="1718" label="WMDESKSPRIVATE_GETACTIVEDESK"/> <int value="1719" label="WMDESKSPRIVATE_SWITCHDESK"/> <int value="1720" label="OS_TELEMETRY_GETTPMINFO"/> + <int value="1721" + label="INPUTMETHODPRIVATE_NOTIFYINPUTMETHODREADYFORTESTING"/> </enum> <enum name="ExtensionIconState"> @@ -36314,6 +36329,7 @@ <int value="241" label="kSidePanel"/> <int value="242" label="kDownloadsUi"/> <int value="243" label="kWebRequestAuthProvider"/> + <int value="244" label="kChromeOSTelemetryNetworkInformation"/> </enum> <enum name="ExtensionPointEnableState"> @@ -43636,13 +43652,6 @@ <int value="4" label="User left the page before first contentful paint"/> </enum> -<enum name="FirstPartySetsClearSiteDataOutcomeType"> - <int value="0" label="Success"/> - <int value="1" label="Failed to clear cookies"/> - <int value="2" label="Failed to clear storage"/> - <int value="3" label="Failed to clear cookies and storage"/> -</enum> - <enum name="FirstPartySetsDatabaseInitStatus"> <int value="0" label="Unattempted"/> <int value="1" label="Success"/> @@ -53850,7 +53859,8 @@ <enum name="KioskBrowserWindowType"> <int value="0" label="Settings Page"/> - <int value="1" label="Other, immediately closed"/> + <int value="1" label="Closed regular browser"/> + <int value="2" label="Opened regular browser"/> </enum> <enum name="KioskLaunchError"> @@ -61300,6 +61310,7 @@ <int value="749516419" label="DragToSnapInClamshellMode:disabled"/> <int value="749994865" label="MessagesForAndroidSyncError:enabled"/> <int value="750028579" label="CommerceCoupons:disabled"/> + <int value="751734414" label="OmniboxOnClobberFocusTypeOnContent:disabled"/> <int value="751862578" label="OffsetParentNewSpecBehavior:enabled"/> <int value="752194066" label="enable-app-window-cycling"/> <int value="752416911" label="FastPair:disabled"/> @@ -61621,7 +61632,6 @@ label="HappinessTrackingSurveysForDesktopDevToolsIssuesCookiesSameSite:disabled"/> <int value="956716414" label="GlobalMediaControlsPictureInPicture:disabled"/> <int value="957191538" label="EcheSWADebugMode:enabled"/> - <int value="962834398" label="OmniboxOnClobberFocusTypeOnAndroid:disabled"/> <int value="963457392" label="ChromeHomeModernLayout:disabled"/> <int value="963671232" label="DrawOcclusion:disabled"/> <int value="964613807" label="ContextualSearchTranslationModel:disabled"/> @@ -61940,7 +61950,6 @@ <int value="1142788238" label="FontCacheScaling:disabled"/> <int value="1142970266" label="SignedExchangePrefetchCacheForNavigations:disabled"/> - <int value="1143538862" label="OmniboxOnClobberFocusTypeOnAndroid:enabled"/> <int value="1147703885" label="SecondaryGoogleAccountUsage:enabled"/> <int value="1147924185" label="enable-navigation-predictor-renderer-warmup"/> <int value="1148284632" label="NewTabPageUIMd:disabled"/> @@ -62196,6 +62205,7 @@ <int value="1293697921" label="RequestDesktopSiteExceptions:enabled"/> <int value="1294131571" label="disable-winrt-midi-api"/> <int value="1294306055" label="FeedInteractiveRefresh:disabled"/> + <int value="1295669314" label="OmniboxOnClobberFocusTypeOnContent:enabled"/> <int value="1296661698" label="CrOSLateBootMediaDynamicCgroup:disabled"/> <int value="1296878388" label="PermissionPredictions:disabled"/> <int value="1296958520" label="hide-active-apps-from-shelf"/>
diff --git a/tools/metrics/histograms/metadata/arc/histograms.xml b/tools/metrics/histograms/metadata/arc/histograms.xml index ec79acde..936b6cd 100644 --- a/tools/metrics/histograms/metadata/arc/histograms.xml +++ b/tools/metrics/histograms/metadata/arc/histograms.xml
@@ -353,7 +353,7 @@ </histogram> <histogram name="Arc.App.LowMemoryKills.{ArcAppKillType}Count10Minutes" - units="Apps" expires_after="2022-10-04"> + units="Apps" expires_after="2023-04-07"> <owner>cwd@google.com</owner> <owner>cros-platform-kernel-core@google.com</owner> <summary> @@ -365,7 +365,7 @@ <histogram name="Arc.App.LowMemoryKills.{ArcBackgroundVms}.{ArcAppKillType}Count10Minutes" - units="Apps" expires_after="2022-10-04"> + units="Apps" expires_after="2023-04-07"> <owner>cwd@google.com</owner> <owner>cros-platform-kernel-core@google.com</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/histogram_suffixes_list.xml b/tools/metrics/histograms/metadata/histogram_suffixes_list.xml index f3d88fb1..4bb8d56 100644 --- a/tools/metrics/histograms/metadata/histogram_suffixes_list.xml +++ b/tools/metrics/histograms/metadata/histogram_suffixes_list.xml
@@ -875,6 +875,8 @@ <affected-histogram name="Blink.HitTestDocumentUpdate.UpdateTime"/> <affected-histogram name="Blink.ImplCompositorCommit.UpdateTime"/> <affected-histogram name="Blink.IntersectionObservation.UpdateTime"/> + <affected-histogram name="Blink.IntersectionObservationInternalCount.UpdateTime"/> + <affected-histogram name="Blink.IntersectionObservationJavascriptCount.UpdateTime"/> <affected-histogram name="Blink.JavascriptDocumentUpdate.UpdateTime"/> <affected-histogram name="Blink.JavascriptIntersectionObserver.UpdateTime"/> <affected-histogram name="Blink.Layout.UpdateTime"/> @@ -908,6 +910,8 @@ <affected-histogram name="Blink.HitTestDocumentUpdate.UpdateTime"/> <affected-histogram name="Blink.ImplCompositorCommit.UpdateTime"/> <affected-histogram name="Blink.IntersectionObservation.UpdateTime"/> + <affected-histogram name="Blink.IntersectionObservationInternalCount.UpdateTime"/> + <affected-histogram name="Blink.IntersectionObservationJavascriptCount.UpdateTime"/> <affected-histogram name="Blink.JavascriptDocumentUpdate.UpdateTime"/> <affected-histogram name="Blink.JavascriptIntersectionObserver.UpdateTime"/> <affected-histogram name="Blink.Layout.UpdateTime"/> @@ -941,6 +945,8 @@ <affected-histogram name="Blink.HitTestDocumentUpdate.UpdateTime"/> <affected-histogram name="Blink.ImplCompositorCommit.UpdateTime"/> <affected-histogram name="Blink.IntersectionObservation.UpdateTime"/> + <affected-histogram name="Blink.IntersectionObservationInternalCount.UpdateTime"/> + <affected-histogram name="Blink.IntersectionObservationJavascriptCount.UpdateTime"/> <affected-histogram name="Blink.JavascriptDocumentUpdate.UpdateTime"/> <affected-histogram name="Blink.JavascriptIntersectionObserver.UpdateTime"/> <affected-histogram name="Blink.Layout.UpdateTime"/>
diff --git a/tools/metrics/histograms/metadata/kiosk/histograms.xml b/tools/metrics/histograms/metadata/kiosk/histograms.xml index 64771f43e..29b961b3 100644 --- a/tools/metrics/histograms/metadata/kiosk/histograms.xml +++ b/tools/metrics/histograms/metadata/kiosk/histograms.xml
@@ -150,13 +150,13 @@ </histogram> <histogram name="Kiosk.NewBrowserWindow" enum="KioskBrowserWindowType" - expires_after="2023-07-01"> + expires_after="2023-10-07"> <owner>pbond@chromium.org</owner> <owner>chromeos-kiosk-eng@google.com</owner> <summary> ChromeOS only. Records a new browser window type once a new browser window - is attempted to be shown in a kiosk session. Currently distinguishes only - settings page from others, which get closed immediately. + is attempted to be shown in a kiosk session. Distinguishes settings page, + closed regular browser and opened regular browser. </summary> </histogram>
diff --git a/tools/metrics/histograms/metadata/others/histograms.xml b/tools/metrics/histograms/metadata/others/histograms.xml index f6a450f5..003ab36 100644 --- a/tools/metrics/histograms/metadata/others/histograms.xml +++ b/tools/metrics/histograms/metadata/others/histograms.xml
@@ -6225,16 +6225,6 @@ </summary> </histogram> -<histogram name="FirstPartySets.Initialization.ClearSiteDataOutcomeType" - enum="FirstPartySetsClearSiteDataOutcomeType" expires_after="2023-08-20"> - <owner>shuuran@google.com</owner> - <owner>kaustubhag@google.com</owner> - <summary> - Measures the outcome of site data clearing. Recorded when First-Party Sets - initialization triggers site data clearing for a given browser context. - </summary> -</histogram> - <histogram name="FirstRun.IOSFirebaseConfigured" enum="FirebaseConfiguredState" expires_after="M89"> <owner>ghendel@chromium.org</owner>
diff --git a/tools/metrics/histograms/metadata/security/histograms.xml b/tools/metrics/histograms/metadata/security/histograms.xml index 02e6a2fe..70e7362 100644 --- a/tools/metrics/histograms/metadata/security/histograms.xml +++ b/tools/metrics/histograms/metadata/security/histograms.xml
@@ -250,6 +250,17 @@ </summary> </histogram> +<histogram name="Security.PageInfo.Cookies.HasFPSInfo" enum="Boolean" + expires_after="M115"> + <owner>tommasin@chromium.org</owner> + <owner>sauski@google.com</owner> + <owner>olesiamarukhno@google.com</owner> + <summary> + Tracks whether the FPS section was shown in the Cookies subpage. Recorded + every time Cookie subpage from PageInfo is opened. + </summary> +</histogram> + <histogram name="Security.PageInfo.TimeOpen" units="ms" expires_after="2022-10-30"> <owner>cthomp@chromium.org</owner>
diff --git a/tools/metrics/histograms/metadata/webapps/histograms.xml b/tools/metrics/histograms/metadata/webapps/histograms.xml index 556b70b6..06325135 100644 --- a/tools/metrics/histograms/metadata/webapps/histograms.xml +++ b/tools/metrics/histograms/metadata/webapps/histograms.xml
@@ -459,6 +459,65 @@ </summary> </histogram> +<histogram name="WebApp.Icon.AppsWithEmptyDownloadedIconSizes" units="web apps" + expires_after="2023-08-01"> + <owner>alancutter@chromium.org</owner> + <owner>desktop-pwas-team@google.com</owner> + <summary> + Records the number of web apps that have an empty + WebApp::downloaded_icon_sizes field. This indicates an icon failure state + caused by an installation bug. This gets recorded at browser profile start + up in both the Lacros and Ash processes. + </summary> +</histogram> + +<histogram name="WebApp.Icon.AppsWithEmptyIconBitmap" units="web apps" + expires_after="2023-08-01"> + <owner>alancutter@chromium.org</owner> + <owner>desktop-pwas-team@google.com</owner> + <summary> + Records the number of web apps that have missing icon bitmap data. This gets + recorded at browser profile start up in both the Lacros and Ash processes. + </summary> +</histogram> + +<histogram name="WebApp.Icon.AppsWithGeneratedIconBitmap" units="web apps" + expires_after="2023-08-01"> + <owner>alancutter@chromium.org</owner> + <owner>desktop-pwas-team@google.com</owner> + <summary> + Records the number of web apps that have a generated letter icon bitmap + (distinct from the is_generated_icon flag). This gets recorded at browser + profile start up in both the Lacros and Ash processes. + </summary> +</histogram> + +<histogram name="WebApp.Icon.AppsWithGeneratedIconFlag" units="web apps" + expires_after="2023-08-01"> + <owner>alancutter@chromium.org</owner> + <owner>desktop-pwas-team@google.com</owner> + <summary> + Records the number of web apps that have their WebApp::is_generated_icon + field set. This indicates a letter icon was generated during installation + instead of using a real app icon. This gets recorded at browser profile + start up in both the Lacros and Ash processes. + </summary> +</histogram> + +<histogram name="WebApp.Icon.AppsWithGeneratedIconFlagFalseNegative" + units="web apps" expires_after="2023-08-01"> + <owner>alancutter@chromium.org</owner> + <owner>desktop-pwas-team@google.com</owner> + <summary> + Records the number of web apps that have their WebApp::is_generated_icon + field unset but actually have a generated icon bitmap. This indicates a + letter icon was generated during installation instead of using a real app + icon and a manifest update clobbered the correct value of is_generated_icon + (https://crbug.com/1317922). This gets recorded at browser profile start up + in both the Lacros and Ash processes. + </summary> +</histogram> + <histogram name="WebApp.Icon.DownloadedHttpStatusCodeOnCreate" enum="HttpResponseCode" expires_after="2024-01-01"> <owner>alancutter@chromium.org</owner>
diff --git a/tools/perf/core/perfetto_binary_roller/binary_deps.json b/tools/perf/core/perfetto_binary_roller/binary_deps.json index f3016554..2fdb9a6 100644 --- a/tools/perf/core/perfetto_binary_roller/binary_deps.json +++ b/tools/perf/core/perfetto_binary_roller/binary_deps.json
@@ -6,15 +6,15 @@ }, "win": { "hash": "be4872c1a4df41e8b5e751d85266d95d99fd27e1", - "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/win/f6f851f265bdd96022f4c4af1bfd4fae6385db5e/trace_processor_shell.exe" + "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/win/6f9968b593b7f806a59655e7fa1f3682b5c2f5aa/trace_processor_shell.exe" }, "linux_arm": { "hash": "58893933be305d3bfe0a72ebebcacde2ac3ca893", "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/linux_arm/49b4b5dcbc312d8d2c3751cf29238b8efeb4e494/trace_processor_shell" }, "mac": { - "hash": "737cf0363daca9132cffb814092f8c6cb8ff91f4", - "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/mac/f6f851f265bdd96022f4c4af1bfd4fae6385db5e/trace_processor_shell" + "hash": "182c1a852aee872ccc7fbc57972d077b17ea0198", + "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/mac/6f9968b593b7f806a59655e7fa1f3682b5c2f5aa/trace_processor_shell" }, "mac_arm64": { "hash": "e1ad4861384b06d911a65f035317914b8cc975c6",
diff --git a/ui/accessibility/ax_node_position.cc b/ui/accessibility/ax_node_position.cc index b98b1d50..5e0f8d88 100644 --- a/ui/accessibility/ax_node_position.cc +++ b/ui/accessibility/ax_node_position.cc
@@ -76,8 +76,7 @@ << "\n* IsLeafNodeForTreePosition(): " << IsLeafNodeForTreePosition(node) << "\n* Tree: " << node.tree()->ToString(); - return CreateTreePosition(*node.tree(), node.id(), - child_index_or_text_offset); + return CreateTreePosition(*node.tree(), node, child_index_or_text_offset); } // static
diff --git a/ui/accessibility/ax_node_position_perftest.cc b/ui/accessibility/ax_node_position_perftest.cc index 682932a..a36d2c8 100644 --- a/ui/accessibility/ax_node_position_perftest.cc +++ b/ui/accessibility/ax_node_position_perftest.cc
@@ -143,7 +143,7 @@ TEST_F(AXPositionPerfTest, AsLeafTextPositionFromTreePosition) { TestPositionType tree_position = AXNodePosition::CreateTreePosition( - *ax_tree(), /*anchor_id=*/1, /*child_index=*/4); + *ax_tree(), *ax_tree()->root(), /*child_index=*/4); base::LapTimer timer(kWarmupLaps, base::TimeDelta(), kLaps); for (int i = 0; i < kLaps + kWarmupLaps; ++i) {
diff --git a/ui/accessibility/ax_node_position_unittest.cc b/ui/accessibility/ax_node_position_unittest.cc index c124a6f..8581fba 100644 --- a/ui/accessibility/ax_node_position_unittest.cc +++ b/ui/accessibility/ax_node_position_unittest.cc
@@ -115,6 +115,40 @@ const std::vector<AXNodeData>& nodes, const AXTreeID& parent_tree_id = AXTreeID()) const; + const AXNode& GetRootNode() const { return *ax_tree()->GetFromId(root_.id); } + + const AXNode& GetButtonNode() const { + return *ax_tree()->GetFromId(button_.id); + } + + const AXNode& GetCheckBoxNode() const { + return *ax_tree()->GetFromId(check_box_.id); + } + + const AXNode& GetTextFieldNode() const { + return *ax_tree()->GetFromId(text_field_.id); + } + + const AXNode& GetStaticText1Node() const { + return *ax_tree()->GetFromId(static_text1_.id); + } + + const AXNode& GetLineBreakNode() const { + return *ax_tree()->GetFromId(line_break_.id); + } + + const AXNode& GetStaticText2Node() const { + return *ax_tree()->GetFromId(static_text2_.id); + } + + const AXNode& GetInlineBox1Node() const { + return *ax_tree()->GetFromId(inline_box1_.id); + } + + const AXNode& GetInlineBox2Node() const { + return *ax_tree()->GetFromId(inline_box2_.id); + } + AXNodeData root_; AXNodeData button_; AXNodeData check_box_; @@ -695,7 +729,7 @@ EXPECT_EQ(AXNodePosition::INVALID_OFFSET, copy_position->text_offset()); TestPositionType tree_position = AXNodePosition::CreateTreePosition( - *ax_tree(), root_.id, 0 /* child_index */); + *ax_tree(), GetRootNode(), 0 /* child_index */); ASSERT_NE(nullptr, tree_position); copy_position = tree_position->Clone(); ASSERT_NE(nullptr, copy_position); @@ -704,7 +738,7 @@ EXPECT_EQ(0, copy_position->child_index()); EXPECT_EQ(AXNodePosition::INVALID_OFFSET, copy_position->text_offset()); - tree_position = AXNodePosition::CreateTreePosition(*ax_tree(), root_.id, + tree_position = AXNodePosition::CreateTreePosition(*ax_tree(), GetRootNode(), 1 /* child_index */); ASSERT_NE(nullptr, tree_position); copy_position = tree_position->Clone(); @@ -718,7 +752,7 @@ // a leaf. A non-leaf must use a child index >= 0 and <= AnchorChildOffset(). // A child index of BEFORE_TEXT can only be used with a leaf anchor. EXPECT_DEATH_IF_SUPPORTED( - AXNodePosition::CreateTreePosition(*ax_tree(), root_.id, + AXNodePosition::CreateTreePosition(*ax_tree(), GetRootNode(), AXNodePosition::BEFORE_TEXT), "Creating invalid positions is disallowed."); @@ -757,7 +791,7 @@ EXPECT_TRUE(copy_position->IsNullPosition()); TestPositionType tree_position = AXNodePosition::CreateTreePosition( - *ax_tree(), root_.id, 1 /* child_index */); + *ax_tree(), GetRootNode(), 1 /* child_index */); ASSERT_NE(nullptr, tree_position); copy_position = AXNodePosition::Unserialize(tree_position->Serialize()); ASSERT_NE(nullptr, copy_position); @@ -767,7 +801,7 @@ EXPECT_EQ(AXNodePosition::INVALID_OFFSET, copy_position->text_offset()); tree_position = AXNodePosition::CreateTreePosition( - *ax_tree(), inline_box2_.id, AXNodePosition::BEFORE_TEXT); + *ax_tree(), GetInlineBox2Node(), AXNodePosition::BEFORE_TEXT); ASSERT_NE(nullptr, tree_position); copy_position = AXNodePosition::Unserialize(tree_position->Serialize()); ASSERT_NE(nullptr, copy_position); @@ -973,6 +1007,10 @@ CreateAXTree({root_data, static_text_data_1, inline_box_data_1, container_data, static_text_data_2, inline_box_data_2})); + AXNode* root = ax_tree()->GetFromId(root_data.id); + AXNode* static_text_1 = ax_tree()->GetFromId(static_text_data_1.id); + AXNode* inline_box_1 = ax_tree()->GetFromId(inline_box_data_1.id); + // // Text positions. // @@ -1031,32 +1069,32 @@ // A "before children" position on the root should be ignored because the // first child of the root is ignored. TestPositionType tree_position_1 = AXNodePosition::CreateTreePosition( - *ax_tree(), root_data.id, 0 /* child_index */); + *ax_tree(), *root, 0 /* child_index */); ASSERT_TRUE(tree_position_1->IsTreePosition()); EXPECT_TRUE(tree_position_1->IsIgnored()); // A tree position pointing to an ignored child node should be ignored. TestPositionType tree_position_2 = AXNodePosition::CreateTreePosition( - *ax_tree(), root_data.id, 1 /* child_index */); + *ax_tree(), *root, 1 /* child_index */); ASSERT_TRUE(tree_position_2->IsTreePosition()); EXPECT_TRUE(tree_position_2->IsIgnored()); // An "after text" tree position on an ignored leaf node should be ignored. TestPositionType tree_position_3 = AXNodePosition::CreateTreePosition( - *ax_tree(), inline_box_data_1.id, 0 /* child_index */); + *ax_tree(), *inline_box_1, 0 /* child_index */); ASSERT_TRUE(tree_position_3->IsTreePosition()); EXPECT_TRUE(tree_position_3->IsIgnored()); // A "before text" tree position on an ignored leaf node should be ignored. TestPositionType tree_position_4 = AXNodePosition::CreateTreePosition( - *ax_tree(), inline_box_data_1.id, AXNodePosition::BEFORE_TEXT); + *ax_tree(), *inline_box_1, AXNodePosition::BEFORE_TEXT); ASSERT_TRUE(tree_position_4->IsTreePosition()); EXPECT_TRUE(tree_position_4->IsIgnored()); // An "after children" tree position on the root node, where the last child is // ignored, should be ignored. TestPositionType tree_position_5 = AXNodePosition::CreateTreePosition( - *ax_tree(), root_data.id, 2 /* child_index */); + *ax_tree(), *root, 2 /* child_index */); ASSERT_TRUE(tree_position_5->IsTreePosition()); EXPECT_TRUE(tree_position_5->IsIgnored()); @@ -1064,7 +1102,7 @@ // However, such a position is illegal. The child index must point to one // node's children. EXPECT_DEATH_IF_SUPPORTED( - AXNodePosition::CreateTreePosition(*ax_tree(), static_text_data_1.id, + AXNodePosition::CreateTreePosition(*ax_tree(), *static_text_1, AXNodePosition::BEFORE_TEXT), "Creating invalid positions is disallowed."); } @@ -1425,7 +1463,7 @@ TEST_F(AXPositionTest, AtStartOfAnchorWithTreePosition) { TestPositionType tree_position = AXNodePosition::CreateTreePosition( - *ax_tree(), root_.id, 0 /* child_index */); + *ax_tree(), GetRootNode(), 0 /* child_index */); ASSERT_NE(nullptr, tree_position); EXPECT_TRUE(tree_position->AtStartOfAnchor()); @@ -1441,13 +1479,13 @@ // A "before text" position. tree_position = AXNodePosition::CreateTreePosition( - *ax_tree(), inline_box1_.id, AXNodePosition::BEFORE_TEXT); + *ax_tree(), GetInlineBox1Node(), AXNodePosition::BEFORE_TEXT); ASSERT_NE(nullptr, tree_position); EXPECT_TRUE(tree_position->AtStartOfAnchor()); // An "after text" position. tree_position = AXNodePosition::CreateTreePosition( - *ax_tree(), inline_box1_.id, 0 /* child_index */); + *ax_tree(), GetInlineBox1Node(), 0 /* child_index */); ASSERT_NE(nullptr, tree_position); EXPECT_FALSE(tree_position->AtStartOfAnchor()); } @@ -1483,16 +1521,16 @@ TEST_F(AXPositionTest, AtEndOfAnchorWithTreePosition) { TestPositionType tree_position = AXNodePosition::CreateTreePosition( - *ax_tree(), root_.id, 3 /* child_index */); + *ax_tree(), GetRootNode(), 3 /* child_index */); ASSERT_NE(nullptr, tree_position); EXPECT_TRUE(tree_position->AtEndOfAnchor()); - tree_position = AXNodePosition::CreateTreePosition(GetTreeID(), root_.id, + tree_position = AXNodePosition::CreateTreePosition(*ax_tree(), GetRootNode(), 2 /* child_index */); ASSERT_NE(nullptr, tree_position); EXPECT_FALSE(tree_position->AtEndOfAnchor()); - tree_position = AXNodePosition::CreateTreePosition(GetTreeID(), root_.id, + tree_position = AXNodePosition::CreateTreePosition(*ax_tree(), GetRootNode(), 0 /* child_index */); ASSERT_NE(nullptr, tree_position); EXPECT_FALSE(tree_position->AtEndOfAnchor()); @@ -1682,7 +1720,7 @@ ASSERT_TRUE(GetTree()->Unserialize(update)); TestPositionType tree_position = AXNodePosition::CreateTreePosition( - *ax_tree(), text_field_.id, 1 /* child_index */); + *ax_tree(), GetTextFieldNode(), 1 /* child_index */); ASSERT_NE(nullptr, tree_position); ASSERT_TRUE(tree_position->IsTreePosition()); EXPECT_TRUE(tree_position->AtStartOfLine()); @@ -1714,7 +1752,7 @@ ASSERT_TRUE(GetTree()->Unserialize(update)); TestPositionType tree_position = AXNodePosition::CreateTreePosition( - *ax_tree(), text_field_.id, 1 /* child_index */); + *ax_tree(), GetTextFieldNode(), 1 /* child_index */); ASSERT_NE(nullptr, tree_position); ASSERT_TRUE(tree_position->IsTreePosition()); EXPECT_FALSE(tree_position->AtEndOfLine()); @@ -1829,9 +1867,12 @@ inline_box_data_2, inline_box_data_3, inline_box_data_4, static_text_data_2, inline_box_data_5})); + AXNode* inline_box_2 = ax_tree()->GetFromId(inline_box_data_2.id); + AXNode* inline_box_4 = ax_tree()->GetFromId(inline_box_data_4.id); + // An "after text" tree position - after the soft line break. TestPositionType tree_position = AXNodePosition::CreateTreePosition( - *ax_tree(), inline_box_data_2.id, 0 /* child_index */); + *ax_tree(), *inline_box_2, 0 /* child_index */); ASSERT_NE(nullptr, tree_position); ASSERT_TRUE(tree_position->IsTreePosition()); EXPECT_TRUE(tree_position->AtStartOfLine()); @@ -1839,8 +1880,8 @@ // An "after text" tree position - after the space character and before the // hard line break caused by the second static text object. - tree_position = AXNodePosition::CreateTreePosition( - *ax_tree(), inline_box_data_4.id, 0 /* child_index */); + tree_position = AXNodePosition::CreateTreePosition(*ax_tree(), *inline_box_4, + 0 /* child_index */); ASSERT_NE(nullptr, tree_position); ASSERT_TRUE(tree_position->IsTreePosition()); EXPECT_FALSE(tree_position->AtStartOfLine()); @@ -1972,29 +2013,32 @@ text_field_data_2, static_text_data_2, inline_box_data_4, inline_box_data_5, inline_box_data_6})); + AXNode* text_field_1 = ax_tree()->GetFromId(text_field_data_1.id); + AXNode* text_field_2 = ax_tree()->GetFromId(text_field_data_2.id); + TestPositionType tree_position = AXNodePosition::CreateTreePosition( - *ax_tree(), text_field_data_1.id, 0 /* child_index */); + *ax_tree(), *text_field_1, 0 /* child_index */); ASSERT_NE(nullptr, tree_position); ASSERT_TRUE(tree_position->IsTreePosition()); EXPECT_TRUE(tree_position->AtStartOfLine()); EXPECT_FALSE(tree_position->AtEndOfLine()); - tree_position = AXNodePosition::CreateTreePosition( - *ax_tree(), text_field_data_1.id, 1 /* child_index */); + tree_position = AXNodePosition::CreateTreePosition(*ax_tree(), *text_field_1, + 1 /* child_index */); ASSERT_NE(nullptr, tree_position); ASSERT_TRUE(tree_position->IsTreePosition()); EXPECT_FALSE(tree_position->AtStartOfLine()); EXPECT_TRUE(tree_position->AtEndOfLine()); - tree_position = AXNodePosition::CreateTreePosition( - *ax_tree(), text_field_data_2.id, 0 /* child_index */); + tree_position = AXNodePosition::CreateTreePosition(*ax_tree(), *text_field_2, + 0 /* child_index */); ASSERT_NE(nullptr, tree_position); ASSERT_TRUE(tree_position->IsTreePosition()); EXPECT_TRUE(tree_position->AtStartOfLine()); EXPECT_FALSE(tree_position->AtEndOfLine()); - tree_position = AXNodePosition::CreateTreePosition( - *ax_tree(), text_field_data_2.id, 1 /* child_index */); + tree_position = AXNodePosition::CreateTreePosition(*ax_tree(), *text_field_2, + 1 /* child_index */); ASSERT_NE(nullptr, tree_position); ASSERT_TRUE(tree_position->IsTreePosition()); EXPECT_FALSE(tree_position->AtStartOfLine()); @@ -3398,20 +3442,20 @@ ASSERT_NE(nullptr, null_position); // An "after children" position. TestPositionType root_position = AXNodePosition::CreateTreePosition( - *ax_tree(), root_.id, 3 /* child_index */); + *ax_tree(), GetRootNode(), 3 /* child_index */); ASSERT_NE(nullptr, root_position); // A "before text" position. TestPositionType button_position = AXNodePosition::CreateTreePosition( - *ax_tree(), button_.id, AXNodePosition::BEFORE_TEXT); + *ax_tree(), GetButtonNode(), AXNodePosition::BEFORE_TEXT); ASSERT_NE(nullptr, button_position); TestPositionType text_field_position = AXNodePosition::CreateTreePosition( - *ax_tree(), text_field_.id, 2 /* child_index */); + *ax_tree(), GetTextFieldNode(), 2 /* child_index */); ASSERT_NE(nullptr, text_field_position); TestPositionType static_text1_position = AXNodePosition::CreateTreePosition( - *ax_tree(), static_text1_.id, 0 /* child_index */); + *ax_tree(), GetStaticText1Node(), 0 /* child_index */); ASSERT_NE(nullptr, static_text1_position); TestPositionType static_text2_position = AXNodePosition::CreateTreePosition( - *ax_tree(), static_text2_.id, 0 /* child_index */); + *ax_tree(), GetStaticText2Node(), 0 /* child_index */); ASSERT_NE(nullptr, static_text2_position); TestPositionType inline_box1_position = AXNodePosition::CreateTextPosition( GetTreeID(), inline_box1_.id, 0 /* text_offset */, @@ -3488,7 +3532,7 @@ TEST_F(AXPositionTest, AsTreePositionWithTreePosition) { TestPositionType tree_position = AXNodePosition::CreateTreePosition( - *ax_tree(), root_.id, 1 /* child_index */); + *ax_tree(), GetRootNode(), 1 /* child_index */); ASSERT_NE(nullptr, tree_position); TestPositionType test_position = tree_position->AsTreePosition(); ASSERT_NE(nullptr, test_position); @@ -3558,7 +3602,7 @@ // Create a tree position pointing to the line break node inside the text // field. TestPositionType tree_position = AXNodePosition::CreateTreePosition( - *ax_tree(), text_field_.id, 1 /* child_index */); + *ax_tree(), GetTextFieldNode(), 1 /* child_index */); ASSERT_NE(nullptr, tree_position); TestPositionType test_position = tree_position->AsTextPosition(); ASSERT_NE(nullptr, test_position); @@ -3577,7 +3621,7 @@ // Test for a "before text" position. tree_position = AXNodePosition::CreateTreePosition( - *ax_tree(), inline_box1_.id, AXNodePosition::BEFORE_TEXT); + *ax_tree(), GetInlineBox1Node(), AXNodePosition::BEFORE_TEXT); ASSERT_NE(nullptr, tree_position); test_position = tree_position->AsTextPosition(); ASSERT_NE(nullptr, test_position); @@ -3590,7 +3634,7 @@ // Test for an "after text" position. tree_position = AXNodePosition::CreateTreePosition( - *ax_tree(), inline_box1_.id, 0 /* child_index */); + *ax_tree(), GetInlineBox1Node(), 0 /* child_index */); ASSERT_NE(nullptr, tree_position); test_position = tree_position->AsTextPosition(); ASSERT_NE(nullptr, test_position); @@ -3630,7 +3674,7 @@ // Create a tree position pointing to the first static text node inside the // text field: a "before children" position. TestPositionType tree_position = AXNodePosition::CreateTreePosition( - *ax_tree(), text_field_.id, 0 /* child_index */); + *ax_tree(), GetTextFieldNode(), 0 /* child_index */); ASSERT_NE(nullptr, tree_position); TestPositionType test_position = tree_position->AsLeafTreePosition(); ASSERT_NE(nullptr, test_position); @@ -3641,8 +3685,8 @@ // Create a tree position pointing to the line break node inside the text // field. - tree_position = AXNodePosition::CreateTreePosition(*ax_tree(), text_field_.id, - 1 /* child_index */); + tree_position = AXNodePosition::CreateTreePosition( + *ax_tree(), GetTextFieldNode(), 1 /* child_index */); ASSERT_NE(nullptr, tree_position); test_position = tree_position->AsLeafTreePosition(); ASSERT_NE(nullptr, test_position); @@ -3653,8 +3697,8 @@ // Create a text position pointing to the second static text node inside the // text field. - tree_position = AXNodePosition::CreateTreePosition(*ax_tree(), text_field_.id, - 2 /* child_index */); + tree_position = AXNodePosition::CreateTreePosition( + *ax_tree(), GetTextFieldNode(), 2 /* child_index */); ASSERT_NE(nullptr, tree_position); test_position = tree_position->AsLeafTreePosition(); ASSERT_NE(nullptr, test_position); @@ -3820,7 +3864,7 @@ // Create a tree position pointing to the first static text node inside the // text field. TestPositionType tree_position = AXNodePosition::CreateTreePosition( - *ax_tree(), text_field_.id, 0 /* child_index */); + *ax_tree(), GetTextFieldNode(), 0 /* child_index */); ASSERT_NE(nullptr, tree_position); TestPositionType test_position = tree_position->AsLeafTextPosition(); ASSERT_NE(nullptr, test_position); @@ -3832,8 +3876,8 @@ // Create a tree position pointing to the line break node inside the text // field. - tree_position = AXNodePosition::CreateTreePosition(*ax_tree(), text_field_.id, - 1 /* child_index */); + tree_position = AXNodePosition::CreateTreePosition( + *ax_tree(), GetTextFieldNode(), 1 /* child_index */); ASSERT_NE(nullptr, tree_position); test_position = tree_position->AsLeafTextPosition(); ASSERT_NE(nullptr, test_position); @@ -3845,8 +3889,8 @@ // Create a text position pointing to the second static text node inside the // text field. - tree_position = AXNodePosition::CreateTreePosition(*ax_tree(), text_field_.id, - 2 /* child_index */); + tree_position = AXNodePosition::CreateTreePosition( + *ax_tree(), GetTextFieldNode(), 2 /* child_index */); ASSERT_NE(nullptr, tree_position); test_position = tree_position->AsLeafTextPosition(); ASSERT_NE(nullptr, test_position); @@ -3879,9 +3923,11 @@ SetTree(CreateAXTree({root_data, empty_div_data1, empty_div_data2})); + AXNode* root = ax_tree()->GetFromId(root_data.id); + // Create a tree position on the root pointing to the second empty div child. TestPositionType tree_position = AXNodePosition::CreateTreePosition( - *ax_tree(), root_data.id, 1 /* child_index */); + *ax_tree(), *root, 1 /* child_index */); ASSERT_FALSE(tree_position->IsLeafTextPosition()); TestPositionType test_position = tree_position->AsLeafTextPosition(); ASSERT_NE(nullptr, test_position); @@ -3892,7 +3938,7 @@ EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity()); // Create an "after children" tree position. - tree_position = AXNodePosition::CreateTreePosition(GetTreeID(), root_data.id, + tree_position = AXNodePosition::CreateTreePosition(*ax_tree(), *root, 2 /* child_index */); ASSERT_FALSE(tree_position->IsLeafTextPosition()); test_position = tree_position->AsLeafTextPosition(); @@ -4327,6 +4373,9 @@ inline_box_data_2, container_data, static_text_data_2, inline_box_data_3})); + AXNode* container = ax_tree()->GetFromId(container_data.id); + AXNode* static_text_1 = ax_tree()->GetFromId(static_text_data_1.id); + // 1. In the case of a text position, we move up the parent positions until we // find the next unignored equivalent parent position. We don't do this for // tree positions because, unlike text positions which maintain the @@ -4364,7 +4413,7 @@ // "Before children" position. TestPositionType tree_position = AXNodePosition::CreateTreePosition( - *ax_tree(), container_data.id, 0 /* child_index */); + *ax_tree(), *container, 0 /* child_index */); EXPECT_TRUE(tree_position->IsIgnored()); test_position = tree_position->AsUnignoredPosition( AXPositionAdjustmentBehavior::kMoveForward); @@ -4374,8 +4423,8 @@ EXPECT_EQ(AXNodePosition::BEFORE_TEXT, test_position->child_index()); // "After children" position. - tree_position = AXNodePosition::CreateTreePosition( - *ax_tree(), container_data.id, 1 /* child_index */); + tree_position = AXNodePosition::CreateTreePosition(*ax_tree(), *container, + 1 /* child_index */); EXPECT_TRUE(tree_position->IsIgnored()); // Changing the adjustment behavior should not affect the outcome. test_position = tree_position->AsUnignoredPosition( @@ -4387,8 +4436,8 @@ // "After children" tree positions that are anchored to an unignored node // whose last child is ignored. - tree_position = AXNodePosition::CreateTreePosition( - *ax_tree(), static_text_data_1.id, 2 /* child_index */); + tree_position = AXNodePosition::CreateTreePosition(*ax_tree(), *static_text_1, + 2 /* child_index */); EXPECT_TRUE(tree_position->IsIgnored()); test_position = tree_position->AsUnignoredPosition( AXPositionAdjustmentBehavior::kMoveBackward); @@ -4407,9 +4456,13 @@ inline_box_data_2, container_data, static_text_data_2, inline_box_data_3})); + AXNode* root = ax_tree()->GetFromId(root_data.id); + AXNode* inline_box_2 = ax_tree()->GetFromId(inline_box_data_2.id); + container = ax_tree()->GetFromId(container_data.id); + // TODO(nektar): AXTree has a bug whereby it doesn't update the unignored // cached values when the ignored state is flipped on the root. - GetNode(root_data.id)->UpdateUnignoredCachedValues(); + root->UpdateUnignoredCachedValues(); text_position = AXNodePosition::CreateTextPosition( GetTreeID(), root_data.id, 0 /* text_offset */, @@ -4455,7 +4508,7 @@ EXPECT_EQ(AXNodePosition::BEFORE_TEXT, test_position->child_index()); // "After children" position. - tree_position = AXNodePosition::CreateTreePosition(GetTreeID(), root_data.id, + tree_position = AXNodePosition::CreateTreePosition(*ax_tree(), *root, 2 /* child_index */); EXPECT_TRUE(tree_position->IsIgnored()); test_position = tree_position->AsUnignoredPosition( @@ -4474,8 +4527,8 @@ EXPECT_EQ(0, test_position->child_index()); // "Before children" position. - tree_position = AXNodePosition::CreateTreePosition( - *ax_tree(), container_data.id, 0 /* child_index */); + tree_position = AXNodePosition::CreateTreePosition(*ax_tree(), *container, + 0 /* child_index */); EXPECT_TRUE(tree_position->IsIgnored()); test_position = tree_position->AsUnignoredPosition( AXPositionAdjustmentBehavior::kMoveForward); @@ -4485,8 +4538,8 @@ EXPECT_EQ(AXNodePosition::BEFORE_TEXT, test_position->child_index()); // "After children" position. - tree_position = AXNodePosition::CreateTreePosition( - *ax_tree(), container_data.id, 1 /* child_index */); + tree_position = AXNodePosition::CreateTreePosition(*ax_tree(), *container, + 1 /* child_index */); EXPECT_TRUE(tree_position->IsIgnored()); // Changing the adjustment behavior should not affect the outcome. test_position = tree_position->AsUnignoredPosition( @@ -4534,7 +4587,7 @@ EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity()); tree_position = AXNodePosition::CreateTreePosition( - *ax_tree(), inline_box_data_2.id, AXNodePosition::BEFORE_TEXT); + *ax_tree(), *inline_box_2, AXNodePosition::BEFORE_TEXT); EXPECT_TRUE(tree_position->IsIgnored()); test_position = tree_position->AsUnignoredPosition( @@ -4739,7 +4792,7 @@ TEST_F(AXPositionTest, CreatePositionAtStartOfAnchorWithTreePosition) { TestPositionType tree_position = AXNodePosition::CreateTreePosition( - *ax_tree(), root_.id, 0 /* child_index */); + *ax_tree(), GetRootNode(), 0 /* child_index */); ASSERT_NE(nullptr, tree_position); TestPositionType test_position = tree_position->CreatePositionAtStartOfAnchor(); @@ -4748,7 +4801,7 @@ EXPECT_EQ(root_.id, test_position->anchor_id()); EXPECT_EQ(0, test_position->child_index()); - tree_position = AXNodePosition::CreateTreePosition(GetTreeID(), root_.id, + tree_position = AXNodePosition::CreateTreePosition(*ax_tree(), GetRootNode(), 1 /* child_index */); ASSERT_NE(nullptr, tree_position); test_position = tree_position->CreatePositionAtStartOfAnchor(); @@ -4759,7 +4812,7 @@ // An "after text" position. tree_position = AXNodePosition::CreateTreePosition( - *ax_tree(), inline_box1_.id, 0 /* child_index */); + *ax_tree(), GetInlineBox1Node(), 0 /* child_index */); ASSERT_NE(nullptr, tree_position); test_position = tree_position->CreatePositionAtStartOfAnchor(); EXPECT_NE(nullptr, test_position); @@ -4806,7 +4859,7 @@ TEST_F(AXPositionTest, CreatePositionAtEndOfAnchorWithTreePosition) { TestPositionType tree_position = AXNodePosition::CreateTreePosition( - *ax_tree(), root_.id, 3 /* child_index */); + *ax_tree(), GetRootNode(), 3 /* child_index */); ASSERT_NE(nullptr, tree_position); TestPositionType test_position = tree_position->CreatePositionAtEndOfAnchor(); EXPECT_NE(nullptr, test_position); @@ -4814,7 +4867,7 @@ EXPECT_EQ(root_.id, test_position->anchor_id()); EXPECT_EQ(3, test_position->child_index()); - tree_position = AXNodePosition::CreateTreePosition(GetTreeID(), root_.id, + tree_position = AXNodePosition::CreateTreePosition(*ax_tree(), GetRootNode(), 1 /* child_index */); ASSERT_NE(nullptr, tree_position); test_position = tree_position->CreatePositionAtEndOfAnchor(); @@ -4876,7 +4929,7 @@ ScopedAXEmbeddedObjectBehaviorSetter ax_embedded_object_behavior( AXEmbeddedObjectBehavior::kExposeCharacter); TestPositionType tree_position = AXNodePosition::CreateTreePosition( - *ax_tree(), static_text1_.id, 1 /* child_index */); + *ax_tree(), GetStaticText1Node(), 1 /* child_index */); ASSERT_NE(nullptr, tree_position); ASSERT_TRUE(tree_position->IsTreePosition()); @@ -5013,7 +5066,7 @@ ScopedAXEmbeddedObjectBehaviorSetter ax_embedded_object_behavior( AXEmbeddedObjectBehavior::kExposeCharacter); TestPositionType tree_position = AXNodePosition::CreateTreePosition( - *ax_tree(), button_.id, 0 /* child_index */); + *ax_tree(), GetButtonNode(), 0 /* child_index */); ASSERT_NE(nullptr, tree_position); ASSERT_TRUE(tree_position->IsTreePosition()); @@ -5735,9 +5788,11 @@ page_2_data, page_2_text_data, page_3_data, page_3_text_data)); + AXNode* page_1 = ax_tree()->GetFromId(page_1_data.id); + // Test CreateNextPageStartPosition at the start of the whole content. TestPositionType tree_position = AXNodePosition::CreateTreePosition( - *ax_tree(), page_1_data.id, 0 /* child_index */); + *ax_tree(), *page_1, 0 /* child_index */); ASSERT_NE(nullptr, tree_position); ASSERT_TRUE(tree_position->IsTreePosition()); @@ -7589,7 +7644,7 @@ TEST_F(AXPositionTest, CreateChildPositionAtWithTreePosition) { TestPositionType tree_position = AXNodePosition::CreateTreePosition( - *ax_tree(), root_.id, 2 /* child_index */); + *ax_tree(), GetRootNode(), 2 /* child_index */); ASSERT_NE(nullptr, tree_position); TestPositionType test_position = tree_position->CreateChildPositionAt(1); EXPECT_NE(nullptr, test_position); @@ -7599,8 +7654,8 @@ // a "before text" position. EXPECT_EQ(AXNodePosition::BEFORE_TEXT, test_position->child_index()); - tree_position = AXNodePosition::CreateTreePosition(GetTreeID(), button_.id, - 0 /* child_index */); + tree_position = AXNodePosition::CreateTreePosition( + *ax_tree(), GetButtonNode(), 0 /* child_index */); ASSERT_NE(nullptr, tree_position); test_position = tree_position->CreateChildPositionAt(0); EXPECT_NE(nullptr, test_position); @@ -7639,7 +7694,8 @@ TEST_F(AXPositionTest, CreateParentPositionWithTreePosition) { TestPositionType tree_position = AXNodePosition::CreateTreePosition( - *ax_tree(), check_box_.id, AXNodePosition::BEFORE_TEXT /* child_index */); + *ax_tree(), GetCheckBoxNode(), + AXNodePosition::BEFORE_TEXT /* child_index */); ASSERT_NE(nullptr, tree_position); TestPositionType test_position = tree_position->CreateParentPosition(); EXPECT_NE(nullptr, test_position); @@ -7671,7 +7727,7 @@ << "We should cross into a minimalistic Views tree."; tree_position = AXNodePosition::CreateTreePosition( - *ax_tree(), inline_box2_.id, + *ax_tree(), GetInlineBox2Node(), AXNodePosition::BEFORE_TEXT /* child_index */); ASSERT_NE(nullptr, tree_position); ASSERT_TRUE(tree_position->IsTreePosition()); @@ -7691,7 +7747,7 @@ EXPECT_EQ(2, test_position->child_index()); tree_position = AXNodePosition::CreateTreePosition( - *ax_tree(), inline_box2_.id, 0 /* child_index */); + *ax_tree(), GetInlineBox2Node(), 0 /* child_index */); ASSERT_NE(nullptr, tree_position); ASSERT_TRUE(tree_position->IsTreePosition()); @@ -7834,6 +7890,9 @@ SetTree(CreateAXTree({root_1, link_2, static_text_3, inline_box_4, paragraph_5, static_text_6, inline_box_7})); + AXNode* inline_box_4_node = ax_tree()->GetFromId(inline_box_4.id); + AXNode* inline_box_7_node = ax_tree()->GetFromId(inline_box_7.id); + // // Tree positions. // @@ -7841,7 +7900,7 @@ // Find the equivalent position on the root, when the original position is // before "Hello", with a forward direction. TestPositionType tree_position = AXNodePosition::CreateTreePosition( - *ax_tree(), inline_box_4.id, + *ax_tree(), *inline_box_4_node, AXNodePosition::BEFORE_TEXT /* child_index */); ASSERT_NE(nullptr, tree_position); TestPositionType ancestor_position = tree_position->CreateAncestorPosition( @@ -7858,7 +7917,7 @@ // Find the equivalent position on the root, when the original position is // before "Hello", with a backward direction. tree_position = AXNodePosition::CreateTreePosition( - *ax_tree(), inline_box_4.id, + *ax_tree(), *inline_box_4_node, AXNodePosition::BEFORE_TEXT /* child_index */); ASSERT_NE(nullptr, tree_position); ancestor_position = tree_position->CreateAncestorPosition( @@ -7875,7 +7934,7 @@ // Find the equivalent position on the root, when the original position is // after "Hello", with a forward direction. tree_position = AXNodePosition::CreateTreePosition( - *ax_tree(), inline_box_4.id, 0 /* child_index */); + *ax_tree(), *inline_box_4_node, 0 /* child_index */); ASSERT_NE(nullptr, tree_position); ancestor_position = tree_position->CreateAncestorPosition( GetRoot(), ax::mojom::MoveDirection::kForward); @@ -7890,7 +7949,7 @@ // Find the equivalent position on the root, when the original position is // after "Hello", with a backward direction. tree_position = AXNodePosition::CreateTreePosition( - *ax_tree(), inline_box_4.id, 0 /* child_index */); + *ax_tree(), *inline_box_4_node, 0 /* child_index */); ASSERT_NE(nullptr, tree_position); ancestor_position = tree_position->CreateAncestorPosition( GetRoot(), ax::mojom::MoveDirection::kBackward); @@ -7905,7 +7964,7 @@ // Find the equivalent position on the root, when the original position is // after "world.", with a forward direction. tree_position = AXNodePosition::CreateTreePosition( - *ax_tree(), inline_box_7.id, 0 /* child_index */); + *ax_tree(), *inline_box_7_node, 0 /* child_index */); ASSERT_NE(nullptr, tree_position); ancestor_position = tree_position->CreateAncestorPosition( GetRoot(), ax::mojom::MoveDirection::kForward); @@ -7921,7 +7980,7 @@ // Find the equivalent position on the root, when the original position is // after "world.", with a backward direction. tree_position = AXNodePosition::CreateTreePosition( - *ax_tree(), inline_box_7.id, 0 /* child_index */); + *ax_tree(), *inline_box_7_node, 0 /* child_index */); ASSERT_NE(nullptr, tree_position); ancestor_position = tree_position->CreateAncestorPosition( GetRoot(), ax::mojom::MoveDirection::kBackward); @@ -8145,6 +8204,11 @@ inline_box_ignored_1, static_text_ignored_2, inline_box_ignored_2, static_text_2, inline_box_2})); + AXNode* inline_box_ignored_1_node = + ax_tree()->GetFromId(inline_box_ignored_1.id); + AXNode* inline_box_ignored_2_node = + ax_tree()->GetFromId(inline_box_ignored_2.id); + // "<H>elloWorld" TestPositionType before_root = AXNodePosition::CreateTextPosition( GetTreeID(), root.id, 0 /* text_offset */, @@ -8195,12 +8259,12 @@ TestPositionType before_inline_box_ignored_1_tree = AXNodePosition::CreateTreePosition( - *ax_tree(), inline_box_ignored_1.id, + *ax_tree(), *inline_box_ignored_1_node, AXNodePosition::BEFORE_TEXT /* child_index */); ASSERT_FALSE(before_inline_box_ignored_1_tree->IsNullPosition()); ASSERT_TRUE(before_inline_box_ignored_1_tree->IsIgnored()); TestPositionType after_inline_box_ignored_1_tree = - AXNodePosition::CreateTreePosition(GetTreeID(), inline_box_ignored_1.id, + AXNodePosition::CreateTreePosition(*ax_tree(), *inline_box_ignored_1_node, 0 /* child_index */); ASSERT_FALSE(after_inline_box_ignored_1_tree->IsNullPosition()); ASSERT_TRUE(after_inline_box_ignored_1_tree->IsIgnored()); @@ -8215,12 +8279,12 @@ TestPositionType before_inline_box_ignored_2_tree = AXNodePosition::CreateTreePosition( - *ax_tree(), inline_box_ignored_2.id, + *ax_tree(), *inline_box_ignored_2_node, AXNodePosition::BEFORE_TEXT /* child_index */); ASSERT_FALSE(before_inline_box_ignored_2_tree->IsNullPosition()); ASSERT_TRUE(before_inline_box_ignored_2_tree->IsIgnored()); TestPositionType after_inline_box_ignored_2_tree = - AXNodePosition::CreateTreePosition(GetTreeID(), inline_box_ignored_2.id, + AXNodePosition::CreateTreePosition(*ax_tree(), *inline_box_ignored_2_node, 0 /* child_index */); ASSERT_FALSE(after_inline_box_ignored_2_tree->IsNullPosition()); ASSERT_TRUE(after_inline_box_ignored_2_tree->IsIgnored()); @@ -8435,6 +8499,9 @@ static_text_empty, inline_box_empty, button_empty, static_text_2, inline_box_2})); + AXNode* inline_box_empty_node = ax_tree()->GetFromId(inline_box_empty.id); + AXNode* button_empty_node = ax_tree()->GetFromId(button_empty.id); + // "<H>elloWorld" TestPositionType before_root = AXNodePosition::CreateTextPosition( GetTreeID(), root.id, 0 /* text_offset */, @@ -8473,11 +8540,11 @@ TestPositionType before_inline_box_empty_tree = AXNodePosition::CreateTreePosition( - *ax_tree(), inline_box_empty.id, + *ax_tree(), *inline_box_empty_node, AXNodePosition::BEFORE_TEXT /* child_index */); ASSERT_FALSE(before_inline_box_empty_tree->IsNullPosition()); TestPositionType after_inline_box_empty_tree = - AXNodePosition::CreateTreePosition(GetTreeID(), inline_box_empty.id, + AXNodePosition::CreateTreePosition(*ax_tree(), *inline_box_empty_node, 0 /* child_index */); ASSERT_FALSE(after_inline_box_empty_tree->IsNullPosition()); @@ -8488,11 +8555,11 @@ TestPositionType before_button_empty_tree = AXNodePosition::CreateTreePosition( - *ax_tree(), button_empty.id, + *ax_tree(), *button_empty_node, AXNodePosition::BEFORE_TEXT /* child_index */); ASSERT_FALSE(before_button_empty_tree->IsNullPosition()); TestPositionType after_button_empty_tree = AXNodePosition::CreateTreePosition( - *ax_tree(), button_empty.id, 0 /* child_index */); + *ax_tree(), *button_empty_node, 0 /* child_index */); ASSERT_FALSE(after_button_empty_tree->IsNullPosition()); // "<W>orld" @@ -8679,6 +8746,10 @@ SetTree(CreateAXTree({root, paragraph, static_text_1, inline_box_1, static_text_2, inline_box_2, button_empty})); + AXNode* inline_box_1_node = ax_tree()->GetFromId(inline_box_1.id); + AXNode* inline_box_2_node = ax_tree()->GetFromId(inline_box_2.id); + AXNode* button_empty_node = ax_tree()->GetFromId(button_empty.id); + TestPositionType before_root = AXNodePosition::CreateTextPosition( GetTreeID(), root.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); @@ -8717,7 +8788,7 @@ ASSERT_FALSE(after_inline_box_1->IsNullPosition()); TestPositionType after_inline_box_1_tree = AXNodePosition::CreateTreePosition( - *ax_tree(), inline_box_1.id, 0 /* child_index */); + *ax_tree(), *inline_box_1_node, 0 /* child_index */); ASSERT_FALSE(after_inline_box_1_tree->IsNullPosition()); // "<H>ello" @@ -8733,11 +8804,11 @@ TestPositionType before_inline_box_2_tree = AXNodePosition::CreateTreePosition( - *ax_tree(), inline_box_2.id, + *ax_tree(), *inline_box_2_node, AXNodePosition::BEFORE_TEXT /* child_index */); ASSERT_FALSE(before_inline_box_2_tree->IsNullPosition()); TestPositionType after_inline_box_2_tree = AXNodePosition::CreateTreePosition( - *ax_tree(), inline_box_2.id, 0 /* child_index */); + *ax_tree(), *inline_box_2_node, 0 /* child_index */); ASSERT_FALSE(after_inline_box_2_tree->IsNullPosition()); TestPositionType before_button_empty = AXNodePosition::CreateTextPosition( @@ -8747,11 +8818,11 @@ TestPositionType before_button_empty_tree = AXNodePosition::CreateTreePosition( - *ax_tree(), button_empty.id, + *ax_tree(), *button_empty_node, AXNodePosition::BEFORE_TEXT /* child_index */); ASSERT_FALSE(before_button_empty_tree->IsNullPosition()); TestPositionType after_button_empty_tree = AXNodePosition::CreateTreePosition( - *ax_tree(), button_empty.id, 0 /* child_index */); + *ax_tree(), *button_empty_node, 0 /* child_index */); ASSERT_FALSE(after_button_empty_tree->IsNullPosition()); TestPositionType parent_position = before_inline_box_1->CreateParentPosition() @@ -8885,7 +8956,7 @@ TEST_F(AXPositionTest, CreateNextLeafTextPosition) { TestPositionType check_box_position = AXNodePosition::CreateTreePosition( - *ax_tree(), root_.id, 1 /* child_index */); + *ax_tree(), GetRootNode(), 1 /* child_index */); ASSERT_NE(nullptr, check_box_position); TestPositionType test_position = check_box_position->CreateNextLeafTextPosition(); @@ -8947,7 +9018,7 @@ EXPECT_TRUE(test_position->IsNullPosition()); TestPositionType text_field_position = AXNodePosition::CreateTreePosition( - *ax_tree(), root_.id, 2 /* child_index */); + *ax_tree(), GetRootNode(), 2 /* child_index */); ASSERT_NE(nullptr, text_field_position); test_position = text_field_position->CreateNextLeafTextPosition(); EXPECT_NE(nullptr, test_position); @@ -8987,7 +9058,7 @@ // Create a "before text" tree position on the second line of the text box. TestPositionType before_text_position = AXNodePosition::CreateTreePosition( - *ax_tree(), inline_box2_.id, AXNodePosition::BEFORE_TEXT); + *ax_tree(), GetInlineBox2Node(), AXNodePosition::BEFORE_TEXT); ASSERT_NE(nullptr, before_text_position); test_position = before_text_position->CreatePreviousLeafTextPosition(); EXPECT_NE(nullptr, test_position); @@ -9022,7 +9093,7 @@ EXPECT_TRUE(test_position->IsNullPosition()); TestPositionType text_field_position = AXNodePosition::CreateTreePosition( - *ax_tree(), text_field_.id, 2 /* child_index */); + *ax_tree(), GetTextFieldNode(), 2 /* child_index */); ASSERT_NE(nullptr, text_field_position); test_position = text_field_position->CreatePreviousLeafTextPosition(); EXPECT_NE(nullptr, test_position); @@ -9062,19 +9133,19 @@ TEST_F(AXPositionTest, CreateNextLeafTreePosition) { TestPositionType root_position = AXNodePosition::CreateTreePosition( - *ax_tree(), root_.id, 0 /* child_index */); + *ax_tree(), GetRootNode(), 0 /* child_index */); ASSERT_TRUE(root_position->IsTreePosition()); TestPositionType button_position = AXNodePosition::CreateTreePosition( - *ax_tree(), button_.id, AXNodePosition::BEFORE_TEXT); + *ax_tree(), GetButtonNode(), AXNodePosition::BEFORE_TEXT); TestPositionType checkbox_position = AXNodePosition::CreateTreePosition( - *ax_tree(), check_box_.id, AXNodePosition::BEFORE_TEXT); + *ax_tree(), GetCheckBoxNode(), AXNodePosition::BEFORE_TEXT); TestPositionType inline_box1_position = AXNodePosition::CreateTreePosition( - *ax_tree(), inline_box1_.id, AXNodePosition::BEFORE_TEXT); + *ax_tree(), GetInlineBox1Node(), AXNodePosition::BEFORE_TEXT); TestPositionType line_break_position = AXNodePosition::CreateTreePosition( - *ax_tree(), line_break_.id, AXNodePosition::BEFORE_TEXT); + *ax_tree(), GetLineBreakNode(), AXNodePosition::BEFORE_TEXT); TestPositionType inline_box2_position = AXNodePosition::CreateTreePosition( - *ax_tree(), inline_box2_.id, AXNodePosition::BEFORE_TEXT); + *ax_tree(), GetInlineBox2Node(), AXNodePosition::BEFORE_TEXT); TestPositionType test_position = root_position->CreateNextLeafTreePosition(); EXPECT_TRUE(test_position->IsTreePosition()); @@ -9121,17 +9192,17 @@ TEST_F(AXPositionTest, CreatePreviousLeafTreePosition) { TestPositionType inline_box2_position = AXNodePosition::CreateTreePosition( - *ax_tree(), inline_box2_.id, AXNodePosition::BEFORE_TEXT); + *ax_tree(), GetInlineBox2Node(), AXNodePosition::BEFORE_TEXT); ASSERT_TRUE(inline_box2_position->IsTreePosition()); TestPositionType line_break_position = AXNodePosition::CreateTreePosition( - *ax_tree(), line_break_.id, AXNodePosition::BEFORE_TEXT); + *ax_tree(), GetLineBreakNode(), AXNodePosition::BEFORE_TEXT); TestPositionType inline_box1_position = AXNodePosition::CreateTreePosition( - *ax_tree(), inline_box1_.id, AXNodePosition::BEFORE_TEXT); + *ax_tree(), GetInlineBox1Node(), AXNodePosition::BEFORE_TEXT); TestPositionType checkbox_position = AXNodePosition::CreateTreePosition( - *ax_tree(), check_box_.id, AXNodePosition::BEFORE_TEXT); + *ax_tree(), GetCheckBoxNode(), AXNodePosition::BEFORE_TEXT); TestPositionType button_position = AXNodePosition::CreateTreePosition( - *ax_tree(), button_.id, AXNodePosition::BEFORE_TEXT); + *ax_tree(), GetButtonNode(), AXNodePosition::BEFORE_TEXT); TestPositionType test_position = inline_box2_position->CreatePreviousLeafTreePosition(); @@ -10281,7 +10352,7 @@ TEST_F(AXPositionTest, ReciprocalCreateNextAndPreviousCharacterPosition) { TestPositionType tree_position = AXNodePosition::CreateTreePosition( - *ax_tree(), root_.id, 0 /* child_index */); + *ax_tree(), GetRootNode(), 0 /* child_index */); TestPositionType text_position = tree_position->AsTextPosition(); ASSERT_NE(nullptr, text_position); ASSERT_TRUE(text_position->IsTextPosition()); @@ -10299,7 +10370,7 @@ } tree_position = AXNodePosition::CreateTreePosition( - *ax_tree(), root_.id, root_.child_ids.size() /* child_index */); + *ax_tree(), GetRootNode(), root_.child_ids.size() /* child_index */); text_position = tree_position->AsTextPosition(); ASSERT_NE(nullptr, text_position); ASSERT_TRUE(text_position->IsTextPosition()); @@ -10359,10 +10430,10 @@ // Child indices must match. TestPositionType button_position1 = AXNodePosition::CreateTreePosition( - *ax_tree(), root_.id, 0 /* child_index */); + *ax_tree(), GetRootNode(), 0 /* child_index */); ASSERT_NE(nullptr, button_position1); TestPositionType button_position2 = AXNodePosition::CreateTreePosition( - *ax_tree(), root_.id, 0 /* child_index */); + *ax_tree(), GetRootNode(), 0 /* child_index */); ASSERT_NE(nullptr, button_position2); EXPECT_EQ(*button_position1, *button_position2); @@ -10374,7 +10445,7 @@ // An invalid position should not be equivalent to an "after children" // position. TestPositionType tree_position1 = AXNodePosition::CreateTreePosition( - GetTreeID(), root_.id, 3 /* child_index */); + *ax_tree(), GetRootNode(), 3 /* child_index */); ASSERT_NE(nullptr, tree_position1); TestPositionType tree_position2 = AXNodePosition::CreateNullPosition(); ASSERT_NE(nullptr, tree_position2); @@ -10382,19 +10453,19 @@ // Two "after children" positions on the same node should be equivalent. tree_position1 = AXNodePosition::CreateTreePosition( - *ax_tree(), text_field_.id, 3 /* child_index */); + *ax_tree(), GetTextFieldNode(), 3 /* child_index */); ASSERT_NE(nullptr, tree_position1); tree_position2 = AXNodePosition::CreateTreePosition( - *ax_tree(), text_field_.id, 3 /* child_index */); + *ax_tree(), GetTextFieldNode(), 3 /* child_index */); ASSERT_NE(nullptr, tree_position2); EXPECT_EQ(*tree_position1, *tree_position2); // Two "before text" positions on the same node should be equivalent. tree_position1 = AXNodePosition::CreateTreePosition( - *ax_tree(), inline_box1_.id, AXNodePosition::BEFORE_TEXT); + *ax_tree(), GetInlineBox1Node(), AXNodePosition::BEFORE_TEXT); ASSERT_NE(nullptr, tree_position1); tree_position2 = AXNodePosition::CreateTreePosition( - *ax_tree(), inline_box1_.id, AXNodePosition::BEFORE_TEXT); + *ax_tree(), GetInlineBox1Node(), AXNodePosition::BEFORE_TEXT); ASSERT_NE(nullptr, tree_position2); EXPECT_EQ(*tree_position1, *tree_position2); @@ -10773,44 +10844,50 @@ CreateAXTree({root_1, paragraph_2, link_3, static_text_4, inline_box_5, paragraph_6, static_text_7, inline_box_8})); + AXNode* root_1_node = ax_tree()->GetFromId(root_1.id); + AXNode* paragraph_2_node = ax_tree()->GetFromId(paragraph_2.id); + AXNode* paragraph_6_node = ax_tree()->GetFromId(paragraph_6.id); + AXNode* inline_box_5_node = ax_tree()->GetFromId(inline_box_5.id); + AXNode* inline_box_8_node = ax_tree()->GetFromId(inline_box_8.id); + TestPositionType before_root_1 = AXNodePosition::CreateTreePosition( - *ax_tree(), root_1.id, 0 /* child_index */); + *ax_tree(), *root_1_node, 0 /* child_index */); ASSERT_NE(nullptr, before_root_1); TestPositionType middle_root_1 = AXNodePosition::CreateTreePosition( - *ax_tree(), root_1.id, 1 /* child_index */); + *ax_tree(), *root_1_node, 1 /* child_index */); ASSERT_NE(nullptr, middle_root_1); TestPositionType after_root_1 = AXNodePosition::CreateTreePosition( - *ax_tree(), root_1.id, 2 /* child_index */); + *ax_tree(), *root_1_node, 2 /* child_index */); ASSERT_NE(nullptr, after_root_1); TestPositionType before_paragraph_2 = AXNodePosition::CreateTreePosition( - *ax_tree(), paragraph_2.id, 0 /* child_index */); + *ax_tree(), *paragraph_2_node, 0 /* child_index */); ASSERT_NE(nullptr, before_paragraph_2); TestPositionType after_paragraph_2 = AXNodePosition::CreateTreePosition( - *ax_tree(), paragraph_2.id, 1 /* child_index */); + *ax_tree(), *paragraph_2_node, 1 /* child_index */); ASSERT_NE(nullptr, after_paragraph_2); TestPositionType before_paragraph_6 = AXNodePosition::CreateTreePosition( - *ax_tree(), paragraph_6.id, 0 /* child_index */); + *ax_tree(), *paragraph_6_node, 0 /* child_index */); ASSERT_NE(nullptr, before_paragraph_6); TestPositionType after_paragraph_6 = AXNodePosition::CreateTreePosition( - *ax_tree(), paragraph_6.id, 1 /* child_index */); + *ax_tree(), *paragraph_6_node, 1 /* child_index */); ASSERT_NE(nullptr, before_paragraph_6); TestPositionType before_inline_box_5 = AXNodePosition::CreateTreePosition( - *ax_tree(), inline_box_5.id, + *ax_tree(), *inline_box_5_node, AXNodePosition::BEFORE_TEXT /* child_index */); ASSERT_NE(nullptr, before_inline_box_5); TestPositionType after_inline_box_5 = AXNodePosition::CreateTreePosition( - *ax_tree(), inline_box_5.id, 0 /* child_index */); + *ax_tree(), *inline_box_5_node, 0 /* child_index */); ASSERT_NE(nullptr, after_inline_box_5); TestPositionType before_inline_box_8 = AXNodePosition::CreateTreePosition( - *ax_tree(), inline_box_8.id, + *ax_tree(), *inline_box_8_node, AXNodePosition::BEFORE_TEXT /* child_index */); ASSERT_NE(nullptr, before_inline_box_8); TestPositionType after_inline_box_8 = AXNodePosition::CreateTreePosition( - *ax_tree(), inline_box_8.id, 0 /* child_index */); + *ax_tree(), *inline_box_8_node, 0 /* child_index */); ASSERT_NE(nullptr, after_inline_box_8); EXPECT_EQ(*before_root_1, *before_paragraph_2); @@ -11071,31 +11148,31 @@ EXPECT_FALSE(*null_position1 > *null_position2); TestPositionType button_position1 = AXNodePosition::CreateTreePosition( - *ax_tree(), root_.id, 0 /* child_index */); + *ax_tree(), GetRootNode(), 0 /* child_index */); ASSERT_NE(nullptr, button_position1); TestPositionType button_position2 = AXNodePosition::CreateTreePosition( - *ax_tree(), root_.id, 1 /* child_index */); + *ax_tree(), GetRootNode(), 1 /* child_index */); ASSERT_NE(nullptr, button_position2); EXPECT_LT(*button_position1, *button_position2); EXPECT_GT(*button_position2, *button_position1); TestPositionType tree_position1 = AXNodePosition::CreateTreePosition( - *ax_tree(), text_field_.id, 2 /* child_index */); + *ax_tree(), GetTextFieldNode(), 2 /* child_index */); ASSERT_NE(nullptr, tree_position1); // An "after children" position. TestPositionType tree_position2 = AXNodePosition::CreateTreePosition( - *ax_tree(), text_field_.id, 3 /* child_index */); + *ax_tree(), GetTextFieldNode(), 3 /* child_index */); ASSERT_NE(nullptr, tree_position2); EXPECT_LT(*tree_position1, *tree_position2); EXPECT_GT(*tree_position2, *tree_position1); // A "before text" position. tree_position1 = AXNodePosition::CreateTreePosition( - *ax_tree(), inline_box1_.id, AXNodePosition::BEFORE_TEXT); + *ax_tree(), GetInlineBox1Node(), AXNodePosition::BEFORE_TEXT); ASSERT_NE(nullptr, tree_position1); // An "after text" position. tree_position2 = AXNodePosition::CreateTreePosition( - *ax_tree(), inline_box1_.id, 0 /* child_index */); + *ax_tree(), GetInlineBox1Node(), 0 /* child_index */); ASSERT_NE(nullptr, tree_position2); EXPECT_LT(*tree_position1, *tree_position2); EXPECT_GT(*tree_position2, *tree_position1); @@ -11215,10 +11292,10 @@ EXPECT_TRUE(null_position2->IsNullPosition()); TestPositionType tree_position1 = AXNodePosition::CreateTreePosition( - *ax_tree(), root_.id, 2 /* child_index */); + *ax_tree(), GetRootNode(), 2 /* child_index */); ASSERT_NE(nullptr, tree_position1); TestPositionType tree_position2 = AXNodePosition::CreateTreePosition( - *ax_tree(), text_field_.id, 3 /* child_index */); + *ax_tree(), GetTextFieldNode(), 3 /* child_index */); ASSERT_NE(nullptr, tree_position2); swap(*tree_position1, *tree_position2); @@ -12127,6 +12204,8 @@ embed_object.AddChildTreeId(child_tree_id); SetTree(CreateAXTree({root, embed_object})); + AXNode* embed_object_node = ax_tree()->GetFromId(embed_object.id); + // Create tree manager for child tree. AXNodeData child_root; child_root.id = 1; @@ -12143,7 +12222,7 @@ // Verify that kEmbeddedObject node with child tree is not treated as an // empty object. TestPositionType tree_position = AXNodePosition::CreateTreePosition( - *ax_tree(), embed_object.id, 0 /* child_index */); + *ax_tree(), *embed_object_node, 0 /* child_index */); ASSERT_TRUE(tree_position->IsTreePosition()); EXPECT_FALSE(tree_position->IsLeaf()); }
diff --git a/ui/accessibility/ax_position.h b/ui/accessibility/ax_position.h index a929694..f7c7025 100644 --- a/ui/accessibility/ax_position.h +++ b/ui/accessibility/ax_position.h
@@ -254,9 +254,9 @@ } static AXPositionInstance CreateTreePosition(const AXTree& tree, - AXNodeID anchor_id, + const AXNode& anchor, int child_index) { - return CreateTreePosition(tree.GetAXTreeID(), anchor_id, child_index); + return CreateTreePosition(tree.GetAXTreeID(), anchor.id(), child_index); } static AXPositionInstance CreateTreePositionAtStartOfAnchor( @@ -265,13 +265,13 @@ // - For a leaf, the child index will be BEFORE_TEXT. // - Otherwise the child index will be 0. int child_index = IsLeafNodeForTreePosition(anchor) ? BEFORE_TEXT : 0; - return CreateTreePosition(*anchor.tree(), anchor.id(), child_index); + return CreateTreePosition(*anchor.tree(), anchor, child_index); } static AXPositionInstance CreateTreePositionAtEndOfAnchor( const AXNode& anchor) { // Initialize the child index to the anchor's child count. - return CreateTreePosition(*anchor.tree(), anchor.id(), + return CreateTreePosition(*anchor.tree(), anchor, anchor.GetChildCountCrossingTreeBoundary()); } @@ -2444,9 +2444,6 @@ const AXTree* tree = parent_anchor->tree(); DCHECK(tree); - AXNodeID parent_anchor_id = parent_anchor->id(); - DCHECK_NE(parent_anchor_id, kInvalidAXNodeID); - switch (kind_) { case AXPositionKind::NULL_POSITION: NOTREACHED(); @@ -2473,7 +2470,7 @@ // last child in its parent anchor. int child_index = AnchorIndexInParent(); if (AtEndOfAnchor()) - return CreateTreePosition(*tree, parent_anchor_id, (child_index + 1)); + return CreateTreePosition(*tree, *parent_anchor, (child_index + 1)); switch (move_direction) { case ax::mojom::MoveDirection::kNone: @@ -2490,7 +2487,7 @@ // "AnchorIndexInParent" always returns a child index that is before // any "object replacement character" in our parent, we use that for // both situations. - return CreateTreePosition(*tree, parent_anchor_id, child_index); + return CreateTreePosition(*tree, *parent_anchor, child_index); case ax::mojom::MoveDirection::kForward: // "move_direction" is only important when this position is an // "embedded object in parent", i.e., when this position's anchor is @@ -2502,7 +2499,7 @@ // "AnchorIndexInParent" for the child index. if (!AtStartOfAnchor() && IsEmbeddedObjectInParent()) ++child_index; - return CreateTreePosition(*tree, parent_anchor_id, child_index); + return CreateTreePosition(*tree, *parent_anchor, child_index); } } @@ -2623,6 +2620,7 @@ // breaks, which would create false positives. const AXTreeID& parent_tree_id = parent_anchor->tree()->GetAXTreeID(); + const AXNodeID& parent_anchor_id = parent_anchor->id(); AXPositionInstance parent_position = CreateTextPosition( parent_tree_id, parent_anchor_id, parent_offset, parent_affinity); if (AtEndOfAnchor() && !parent_position->AtStartOfAnchor() &&
diff --git a/ui/accessibility/ax_range_unittest.cc b/ui/accessibility/ax_range_unittest.cc index 3020630..d9be4fc 100644 --- a/ui/accessibility/ax_range_unittest.cc +++ b/ui/accessibility/ax_range_unittest.cc
@@ -124,6 +124,20 @@ protected: void SetUp() override; + const AXNode& GetRootNode() const { return *ax_tree()->GetFromId(root_.id); } + + const AXNode& GetButtonNode() const { + return *ax_tree()->GetFromId(button_.id); + } + + const AXNode& GetTextFieldNode() const { + return *ax_tree()->GetFromId(text_field_.id); + } + + const AXNode& GetInlineBox1Node() const { + return *ax_tree()->GetFromId(inline_box1_.id); + } + AXNodeData root_; AXNodeData div1_; AXNodeData div2_; @@ -515,7 +529,7 @@ EXPECT_TRUE(null_range.IsNull()); TestPositionInstance tree_position = AXNodePosition::CreateTreePosition( - *ax_tree(), button_.id, 0 /* child_index */); + *ax_tree(), GetButtonNode(), 0 /* child_index */); TestPositionInstance text_position1 = AXNodePosition::CreateTextPosition( GetTreeID(), line_break1_.id, 1 /* text_offset */, ax::mojom::TextAffinity::kDownstream); @@ -543,13 +557,13 @@ EXPECT_FALSE(null_range.IsCollapsed()); TestPositionInstance tree_position1 = AXNodePosition::CreateTreePosition( - *ax_tree(), text_field_.id, 0 /* child_index */); + *ax_tree(), GetTextFieldNode(), 0 /* child_index */); // Since there are no children in inline_box1_, the following is essentially // an "after text" position which should not compare as equivalent to the // above tree position which is a "before text" position inside the text // field. TestPositionInstance tree_position2 = AXNodePosition::CreateTreePosition( - *ax_tree(), inline_box1_.id, 0 /* child_index */); + *ax_tree(), GetInlineBox1Node(), 0 /* child_index */); TestPositionInstance text_position1 = AXNodePosition::CreateTextPosition( GetTreeID(), static_text1_.id, 0 /* text_offset */, @@ -821,7 +835,7 @@ TestRangeIterator(ending_at_start_position_backward_range); TestPositionInstance range_start = AXNodePosition::CreateTreePosition( - *ax_tree(), root_.id, 0 /* child_index */); + *ax_tree(), GetRootNode(), 0 /* child_index */); TestPositionInstance range_end = AXNodePosition::CreateTextPosition( GetTreeID(), root_.id, ALL_TEXT.length() /* text_offset */, ax::mojom::TextAffinity::kDownstream); @@ -853,7 +867,7 @@ // character of the root, i.e. at the last character of the second line in the // text field. TestPositionInstance start = AXNodePosition::CreateTreePosition( - *ax_tree(), root_.id, 0 /* child_index */); + *ax_tree(), GetRootNode(), 0 /* child_index */); TestPositionInstance end = AXNodePosition::CreateTextPosition( GetTreeID(), root_.id, ALL_TEXT.length() /* text_offset */, ax::mojom::TextAffinity::kDownstream); @@ -969,7 +983,7 @@ // root_ to static_text2_'s end std::u16string text_up_to_text2_end = BUTTON.substr(0).append(LINE_1).append(NEWLINE).append(LINE_2); - start = AXNodePosition::CreateTreePosition(GetTreeID(), root_.id, + start = AXNodePosition::CreateTreePosition(*ax_tree(), GetRootNode(), 0 /* child_index */); end = AXNodePosition::CreateTextPosition( GetTreeID(), static_text2_.id, LINE_2.length() /* text_offset */, @@ -990,7 +1004,7 @@ // root_ to static_text2_'s start std::u16string text_up_to_text2_start = BUTTON.substr(0).append(LINE_1).append(NEWLINE); - start = AXNodePosition::CreateTreePosition(GetTreeID(), root_.id, + start = AXNodePosition::CreateTreePosition(*ax_tree(), GetRootNode(), 0 /* child_index */); end = AXNodePosition::CreateTreePosition(GetTreeID(), static_text2_.id, 0 /* child_index */); @@ -1031,7 +1045,7 @@ // root_ to static_text2_'s start with offsets std::u16string text_up_to_text2_tree_start = BUTTON.substr(0).append(TEXT_FIELD.substr(0, 10)); - start = AXNodePosition::CreateTreePosition(GetTreeID(), root_.id, + start = AXNodePosition::CreateTreePosition(*ax_tree(), GetRootNode(), 0 /* child_index */); end = AXNodePosition::CreateTextPosition( GetTreeID(), static_text2_.id, 3 /* text_offset */, @@ -1053,12 +1067,12 @@ TEST_F(AXRangeTest, GetTextWithEmptyRanges) { // empty string with non-leaf tree position TestPositionInstance start = AXNodePosition::CreateTreePosition( - *ax_tree(), root_.id, 0 /* child_index */); + *ax_tree(), GetRootNode(), 0 /* child_index */); TestPositionRange non_leaf_tree_range(start->Clone(), start->Clone()); EXPECT_EQ(EMPTY, non_leaf_tree_range.GetText()); // empty string with leaf tree position - start = AXNodePosition::CreateTreePosition(GetTreeID(), inline_box1_.id, + start = AXNodePosition::CreateTreePosition(*ax_tree(), GetInlineBox1Node(), 0 /* child_index */); TestPositionRange leaf_empty_range(start->Clone(), start->Clone()); EXPECT_EQ(EMPTY, leaf_empty_range.GetText());
diff --git a/ui/accessibility/platform/ax_platform_node_textrangeprovider_win_unittest.cc b/ui/accessibility/platform/ax_platform_node_textrangeprovider_win_unittest.cc index 6a322ff..3a43b3f5 100644 --- a/ui/accessibility/platform/ax_platform_node_textrangeprovider_win_unittest.cc +++ b/ui/accessibility/platform/ax_platform_node_textrangeprovider_win_unittest.cc
@@ -7119,11 +7119,12 @@ update.nodes = {root_1, generic_container_2, heading_3, static_text_4, inline_box_5, generic_container_6, button_7}; - Init(update); + AXTree* tree = Init(update); AXNode* root_node = GetRoot(); + AXNode* generic_container_2_node = tree->GetFromId(generic_container_2.id); AXNodePosition::AXPositionInstance range_start = - AXNodePosition::CreateTreePosition(*GetTree(), generic_container_2.id, + AXNodePosition::CreateTreePosition(*tree, *generic_container_2_node, /*child_index*/ 3); AXNodePosition::AXPositionInstance range_end = range_start->Clone(); @@ -7137,11 +7138,11 @@ generic_container_2.child_ids = {heading_3.id, button_7.id}; AXTreeUpdate test_update; test_update.nodes = {generic_container_2}; - ASSERT_TRUE(GetTree()->Unserialize(test_update)); + ASSERT_TRUE(tree->Unserialize(test_update)); root_1.child_ids = {}; test_update.nodes = {root_1}; - ASSERT_TRUE(GetTree()->Unserialize(test_update)); + ASSERT_TRUE(tree->Unserialize(test_update)); } TEST_F(AXPlatformNodeTextRangeProviderTest,
diff --git a/ui/accessibility/platform/test_ax_node_wrapper.cc b/ui/accessibility/platform/test_ax_node_wrapper.cc index 2ad5d982..92c1245 100644 --- a/ui/accessibility/platform/test_ax_node_wrapper.cc +++ b/ui/accessibility/platform/test_ax_node_wrapper.cc
@@ -157,7 +157,7 @@ return ui::AXNodePosition::CreateTextPosition( GetTreeData().tree_id, node_->id(), offset, affinity); } - return AXNodePosition::CreateTreePosition(*tree_, node_->id(), offset); + return AXNodePosition::CreateTreePosition(*tree_, *node_, offset); } AXNodePosition::AXPositionInstance TestAXNodeWrapper::CreateTextPositionAt(
diff --git a/ui/android/java/src/org/chromium/ui/resources/dynamics/ViewResourceAdapter.java b/ui/android/java/src/org/chromium/ui/resources/dynamics/ViewResourceAdapter.java index c37ae7f..1ca3257 100644 --- a/ui/android/java/src/org/chromium/ui/resources/dynamics/ViewResourceAdapter.java +++ b/ui/android/java/src/org/chromium/ui/resources/dynamics/ViewResourceAdapter.java
@@ -194,7 +194,12 @@ /** Returns the dirty rect that will be drawn on capture. */ @VisibleForTesting - protected Rect getDirtyRect() { + public Rect getDirtyRect() { return mDirtyRect; } + + /** Clears the contents of the current dirty rect. */ + protected void setDirtyRectEmpty() { + mDirtyRect.setEmpty(); + } }
diff --git a/ui/base/test/skia_gold_matching_algorithm.h b/ui/base/test/skia_gold_matching_algorithm.h index 8fb20a96..21eb893 100644 --- a/ui/base/test/skia_gold_matching_algorithm.h +++ b/ui/base/test/skia_gold_matching_algorithm.h
@@ -46,7 +46,6 @@ // Append the algorithm parameter to |cmd|. virtual void AppendAlgorithmToCmdline(base::CommandLine& cmd) const; - protected: // The algorithm name for commandline. virtual std::string GetCommandLineSwitchName() const = 0; };
diff --git a/ui/color/color_id.h b/ui/color/color_id.h index ccbfada8..a0ea9923 100644 --- a/ui/color/color_id.h +++ b/ui/color/color_id.h
@@ -237,6 +237,9 @@ E_CPONLY(kColorOverlayScrollbarStrokeHoveredLight) \ E_CPONLY(kColorProgressBar) \ E_CPONLY(kColorProgressBarPaused) \ + E_CPONLY(kColorReadAnythingForegroundDark) \ + E_CPONLY(kColorReadAnythingForegroundLight) \ + E_CPONLY(kColorReadAnythingForegroundYellow) \ E_CPONLY(kColorSeparator) \ E_CPONLY(kColorShadowBase) \ E_CPONLY(kColorShadowValueAmbientShadowElevationSixteen) \
diff --git a/ui/color/ui_color_mixer.cc b/ui/color/ui_color_mixer.cc index 9f16d549f..2b8697c 100644 --- a/ui/color/ui_color_mixer.cc +++ b/ui/color/ui_color_mixer.cc
@@ -151,6 +151,9 @@ gfx::kGoogleGreyAlpha500); mixer[kColorProgressBarPaused] = {kColorDisabledForeground}; mixer[kColorProgressBar] = {kColorAccent}; + mixer[kColorReadAnythingForegroundDark] = {gfx::kGoogleGrey200}; + mixer[kColorReadAnythingForegroundLight] = {gfx::kGoogleGrey800}; + mixer[kColorReadAnythingForegroundYellow] = {gfx::kGoogleGrey800}; mixer[kColorSeparator] = {kColorMidground}; mixer[kColorShadowBase] = {dark_mode ? SK_ColorBLACK : gfx::kGoogleGrey800}; mixer[kColorShadowValueAmbientShadowElevationThree] =
diff --git a/ui/file_manager/file_manager/common/js/volume_manager_types.js b/ui/file_manager/file_manager/common/js/volume_manager_types.js index 63e25e4..eff2a93 100644 --- a/ui/file_manager/file_manager/common/js/volume_manager_types.js +++ b/ui/file_manager/file_manager/common/js/volume_manager_types.js
@@ -203,6 +203,7 @@ UNSUPPORTED_FILESYSTEM: 'error_unsupported_filesystem', INVALID_ARCHIVE: 'error_invalid_archive', NEED_PASSWORD: 'error_need_password', + BUSY: 'error_busy', }; Object.freeze(VolumeManagerCommon.VolumeError);
diff --git a/ui/gfx/BUILD.gn b/ui/gfx/BUILD.gn index 0fc8d92..dbeba7d1 100644 --- a/ui/gfx/BUILD.gn +++ b/ui/gfx/BUILD.gn
@@ -131,6 +131,7 @@ "text_elider.h", "text_utils.cc", "text_utils.h", + "ubidi_deleter.h", "ui_gfx_exports.cc", "utf16_indexing.cc", "utf16_indexing.h",
diff --git a/ui/gfx/bidi_line_iterator.h b/ui/gfx/bidi_line_iterator.h index 6cb06b7..8d85d13 100644 --- a/ui/gfx/bidi_line_iterator.h +++ b/ui/gfx/bidi_line_iterator.h
@@ -12,15 +12,11 @@ #include "third_party/icu/source/common/unicode/ubidi.h" #include "third_party/icu/source/common/unicode/uchar.h" #include "ui/gfx/gfx_export.h" +#include "ui/gfx/ubidi_deleter.h" namespace ui { namespace gfx { -class UBiDiDeleter { - public: - void operator()(UBiDi* ptr) { ubidi_close(ptr); } -}; - // A simple wrapper class for the bidirectional iterator of ICU. // This class uses the bidirectional iterator of ICU to split a line of // bidirectional texts into visual runs in its display order.
diff --git a/ui/gfx/ubidi_deleter.h b/ui/gfx/ubidi_deleter.h new file mode 100644 index 0000000..5476e8d9 --- /dev/null +++ b/ui/gfx/ubidi_deleter.h
@@ -0,0 +1,21 @@ +// 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_GFX_UBIDI_DELETER_H_ +#define UI_GFX_UBIDI_DELETER_H_ + +#include "third_party/icu/source/common/unicode/ubidi.h" + +namespace ui::gfx { + +struct UBiDiDeleter { + void operator()(UBiDi* bidi) { + if (bidi) + ubidi_close(bidi); + } +}; + +} // namespace ui::gfx + +#endif // UI_GFX_UBIDI_DELETER_H_
diff --git a/ui/ozone/platform/wayland/host/org_gnome_mutter_idle_monitor.cc b/ui/ozone/platform/wayland/host/org_gnome_mutter_idle_monitor.cc index f780034..4951911 100644 --- a/ui/ozone/platform/wayland/host/org_gnome_mutter_idle_monitor.cc +++ b/ui/ozone/platform/wayland/host/org_gnome_mutter_idle_monitor.cc
@@ -63,7 +63,7 @@ dbus_proxy->CallMethod( &name_has_owner_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT, base::BindOnce(&OrgGnomeMutterIdleMonitor::OnServiceHasOwner, - weak_factory_.GetWeakPtr())); + weak_factory_.GetMutableWeakPtr())); } return base::Seconds(0);
diff --git a/ui/ozone/platform/wayland/host/shell_toplevel_wrapper.h b/ui/ozone/platform/wayland/host/shell_toplevel_wrapper.h index 877bbe8..de951aa 100644 --- a/ui/ozone/platform/wayland/host/shell_toplevel_wrapper.h +++ b/ui/ozone/platform/wayland/host/shell_toplevel_wrapper.h
@@ -59,15 +59,6 @@ // Unsets a native window from fullscreen state. virtual void UnSetFullscreen() = 0; -#if BUILDFLAG(IS_CHROMEOS_LACROS) - // Sets a native window's immersive mode. - virtual void SetUseImmersiveMode(bool immersive) = 0; - - // Whether the shell supports top level immersive status. The deprecated - // immersive status used to be set on the surface level. - virtual bool SupportsTopLevelImmersiveStatus() const = 0; -#endif - // Sets a native window to minimized state. virtual void SetMinimized() = 0;
diff --git a/ui/ozone/platform/wayland/host/wayland_toplevel_window.cc b/ui/ozone/platform/wayland/host/wayland_toplevel_window.cc index 72c398f..f5bd38fb 100644 --- a/ui/ozone/platform/wayland/host/wayland_toplevel_window.cc +++ b/ui/ozone/platform/wayland/host/wayland_toplevel_window.cc
@@ -228,17 +228,7 @@ return; } - // Unset needs to be used instead of SetWindowState in order to prevent - // flickering on restore. This is because exo will emit a configure event - // on restore. If exo and ozone have different window states, a flicker - // will occur from the rapid switching of states. - if (state_ == PlatformWindowState::kFullScreen) { - shell_toplevel_->UnSetFullscreen(); - } else if (state_ == PlatformWindowState::kMaximized) { - shell_toplevel_->UnSetMaximized(); - } else { - SetWindowState(PlatformWindowState::kNormal); - } + SetWindowState(PlatformWindowState::kNormal); } PlatformWindowState WaylandToplevelWindow::GetPlatformWindowState() const { @@ -424,13 +414,6 @@ } else { state_ = PlatformWindowState::kNormal; } -#if BUILDFLAG(IS_CHROMEOS_LACROS) - if (shell_toplevel_ && shell_toplevel()->SupportsTopLevelImmersiveStatus() && - is_immersive_fullscreen_ != window_states.is_immersive_fullscreen) { - is_immersive_fullscreen_ = window_states.is_immersive_fullscreen; - delegate()->OnImmersiveModeChanged(is_immersive_fullscreen_); - } -#endif const bool did_send_delegate_notification = !!requested_window_show_state_count_; @@ -705,21 +688,12 @@ } } -#if BUILDFLAG(IS_CHROMEOS_LACROS) void WaylandToplevelWindow::SetImmersiveFullscreenStatus(bool status) { - if (shell_toplevel_ && shell_toplevel_->SupportsTopLevelImmersiveStatus()) { - shell_toplevel_->SetUseImmersiveMode(status); - } else if (aura_surface_ && - zaura_surface_get_version(aura_surface_.get()) >= - ZAURA_SURFACE_SET_FULLSCREEN_MODE_SINCE_VERSION) { + if (aura_surface_ && zaura_surface_get_version(aura_surface_.get()) >= + ZAURA_SURFACE_SET_FULLSCREEN_MODE_SINCE_VERSION) { auto mode = status ? ZAURA_SURFACE_FULLSCREEN_MODE_IMMERSIVE : ZAURA_SURFACE_FULLSCREEN_MODE_PLAIN; zaura_surface_set_fullscreen_mode(aura_surface_.get(), mode); - // TODO(ffred): the deprecated immersive mode flow used to transition - // immediately after sending the request to exo. This is needed to - // maintain backwards compatibility. Remove once we have rolled past the - // supported skew. - delegate()->OnImmersiveModeChanged(status); } else { // TODO(https://crbug.com/1113900): Implement AuraShell support for // non-browser windows and replace this if-else clause by a DCHECK. @@ -727,7 +701,6 @@ << "Implement AuraShell support for non-browser windows."; } } -#endif void WaylandToplevelWindow::ShowSnapPreview( WaylandWindowSnapDirection snap_direction, @@ -970,10 +943,7 @@ this); } zaura_surface_set_occlusion_tracking(aura_surface_.get()); - -#if BUILDFLAG(IS_CHROMEOS_LACROS) SetImmersiveFullscreenStatus(false); -#endif // We pass the value of `z_order_` to the `shell_toplevel_` here in order to // set the initial z order of the window.
diff --git a/ui/ozone/platform/wayland/host/wayland_toplevel_window.h b/ui/ozone/platform/wayland/host/wayland_toplevel_window.h index 74cb90f..7bbaaf8 100644 --- a/ui/ozone/platform/wayland/host/wayland_toplevel_window.h +++ b/ui/ozone/platform/wayland/host/wayland_toplevel_window.h
@@ -145,9 +145,7 @@ // WaylandExtension: void StartWindowDraggingSessionIfNeeded(bool allow_system_drag) override; -#if BUILDFLAG(IS_CHROMEOS_LACROS) void SetImmersiveFullscreenStatus(bool status) override; -#endif void ShowSnapPreview(WaylandWindowSnapDirection snap, bool allow_haptic_feedback) override; void CommitSnap(WaylandWindowSnapDirection snap) override; @@ -233,8 +231,6 @@ bool is_active_ = false; #if BUILDFLAG(IS_CHROMEOS_LACROS) - bool is_immersive_fullscreen_ = false; - // Unique ID for this window. May be shared over non-Wayland IPC transports // (e.g. mojo) to identify the window. std::string window_unique_id_;
diff --git a/ui/ozone/platform/wayland/host/wayland_window.h b/ui/ozone/platform/wayland/host/wayland_window.h index 5fc21542..f0f75d4 100644 --- a/ui/ozone/platform/wayland/host/wayland_window.h +++ b/ui/ozone/platform/wayland/host/wayland_window.h
@@ -221,9 +221,6 @@ struct WindowStates { bool is_maximized = false; bool is_fullscreen = false; -#if BUILDFLAG(IS_CHROMEOS_LACROS) - bool is_immersive_fullscreen = false; -#endif bool is_activated = false; bool is_snapped_primary = false; bool is_snapped_secondary = false;
diff --git a/ui/ozone/platform/wayland/host/wayland_window_unittest.cc b/ui/ozone/platform/wayland/host/wayland_window_unittest.cc index 8f73732b..7aa5f89 100644 --- a/ui/ozone/platform/wayland/host/wayland_window_unittest.cc +++ b/ui/ozone/platform/wayland/host/wayland_window_unittest.cc
@@ -783,8 +783,6 @@ } TEST_P(WaylandWindowTest, SetFullscreenAndRestore) { - uint32_t serial = 0; - // Make sure the window is initialized to normal state from the beginning. EXPECT_EQ(PlatformWindowState::kNormal, window_->GetPlatformWindowState()); @@ -807,12 +805,7 @@ EXPECT_CALL(*GetXdgToplevel(), UnsetFullscreen()); EXPECT_CALL(delegate_, OnWindowStateChanged(_, _)).Times(1); window_->Restore(); - states = InitializeWlArrayWithActivatedState(); - SendConfigureEvent(xdg_surface_, {0, 0}, ++serial, states.get()); - Sync(); EXPECT_EQ(window_->GetPlatformWindowState(), PlatformWindowState::kNormal); - VerifyAndClearExpectations(); - // Reinitialize wl_array, which removes previous old states. states = InitializeWlArrayWithActivatedState(); SendConfigureEvent(xdg_surface_, {0, 0}, 3, states.get()); @@ -1031,7 +1024,7 @@ SendConfigureEvent(xdg_surface_, {0, 0}, ++serial, empty_state.get()); Sync(); - auto states = MakeStateArray( + auto active_maximized = MakeStateArray( {XDG_TOPLEVEL_STATE_ACTIVATED, XDG_TOPLEVEL_STATE_MAXIMIZED}); EXPECT_CALL(*GetXdgToplevel(), SetMaximized()); EXPECT_CALL(*xdg_surface_, @@ -1043,7 +1036,7 @@ // State changes are synchronous. EXPECT_EQ(PlatformWindowState::kMaximized, window_->GetPlatformWindowState()); SendConfigureEvent(xdg_surface_, kMaximizedBounds.size(), ++serial, - states.get()); + active_maximized.get()); Sync(); // Verify that the state has not been changed. EXPECT_EQ(PlatformWindowState::kMaximized, window_->GetPlatformWindowState()); @@ -1058,27 +1051,22 @@ // State changes are synchronous. EXPECT_EQ(PlatformWindowState::kFullScreen, window_->GetPlatformWindowState()); - AddStateToWlArray(XDG_TOPLEVEL_STATE_FULLSCREEN, states.get()); + AddStateToWlArray(XDG_TOPLEVEL_STATE_FULLSCREEN, active_maximized.get()); SendConfigureEvent(xdg_surface_, kMaximizedBounds.size(), ++serial, - states.get()); + active_maximized.get()); Sync(); // Verify that the state has not been changed. EXPECT_EQ(PlatformWindowState::kFullScreen, window_->GetPlatformWindowState()); VerifyAndClearExpectations(); + EXPECT_CALL(*xdg_surface_, + SetWindowGeometry(gfx::Rect(kNormalBounds.size()))); EXPECT_CALL(*GetXdgToplevel(), UnsetFullscreen()); + EXPECT_CALL(delegate_, OnBoundsChanged(Eq(kDefaultBoundsChange))); EXPECT_CALL(delegate_, OnWindowStateChanged(_, _)).Times(1); window_->Restore(); - auto active_maximized = MakeStateArray( - {XDG_TOPLEVEL_STATE_ACTIVATED, XDG_TOPLEVEL_STATE_MAXIMIZED}); - SendConfigureEvent(xdg_surface_, - {kMaximizedBounds.width(), kMaximizedBounds.height()}, - ++serial, active_maximized.get()); - Sync(); - EXPECT_EQ(PlatformWindowState::kMaximized, window_->GetPlatformWindowState()); - VerifyAndClearExpectations(); - + EXPECT_EQ(PlatformWindowState::kNormal, window_->GetPlatformWindowState()); // Reinitialize wl_array, which removes previous old states. auto active = InitializeWlArrayWithActivatedState(); SendConfigureEvent(xdg_surface_, {0, 0}, ++serial, active.get()); @@ -3314,54 +3302,6 @@ EXPECT_EQ(gfx::Rect(100, 0, 100, 200), toplevel->GetBoundsInDIP()); } -#if BUILDFLAG(IS_CHROMEOS_LACROS) - -TEST_P(WaylandWindowTest, ImmersiveFullscreen) { - if (GetParam().shell_version == wl::ShellVersion::kV6) - GTEST_SKIP(); - - testing::NiceMock<MockWaylandPlatformWindowDelegate> delegate_2; - auto toplevel = CreateWaylandWindowWithParams( - PlatformWindowType::kWindow, 0, gfx::Rect(10, 10, 200, 200), &delegate_2); - EXPECT_CALL(delegate_2, OnImmersiveModeChanged(true)).Times(1); - toplevel->HandleAuraToplevelConfigure(0, 0, 0, 0, - {.is_maximized = false, - .is_fullscreen = true, - .is_immersive_fullscreen = true, - .is_activated = true}); - toplevel->HandleSurfaceConfigure(2); -} - -TEST_P(WaylandWindowTest, ImmersiveFullscreen_Disabled) { - if (GetParam().shell_version == wl::ShellVersion::kV6) - GTEST_SKIP(); - - uint32_t serial = 0; - - testing::NiceMock<MockWaylandPlatformWindowDelegate> delegate_2; - auto toplevel = CreateWaylandWindowWithParams( - PlatformWindowType::kWindow, 0, gfx::Rect(10, 10, 200, 200), &delegate_2); - - // First we have to enable it, or the top level window will not detect - // immersive state change. - toplevel->HandleAuraToplevelConfigure(0, 0, 0, 0, - {.is_maximized = false, - .is_fullscreen = true, - .is_immersive_fullscreen = true, - .is_activated = true}); - toplevel->HandleSurfaceConfigure(++serial); - - EXPECT_CALL(delegate_2, OnImmersiveModeChanged(false)).Times(1); - toplevel->HandleAuraToplevelConfigure(0, 0, 0, 0, - {.is_maximized = false, - .is_fullscreen = false, - .is_immersive_fullscreen = false, - .is_activated = true}); - toplevel->HandleSurfaceConfigure(++serial); -} - -#endif - namespace { class WaylandSubsurfaceTest : public WaylandWindowTest {
diff --git a/ui/ozone/platform/wayland/host/wayland_zaura_shell.cc b/ui/ozone/platform/wayland/host/wayland_zaura_shell.cc index 9766b1a..e9bae3403 100644 --- a/ui/ozone/platform/wayland/host/wayland_zaura_shell.cc +++ b/ui/ozone/platform/wayland/host/wayland_zaura_shell.cc
@@ -20,7 +20,7 @@ namespace { constexpr uint32_t kMinVersion = 1; -constexpr uint32_t kMaxVersion = 43; +constexpr uint32_t kMaxVersion = 42; } // static
diff --git a/ui/ozone/platform/wayland/host/xdg_activation.cc b/ui/ozone/platform/wayland/host/xdg_activation.cc index a0a9ecc2..b9d39f2 100644 --- a/ui/ozone/platform/wayland/host/xdg_activation.cc +++ b/ui/ozone/platform/wayland/host/xdg_activation.cc
@@ -107,8 +107,8 @@ connection_->serial_tracker().GetSerial( {wl::SerialType::kTouchPress, wl::SerialType::kMousePress, wl::SerialType::kMouseEnter, wl::SerialType::kKeyPress}), - base::BindOnce(&XdgActivation::OnActivateDone, weak_factory_.GetWeakPtr(), - surface)); + base::BindOnce(&XdgActivation::OnActivateDone, + weak_factory_.GetMutableWeakPtr(), surface)); } void XdgActivation::OnActivateDone(wl_surface* surface, std::string token) {
diff --git a/ui/ozone/platform/wayland/host/xdg_toplevel_wrapper_impl.cc b/ui/ozone/platform/wayland/host/xdg_toplevel_wrapper_impl.cc index 16b10eae..621786c1 100644 --- a/ui/ozone/platform/wayland/host/xdg_toplevel_wrapper_impl.cc +++ b/ui/ozone/platform/wayland/host/xdg_toplevel_wrapper_impl.cc
@@ -160,21 +160,6 @@ xdg_toplevel_set_fullscreen(xdg_toplevel_.get(), nullptr); } -#if BUILDFLAG(IS_CHROMEOS_LACROS) -void XDGToplevelWrapperImpl::SetUseImmersiveMode(bool immersive) { - if (SupportsTopLevelImmersiveStatus()) { - auto mode = immersive ? ZAURA_TOPLEVEL_FULLSCREEN_MODE_IMMERSIVE - : ZAURA_TOPLEVEL_FULLSCREEN_MODE_PLAIN; - zaura_toplevel_set_fullscreen_mode(aura_toplevel_.get(), mode); - } -} - -bool XDGToplevelWrapperImpl::SupportsTopLevelImmersiveStatus() const { - return aura_toplevel_ && zaura_toplevel_get_version(aura_toplevel_.get()) >= - ZAURA_TOPLEVEL_SET_FULLSCREEN_MODE_SINCE_VERSION; -} -#endif - void XDGToplevelWrapperImpl::UnSetFullscreen() { DCHECK(xdg_toplevel_); xdg_toplevel_unset_fullscreen(xdg_toplevel_.get()); @@ -301,23 +286,20 @@ auto* surface = static_cast<XDGToplevelWrapperImpl*>(data); DCHECK(surface); - surface->wayland_window_->HandleAuraToplevelConfigure(x, y, width, height, { - .is_maximized = - CheckIfWlArrayHasValue(states, XDG_TOPLEVEL_STATE_MAXIMIZED), - .is_fullscreen = - CheckIfWlArrayHasValue(states, XDG_TOPLEVEL_STATE_FULLSCREEN), -#if BUILDFLAG(IS_CHROMEOS_LACROS) - .is_immersive_fullscreen = - CheckIfWlArrayHasValue(states, ZAURA_TOPLEVEL_STATE_IMMERSIVE), -#endif - .is_activated = - CheckIfWlArrayHasValue(states, XDG_TOPLEVEL_STATE_ACTIVATED), - .is_snapped_primary = - CheckIfWlArrayHasValue(states, ZAURA_TOPLEVEL_STATE_SNAPPED_PRIMARY), - .is_snapped_secondary = - CheckIfWlArrayHasValue(states, ZAURA_TOPLEVEL_STATE_SNAPPED_SECONDARY), - .is_floated = CheckIfWlArrayHasValue(states, ZAURA_TOPLEVEL_STATE_FLOATED) - }); + surface->wayland_window_->HandleAuraToplevelConfigure( + x, y, width, height, + {.is_maximized = + CheckIfWlArrayHasValue(states, XDG_TOPLEVEL_STATE_MAXIMIZED), + .is_fullscreen = + CheckIfWlArrayHasValue(states, XDG_TOPLEVEL_STATE_FULLSCREEN), + .is_activated = + CheckIfWlArrayHasValue(states, XDG_TOPLEVEL_STATE_ACTIVATED), + .is_snapped_primary = + CheckIfWlArrayHasValue(states, ZAURA_TOPLEVEL_STATE_SNAPPED_PRIMARY), + .is_snapped_secondary = CheckIfWlArrayHasValue( + states, ZAURA_TOPLEVEL_STATE_SNAPPED_SECONDARY), + .is_floated = + CheckIfWlArrayHasValue(states, ZAURA_TOPLEVEL_STATE_FLOATED)}); } // static
diff --git a/ui/ozone/platform/wayland/host/xdg_toplevel_wrapper_impl.h b/ui/ozone/platform/wayland/host/xdg_toplevel_wrapper_impl.h index 47d2e2e..80d2d9c 100644 --- a/ui/ozone/platform/wayland/host/xdg_toplevel_wrapper_impl.h +++ b/ui/ozone/platform/wayland/host/xdg_toplevel_wrapper_impl.h
@@ -33,10 +33,6 @@ void UnSetMaximized() override; void SetFullscreen() override; void UnSetFullscreen() override; -#if BUILDFLAG(IS_CHROMEOS_LACROS) - void SetUseImmersiveMode(bool immersive) override; - bool SupportsTopLevelImmersiveStatus() const override; -#endif void SetMinimized() override; void SurfaceMove(WaylandConnection* connection) override; void SurfaceResize(WaylandConnection* connection, uint32_t hittest) override;
diff --git a/ui/ozone/platform/wayland/host/zxdg_toplevel_v6_wrapper_impl.cc b/ui/ozone/platform/wayland/host/zxdg_toplevel_v6_wrapper_impl.cc index 3c1c534..64bd18b 100644 --- a/ui/ozone/platform/wayland/host/zxdg_toplevel_v6_wrapper_impl.cc +++ b/ui/ozone/platform/wayland/host/zxdg_toplevel_v6_wrapper_impl.cc
@@ -91,12 +91,6 @@ zxdg_toplevel_v6_unset_fullscreen(zxdg_toplevel_v6_.get()); } -#if BUILDFLAG(IS_CHROMEOS_LACROS) -bool ZXDGToplevelV6WrapperImpl::SupportsTopLevelImmersiveStatus() const { - return false; -} -#endif - void ZXDGToplevelV6WrapperImpl::SetMinimized() { DCHECK(zxdg_toplevel_v6_); zxdg_toplevel_v6_set_minimized(zxdg_toplevel_v6_.get());
diff --git a/ui/ozone/platform/wayland/host/zxdg_toplevel_v6_wrapper_impl.h b/ui/ozone/platform/wayland/host/zxdg_toplevel_v6_wrapper_impl.h index 3e0eb33..458f6ab 100644 --- a/ui/ozone/platform/wayland/host/zxdg_toplevel_v6_wrapper_impl.h +++ b/ui/ozone/platform/wayland/host/zxdg_toplevel_v6_wrapper_impl.h
@@ -33,10 +33,6 @@ void UnSetMaximized() override; void SetFullscreen() override; void UnSetFullscreen() override; -#if BUILDFLAG(IS_CHROMEOS_LACROS) - void SetUseImmersiveMode(bool mode) override {} - bool SupportsTopLevelImmersiveStatus() const override; -#endif void SetMinimized() override; void SurfaceMove(WaylandConnection* connection) override; void SurfaceResize(WaylandConnection* connection, uint32_t hittest) override;
diff --git a/ui/ozone/platform/wayland/test/mock_zaura_shell.cc b/ui/ozone/platform/wayland/test/mock_zaura_shell.cc index 6568700d..1cd66b2 100644 --- a/ui/ozone/platform/wayland/test/mock_zaura_shell.cc +++ b/ui/ozone/platform/wayland/test/mock_zaura_shell.cc
@@ -16,7 +16,7 @@ namespace { -constexpr uint32_t kZAuraShellVersion = 43; +constexpr uint32_t kZAuraShellVersion = 42; constexpr uint32_t kZAuraOutputVersion = 38; void GetAuraSurface(wl_client* client,
diff --git a/ui/ozone/platform/wayland/test/test_zaura_toplevel.cc b/ui/ozone/platform/wayland/test/test_zaura_toplevel.cc index 0c88ff74..bc6aac08 100644 --- a/ui/ozone/platform/wayland/test/test_zaura_toplevel.cc +++ b/ui/ozone/platform/wayland/test/test_zaura_toplevel.cc
@@ -90,20 +90,6 @@ NOTIMPLEMENTED_LOG_ONCE(); } -void Activate(struct wl_client* client, struct wl_resource* resource) { - NOTIMPLEMENTED_LOG_ONCE(); -} - -void Dectivate(struct wl_client* client, struct wl_resource* resource) { - NOTIMPLEMENTED_LOG_ONCE(); -} - -void SetFullscreenMode(struct wl_client* client, - struct wl_resource* resource, - uint32_t mode) { - NOTIMPLEMENTED_LOG_ONCE(); -} - } // namespace TestZAuraToplevel::TestZAuraToplevel(wl_resource* resource) @@ -126,9 +112,6 @@ &UnSetFloat, &SetZOrder, &SetOrigin, - &Activate, - &Dectivate, - &SetFullscreenMode, }; } // namespace wl
diff --git a/ui/ozone/test/mock_platform_window_delegate.h b/ui/ozone/test/mock_platform_window_delegate.h index 6e3c7ba7..fe4d078 100644 --- a/ui/ozone/test/mock_platform_window_delegate.h +++ b/ui/ozone/test/mock_platform_window_delegate.h
@@ -48,7 +48,6 @@ MOCK_METHOD0(GetOwnedWindowAnchorAndRectInDIP, absl::optional<OwnedWindowAnchor>()); MOCK_METHOD0(OnMouseEnter, void()); - MOCK_METHOD1(OnImmersiveModeChanged, void(bool immersive)); }; bool operator==(const PlatformWindowDelegate::BoundsChange& a,
diff --git a/ui/platform_window/extensions/wayland_extension.h b/ui/platform_window/extensions/wayland_extension.h index b9147b9..04c91d0 100644 --- a/ui/platform_window/extensions/wayland_extension.h +++ b/ui/platform_window/extensions/wayland_extension.h
@@ -6,7 +6,6 @@ #define UI_PLATFORM_WINDOW_EXTENSIONS_WAYLAND_EXTENSION_H_ #include "base/component_export.h" -#include "build/chromeos_buildflags.h" namespace ui { @@ -39,13 +38,11 @@ // features. virtual void StartWindowDraggingSessionIfNeeded(bool allow_system_drag) = 0; -#if BUILDFLAG(IS_CHROMEOS_LACROS) // Signals the underneath platform that browser is entering (or exiting) // 'immersive fullscreen mode'. // Under lacros, it controls for instance interaction with the system shelf // widget, when browser goes in fullscreen. virtual void SetImmersiveFullscreenStatus(bool status) = 0; -#endif // Signals the underneath platform to shows a preview for the given window // snap direction. `allow_haptic_feedback` indicates if it should send haptic
diff --git a/ui/platform_window/platform_window_delegate.h b/ui/platform_window/platform_window_delegate.h index 1c0a9d08..be4e43a 100644 --- a/ui/platform_window/platform_window_delegate.h +++ b/ui/platform_window/platform_window_delegate.h
@@ -101,15 +101,6 @@ virtual void OnWindowTiledStateChanged(WindowTiledEdges new_tiled_edges); #endif -#if BUILDFLAG(IS_CHROMEOS_LACROS) - // TODO(ffred): We should just add kImmersiveFullscreen as a state. However, - // that will require more refactoring in other places to understand that - // kImmersiveFullscreen is a fullscreen status. - // Sets the immersive mode for the window. This will only have an effect on - // ChromeOS platforms. - virtual void OnImmersiveModeChanged(bool immersive) {} -#endif - virtual void OnLostCapture() = 0; virtual void OnAcceleratedWidgetAvailable(gfx::AcceleratedWidget widget) = 0;
diff --git a/ui/views/bubble/bubble_dialog_delegate_view.cc b/ui/views/bubble/bubble_dialog_delegate_view.cc index 2dd17a36..419ce7e7e 100644 --- a/ui/views/bubble/bubble_dialog_delegate_view.cc +++ b/ui/views/bubble/bubble_dialog_delegate_view.cc
@@ -118,7 +118,7 @@ return bubble_delegate ? bubble_delegate->anchor_widget() : nullptr; } Widget* GetAnchorWidget() { - return const_cast<Widget*>(base::as_const(*this).GetAnchorWidget()); + return const_cast<Widget*>(std::as_const(*this).GetAnchorWidget()); } };
diff --git a/ui/views/test/view_skia_gold_pixel_diff.cc b/ui/views/test/view_skia_gold_pixel_diff.cc index 90db006..e27dd60 100644 --- a/ui/views/test/view_skia_gold_pixel_diff.cc +++ b/ui/views/test/view_skia_gold_pixel_diff.cc
@@ -8,6 +8,10 @@ #include "base/run_loop.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/skia/include/core/SkBitmap.h" +#include "third_party/skia/include/core/SkCanvas.h" +#include "third_party/skia/include/core/SkImage.h" +#include "ui/base/test/skia_gold_matching_algorithm.h" +#include "ui/gfx/geometry/skia_conversions.h" #include "ui/gfx/image/image.h" #include "ui/snapshot/snapshot.h" #include "ui/views/view.h" @@ -60,10 +64,31 @@ gfx::Image image; bool ret = GrabWindowSnapshotInternal(window, snapshot_bounds, &image); - if (!ret) { - LOG(ERROR) << "Grab screenshot failed."; + if (!ret) return false; - } + + return SkiaGoldPixelDiff::CompareScreenshot(screenshot_name, + *image.ToSkBitmap(), algorithm); +} + +bool ViewSkiaGoldPixelDiff::CompareNativeWindowScreenshotInRects( + const std::string& screenshot_name, + gfx::NativeWindow window, + const gfx::Rect& snapshot_bounds, + const ui::test::SkiaGoldMatchingAlgorithm* algorithm, + const std::vector<gfx::Rect>& regions_of_interest) const { + DCHECK(Initialized()) << "Initialize the class before using this method."; + CHECK(!algorithm || algorithm->GetCommandLineSwitchName() != "sobel"); + + gfx::Image image; + bool ret = GrabWindowSnapshotInternal(window, snapshot_bounds, &image); + if (!ret) + return false; + + // Only keep the pixels within `regions_of_interest` so that the differences + // outside of `regions_of_interest` are ignored. + KeepPixelsInRects(regions_of_interest, &image); + return SkiaGoldPixelDiff::CompareScreenshot(screenshot_name, *image.ToSkBitmap(), algorithm); } @@ -81,7 +106,38 @@ window, snapshot_bounds, base::BindOnce(&SnapshotCallback, &run_loop, image)); run_loop.Run(); - return !image->IsEmpty(); + + const bool success = !image->IsEmpty(); + if (!success) + LOG(ERROR) << "Grab screenshot failed."; + return success; +} + +void ViewSkiaGoldPixelDiff::KeepPixelsInRects( + const std::vector<gfx::Rect>& rects, + gfx::Image* image) const { + // `rects` should not be empty. + CHECK(!rects.empty()); + + // Create a bitmap with the same size as `image`. NOTE: `image` is immutable. + // Therefore, we have to create a new bitmap. + SkBitmap bitmap; + bitmap.allocPixels(image->ToSkBitmap()->info()); + bitmap.eraseColor(SK_ColorTRANSPARENT); + + // Allow `canvas` to draw on `bitmap`. + SkCanvas canvas(bitmap, SkSurfaceProps{}); + + // Only copy the pixels within `rects`. + SkPaint paint; + for (const auto& rect : rects) { + canvas.drawImageRect(image->ToSkBitmap()->asImage(), + gfx::RectToSkRect(rect), gfx::RectToSkRect(rect), + SkSamplingOptions(), &paint, + SkCanvas::kStrict_SrcRectConstraint); + } + + *image = gfx::Image::CreateFrom1xBitmap(bitmap); } } // namespace views
diff --git a/ui/views/test/view_skia_gold_pixel_diff.h b/ui/views/test/view_skia_gold_pixel_diff.h index 4afe661..270b4d0 100644 --- a/ui/views/test/view_skia_gold_pixel_diff.h +++ b/ui/views/test/view_skia_gold_pixel_diff.h
@@ -6,8 +6,8 @@ #define UI_VIEWS_TEST_VIEW_SKIA_GOLD_PIXEL_DIFF_H_ #include <string> +#include <vector> -#include "base/memory/raw_ptr.h" #include "ui/base/test/skia_gold_pixel_diff.h" #include "ui/gfx/native_widget_types.h" @@ -16,12 +16,10 @@ class Image; } // namespace gfx -namespace ui { -namespace test { +namespace ui::test { class SkiaGoldMatchingAlgorithm; class SkiaGoldPixelDiff; -} // namespace test -} // namespace ui +} // namespace ui::test namespace views { class View; @@ -51,6 +49,8 @@ // E.g. 'ToolbarTest_BackButtonHover'. Here `screenshot_prefix` is passed as // an argument during initialization. // `view` is the view you want to take screenshot. + // `algorithm` specifies how two images are matched. Use the exact match as + // default. Read the comment of `SkiaGoldMatchingAlgorithm` to learn more. bool CompareViewScreenshot( const std::string& screenshot_name, views::View* view, @@ -65,12 +65,33 @@ const gfx::Rect& snapshot_bounds, const ui::test::SkiaGoldMatchingAlgorithm* algorithm = nullptr) const; + // Similar to `CompareNativeWindowScreenshot()` but with the difference that + // only the pixel differences within `regions_of_interest` should affect the + // comparison result. Each rect in `regions_of_interest` is in pixel + // coordinates. NOTE: + // 1. If `algorithm` is `FuzzySkiaGoldMatchingAlgorithm`, the total amount of + // different pixels across `regions_of_interest` is compared with the + // threshold carried by `algorithm`. + // 2. `algorithm` cannot be `SobelSkiaGoldMatchingAlgorithm` because the + // border of an image with `regions_of_interest` is ambiguous. + bool CompareNativeWindowScreenshotInRects( + const std::string& screenshot_name, + gfx::NativeWindow window, + const gfx::Rect& snapshot_bounds, + const ui::test::SkiaGoldMatchingAlgorithm* algorithm, + const std::vector<gfx::Rect>& regions_of_interest) const; + protected: // Takes a screenshot of `window` within the specified area and stores the // screenshot in `image`. Returns true if succeeding. virtual bool GrabWindowSnapshotInternal(gfx::NativeWindow window, const gfx::Rect& snapshot_bounds, gfx::Image* image) const; + + private: + // Updates `image` so that only the pixels within `rects` are kept. + void KeepPixelsInRects(const std::vector<gfx::Rect>& rects, + gfx::Image* image) const; }; } // namespace views
diff --git a/ui/views/view.h b/ui/views/view.h index 13442d87..32ee6dda 100644 --- a/ui/views/view.h +++ b/ui/views/view.h
@@ -14,7 +14,6 @@ #include <utility> #include <vector> -#include "base/as_const.h" #include "base/callback.h" #include "base/callback_list.h" #include "base/gtest_prod_util.h" @@ -935,7 +934,7 @@ // Returns the ColorProvider from the ColorProviderManager. ui::ColorProvider* GetColorProvider() { return const_cast<ui::ColorProvider*>( - base::as_const(*this).GetColorProvider()); + std::as_const(*this).GetColorProvider()); } const ui::ColorProvider* GetColorProvider() const; @@ -945,7 +944,7 @@ // set. Warning: the default theme might not be correct; you should probably // override OnThemeChanged(). ui::NativeTheme* GetNativeTheme() { - return const_cast<ui::NativeTheme*>(base::as_const(*this).GetNativeTheme()); + return const_cast<ui::NativeTheme*>(std::as_const(*this).GetNativeTheme()); } const ui::NativeTheme* GetNativeTheme() const; @@ -1135,7 +1134,7 @@ // Convenience method to retrieve the InputMethod associated with the // Widget that contains this view. ui::InputMethod* GetInputMethod() { - return const_cast<ui::InputMethod*>(base::as_const(*this).GetInputMethod()); + return const_cast<ui::InputMethod*>(std::as_const(*this).GetInputMethod()); } const ui::InputMethod* GetInputMethod() const;
diff --git a/ui/views/widget/desktop_aura/desktop_window_tree_host_lacros.cc b/ui/views/widget/desktop_aura/desktop_window_tree_host_lacros.cc index c377a44..dd4bcf1 100644 --- a/ui/views/widget/desktop_aura/desktop_window_tree_host_lacros.cc +++ b/ui/views/widget/desktop_aura/desktop_window_tree_host_lacros.cc
@@ -18,7 +18,6 @@ #include "ui/platform_window/platform_window_init_properties.h" #include "ui/platform_window/wm/wm_move_resize_handler.h" #include "ui/views/views_delegate.h" -#include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h" #include "ui/views/widget/desktop_aura/window_event_filter_lacros.h" #include "ui/views/widget/widget.h" @@ -106,12 +105,6 @@ ToChromeosWindowStateType(new_window_show_state)); } -void DesktopWindowTreeHostLacros::OnImmersiveModeChanged(bool enabled) { - // Keep in sync with ImmersiveFullscreenController::Enable for widget. See - // comment there for details. - GetContentWindow()->SetProperty(chromeos::kImmersiveIsActive, enabled); -} - void DesktopWindowTreeHostLacros::AddAdditionalInitProperties( const Widget::InitParams& params, ui::PlatformWindowInitProperties* properties) {
diff --git a/ui/views/widget/desktop_aura/desktop_window_tree_host_lacros.h b/ui/views/widget/desktop_aura/desktop_window_tree_host_lacros.h index 47743fd..b7d1026 100644 --- a/ui/views/widget/desktop_aura/desktop_window_tree_host_lacros.h +++ b/ui/views/widget/desktop_aura/desktop_window_tree_host_lacros.h
@@ -62,7 +62,6 @@ void OnWindowStateChanged( ui::PlatformWindowState old_window_show_state, ui::PlatformWindowState new_window_show_state) override; - void OnImmersiveModeChanged(bool enabled) override; // DesktopWindowTreeHostPlatform overrides: void AddAdditionalInitProperties(
diff --git a/ui/webui/resources/cr_elements/cr_shared_vars.css b/ui/webui/resources/cr_elements/cr_shared_vars.css index 4eea87f7..2fe906d 100644 --- a/ui/webui/resources/cr_elements/cr_shared_vars.css +++ b/ui/webui/resources/cr_elements/cr_shared_vars.css
@@ -29,6 +29,8 @@ --google-green-50-rgb: 230, 244, 234; /* #e6f4ea */ --google-green-50: rgb(var(--google-green-50-rgb)); + --google-green-200-rgb: 168, 218, 181; /* #a8dab5 */ + --google-green-200: rgb(var(--google-green-200-rgb)); --google-green-300-rgb: 129, 201, 149; /* #81c995 */ --google-green-300: rgb(var(--google-green-300-rgb)); --google-green-400-rgb: 91, 185, 116; /* #5bb974 */ @@ -39,6 +41,10 @@ --google-green-600: rgb(var(--google-green-600-rgb)); --google-green-700-rgb: 24, 128, 56; /* #188038 */ --google-green-700: rgb(var(--google-green-700-rgb)); + --google-green-800-rgb: 19, 115, 51; /* #137333 */ + --google-green-800: rgb(var(--google-green-800-rgb)); + --google-green-900-rgb: 13, 101, 45; /* #0d652d */ + --google-green-900: rgb(var(--google-green-900-rgb)); --google-grey-50-rgb: 248, 249, 250; /* #f8f9fa */ --google-grey-50: rgb(var(--google-grey-50-rgb));
diff --git a/weblayer/browser/autofill_client_impl.cc b/weblayer/browser/autofill_client_impl.cc index 492fd9a..26d69d47 100644 --- a/weblayer/browser/autofill_client_impl.cc +++ b/weblayer/browser/autofill_client_impl.cc
@@ -4,6 +4,8 @@ #include "weblayer/browser/autofill_client_impl.h" +#include <utility> + #include "build/build_config.h" #include "components/autofill/core/browser/data_model/autofill_profile.h" #include "components/autofill/core/browser/ui/suggestion.h" @@ -29,7 +31,7 @@ } PrefService* AutofillClientImpl::GetPrefs() { - return const_cast<PrefService*>(base::as_const(*this).GetPrefs()); + return const_cast<PrefService*>(std::as_const(*this).GetPrefs()); } const PrefService* AutofillClientImpl::GetPrefs() const {