diff --git a/DEPS b/DEPS index 8ea04b79..72e6ba1 100644 --- a/DEPS +++ b/DEPS
@@ -239,11 +239,11 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling Skia # and whatever else without interference from each other. - 'skia_revision': 'c7747909f17c446e97a244a121905734a3056f6e', + 'skia_revision': '06f3d68627c28d3d5faeb45a289acb17150762a3', # 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': 'ffc8cdf5072a93993f0d9e4762f98d870413bc4e', + 'v8_revision': 'b560905d0b45c4a963329318bb38c8d8ec458f49', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling ANGLE # and whatever else without interference from each other. @@ -251,7 +251,7 @@ # 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': '3e61a772b24838bc1ccab8cc8450412b5f952069', + 'swiftshader_revision': '556563cae4c7b814a2321b7338247196c2109c2d', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling PDFium # and whatever else without interference from each other. @@ -286,7 +286,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling freetype # and whatever else without interference from each other. - 'freetype_revision': '1f951898751365e9bd2a920ce76652f2a59c3305', + 'freetype_revision': '012b00f3e67d8d17d411ec1c777b8672e4dffad5', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling freetype # and whatever else without interference from each other. @@ -306,7 +306,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': '96b538653a6d4d3cd5aede9d86ceb08754d19498', + 'catapult_revision': 'dac6246d7d158e5af296232db17ae6d8d211637b', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling libFuzzer # and whatever else without interference from each other. @@ -314,7 +314,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': '3916cabea50d9de25473bc39dedb3f3eba117664', + 'devtools_frontend_revision': 'b154da2d039abadf3dbedabaddf621981faeedbc', # 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. @@ -421,7 +421,7 @@ 'libcxx_revision': '79a2e924d96e2fc1e4b937c42efd08898fa472d7', # GN CIPD package version. - 'gn_version': 'git_revision:297669af11c70e15d465844fdb4cabbcada4dc7d', + 'gn_version': 'git_revision:fc295f3ac7ca4fe7acc6cb5fb052d22909ef3a8f', } # Only these hosts are allowed for dependencies in this DEPS file. @@ -796,7 +796,7 @@ 'packages': [ { 'package': 'chromium/third_party/androidx', - 'version': 'GIDFGuNAP8MxCHXxffVxJJTeBNo3kY7DExIdKQdwVSUC', + 'version': '5lV65l1RfT7BHK1JOXfWWtQhT1aL7x-_2IYlhuxEQisC', }, ], 'condition': 'checkout_android', @@ -1015,7 +1015,7 @@ # Tools used when building Chrome for Chrome OS. This affects both the Simple # Chrome workflow, as well as the chromeos-chrome ebuild. 'src/third_party/chromite': { - 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + 'd7d05e7bc9fb616e105dfd9bf7306587a44c9f56', + 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + 'e9aa4599d44ccc48b4953fe8c63c150bbf768a8e', 'condition': 'checkout_chromeos', }, @@ -1035,7 +1035,7 @@ }, 'src/third_party/depot_tools': - Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + 'b5c7bf81ba5f19ca502165dcf05547a014dae936', + Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + '1693c67f39cc03c883a3821de6e58cfb75f35370', 'src/third_party/devtools-frontend/src': Var('chromium_git') + '/devtools/devtools-frontend' + '@' + Var('devtools_frontend_revision'), @@ -1066,7 +1066,7 @@ Var('chromium_git') + '/external/github.com/google/farmhash.git' + '@' + '816a4ae622e964763ca0862d9dbd19324a1eaf45', 'src/third_party/ffmpeg': - Var('chromium_git') + '/chromium/third_party/ffmpeg.git' + '@' + '731bf2abeb9e5d4fd02f6c7b8c743961130de5b0', + Var('chromium_git') + '/chromium/third_party/ffmpeg.git' + '@' + 'd151785b5b0ef367e225f8a5702c36d2dccc8bb3', 'src/third_party/flac': Var('chromium_git') + '/chromium/deps/flac.git' + '@' + 'af862024c8c8fa0ae07ced05e89013d881b00596', @@ -1600,7 +1600,7 @@ 'src/third_party/usrsctp/usrsctplib': Var('chromium_git') + '/external/github.com/sctplab/usrsctp' + '@' + '62d7d0c928c9a040dce96aa2f16c00e7e67d59cb', - 'src/third_party/vulkan-deps': '{chromium_git}/vulkan-deps@5c0e645249827ec0cf8c466f8df0df06e8f565ba', + 'src/third_party/vulkan-deps': '{chromium_git}/vulkan-deps@3dda549d26ad5fab1fcfeba3f2d1b631e03473f9', 'src/third_party/vulkan_memory_allocator': Var('chromium_git') + '/external/github.com/GPUOpen-LibrariesAndSDKs/VulkanMemoryAllocator.git' + '@' + '5e49f57a6e71a026a54eb42e366de09a4142d24e', @@ -1639,7 +1639,7 @@ Var('chromium_git') + '/external/github.com/gpuweb/cts.git' + '@' + '4f2c3b6ac243f7e97ae1afb664d2b14b65fcf097', 'src/third_party/webrtc': - Var('webrtc_git') + '/src.git' + '@' + 'adf7dc34f036eba9283bb6ee022333009fda05fb', + Var('webrtc_git') + '/src.git' + '@' + '95c2f300695d6740cfa27f6192e488bbfbee7886', 'src/third_party/libgifcodec': Var('skia_git') + '/libgifcodec' + '@'+ Var('libgifcodec_revision'), @@ -1697,7 +1697,7 @@ Var('chromium_git') + '/v8/v8.git' + '@' + Var('v8_revision'), 'src-internal': { - 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@3d4ed74a71b3bb522cf896ca03af47b76d5dced3', + 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@32e38a05454f1bdbd75cbe0868d87378efcbe8e0', 'condition': 'checkout_src_internal', }, @@ -1727,7 +1727,7 @@ 'packages': [ { 'package': 'chromeos_internal/apps/media_app/app', - 'version': 'kNS5SXccgTwgM-K29kyN5c9oxZ-iItSZj6wwU-bp9CoC', + 'version': 'aBZpcE5gHkYFagIWmaLu2oBSMG0Gi5ikerNVntlp1xoC', }, ], 'condition': 'checkout_chromeos and checkout_src_internal',
diff --git a/WATCHLISTS b/WATCHLISTS index 013d093..b07f110 100644 --- a/WATCHLISTS +++ b/WATCHLISTS
@@ -730,8 +730,7 @@ '|ui/webui/resources/cr_components/chromeos/bluetooth*' }, 'chromeos_cellular': { - 'filepath': 'chrome/browser/resources/chromeos/cellular_setup/|'\ - 'chrome/browser/ui/webui/chromeos/cellular_setup/|'\ + 'filepath': 'chromeos/dbus/hermes/|'\ 'chromeos/services/cellular_setup/|'\ 'ui/webui/resources/cr_components/chromeos/cellular_setup/', }, @@ -754,6 +753,7 @@ }, 'chromeos_net': { 'filepath': 'ash/system/network/|'\ + 'chromeos/dbus/shill/|'\ 'chromeos/network/|'\ 'chromeos/services/network_config/|'\ 'chrome/browser/ash/net/|'\ @@ -2370,8 +2370,13 @@ 'chromeos_attestation': ['dkrahn+watch@chromium.org'], 'chromeos_bluetooth': ['hansberry+watch-bluetooth@chromium.org'], 'chromeos_cellular': ['azeemarshad+watch-cellular@chromium.org', - 'benchan+watch-cellular@chromium.org', - 'ejcaruso+watch-cellular@chromium.org'], + 'chadduffin+watch-cellular@chromium.org', + 'ejcaruso+watch-cellular@chromium.org', + 'gordonseto+watch-cellular@google.com', + 'hsuregan+watch-cellular@chromium.org', + 'jiajunz+watch-cellular@google.com', + 'khorimoto+watch-cellular@chromium.org', + 'tjohnsonkanu+watch-cellular@google.com'], 'chromeos_geolocation': ['alemate+watch@chromium.org'], 'chromeos_lkgm': ['achuith+watch@chromium.org', 'bpastene+watch@chromium.org'], @@ -2380,10 +2385,15 @@ 'tbarzic+watch@chromium.org'], 'chromeos_media_app': ['cros-essential-apps-dev-watch@chromium.org'], 'chromeos_net': ['azeemarshad+watch-network@chromium.org', - 'benchan+watch-network@chromium.org', + 'chadduffin+watch-network@chromium.org', 'ejcaruso+watch-network@chromium.org', + 'gordonseto+watch-network@google.com', + 'hsuregan+watch-network@chromium.org', + 'jiajunz+watch-network@google.com', 'jonmann+watch-network@chromium.org', - 'stevenjb+watch-network@chromium.org'], + 'khorimoto+watch-network@chromium.org', + 'stevenjb+watch-network@chromium.org', + 'tjohnsonkanu+watch-network@google.com'], 'chromeos_tast_control': ['chromeos-engprod+watch@google.com', 'bpastene+watch@chromium.org', 'chrome-os-gardeners+watch@google.com'],
diff --git a/android_webview/browser/aw_autofill_client.cc b/android_webview/browser/aw_autofill_client.cc index d913422..7e7cde5 100644 --- a/android_webview/browser/aw_autofill_client.cc +++ b/android_webview/browser/aw_autofill_client.cc
@@ -55,7 +55,7 @@ autofill::AutocompleteHistoryManager* AwAutofillClient::GetAutocompleteHistoryManager() { - return AwBrowserContext::FromWebContents(web_contents_) + return AwBrowserContext::FromWebContents(&GetWebContents()) ->GetAutocompleteHistoryManager(); } @@ -64,8 +64,8 @@ } const PrefService* AwAutofillClient::GetPrefs() const { - return user_prefs::UserPrefs::Get( - AwBrowserContext::FromWebContents(web_contents_)); + return user_prefs::UserPrefs::Get(AwBrowserContext::FromWebContents( + const_cast<WebContents*>(&GetWebContents()))); } syncer::SyncService* AwAutofillClient::GetSyncService() { @@ -102,7 +102,7 @@ } const GURL& AwAutofillClient::GetLastCommittedURL() const { - return web_contents_->GetLastCommittedURL(); + return GetWebContents().GetLastCommittedURL(); } security_state::SecurityLevel @@ -195,7 +195,7 @@ delegate_ = delegate; // Convert element_bounds to be in screen space. - gfx::Rect client_area = web_contents_->GetContainerBounds(); + gfx::Rect client_area = GetWebContents().GetContainerBounds(); gfx::RectF element_bounds_in_screen_space = open_args.element_bounds + client_area.OffsetFromOrigin(); @@ -258,7 +258,7 @@ bool AwAutofillClient::IsContextSecure() const { content::SSLStatus ssl_status; content::NavigationEntry* navigation_entry = - web_contents_->GetController().GetLastCommittedEntry(); + GetWebContents().GetController().GetLastCommittedEntry(); if (!navigation_entry) return false; @@ -310,13 +310,13 @@ // autofill functionality at the java side. The java peer is owned by Java // AwContents. The native object only maintains a weak ref to it. AwAutofillClient::AwAutofillClient(WebContents* contents) - : web_contents_(contents) { + : content::WebContentsUserData<AwAutofillClient>(*contents) { JNIEnv* env = AttachCurrentThread(); ScopedJavaLocalRef<jobject> delegate; delegate.Reset( Java_AwAutofillClient_create(env, reinterpret_cast<intptr_t>(this))); - AwContents* aw_contents = AwContents::FromWebContents(web_contents_); + AwContents* aw_contents = AwContents::FromWebContents(contents); aw_contents->SetAwAutofillClient(delegate); java_ref_ = JavaObjectWeakGlobalRef(env, delegate); } @@ -344,7 +344,7 @@ Java_AwAutofillClient_addToAutofillSuggestionArray( env, data_array, i, name, label, suggestions[i].frontend_id); } - ui::ViewAndroid* view_android = web_contents_->GetNativeView(); + ui::ViewAndroid* view_android = GetWebContents().GetNativeView(); if (!view_android) return; @@ -360,6 +360,14 @@ Java_AwAutofillClient_showAutofillPopup(env, obj, view, is_rtl, data_array); } +content::WebContents& AwAutofillClient::GetWebContents() const { + // While a const_cast is not ideal. The Autofill API uses const in various + // spots and the content public API doesn't have const accessors. So the const + // cast is the lesser of two evils. + return const_cast<content::WebContents&>( + content::WebContentsUserData<AwAutofillClient>::GetWebContents()); +} + WEB_CONTENTS_USER_DATA_KEY_IMPL(AwAutofillClient); } // namespace android_webview
diff --git a/android_webview/browser/aw_autofill_client.h b/android_webview/browser/aw_autofill_client.h index 351c2485..b5468a947 100644 --- a/android_webview/browser/aw_autofill_client.h +++ b/android_webview/browser/aw_autofill_client.h
@@ -152,8 +152,8 @@ bool is_rtl, const std::vector<autofill::Suggestion>& suggestions); - // The web_contents associated with this delegate. - raw_ptr<content::WebContents> web_contents_; + content::WebContents& GetWebContents() const; + bool save_form_data_ = false; JavaObjectWeakGlobalRef java_ref_;
diff --git a/ash/BUILD.gn b/ash/BUILD.gn index 918c9e91..86b8d816 100644 --- a/ash/BUILD.gn +++ b/ash/BUILD.gn
@@ -1689,6 +1689,8 @@ "wm/desks/root_window_desk_switch_animator.h", "wm/desks/scroll_arrow_button.cc", "wm/desks/scroll_arrow_button.h", + "wm/desks/templates/desks_templates_animations.cc", + "wm/desks/templates/desks_templates_animations.h", "wm/desks/templates/desks_templates_dialog_controller.cc", "wm/desks/templates/desks_templates_dialog_controller.h", "wm/desks/templates/desks_templates_grid_view.cc",
diff --git a/ash/app_list/app_list_presenter_unittest.cc b/ash/app_list/app_list_presenter_unittest.cc index 7c91c934..b77a077 100644 --- a/ash/app_list/app_list_presenter_unittest.cc +++ b/ash/app_list/app_list_presenter_unittest.cc
@@ -1384,8 +1384,7 @@ EXPECT_TRUE(apps_grid_view_->IsDragging()); // Delete the dragged item. - app_list_test_model_->DeleteItem(dragged_view->item()->id(), - /*can_clean_folder=*/true); + app_list_test_model_->DeleteItem(dragged_view->item()->id()); EXPECT_FALSE(apps_grid_view_->IsDragging()); // Verify that mouse drag has been canceled. @@ -1429,8 +1428,7 @@ EXPECT_TRUE(folder_view()->items_grid_view()->IsDragging()); // Delete the dragged item. - app_list_test_model_->DeleteItem(dragged_view->item()->id(), - /*can_clean_folder=*/true); + app_list_test_model_->DeleteItem(dragged_view->item()->id()); // Verify that drag has been canceled. EXPECT_FALSE(apps_grid_view_->IsDragging()); @@ -1491,8 +1489,7 @@ EXPECT_TRUE(folder_view()->items_grid_view()->IsDragging()); // Delete the dragged item. - app_list_test_model_->DeleteItem(dragged_view->item()->id(), - /*can_clean_folder=*/true); + app_list_test_model_->DeleteItem(dragged_view->item()->id()); // Verify that drag has been canceled. EXPECT_FALSE(apps_grid_view_->IsDragging()); @@ -1550,9 +1547,10 @@ EXPECT_TRUE(apps_grid_view_->IsDragging()); EXPECT_TRUE(folder_view()->items_grid_view()->IsDragging()); - // Delete the dragged item. - app_list_test_model_->DeleteItem(dragged_view->item()->id(), - /*can_clean_folder=*/true); + // Leave the dragged item as it's folder only child, and then delete it, which + // should also delete the folder. + app_list_test_model_->DeleteItem("Item 3"); + app_list_test_model_->DeleteItem(dragged_view->item()->id()); // Verify that drag has been canceled. EXPECT_FALSE(apps_grid_view_->IsDragging()); @@ -1560,8 +1558,8 @@ EXPECT_EQ("Item 0", apps_grid_view_->GetItemViewAt(0)->item()->id()); EXPECT_EQ("Item 1", apps_grid_view_->GetItemViewAt(1)->item()->id()); - EXPECT_EQ("Item 3", apps_grid_view_->GetItemViewAt(2)->item()->id()); - EXPECT_EQ("Item 4", apps_grid_view_->GetItemViewAt(3)->item()->id()); + EXPECT_EQ("Item 4", apps_grid_view_->GetItemViewAt(2)->item()->id()); + EXPECT_EQ("Item 5", apps_grid_view_->GetItemViewAt(3)->item()->id()); // Hide and show the app list again to verify checks done when resetting the // apps grid for show pass (e.g. verification that size of the app list views @@ -1871,12 +1869,13 @@ // that item. See https://crbug.com/1083942 TEST_F(PopulatedAppListTest, RemoveFolderItemAfterFolderCreation) { InitializeAppsGrid(); - const int kItemCount = 5; + const int kItemCount = 6; PopulateApps(kItemCount); // Dragging the item with index 4. AppListItemView* const dragged_view = apps_grid_view_->GetItemViewAt(4); AppListItem* const dragged_item = dragged_view->item(); + AppListItem* const merged_item = apps_grid_view_->GetItemViewAt(3)->item(); // Drag the item on top of the item with index 3. ui::test::EventGenerator* event_generator = GetEventGenerator(); @@ -1922,9 +1921,82 @@ apps_grid_view_->InvalidateLayout(); apps_grid_view_->GetWidget()->LayoutRootViewIfNecessary(); + // Remove an item from the folder, and leave it as a single item folder. + app_list_test_model_->DeleteItem(merged_item->id()); + EXPECT_TRUE(AppListIsInFolderView()); + apps_grid_view_->GetWidget()->LayoutRootViewIfNecessary(); + // Remove the original drag view item. - app_list_test_model_->DeleteItem(dragged_item->id(), - /*can_clean_folder=*/true); + app_list_test_model_->DeleteItem(dragged_item->id()); + apps_grid_test_api_->WaitForItemMoveAnimationDone(); + + EXPECT_FALSE(AppListIsInFolderView()); + EXPECT_FALSE(apps_grid_view_->GetItemViewAt(3)->item()->is_folder()); + + // Verify that a pending layout, if any, does not cause a crash. + apps_grid_view_->InvalidateLayout(); + apps_grid_view_->GetWidget()->LayoutRootViewIfNecessary(); +} + +TEST_F(PopulatedAppListTest, ReparentLastFolderItemAfterFolderCreation) { + InitializeAppsGrid(); + const int kItemCount = 5; + PopulateApps(kItemCount); + + // Dragging the item with index 4. + AppListItemView* const dragged_view = apps_grid_view_->GetItemViewAt(4); + AppListItem* const dragged_item = dragged_view->item(); + AppListItem* const merged_item = apps_grid_view_->GetItemViewAt(3)->item(); + + // Drag the item on top of the item with index 3. + ui::test::EventGenerator* event_generator = GetEventGenerator(); + event_generator->MoveMouseTo(dragged_view->GetBoundsInScreen().CenterPoint()); + event_generator->PressLeftButton(); + dragged_view->FireMouseDragTimerForTest(); + // Move mouse to switch to cardified state -the cardified state starts only + // once the drag distance exceeds a drag threshold, so the pointer has to + // sufficiently move from the original position. + event_generator->MoveMouseBy(10, 10); + event_generator->MoveMouseTo( + apps_grid_view_->GetItemViewAt(3)->GetBoundsInScreen().CenterPoint()); + event_generator->ReleaseLeftButton(); + EXPECT_FALSE(apps_grid_view_->IsDragging()); + + AppListItem* folder_item = apps_grid_view_->GetItemViewAt(3)->item(); + EXPECT_TRUE(folder_item->is_folder()); + EXPECT_EQ(dragged_item->folder_id(), folder_item->id()); + + // Verify that item layers have been destroyed after the drag operation ended. + apps_grid_test_api_->WaitForItemMoveAnimationDone(); + + for (int i = 0; i < apps_grid_view_->view_model()->view_size(); ++i) { + views::View* item_view = apps_grid_view_->view_model()->view_at(i); + EXPECT_FALSE(item_view->layer()) << "at " << i; + } + + // Open the newly created folder. + event_generator->MoveMouseTo( + apps_grid_view_->GetItemViewAt(3)->GetBoundsInScreen().CenterPoint()); + event_generator->ClickLeftButton(); + event_generator->ReleaseLeftButton(); + + // Verify that item views have no layers after the folder has been opened. + apps_grid_test_api_->WaitForItemMoveAnimationDone(); + EXPECT_TRUE(AppListIsInFolderView()); + for (int i = 0; i < apps_grid_view_->view_model()->view_size(); ++i) { + views::View* item_view = apps_grid_view_->view_model()->view_at(i); + EXPECT_FALSE(item_view->layer()) << "at " << i; + } + + // Verify that a pending layout, if any, does not cause a crash. + apps_grid_view_->InvalidateLayout(); + apps_grid_view_->GetWidget()->LayoutRootViewIfNecessary(); + + // Remove the original drag view item. + app_list_test_model_->DeleteItem(dragged_item->id()); + // Reparent the remaining folder item to the root apps grid (as it's done by + // Chrome when cleaning up single-item folders). + app_list_test_model_->MoveItemToRootAt(merged_item, folder_item->position()); apps_grid_test_api_->WaitForItemMoveAnimationDone(); EXPECT_FALSE(AppListIsInFolderView());
diff --git a/ash/app_list/folder_image_unittest.cc b/ash/app_list/folder_image_unittest.cc index 0221925..1c4b6602 100644 --- a/ash/app_list/folder_image_unittest.cc +++ b/ash/app_list/folder_image_unittest.cc
@@ -147,7 +147,7 @@ EXPECT_TRUE(ImagesAreEqual(icon3, folder_image_->icon())); // Delete an item. Ensure that the observer fired and the icon changed. - app_list_model_->DeleteItem("app2", /*can_clean_folder=*/false); + app_list_model_->DeleteItem("app2"); EXPECT_TRUE(observer_.updated()); observer_.Reset(); gfx::ImageSkia icon4 = folder_image_->icon(); @@ -167,8 +167,8 @@ } TEST_P(FolderImageTest, GetTargetIconRectInFolderWithSingleItem) { - app_list_model_->DeleteItem("app2", /*can_clean_folder=*/false); - app_list_model_->DeleteItem("app3", /*can_clean_folder=*/false); + app_list_model_->DeleteItem("app2"); + app_list_model_->DeleteItem("app3"); const AppListConfig* config = AppListConfigProvider::Get().GetConfigForType(GetParam(), false); ASSERT_TRUE(config); @@ -198,7 +198,7 @@ } TEST_P(FolderImageTest, GetTargetIconRectInFolderWithTwoItems) { - app_list_model_->DeleteItem("app3", /*can_clean_folder=*/false); + app_list_model_->DeleteItem("app3"); const AppListConfig* config = AppListConfigProvider::Get().GetConfigForType(GetParam(), false); ASSERT_TRUE(config);
diff --git a/ash/app_list/model/app_list_folder_item.cc b/ash/app_list/model/app_list_folder_item.cc index e01a57a..f64ba57 100644 --- a/ash/app_list/model/app_list_folder_item.cc +++ b/ash/app_list/model/app_list_folder_item.cc
@@ -59,6 +59,10 @@ return item_list_->FindItem(id); } +AppListItem* AppListFolderItem::GetChildItemAt(size_t index) { + return item_list_->item_at(index); +} + size_t AppListFolderItem::ChildItemCount() const { return item_list_->item_count(); }
diff --git a/ash/app_list/model/app_list_folder_item.h b/ash/app_list/model/app_list_folder_item.h index 9d2ab6a..3325e7f 100644 --- a/ash/app_list/model/app_list_folder_item.h +++ b/ash/app_list/model/app_list_folder_item.h
@@ -74,6 +74,7 @@ // AppListItem overrides: const char* GetItemType() const override; AppListItem* FindChildItem(const std::string& id) override; + AppListItem* GetChildItemAt(size_t index) override; size_t ChildItemCount() const override; // AppListConfigProvider::Observer override:
diff --git a/ash/app_list/model/app_list_item.cc b/ash/app_list/model/app_list_item.cc index d351f02..d8dffd2 100644 --- a/ash/app_list/model/app_list_item.cc +++ b/ash/app_list/model/app_list_item.cc
@@ -109,6 +109,10 @@ return nullptr; } +AppListItem* AppListItem::GetChildItemAt(size_t index) { + return nullptr; +} + size_t AppListItem::ChildItemCount() const { return 0; }
diff --git a/ash/app_list/model/app_list_item.h b/ash/app_list/model/app_list_item.h index 19ca56f..20be0ba 100644 --- a/ash/app_list/model/app_list_item.h +++ b/ash/app_list/model/app_list_item.h
@@ -91,6 +91,10 @@ // a folder), or nullptr if the item was not found or this is not a container. virtual AppListItem* FindChildItem(const std::string& id); + // Returns the child item at the provided index in the child item list. + // Returns nullptr for non-folder items. + virtual AppListItem* GetChildItemAt(size_t index); + // Returns the number of child items if it has any (e.g. is a folder) or 0. virtual size_t ChildItemCount() const;
diff --git a/ash/app_list/model/app_list_model.cc b/ash/app_list/model/app_list_model.cc index e3e072c5..b2e0aaa 100644 --- a/ash/app_list/model/app_list_model.cc +++ b/ash/app_list/model/app_list_model.cc
@@ -243,7 +243,7 @@ observer.OnAppListItemUpdated(item); } -void AppListModel::DeleteItem(const std::string& id, bool can_clean_folder) { +void AppListModel::DeleteItem(const std::string& id) { AppListItem* item = FindItem(id); if (!item) return; @@ -265,17 +265,6 @@ // Destroy `item`. ReparentOrDeleteItemInFolder(item, /*destination_folder_id=*/absl::nullopt); - - if (!can_clean_folder) - return; - - AppListFolderItem* folder = FindFolderItem(copied_folder_id); - if (folder && folder->ShouldAutoRemove() && - folder->item_list()->item_count() == 1) { - // If the parent folder should be removed, reparent the last child first. - AppListItem* last_item = folder->item_list()->item_at(0); - MoveItemToRootAt(last_item, folder->position()); - } } void AppListModel::AddFolderItemForTest(const std::string& folder_id) { @@ -411,7 +400,7 @@ DVLOG(2) << "Deleting empty folder: " << folder->ToDebugString(); std::string copy_id = folder->id(); - DeleteItem(copy_id, /*can_clean_folder=*/false); + DeleteItem(copy_id); } void AppListModel::SetRootItemPosition(
diff --git a/ash/app_list/model/app_list_model.h b/ash/app_list/model/app_list_model.h index d8a66c1..8fa28e4 100644 --- a/ash/app_list/model/app_list_model.h +++ b/ash/app_list/model/app_list_model.h
@@ -114,9 +114,8 @@ void SetItemName(AppListItem* item, const std::string& name); // Deletes the item matching |id| from |top_level_item_list_| or from the - // appropriate folder. If `can_clean_folder` is true, the deleted item's - // parent folder could be removed as well. - void DeleteItem(const std::string& id, bool can_clean_folder); + // appropriate folder. + void DeleteItem(const std::string& id); // Creates and adds an empty folder item with the provided ID. void AddFolderItemForTest(const std::string& folder_id);
diff --git a/ash/app_list/model/app_list_model_unittest.cc b/ash/app_list/model/app_list_model_unittest.cc index d95adfb..aa41eaba 100644 --- a/ash/app_list/model/app_list_model_unittest.cc +++ b/ash/app_list/model/app_list_model_unittest.cc
@@ -211,18 +211,17 @@ const size_t num_apps = 4; model_->PopulateApps(num_apps); // Remove an item in the middle. - model_->DeleteItem(model_->GetItemName(1), /*can_clean_folder=*/false); + model_->DeleteItem(model_->GetItemName(1)); EXPECT_EQ(num_apps - 1, model_->top_level_item_list()->item_count()); EXPECT_EQ(1u, observer_.items_removed()); EXPECT_EQ("Item 0,Item 2,Item 3", GetModelContents()); // Remove the first item in the list. - model_->DeleteItem(model_->GetItemName(0), /*can_clean_folder=*/false); + model_->DeleteItem(model_->GetItemName(0)); EXPECT_EQ(num_apps - 2, model_->top_level_item_list()->item_count()); EXPECT_EQ(2u, observer_.items_removed()); EXPECT_EQ("Item 2,Item 3", GetModelContents()); // Remove the last item in the list. - model_->DeleteItem(model_->GetItemName(num_apps - 1), - /*can_clean_folder=*/false); + model_->DeleteItem(model_->GetItemName(num_apps - 1)); EXPECT_EQ(num_apps - 3, model_->top_level_item_list()->item_count()); EXPECT_EQ(3u, observer_.items_removed()); EXPECT_EQ("Item 2", GetModelContents()); @@ -512,14 +511,14 @@ EXPECT_EQ("folder1", GetModelContents()); // Delete Item 2 from folder. - model_->DeleteItem("Item 2", /*can_clean_folder=*/true); + model_->DeleteItem("Item 2"); EXPECT_EQ("Item 0,Item 1", GetItemListContents(folder1->item_list())); EXPECT_EQ("folder1", GetModelContents()); // Delete Item 1 from folder, should reparent Item 0 and delete folder1. - model_->DeleteItem("Item 1", /*can_clean_folder=*/true); - EXPECT_EQ(nullptr, model_->FindItem("folder1")); - EXPECT_EQ("Item 0", GetModelContents()); + model_->DeleteItem("Item 1"); + EXPECT_EQ("Item 0", GetItemListContents(folder1->item_list())); + EXPECT_EQ("folder1", GetModelContents()); } TEST_F(AppListModelFolderTest, UninstallPersistentFolderItem) { @@ -537,7 +536,7 @@ EXPECT_EQ("folder1", GetModelContents()); // Delete Item from folder. - model_->DeleteItem("Item 1", /*can_clean_folder=*/true); + model_->DeleteItem("Item 1"); ASSERT_EQ("folder1", GetModelContents()); EXPECT_EQ("Item 0", GetItemListContents(folder1->item_list())); } @@ -554,7 +553,7 @@ EXPECT_EQ("folder1", GetModelContents()); // Delete only item from folder, folder should also be removed. - model_->DeleteItem("Item 0", /*can_clean_folder=*/true); + model_->DeleteItem("Item 0"); EXPECT_EQ(nullptr, model_->FindItem("folder1")); EXPECT_EQ("", GetModelContents()); }
diff --git a/ash/app_list/paged_view_structure.cc b/ash/app_list/paged_view_structure.cc index 1aa8c86..acbb3781 100644 --- a/ash/app_list/paged_view_structure.cc +++ b/ash/app_list/paged_view_structure.cc
@@ -145,7 +145,7 @@ // Do not increase |item_index| after this call because it modifies // |item_list|. - model->DeleteItem(item->id(), /*can_clean_folder=*/false); + model->DeleteItem(item->id()); item_list->AddObserver(apps_grid_view_); continue; }
diff --git a/ash/app_list/views/apps_grid_view.cc b/ash/app_list/views/apps_grid_view.cc index 06219e3..70fb00a 100644 --- a/ash/app_list/views/apps_grid_view.cc +++ b/ash/app_list/views/apps_grid_view.cc
@@ -1946,7 +1946,6 @@ { ScopedModelUpdate update(this); model_->MoveItemToRootAt(item, target_position); - RemoveLastItemFromReparentItemFolderIfNecessary(source_folder_id); } } @@ -1977,39 +1976,12 @@ LOG(ERROR) << "Unable to reparent to item id: " << target_item->id(); return false; } - RemoveLastItemFromReparentItemFolderIfNecessary(source_folder_id); } RecordAppMovingTypeMetrics(kMoveIntoAnotherFolder); return true; } -// After moving the re-parenting item out of the folder, if there is only 1 item -// left, remove the last item out of the folder, delete the folder and insert it -// to the data model at the same position. Make the same change to view_model_ -// accordingly. -void AppsGridView::RemoveLastItemFromReparentItemFolderIfNecessary( - const std::string& source_folder_id) { - // This function should be called along with other model updates, such as - // moving an item out of the parent folder. - DCHECK(updating_model_); - - AppListFolderItem* source_folder = - static_cast<AppListFolderItem*>(item_list_->FindItem(source_folder_id)); - if (!source_folder || (source_folder && !source_folder->ShouldAutoRemove())) - return; - - // For single-app folders (which can exist for system-managed folders, see - // crbug.com/925052) there will not be a "last item" so we can ignore the - // rest. - if (!source_folder || source_folder->item_list()->item_count() != 1) - return; - - // Now make the data change to remove the folder item in model. - AppListItem* last_item = source_folder->item_list()->item_at(0); - model_->MoveItemToRootAt(last_item, source_folder->position()); -} - void AppsGridView::CancelContextMenusOnCurrentPage() { GridIndex start_index(GetSelectedPage(), 0); if (!IsValidIndex(start_index))
diff --git a/ash/app_list/views/apps_grid_view.h b/ash/app_list/views/apps_grid_view.h index 7fcc04f..951b507 100644 --- a/ash/app_list/views/apps_grid_view.h +++ b/ash/app_list/views/apps_grid_view.h
@@ -617,12 +617,6 @@ bool ReparentItemToAnotherFolder(AppListItem* item_view, const GridIndex& target); - // If there is only 1 item left in the source folder after reparenting an item - // from it, updates data model to remove last item from the source folder and - // remove the source folder. - void RemoveLastItemFromReparentItemFolderIfNecessary( - const std::string& source_folder_id); - // Removes the AppListItemView at |index| in |view_model_|, removes it from // view structure as well and deletes it. void DeleteItemViewAtIndex(int index);
diff --git a/ash/app_list/views/apps_grid_view_unittest.cc b/ash/app_list/views/apps_grid_view_unittest.cc index 5f688abc..de3602ca 100644 --- a/ash/app_list/views/apps_grid_view_unittest.cc +++ b/ash/app_list/views/apps_grid_view_unittest.cc
@@ -842,8 +842,7 @@ AppListItemView* last_view = GetItemViewInTopLevelGrid(kLastItemIndex); apps_grid_view_->SetSelectedView(last_view); - model_->DeleteItem(model_->GetItemName(kLastItemIndex), - /*can_clean_folder=*/false); + model_->DeleteItem(model_->GetItemName(kLastItemIndex)); EXPECT_FALSE(apps_grid_view_->IsSelectedView(last_view)); @@ -1235,8 +1234,7 @@ // Remove one item from the folder with 4 items. The bound should stay the // same as there are still two rows in the folder view. - model_->DeleteItem(folder_2->item_list()->item_at(0)->id(), - /*can_clean_folder=*/false); + model_->DeleteItem(folder_2->item_list()->item_at(0)->id()); EXPECT_TRUE(GetAppListTestHelper()->IsInFolderView()); items_grid_view->GetWidget()->LayoutRootViewIfNecessary(); EXPECT_EQ(items_grid_view->GetBoundsInScreen().size(), @@ -1244,8 +1242,7 @@ // Remove another item from the folder. The bound should update and become the // folder view with one row. - model_->DeleteItem(folder_2->item_list()->item_at(0)->id(), - /*can_clean_folder=*/false); + model_->DeleteItem(folder_2->item_list()->item_at(0)->id()); EXPECT_TRUE(GetAppListTestHelper()->IsInFolderView()); items_grid_view->GetWidget()->LayoutRootViewIfNecessary(); EXPECT_EQ(items_grid_view->GetBoundsInScreen().size(), @@ -2036,7 +2033,7 @@ gfx::Point to = GetItemRectOnCurrentPageAt(0, 1).CenterPoint(); UpdateDrag(AppsGridView::MOUSE, to, apps_grid_view_, 10 /*steps*/); - model_->DeleteItem(model_->GetItemName(2), /*can_clean_folder=*/false); + model_->DeleteItem(model_->GetItemName(2)); EndDrag(apps_grid_view_, false /*cancel*/); EXPECT_EQ(std::string("Item 0,Item 1"), model_->GetModelContent()); @@ -2838,13 +2835,15 @@ } // Verify the dragged item's focus after the item is dragged from a folder with -// two items. +// a single items. TEST_P(AppsGridViewDragTest, FocusOfReparentedDragViewWithFolderDeleted) { // Creates a folder item with two items. model_->CreateAndPopulateFolderWithApps(2); model_->PopulateApps(1); test_api_->Update(); + // Leave the dragged item as a single folder child. + model_->DeleteItem("Item 1"); // One folder and one app. Therefore the top level view count is 2. EXPECT_EQ(2, apps_grid_view_->view_model()->view_size()); @@ -2874,14 +2873,13 @@ BoundsChangeCounter counter(GetItemViewInTopLevelGrid(1)); EndDrag(folder_apps_grid_view(), /*cancel=*/false); - // The folder should be deleted. The first item should be Item 1, the second - // item should be Item 2 and the last item should be Item 0. - EXPECT_EQ(3, apps_grid_view_->view_model()->view_size()); - EXPECT_EQ("Item 1", GetItemViewInTopLevelGrid(0)->item()->id()); - EXPECT_EQ("Item 2", GetItemViewInTopLevelGrid(1)->item()->id()); - EXPECT_EQ("Item 0", GetItemViewInTopLevelGrid(2)->item()->id()); + // The folder should be deleted. The first item should be Item 2, the second + // item should be Item 0. + EXPECT_EQ(2, apps_grid_view_->view_model()->view_size()); + EXPECT_EQ("Item 2", GetItemViewInTopLevelGrid(0)->item()->id()); + EXPECT_EQ("Item 0", GetItemViewInTopLevelGrid(1)->item()->id()); - AppListItemView* const dragged_view = GetItemViewInTopLevelGrid(2); + AppListItemView* const dragged_view = GetItemViewInTopLevelGrid(1); if (features::IsProductivityLauncherEnabled()) { // Verify that Item 2's bounds do not change after calling `EndDrag()`. EXPECT_EQ(0, counter.bounds_change_count());
diff --git a/ash/app_list/views/scrollable_apps_grid_view_unittest.cc b/ash/app_list/views/scrollable_apps_grid_view_unittest.cc index 4c75dfb3..9886e66e 100644 --- a/ash/app_list/views/scrollable_apps_grid_view_unittest.cc +++ b/ash/app_list/views/scrollable_apps_grid_view_unittest.cc
@@ -91,8 +91,7 @@ void DeleteApps(int n) { AppListItemList* item_list = app_list_test_model_->top_level_item_list(); for (int i = 0; i < n; i++) { - app_list_test_model_->DeleteItem(item_list->item_at(0)->id(), - /*can_clean_folder=*/false); + app_list_test_model_->DeleteItem(item_list->item_at(0)->id()); } }
diff --git a/ash/app_list/views/search_result_view.cc b/ash/app_list/views/search_result_view.cc index ba70463..ec4d66dd 100644 --- a/ash/app_list/views/search_result_view.cc +++ b/ash/app_list/views/search_result_view.cc
@@ -66,6 +66,10 @@ constexpr int kPrimaryTextHeight = 20; constexpr int kAnswerCardDetailsLineHeight = 18; +constexpr int kAnswerCardCardBackgroundCornerRadius = 12; +constexpr int kAnswerCardFocusBarOffset = 24; +constexpr int kAnswerCardFocusBarHeight = 32; + // Corner radius for downloaded image icons. constexpr int kImageIconCornerRadius = 4; @@ -510,15 +514,27 @@ gfx::Rect content_rect(rect); - // Possibly call FillRect a second time (these colours are partially - // transparent, so the previous FillRect is not redundant). if (selected() && !actions_view()->HasSelectedAction()) { - // Fill search result view row item. - canvas->FillRect( - content_rect, - AppListColorProvider::Get()->GetSearchResultViewHighlightColor()); - PaintFocusBar(canvas, GetContentsBounds().origin(), - /*height=*/GetContentsBounds().height()); + switch (view_type_) { + case SearchResultViewType::kDefault: + case SearchResultViewType::kClassic: + canvas->FillRect( + content_rect, + AppListColorProvider::Get()->GetSearchResultViewHighlightColor()); + PaintFocusBar(canvas, GetContentsBounds().origin(), + /*height=*/GetContentsBounds().height()); + break; + case SearchResultViewType::kAnswerCard: { + cc::PaintFlags flags; + flags.setAntiAlias(true); + flags.setColor( + AppListColorProvider::Get()->GetSearchResultViewHighlightColor()); + canvas->DrawRoundRect(content_rect, + kAnswerCardCardBackgroundCornerRadius, flags); + PaintFocusBar(canvas, gfx::Point(0, kAnswerCardFocusBarOffset), + kAnswerCardFocusBarHeight); + } break; + } } }
diff --git a/ash/ash_strings.grd b/ash/ash_strings.grd index 14a82810..7f1876d 100644 --- a/ash/ash_strings.grd +++ b/ash/ash_strings.grd
@@ -1380,6 +1380,9 @@ <message name="IDS_ASH_HOLDING_SPACE_IN_PROGRESS_DOWNLOAD_A11Y_NAME" desc="The accessible name for a view representing an in-progress download holding space item. The placeholder, FILENAME, is the filename of the holding space item's backing file."> Downloading <ph name="FILENAME">$1<ex>example.txt</ex></ph> </message> + <message name="IDS_ASH_HOLDING_SPACE_IN_PROGRESS_DOWNLOAD_A11Y_NAME_CONFIRM" desc="The accessible name for a view representing an in-progress download holding space item which must be kept/discarded via notification. The placeholder, FILENAME, is the filename of the holding space item's backing file."> + Confirm download <ph name="FILENAME">$1<ex>example.txt</ex></ph> + </message> <message name="IDS_ASH_HOLDING_SPACE_IN_PROGRESS_DOWNLOAD_A11Y_NAME_DANGEROUS" desc="The accessible name for a view representing an in-progress download holding space item which is dangerous. The placeholder, FILENAME, is the filename of the holding space item's backing file."> Download dangerous <ph name="FILENAME">$1<ex>example.txt</ex></ph> </message> @@ -1389,6 +1392,9 @@ <message name="IDS_ASH_HOLDING_SPACE_IN_PROGRESS_DOWNLOAD_A11Y_NAME_PAUSED" desc="The accessible name for a view representing an in-progress download holding space item which is paused. The placeholder, FILENAME, is the filename of the holding space item's backing file."> Download paused <ph name="FILENAME">$1<ex>example.txt</ex></ph> </message> + <message name="IDS_ASH_HOLDING_SPACE_IN_PROGRESS_DOWNLOAD_CONFIRM" desc="Text displayed in a holding space download chip to indicate the underlying download must be kept/discarded via notification."> + Confirm download + </message> <message name="IDS_ASH_HOLDING_SPACE_IN_PROGRESS_DOWNLOAD_DANGEROUS_FILE" desc="Text displayed in a holding space download chip to indicate the underlying download is a dangerous file."> Dangerous file </message> @@ -4309,14 +4315,14 @@ <message name="IDS_AUTH_FACTOR_LABEL_CANNOT_UNLOCK" desc="Label on user's lock screen when unlock authentication methods fail."> Can't unlock your Chromebook </message> - <message name="IDS_AUTH_FACTOR_LABEL_UNLOCK_PASSWORD" desc="Label on user's lock screen prompting user to enter password after other unlock authentication methods fail."> - To unlock your Chromebook, enter password - </message> <message name="IDS_AUTH_FACTOR_LABEL_CANNOT_SIGN_IN" desc="Label on user's lock screen when sign in authentication methods fail."> Can't sign in to your Chromebook </message> - <message name="IDS_AUTH_FACTOR_LABEL_SIGN_IN_PASSWORD" desc="Label on user's lock screen prompting user to enter password after other sign in authentication methods fail."> - To sign in to your Chromebook, enter password + <message name="IDS_AUTH_FACTOR_LABEL_PASSWORD_REQUIRED" desc="Label on user's lock screen prompting user to enter password after other sign in authentication methods fail."> + Enter password for more security + </message> + <message name="IDS_AUTH_FACTOR_LABEL_PASSWORD_OR_PIN_REQUIRED" desc="Label on user's lock screen prompting user to enter password or PIN after other sign in authentication methods fail."> + Enter password or PIN for more security </message> <message name="IDS_AUTH_FACTOR_LABEL_CLICK_TO_ENTER" desc="Label on user's lock screen when a user is successfully authenticated and may click to enter Chromebook."> Tap or click to enter
diff --git a/ash/ash_strings_grd/IDS_ASH_HOLDING_SPACE_IN_PROGRESS_DOWNLOAD_A11Y_NAME_CONFIRM.png.sha1 b/ash/ash_strings_grd/IDS_ASH_HOLDING_SPACE_IN_PROGRESS_DOWNLOAD_A11Y_NAME_CONFIRM.png.sha1 new file mode 100644 index 0000000..d0fef4f1 --- /dev/null +++ b/ash/ash_strings_grd/IDS_ASH_HOLDING_SPACE_IN_PROGRESS_DOWNLOAD_A11Y_NAME_CONFIRM.png.sha1
@@ -0,0 +1 @@ +308d8ee6e4c32ff36286ac45bed41f89834179e2 \ No newline at end of file
diff --git a/ash/ash_strings_grd/IDS_ASH_HOLDING_SPACE_IN_PROGRESS_DOWNLOAD_CONFIRM.png.sha1 b/ash/ash_strings_grd/IDS_ASH_HOLDING_SPACE_IN_PROGRESS_DOWNLOAD_CONFIRM.png.sha1 new file mode 100644 index 0000000..1f4d908 --- /dev/null +++ b/ash/ash_strings_grd/IDS_ASH_HOLDING_SPACE_IN_PROGRESS_DOWNLOAD_CONFIRM.png.sha1
@@ -0,0 +1 @@ +6934c75c9cab871d6d7dc154d7d1cf8a68a0d3c1 \ No newline at end of file
diff --git a/ash/ash_strings_grd/IDS_AUTH_FACTOR_LABEL_PASSWORD_OR_PIN_REQUIRED.png.sha1 b/ash/ash_strings_grd/IDS_AUTH_FACTOR_LABEL_PASSWORD_OR_PIN_REQUIRED.png.sha1 new file mode 100644 index 0000000..fc157cdd --- /dev/null +++ b/ash/ash_strings_grd/IDS_AUTH_FACTOR_LABEL_PASSWORD_OR_PIN_REQUIRED.png.sha1
@@ -0,0 +1 @@ +e52c573ba7cbee2cf1759df2f0fc53bc051a6666 \ No newline at end of file
diff --git a/ash/ash_strings_grd/IDS_AUTH_FACTOR_LABEL_PASSWORD_REQUIRED.png.sha1 b/ash/ash_strings_grd/IDS_AUTH_FACTOR_LABEL_PASSWORD_REQUIRED.png.sha1 new file mode 100644 index 0000000..1633ba6c --- /dev/null +++ b/ash/ash_strings_grd/IDS_AUTH_FACTOR_LABEL_PASSWORD_REQUIRED.png.sha1
@@ -0,0 +1 @@ +cbb6d4f70709a4247909725c915c0770b14db068 \ No newline at end of file
diff --git a/ash/ash_strings_grd/IDS_AUTH_FACTOR_LABEL_SIGN_IN_PASSWORD.png.sha1 b/ash/ash_strings_grd/IDS_AUTH_FACTOR_LABEL_SIGN_IN_PASSWORD.png.sha1 deleted file mode 100644 index 8178b0d..0000000 --- a/ash/ash_strings_grd/IDS_AUTH_FACTOR_LABEL_SIGN_IN_PASSWORD.png.sha1 +++ /dev/null
@@ -1 +0,0 @@ -674e098094aa680283025dce9418efd1c3346a23 \ No newline at end of file
diff --git a/ash/ash_strings_grd/IDS_AUTH_FACTOR_LABEL_UNLOCK_PASSWORD.png.sha1 b/ash/ash_strings_grd/IDS_AUTH_FACTOR_LABEL_UNLOCK_PASSWORD.png.sha1 deleted file mode 100644 index 6c14817..0000000 --- a/ash/ash_strings_grd/IDS_AUTH_FACTOR_LABEL_UNLOCK_PASSWORD.png.sha1 +++ /dev/null
@@ -1 +0,0 @@ -0872f00f9524a7331887eeefe3bd433a9cb040a3 \ No newline at end of file
diff --git a/ash/capture_mode/capture_mode_unittests.cc b/ash/capture_mode/capture_mode_unittests.cc index da114808..0bf2483 100644 --- a/ash/capture_mode/capture_mode_unittests.cc +++ b/ash/capture_mode/capture_mode_unittests.cc
@@ -4794,6 +4794,7 @@ auto* projector_session = ProjectorSession::Get(); EXPECT_FALSE(projector_session->is_active()); auto* projector_controller = ProjectorController::Get(); + EXPECT_CALL(projector_client_, MinimizeProjectorApp()); projector_controller->StartProjectorSession("projector_data"); EXPECT_TRUE(projector_session->is_active()); }
diff --git a/ash/components/device_activity/device_activity_client.cc b/ash/components/device_activity/device_activity_client.cc index 66e0270e3..f4c7804 100644 --- a/ash/components/device_activity/device_activity_client.cc +++ b/ash/components/device_activity/device_activity_client.cc
@@ -8,6 +8,7 @@ #include "ash/components/device_activity/fresnel_service.pb.h" #include "base/i18n/time_formatting.h" #include "base/strings/string_util.h" +#include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/time/time.h" #include "components/prefs/pref_service.h" @@ -80,8 +81,11 @@ // TODO(https://crbug.com/1262187): This window identifier will need to support // more use cases in the future. Currently it only supports the kCrosDaily use // case. -std::string GenerateWindowIdentifier(base::Time ts) { - return base::UTF16ToUTF8(base::TimeFormatWithPattern(ts, "yyyyMMdd")); +std::string GenerateUTCWindowIdentifier(base::Time ts) { + base::Time::Exploded exploded; + ts.UTCExplode(&exploded); + return base::StringPrintf("%04d%02d%02d", exploded.year, exploded.month, + exploded.day_of_month); } // Calculates an HMAC of |message| using |key|, encoded as a hexadecimal string. @@ -133,8 +137,8 @@ // support kCrosMonthly and kCrosAllTime use cases. bool IsDailyDeviceActivePingRequired(base::Time prev_ping_ts, base::Time new_ping_ts) { - std::string prev_ping_ts_period = GenerateWindowIdentifier(prev_ping_ts); - std::string new_ping_ts_period = GenerateWindowIdentifier(new_ping_ts); + std::string prev_ping_ts_period = GenerateUTCWindowIdentifier(prev_ping_ts); + std::string new_ping_ts_period = GenerateUTCWindowIdentifier(new_ping_ts); return prev_ping_ts < new_ping_ts && prev_ping_ts_period != new_ping_ts_period; @@ -229,6 +233,12 @@ return; } + // Check the last recorded daily ping timestamp in local state prefs. + // This variable has the default Unix Epoch value if the device is + // new, powerwashed, recovered, or a RMA device. + base::Time last_recorded_daily_ping_time = + local_state_->GetTime(prefs::kDeviceActiveLastKnownDailyPingTimestamp); + // The network is connected and the client |state_| is kIdle. last_transition_out_of_idle_time_ = base::Time::Now(); @@ -236,12 +246,10 @@ // within the given use case window. // TODO(https://crbug.com/1262187): Remove hardcoded use case when adding // support for additional use cases (i.e MONTHLY, ALL_TIME, etc.). - if (IsDailyDeviceActivePingRequired( - local_state_->GetTime( - prefs::kDeviceActiveLastKnownDailyPingTimestamp), - last_transition_out_of_idle_time_)) { + if (IsDailyDeviceActivePingRequired(last_recorded_daily_ping_time, + last_transition_out_of_idle_time_)) { current_day_window_id_ = - GenerateWindowIdentifier(last_transition_out_of_idle_time_); + GenerateUTCWindowIdentifier(last_transition_out_of_idle_time_); current_day_psm_id_ = GeneratePsmIdentifier( psm_device_active_secret_, psm_rlwe::RlweUseCase_Name(kDailyPsmUseCase), current_day_window_id_.value());
diff --git a/ash/login/ui/arrow_button_view.cc b/ash/login/ui/arrow_button_view.cc index d050f64..04182b6 100644 --- a/ash/login/ui/arrow_button_view.cc +++ b/ash/login/ui/arrow_button_view.cc
@@ -12,6 +12,8 @@ #include "cc/paint/paint_flags.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/compositor/layer.h" +#include "ui/compositor/layer_animation_sequence.h" +#include "ui/compositor/layer_animator.h" #include "ui/gfx/animation/multi_animation.h" #include "ui/gfx/animation/tween.h" #include "ui/gfx/canvas.h" @@ -34,6 +36,19 @@ // How long does a single step of the loading animation take - i.e., the time it // takes for the arc to grow from a point to a full circle. constexpr base::TimeDelta kLoadingAnimationStepDuration = base::Seconds(2); +// Size that transform animation will scale view up by. +constexpr SkScalar kTransformScaleSize = 1.2; +// How long a single scale up step of the transform animation takes. +constexpr base::TimeDelta kTransformScaleUpDuration = base::Milliseconds(500); +// How long a single scale down step of the transform animation takes. +constexpr base::TimeDelta kTransformScaleDownDuration = + base::Milliseconds(1350); +// Time delay in between scaling up and down in the middle of transform +// animation cycle. +constexpr base::TimeDelta kTransformScaleDelayDuration = + base::Milliseconds(150); +// Time delay in between each full cycle of the repeating transform animation. +constexpr base::TimeDelta kTransformDelayDuration = base::Milliseconds(1000); void PaintLoadingArc(gfx::Canvas* canvas, const gfx::Rect& bounds, @@ -67,6 +82,8 @@ // Layer rendering is needed for animation. SetPaintToLayer(); layer()->SetFillsBoundsOpaquely(false); + layer()->GetAnimator()->set_preemption_strategy( + ui::LayerAnimator::PreemptionStrategy::IMMEDIATELY_ANIMATE_TO_NEW_TARGET); views::FocusRing::Get(this)->SetPathGenerator( std::make_unique<views::FixedSizeCircleHighlightPathGenerator>( @@ -108,6 +125,49 @@ AshColorProvider::GetDisabledColor(icon_color))); } +void ArrowButtonView::RunTransformAnimation() { + StopAnimating(); + + auto transform_sequence = std::make_unique<ui::LayerAnimationSequence>(); + + // Translate by |center_offset| so that the view scales outward from center + // point. + auto center_offset = gfx::Vector2d(CalculatePreferredSize().width() / 2.0, + CalculatePreferredSize().height() / 2.0); + gfx::Transform transform; + transform.Translate(center_offset); + // Make view larger. + transform.Scale(/*x=*/kTransformScaleSize, /*y=*/kTransformScaleSize); + transform.Translate(-center_offset); + auto element = ui::LayerAnimationElement::CreateTransformElement( + transform, kTransformScaleUpDuration); + element->set_tween_type(gfx::Tween::Type::ACCEL_40_DECEL_20); + transform_sequence->AddElement(std::move(element)); + + element = ui::LayerAnimationElement::CreatePauseElement( + 0, kTransformScaleDelayDuration); + transform_sequence->AddElement(std::move(element)); + + // Make view original size again. + element = ui::LayerAnimationElement::CreateTransformElement( + gfx::Transform(), kTransformScaleDownDuration); + element->set_tween_type(gfx::Tween::Type::FAST_OUT_SLOW_IN_3); + transform_sequence->AddElement(std::move(element)); + + element = + ui::LayerAnimationElement::CreatePauseElement(0, kTransformDelayDuration); + transform_sequence->AddElement(std::move(element)); + + transform_sequence->set_is_repeating(true); + + // Animator takes ownership of transform_sequence. + layer()->GetAnimator()->StartAnimation(transform_sequence.release()); +} + +void ArrowButtonView::StopAnimating() { + layer()->GetAnimator()->StopAnimating(); +} + void ArrowButtonView::EnableLoadingAnimation(bool enabled) { if (!enabled) { if (!loading_animation_)
diff --git a/ash/login/ui/arrow_button_view.h b/ash/login/ui/arrow_button_view.h index 69289c8..aca7e00 100644 --- a/ash/login/ui/arrow_button_view.h +++ b/ash/login/ui/arrow_button_view.h
@@ -34,6 +34,13 @@ void PaintButtonContents(gfx::Canvas* canvas) override; void OnThemeChanged() override; + // Causes the icon to transform bigger and smaller repeatedly to draw user + // attention to click. + void RunTransformAnimation(); + + // Stops any existing animation. + void StopAnimating(); + // Allows to control the loading animation (disabled by default). The // animation is an arc that gradually increases from a point to a full circle; // the animation is looped.
diff --git a/ash/login/ui/auth_factor_model.cc b/ash/login/ui/auth_factor_model.cc index b840246..41a2240 100644 --- a/ash/login/ui/auth_factor_model.cc +++ b/ash/login/ui/auth_factor_model.cc
@@ -7,6 +7,9 @@ namespace ash { +// static +bool AuthFactorModel::can_use_pin_ = false; + AuthFactorModel::AuthFactorModel() = default; AuthFactorModel::~AuthFactorModel() = default; @@ -64,6 +67,14 @@ UpdateIcon(icon_); } +void AuthFactorModel::set_can_use_pin(bool can_use_pin) { + can_use_pin_ = can_use_pin; +} + +bool AuthFactorModel::can_use_pin() { + return can_use_pin_; +} + void AuthFactorModel::OnArrowButtonTapOrClickEvent() {} } // namespace ash
diff --git a/ash/login/ui/auth_factor_model.h b/ash/login/ui/auth_factor_model.h index 8b18d89b..463e212 100644 --- a/ash/login/ui/auth_factor_model.h +++ b/ash/login/ui/auth_factor_model.h
@@ -61,6 +61,11 @@ kAuthenticated, }; + // Should be called when the visibility of PIN authentication changes. + static void set_can_use_pin(bool can_use_pin); + + static bool can_use_pin(); + AuthFactorModel(); AuthFactorModel(AuthFactorModel&) = delete; AuthFactorModel& operator=(AuthFactorModel&) = delete; @@ -117,6 +122,10 @@ // invoke the |update_state_callback_| if set. Calls `UpdateIcon`. void RefreshUI(); + // Indicates whether PIN is visible on the lock/login screen. May be used to + // show different labels depending on whether PIN is available. + static bool can_use_pin_; + // If the auth factor state is kErrorPermanent, this indicates whether the // error has been shown to the user and timed out, which determines whether // the error icon or the disabled icon should be shown.
diff --git a/ash/login/ui/auth_icon_view.cc b/ash/login/ui/auth_icon_view.cc index 3e2e370..28ead8a 100644 --- a/ash/login/ui/auth_icon_view.cc +++ b/ash/login/ui/auth_icon_view.cc
@@ -10,6 +10,7 @@ #include "ui/compositor/layer.h" #include "ui/compositor/layer_animation_sequence.h" #include "ui/compositor/layer_animator.h" +#include "ui/gfx/canvas.h" #include "ui/gfx/geometry/size.h" #include "ui/gfx/paint_throbber.h" #include "ui/gfx/paint_vector_icon.h" @@ -35,6 +36,19 @@ // 1 frame / 30 msec = about 30 frames per second // 30 fps seems to be smooth enough to look good without excessive painting. constexpr base::TimeDelta kProgressFrameDuration = base::Milliseconds(30); +// How long the nudge animation takes to scale up and fade out. +constexpr base::TimeDelta kNudgeAnimationScalingDuration = + base::Milliseconds(2000); +// How long the delay between the repeating nudge animation takes in between +// cycles. +constexpr base::TimeDelta kNudgeAnimationDelayDuration = + base::Milliseconds(1000); +// How opaque the nudge animation will reset the view to. +constexpr float kOpacityReset = 0.5; +// Size that nudge animation scales view up and down by. +constexpr SkScalar kTransformScaleUpSize = 3; +// The interpolation of transform fails when scaling all the way down to 0. +constexpr SkScalar kTransformScaleDownSize = 0.01; // See spec: // https://carbon.googleplex.com/cr-os-motion-work/pages/sign-in/undefined/e05c4091-eea2-4c5a-a6f8-38fd37953e7b#a929eb9f-2840-4b37-be52-97d96ca2aafa @@ -85,6 +99,12 @@ gfx::CreateVectorIcon(icon, kAuthIconSizeDp, GetColor(color))); } +void AuthIconView::SetCircleImage(int size, SkColor color) { + gfx::ImageSkia circle_icon = + gfx::CanvasImageSource::MakeImageSkia<CircleImageSource>(size, color); + icon_->SetImage(circle_icon); +} + void AuthIconView::SetAnimation(int animation_resource_id, base::TimeDelta duration, int num_frames) { @@ -97,8 +117,7 @@ } void AuthIconView::RunErrorShakeAnimation() { - // Stop any existing animation. - icon_->layer()->GetAnimator()->StopAnimating(); + StopAnimating(); auto transform_sequence = std::make_unique<ui::LayerAnimationSequence>(); gfx::Transform transform; @@ -114,6 +133,64 @@ icon_->layer()->GetAnimator()->StartAnimation(transform_sequence.release()); } +void AuthIconView::RunNudgeAnimation() { + StopAnimating(); + + // Create two separate animation sequences and run in parallel. + auto opacity_sequence = std::make_unique<ui::LayerAnimationSequence>(); + auto transform_sequence = std::make_unique<ui::LayerAnimationSequence>(); + + // Fade out view by gradually setting opacity to 0. + auto element = ui::LayerAnimationElement::CreateOpacityElement( + 0, kNudgeAnimationScalingDuration); + element->set_tween_type(gfx::Tween::Type::ACCEL_0_80_DECEL_80); + opacity_sequence->AddElement(std::move(element)); + + // Reset opacity so that |opacity_sequence| can be repeated. + element = ui::LayerAnimationElement::CreateOpacityElement(kOpacityReset, + base::TimeDelta()); + opacity_sequence->AddElement(std::move(element)); + + element = ui::LayerAnimationElement::CreatePauseElement( + 0, kNudgeAnimationDelayDuration); + opacity_sequence->AddElement(std::move(element)); + + opacity_sequence->set_is_repeating(true); + + // Every time it scales, translate by |center_offset| so that the view scales + // outward from center point. + auto center_offset = gfx::Vector2d(CalculatePreferredSize().width() / 2.0, + CalculatePreferredSize().height() / 2.0); + gfx::Transform transform; + transform.Translate(center_offset); + // Make view larger. + transform.Scale(/*x=*/kTransformScaleUpSize, /*y=*/kTransformScaleUpSize); + transform.Translate(-center_offset); + element = ui::LayerAnimationElement::CreateTransformElement( + transform, kNudgeAnimationScalingDuration); + element->set_tween_type(gfx::Tween::Type::ACCEL_0_40_DECEL_100); + transform_sequence->AddElement(std::move(element)); + + transform = gfx::Transform(); + transform.Translate(center_offset); + // Make view smaller. + transform.Scale(/*x=*/kTransformScaleDownSize, /*y=*/kTransformScaleDownSize); + transform.Translate(-center_offset); + element = ui::LayerAnimationElement::CreateTransformElement( + transform, base::TimeDelta()); + transform_sequence->AddElement(std::move(element)); + + element = ui::LayerAnimationElement::CreatePauseElement( + 0, kNudgeAnimationDelayDuration); + transform_sequence->AddElement(std::move(element)); + + transform_sequence->set_is_repeating(true); + + // Animator takes ownership of opacity_sequence and transform_sequence. + icon_->layer()->GetAnimator()->StartAnimation(opacity_sequence.release()); + icon_->layer()->GetAnimator()->StartAnimation(transform_sequence.release()); +} + void AuthIconView::StartProgressAnimation() { // Progress animation already running. if (progress_animation_timer_.IsRunning()) @@ -136,6 +213,10 @@ SchedulePaint(); } +void AuthIconView::StopAnimating() { + icon_->layer()->GetAnimator()->StopAnimating(); +} + void AuthIconView::OnPaint(gfx::Canvas* canvas) { // Draw the icon first. views::View::OnPaint(canvas); @@ -173,4 +254,16 @@ return false; } +AuthIconView::CircleImageSource::CircleImageSource(int size, SkColor color) + : gfx::CanvasImageSource(gfx::Size(size, size)), color_(color) {} + +void AuthIconView::CircleImageSource::Draw(gfx::Canvas* canvas) { + float radius = size().width() / 2.0f; + cc::PaintFlags flags; + flags.setStyle(cc::PaintFlags::kFill_Style); + flags.setAntiAlias(true); + flags.setColor(color_); + canvas->DrawCircle(gfx::PointF(radius, radius), radius, flags); +} + } // namespace ash
diff --git a/ash/login/ui/auth_icon_view.h b/ash/login/ui/auth_icon_view.h index 41e7642c..ba356e5 100644 --- a/ash/login/ui/auth_icon_view.h +++ b/ash/login/ui/auth_icon_view.h
@@ -10,6 +10,7 @@ #include "base/callback.h" #include "base/time/time.h" #include "base/timer/timer.h" +#include "ui/gfx/image/canvas_image_source.h" #include "ui/views/view.h" namespace gfx { @@ -38,6 +39,9 @@ // Show a static icon. void SetIcon(const gfx::VectorIcon& icon, Color color = Color::kPrimary); + // Show a circle icon. + void SetCircleImage(int size, SkColor color); + // Show a sequence of animation frames. |animation_resource_id| should refer // to an image with the frames of the animation layed out horizontally. // |duration| is the total duration of the animation. |num_frames| is the @@ -50,12 +54,19 @@ // occurred. void RunErrorShakeAnimation(); + // Cause the icon to repeatedly emit a circle that gradually scales up and + // fades out in order to nudge user to click. + void RunNudgeAnimation(); + // Starts a progress spinner animation if not already running. void StartProgressAnimation(); // Stops the progress spinner animation if running. void StopProgressAnimation(); + // Stops any existing animations. + void StopAnimating(); + void set_on_tap_or_click_callback(base::RepeatingClosure on_tap_or_click) { on_tap_or_click_callback_ = on_tap_or_click; } @@ -67,6 +78,20 @@ bool OnMousePressed(const ui::MouseEvent& event) override; private: + // Helper class to draw a circle that can be converted to "gfx::ImageSkia" + class CircleImageSource : public gfx::CanvasImageSource { + public: + explicit CircleImageSource(int size, SkColor color); + CircleImageSource(const CircleImageSource&) = delete; + CircleImageSource& operator=(const CircleImageSource&) = delete; + ~CircleImageSource() override = default; + + void Draw(gfx::Canvas* canvas) override; + + private: + SkColor color_; + }; + base::RepeatingClosure on_tap_or_click_callback_; AnimatedRoundedImageView* icon_;
diff --git a/ash/login/ui/fingerprint_auth_factor_model.cc b/ash/login/ui/fingerprint_auth_factor_model.cc index 19029c8c..f668717 100644 --- a/ash/login/ui/fingerprint_auth_factor_model.cc +++ b/ash/login/ui/fingerprint_auth_factor_model.cc
@@ -45,11 +45,6 @@ RefreshUI(); } -void FingerprintAuthFactorModel::SetCanUsePin(bool can_use_pin) { - can_use_pin_ = can_use_pin; - RefreshUI(); -} - AuthFactorModel::AuthFactorState FingerprintAuthFactorModel::GetAuthFactorState() const { if (!available_) @@ -102,11 +97,8 @@ // "Too many fingerprint attempts". return IDS_ASH_LOGIN_FINGERPRINT_UNLOCK_DISABLED_FROM_ATTEMPTS; case FingerprintState::DISABLED_FROM_TIMEOUT: - // TODO(crbug.com/1233614): Merge these "password required" strings with - // those used by Smart Lock. - if (can_use_pin_) - return IDS_ASH_LOGIN_FINGERPRINT_UNLOCK_PIN_OR_PASSWORD_REQUIRED; - return IDS_ASH_LOGIN_FINGERPRINT_UNLOCK_PASSWORD_REQUIRED; + return can_use_pin_ ? IDS_AUTH_FACTOR_LABEL_PASSWORD_OR_PIN_REQUIRED + : IDS_AUTH_FACTOR_LABEL_PASSWORD_REQUIRED; } NOTREACHED(); }
diff --git a/ash/login/ui/fingerprint_auth_factor_model.h b/ash/login/ui/fingerprint_auth_factor_model.h index fd541a0..7591dcb 100644 --- a/ash/login/ui/fingerprint_auth_factor_model.h +++ b/ash/login/ui/fingerprint_auth_factor_model.h
@@ -23,7 +23,6 @@ void SetFingerprintState(FingerprintState state); void NotifyFingerprintAuthResult(bool result); - void SetCanUsePin(bool can_use_pin); // If |available| is false, forces |GetAuthFactorState()| to return // |kUnavailable|, otherwise has no effect. Used to hide Fingerprint auth @@ -44,8 +43,6 @@ FingerprintState state_ = FingerprintState::AVAILABLE_DEFAULT; absl::optional<bool> auth_result_; - // Affects DISABLED_FROM_TIMEOUT message. - bool can_use_pin_ = false; bool available_ = true; };
diff --git a/ash/login/ui/login_auth_factors_view.cc b/ash/login/ui/login_auth_factors_view.cc index 18901128..8e0e3c17 100644 --- a/ash/login/ui/login_auth_factors_view.cc +++ b/ash/login/ui/login_auth_factors_view.cc
@@ -18,6 +18,7 @@ #include "ui/accessibility/ax_node_data.h" #include "ui/base/l10n/l10n_util.h" #include "ui/compositor/layer.h" +#include "ui/compositor/layer_animator.h" #include "ui/gfx/paint_vector_icon.h" #include "ui/views/border.h" #include "ui/views/controls/highlight_path_generator.h" @@ -198,6 +199,10 @@ return view_->arrow_button_; } +AuthIconView* LoginAuthFactorsView::TestApi::arrow_nudge_animation() { + return view_->arrow_nudge_animation_; +} + AuthIconView* LoginAuthFactorsView::TestApi::checkmark_icon() { return view_->checkmark_icon_; } @@ -209,12 +214,7 @@ layer()->SetFillsBoundsOpaquely(false); SetBorder(views::CreateEmptyBorder(kIconTopSpacingDp, 0, 0, 0)); - auto* layout = SetLayoutManager(std::make_unique<views::BoxLayout>( - views::BoxLayout::Orientation::kVertical, gfx::Insets(), - kSpacingBetweenIconsAndLabelDp)); - layout->set_main_axis_alignment(views::BoxLayout::MainAxisAlignment::kCenter); - layout->set_cross_axis_alignment( - views::BoxLayout::CrossAxisAlignment::kCenter); + SetBoxLayout(this); auth_factor_icon_row_ = AddChildView(std::make_unique<views::View>()); auto* animating_layout = auth_factor_icon_row_->SetLayoutManager( @@ -224,15 +224,34 @@ animating_layout->SetTargetLayoutManager( std::make_unique<views::FlexLayout>()); - arrow_button_ = AddChildView(std::make_unique<ArrowButtonView>( - base::BindRepeating(&LoginAuthFactorsView::ArrowButtonPressed, - base::Unretained(this)), - kArrowButtonSizeDp)); + arrow_icon_container_ = AddChildView(std::make_unique<views::View>()); + arrow_icon_container_->SetUseDefaultFillLayout(true); + + arrow_button_container_ = + arrow_icon_container_->AddChildView(std::make_unique<views::View>()); + SetBoxLayout(arrow_button_container_); + + arrow_button_ = + arrow_button_container_->AddChildView(std::make_unique<ArrowButtonView>( + base::BindRepeating(&LoginAuthFactorsView::ArrowButtonPressed, + base::Unretained(this)), + kArrowButtonSizeDp)); arrow_button_->SetInstallFocusRingOnFocus(true); views::InstallCircleHighlightPathGenerator(arrow_button_); arrow_button_->SetAccessibleName( l10n_util::GetStringUTF16(IDS_AUTH_FACTOR_LABEL_CLICK_TO_ENTER)); - arrow_button_->SetVisible(false); + + arrow_nudge_animation_ = + arrow_icon_container_->AddChildView(std::make_unique<AuthIconView>()); + arrow_nudge_animation_->SetCircleImage( + kArrowButtonSizeDp / 2, AshColorProvider::Get()->GetControlsLayerColor( + AshColorProvider::ControlsLayerType:: + kControlBackgroundColorInactive)); + + arrow_nudge_animation_->set_on_tap_or_click_callback(base::BindRepeating( + &LoginAuthFactorsView::RelayArrowButtonPressed, base::Unretained(this))); + + SetArrowVisibility(false); // TODO(crbug.com/1233614): Rename kLockScreenFingerprintSuccessIcon once the // feature flag is removed and FingerprintView no longer needs this. @@ -260,6 +279,14 @@ UpdateState(); } +void LoginAuthFactorsView::SetCanUsePin(bool can_use_pin) { + if (can_use_pin == AuthFactorModel::can_use_pin()) + return; + + AuthFactorModel::set_can_use_pin(can_use_pin); + UpdateState(); +} + void LoginAuthFactorsView::UpdateState() { AuthFactorModel* active_auth_factor = GetHighestPriorityAuthFactor(auth_factors_); @@ -358,10 +385,7 @@ active_auth_factor->GetLabelId(), active_auth_factor->GetAccessibleNameId()); } else { - // TODO(crbug.com/1233614): Check if pin is visible and use "enter - // password or PIN" string if it is. - SetLabelTextAndAccessibleName(IDS_AUTH_FACTOR_LABEL_UNLOCK_PASSWORD, - IDS_AUTH_FACTOR_LABEL_UNLOCK_PASSWORD); + SetLabelTextAndAccessibleName(GetDefaultLabelId(), GetDefaultLabelId()); } return; case PrioritizedAuthFactorViewState::kUnavailable: @@ -372,15 +396,14 @@ void LoginAuthFactorsView::ShowArrowButton() { auth_factor_icon_row_->SetVisible(false); - arrow_button_->SetVisible(true); checkmark_icon_->SetVisible(false); - arrow_button_->EnableLoadingAnimation(false); + SetArrowVisibility(true); } void LoginAuthFactorsView::ShowSingleAuthFactor(AuthFactorModel* auth_factor) { auth_factor_icon_row_->SetVisible(true); - arrow_button_->SetVisible(false); checkmark_icon_->SetVisible(false); + SetArrowVisibility(false); for (auto& factor : auth_factors_) { factor->SetVisible(factor.get() == auth_factor); } @@ -388,8 +411,8 @@ void LoginAuthFactorsView::ShowReadyAndDisabledAuthFactors() { auth_factor_icon_row_->SetVisible(true); - arrow_button_->SetVisible(false); checkmark_icon_->SetVisible(false); + SetArrowVisibility(false); for (auto& factor : auth_factors_) { PrioritizedAuthFactorViewState state = @@ -402,8 +425,8 @@ void LoginAuthFactorsView::ShowCheckmark() { auth_factor_icon_row_->SetVisible(false); - arrow_button_->SetVisible(false); checkmark_icon_->SetVisible(true); + SetArrowVisibility(false); // TODO(crbug.com/1233614): If transitioning from Click Required state, show // animation. } @@ -430,7 +453,7 @@ if (ready_factor_count == 0u) { LOG(ERROR) << "GetReadyLabelId() called without any ready auth factors."; NOTREACHED(); - return IDS_AUTH_FACTOR_LABEL_UNLOCK_PASSWORD; + return GetDefaultLabelId(); } if (ready_factor_count == 1u) @@ -443,7 +466,13 @@ } NOTREACHED(); - return IDS_AUTH_FACTOR_LABEL_UNLOCK_PASSWORD; + return GetDefaultLabelId(); +} + +int LoginAuthFactorsView::GetDefaultLabelId() const { + return AuthFactorModel::can_use_pin() + ? IDS_AUTH_FACTOR_LABEL_PASSWORD_OR_PIN_REQUIRED + : IDS_AUTH_FACTOR_LABEL_PASSWORD_REQUIRED; } // views::View: @@ -468,12 +497,24 @@ } void LoginAuthFactorsView::ArrowButtonPressed(const ui::Event& event) { + arrow_nudge_animation_->SetVisible(false); + arrow_nudge_animation_->StopAnimating(); + arrow_button_->StopAnimating(); + if (on_click_to_enter_callback_) { arrow_button_->EnableLoadingAnimation(true); on_click_to_enter_callback_.Run(); } } +void LoginAuthFactorsView::RelayArrowButtonPressed() { + if (arrow_button_) { + ArrowButtonPressed(ui::MouseEvent(ui::ET_MOUSE_PRESSED, gfx::Point(), + gfx::Point(), base::TimeTicks::Now(), 0, + 0)); + } +} + void LoginAuthFactorsView::OnErrorTimeout() { for (auto& factor : auth_factors_) { // If additional errors occur during the error timeout, then mark all @@ -486,4 +527,29 @@ } } +void LoginAuthFactorsView::SetBoxLayout(views::View* parent_view) { + auto* layout = + parent_view->SetLayoutManager(std::make_unique<views::BoxLayout>( + views::BoxLayout::Orientation::kVertical, gfx::Insets(), + kSpacingBetweenIconsAndLabelDp)); + layout->set_main_axis_alignment(views::BoxLayout::MainAxisAlignment::kCenter); + layout->set_cross_axis_alignment( + views::BoxLayout::CrossAxisAlignment::kCenter); +} + +void LoginAuthFactorsView::SetArrowVisibility(bool is_visible) { + arrow_icon_container_->SetVisible(is_visible); + arrow_button_->SetVisible(is_visible); + arrow_nudge_animation_->SetVisible(is_visible); + + if (is_visible) { + arrow_button_->EnableLoadingAnimation(false); + arrow_button_->RunTransformAnimation(); + arrow_nudge_animation_->RunNudgeAnimation(); + } else { + arrow_nudge_animation_->StopAnimating(); + arrow_button_->StopAnimating(); + } +} + } // namespace ash
diff --git a/ash/login/ui/login_auth_factors_view.h b/ash/login/ui/login_auth_factors_view.h index c344f18..1b6940b 100644 --- a/ash/login/ui/login_auth_factors_view.h +++ b/ash/login/ui/login_auth_factors_view.h
@@ -44,6 +44,7 @@ views::Label* label(); views::View* auth_factor_icon_row(); ArrowButtonView* arrow_button(); + AuthIconView* arrow_nudge_animation(); AuthIconView* checkmark_icon(); private: @@ -63,6 +64,11 @@ gfx::Size CalculatePreferredSize() const override; void OnThemeChanged() override; + // Should be called when the visibility of PIN authentication changes. + // Used to determine whether strings should mention that PIN can be used as an + // authentication mechanism. + void SetCanUsePin(bool can_use_pin); + private: // Recomputes the state and updates the label and icons. Should be called // whenever any auth factor's state changes so that those changes can be @@ -82,16 +88,30 @@ // Ready state. int GetReadyLabelId() const; + // Gets the label to be shown when no auth factor can be used. + int GetDefaultLabelId() const; + // Causes screen readers to read the label as an alert. void FireAlert(); // Should be called when the "click to enter" button is pressed. void ArrowButtonPressed(const ui::Event& event); + // Used when |arrow_nudge_animation_| is pressed. It prevents arrow button + // from receiving its click event directly, so it relays the click event. + void RelayArrowButtonPressed(); + // Should be called when the error timer expires. Communicates the timeout to // the auth factor models. void OnErrorTimeout(); + // Calls views::View::SetLayoutManager with views::BoxLayout for provided + // view. + void SetBoxLayout(views::View* parent_view); + + // Sets visibility of |arrow_icon_container_|, |arrow_button_|, and + // |arrow_nudge_animation_| and starts/stops arrow animations accordingly. + void SetArrowVisibility(bool is_visible); ///////////////////////////////////////////////////////////////////////////// // Child views, owned by the Views hierarchy @@ -101,10 +121,21 @@ // The label shown under the icons. Always visible. AuthFactorsLabel* label_; + // A container laying arrow button and its corresponding animation view on top + // of each other. + views::View* arrow_icon_container_; + + // A box layout container for arrow button and its label. + views::View* arrow_button_container_; + // A button with an arrow icon. Only visible when an auth factor is in the // kClickRequired state. ArrowButtonView* arrow_button_; + // A view with nudge animation expanding from arrow icon to encourage user to + // tap. Only visible when an auth factor is in the kClickRequired state. + AuthIconView* arrow_nudge_animation_; + // A green checkmark icon (or animation) shown when an auth factor reaches // the kAuthenticated state, just before the login/lock screen is dismissed. AuthIconView* checkmark_icon_;
diff --git a/ash/login/ui/login_auth_factors_view_unittest.cc b/ash/login/ui/login_auth_factors_view_unittest.cc index eec83409..a8d9de1e 100644 --- a/ash/login/ui/login_auth_factors_view_unittest.cc +++ b/ash/login/ui/login_auth_factors_view_unittest.cc
@@ -17,6 +17,7 @@ #include "base/test/scoped_feature_list.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/base/l10n/l10n_util.h" +#include "ui/compositor/scoped_animation_duration_scale_mode.h" #include "ui/events/event.h" #include "ui/views/accessibility/ax_event_manager.h" #include "ui/views/accessibility/ax_event_observer.h" @@ -245,6 +246,7 @@ EXPECT_TRUE(test_api.auth_factor_icon_row()->GetVisible()); EXPECT_FALSE(test_api.checkmark_icon()->GetVisible()); EXPECT_FALSE(test_api.arrow_button()->GetVisible()); + EXPECT_FALSE(test_api.arrow_nudge_animation()->GetVisible()); // The number of icons should match the number of auth factors initialized. EXPECT_EQ(auth_factors_.size(), @@ -268,6 +270,7 @@ EXPECT_TRUE(test_api.auth_factor_icon_row()->GetVisible()); EXPECT_FALSE(test_api.checkmark_icon()->GetVisible()); EXPECT_FALSE(test_api.arrow_button()->GetVisible()); + EXPECT_FALSE(test_api.arrow_nudge_animation()->GetVisible()); // The number of icons should match the number of auth factors initialized. EXPECT_EQ(auth_factors_.size(), @@ -283,21 +286,51 @@ } TEST_F(LoginAuthFactorsViewUnittest, ClickRequired) { + ui::ScopedAnimationDurationScaleMode non_zero_duration_mode( + ui::ScopedAnimationDurationScaleMode::NORMAL_DURATION); + AddAuthFactors({AuthFactorType::kFingerprint, AuthFactorType::kSmartLock}); LoginAuthFactorsView::TestApi test_api(view_); auth_factors_[0]->state_ = AuthFactorState::kReady; auth_factors_[1]->state_ = AuthFactorState::kClickRequired; test_api.UpdateState(); - // Check that only the arrow button is shown and that the label has been - // updated. + // Check that the arrow button and arrow nudge animation is shown and that the + // label has been updated. EXPECT_TRUE(test_api.arrow_button()->GetVisible()); + EXPECT_TRUE(test_api.arrow_nudge_animation()->GetVisible()); EXPECT_FALSE(test_api.checkmark_icon()->GetVisible()); EXPECT_FALSE(test_api.auth_factor_icon_row()->GetVisible()); EXPECT_EQ(l10n_util::GetStringUTF16(IDS_AUTH_FACTOR_LABEL_CLICK_TO_ENTER), test_api.label()->GetText()); } +TEST_F(LoginAuthFactorsViewUnittest, ClickingArrowButton) { + ui::ScopedAnimationDurationScaleMode non_zero_duration_mode( + ui::ScopedAnimationDurationScaleMode::NORMAL_DURATION); + + AddAuthFactors({AuthFactorType::kFingerprint, AuthFactorType::kSmartLock}); + LoginAuthFactorsView::TestApi test_api(view_); + auth_factors_[0]->state_ = AuthFactorState::kReady; + auth_factors_[1]->state_ = AuthFactorState::kClickRequired; + test_api.UpdateState(); + + // Check that the arrow button and arrow nudge animation is shown. + EXPECT_TRUE(test_api.arrow_button()->GetVisible()); + EXPECT_TRUE(test_api.arrow_nudge_animation()->GetVisible()); + + // Simulate clicking arrow nudge animation, which sits on top of arrow button + // and should relay arrow button click. + const gfx::Point point(0, 0); + test_api.arrow_nudge_animation()->OnMousePressed(ui::MouseEvent( + ui::ET_MOUSE_PRESSED, point, point, base::TimeTicks::Now(), 0, 0)); + + // Check that arrow button is still visible and that arrow nudge animation is + // no longer shown. + EXPECT_TRUE(test_api.arrow_button()->GetVisible()); + EXPECT_FALSE(test_api.arrow_nudge_animation()->GetVisible()); +} + TEST_F(LoginAuthFactorsViewUnittest, Authenticated) { AddAuthFactors({AuthFactorType::kFingerprint, AuthFactorType::kSmartLock}); LoginAuthFactorsView::TestApi test_api(view_); @@ -309,6 +342,7 @@ // updated. EXPECT_TRUE(test_api.checkmark_icon()->GetVisible()); EXPECT_FALSE(test_api.arrow_button()->GetVisible()); + EXPECT_FALSE(test_api.arrow_nudge_animation()->GetVisible()); EXPECT_FALSE(test_api.auth_factor_icon_row()->GetVisible()); EXPECT_EQ(l10n_util::GetStringUTF16(IDS_AUTH_FACTOR_LABEL_UNLOCKED), test_api.label()->GetText()); @@ -324,6 +358,7 @@ EXPECT_TRUE(test_api.auth_factor_icon_row()->GetVisible()); EXPECT_FALSE(test_api.checkmark_icon()->GetVisible()); EXPECT_FALSE(test_api.arrow_button()->GetVisible()); + EXPECT_FALSE(test_api.arrow_nudge_animation()->GetVisible()); // Only the error should be visible for the first three seconds after the // state update. @@ -345,6 +380,7 @@ EXPECT_TRUE(test_api.auth_factor_icon_row()->GetVisible()); EXPECT_FALSE(test_api.checkmark_icon()->GetVisible()); EXPECT_FALSE(test_api.arrow_button()->GetVisible()); + EXPECT_FALSE(test_api.arrow_nudge_animation()->GetVisible()); // Only the error should be visible for the first three seconds after the // state update. @@ -389,4 +425,15 @@ EXPECT_EQ(2u, GetVisibleIconCount()); } +TEST_F(LoginAuthFactorsViewUnittest, CanUsePin) { + AddAuthFactors({AuthFactorType::kSmartLock, AuthFactorType::kFingerprint}); + + for (bool can_use_pin : {true, false}) { + view_->SetCanUsePin(can_use_pin); + EXPECT_EQ(can_use_pin, AuthFactorModel::can_use_pin()); + EXPECT_EQ(can_use_pin, auth_factors_[0]->can_use_pin()); + EXPECT_EQ(can_use_pin, auth_factors_[1]->can_use_pin()); + } +} + } // namespace ash
diff --git a/ash/login/ui/login_auth_user_view.cc b/ash/login/ui/login_auth_user_view.cc index 3d2905efa..df1070e 100644 --- a/ash/login/ui/login_auth_user_view.cc +++ b/ash/login/ui/login_auth_user_view.cc
@@ -1344,9 +1344,11 @@ if (smart_lock_ui_revamp_enabled_) { DCHECK(fingerprint_auth_factor_model_); + DCHECK(smart_lock_auth_factor_model_); + DCHECK(auth_factors_view_); fingerprint_auth_factor_model_->set_available( current_state.has_fingerprint); - fingerprint_auth_factor_model_->SetCanUsePin(HasAuthMethod(AUTH_PIN)); + auth_factors_view_->SetCanUsePin(HasAuthMethod(AUTH_PIN)); } else { DCHECK(fingerprint_view_); fingerprint_view_->SetVisible(current_state.has_fingerprint);
diff --git a/ash/login/ui/smart_lock_auth_factor_model.cc b/ash/login/ui/smart_lock_auth_factor_model.cc index 60199cb..1ddab8a 100644 --- a/ash/login/ui/smart_lock_auth_factor_model.cc +++ b/ash/login/ui/smart_lock_auth_factor_model.cc
@@ -127,7 +127,8 @@ case SmartLockState::kPrimaryUserAbsent: FALLTHROUGH; case SmartLockState::kPhoneNotAuthenticated: - return IDS_AUTH_FACTOR_LABEL_UNLOCK_PASSWORD; + return can_use_pin_ ? IDS_AUTH_FACTOR_LABEL_PASSWORD_OR_PIN_REQUIRED + : IDS_AUTH_FACTOR_LABEL_PASSWORD_REQUIRED; case SmartLockState::kBluetoothDisabled: return IDS_SMART_LOCK_LABEL_NO_BLUETOOTH; case SmartLockState::kPhoneNotLockable:
diff --git a/ash/login/ui/smart_lock_auth_factor_model_unittest.cc b/ash/login/ui/smart_lock_auth_factor_model_unittest.cc index 14bad928..29c8ebe 100644 --- a/ash/login/ui/smart_lock_auth_factor_model_unittest.cc +++ b/ash/login/ui/smart_lock_auth_factor_model_unittest.cc
@@ -6,6 +6,7 @@ #include "ash/login/ui/auth_factor_model.h" #include "ash/login/ui/auth_icon_view.h" +#include "ash/strings/grit/ash_strings.h" #include "ash/test/ash_test_base.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -16,6 +17,67 @@ using AuthFactorState = AuthFactorModel::AuthFactorState; +struct LabelTestcase { + SmartLockState state; + absl::optional<bool> can_use_pin; + int label_id; + int accessible_name_id; +}; + +constexpr LabelTestcase kLabelTestcases[] = { + {SmartLockState::kDisabled, /*can_use_pin=*/true, + IDS_AUTH_FACTOR_LABEL_PASSWORD_OR_PIN_REQUIRED, + IDS_AUTH_FACTOR_LABEL_PASSWORD_OR_PIN_REQUIRED}, + {SmartLockState::kDisabled, /*can_use_pin=*/false, + IDS_AUTH_FACTOR_LABEL_PASSWORD_REQUIRED, + IDS_AUTH_FACTOR_LABEL_PASSWORD_REQUIRED}, + {SmartLockState::kInactive, /*can_use_pin=*/true, + IDS_AUTH_FACTOR_LABEL_PASSWORD_OR_PIN_REQUIRED, + IDS_AUTH_FACTOR_LABEL_PASSWORD_OR_PIN_REQUIRED}, + {SmartLockState::kInactive, /*can_use_pin=*/false, + IDS_AUTH_FACTOR_LABEL_PASSWORD_REQUIRED, + IDS_AUTH_FACTOR_LABEL_PASSWORD_REQUIRED}, + {SmartLockState::kPasswordReentryRequired, /*can_use_pin=*/true, + IDS_AUTH_FACTOR_LABEL_PASSWORD_OR_PIN_REQUIRED, + IDS_AUTH_FACTOR_LABEL_PASSWORD_OR_PIN_REQUIRED}, + {SmartLockState::kPasswordReentryRequired, /*can_use_pin=*/false, + IDS_AUTH_FACTOR_LABEL_PASSWORD_REQUIRED, + IDS_AUTH_FACTOR_LABEL_PASSWORD_REQUIRED}, + {SmartLockState::kPrimaryUserAbsent, /*can_use_pin=*/true, + IDS_AUTH_FACTOR_LABEL_PASSWORD_OR_PIN_REQUIRED, + IDS_AUTH_FACTOR_LABEL_PASSWORD_OR_PIN_REQUIRED}, + {SmartLockState::kPrimaryUserAbsent, /*can_use_pin=*/false, + IDS_AUTH_FACTOR_LABEL_PASSWORD_REQUIRED, + IDS_AUTH_FACTOR_LABEL_PASSWORD_REQUIRED}, + {SmartLockState::kPhoneNotAuthenticated, /*can_use_pin=*/true, + IDS_AUTH_FACTOR_LABEL_PASSWORD_OR_PIN_REQUIRED, + IDS_AUTH_FACTOR_LABEL_PASSWORD_OR_PIN_REQUIRED}, + {SmartLockState::kPhoneNotAuthenticated, /*can_use_pin=*/false, + IDS_AUTH_FACTOR_LABEL_PASSWORD_REQUIRED, + IDS_AUTH_FACTOR_LABEL_PASSWORD_REQUIRED}, + {SmartLockState::kBluetoothDisabled, /*can_use_pin=*/absl::nullopt, + IDS_SMART_LOCK_LABEL_NO_BLUETOOTH, IDS_SMART_LOCK_LABEL_NO_BLUETOOTH}, + {SmartLockState::kPhoneNotLockable, /*can_use_pin=*/absl::nullopt, + IDS_SMART_LOCK_LABEL_NO_PHONE_LOCK_SCREEN, + IDS_SMART_LOCK_LABEL_NO_PHONE_LOCK_SCREEN}, + {SmartLockState::kConnectingToPhone, /*can_use_pin=*/absl::nullopt, + IDS_SMART_LOCK_LABEL_LOOKING_FOR_PHONE, + IDS_SMART_LOCK_LABEL_LOOKING_FOR_PHONE}, + {SmartLockState::kPhoneFoundLockedAndDistant, /*can_use_pin=*/absl::nullopt, + IDS_SMART_LOCK_LABEL_PHONE_TOO_FAR, IDS_SMART_LOCK_LABEL_PHONE_TOO_FAR}, + {SmartLockState::kPhoneFoundUnlockedAndDistant, + /*can_use_pin=*/absl::nullopt, IDS_SMART_LOCK_LABEL_PHONE_TOO_FAR, + IDS_SMART_LOCK_LABEL_PHONE_TOO_FAR}, + {SmartLockState::kPhoneNotFound, /*can_use_pin=*/absl::nullopt, + IDS_SMART_LOCK_LABEL_NO_PHONE, IDS_SMART_LOCK_LABEL_NO_PHONE}, + {SmartLockState::kPhoneFoundLockedAndProximate, + /*can_use_pin=*/absl::nullopt, IDS_SMART_LOCK_LABEL_PHONE_LOCKED, + IDS_SMART_LOCK_LABEL_PHONE_LOCKED}, + {SmartLockState::kPhoneAuthenticated, /*can_use_pin=*/absl::nullopt, + IDS_AUTH_FACTOR_LABEL_CLICK_TO_ENTER, + IDS_AUTH_FACTOR_LABEL_CLICK_TO_ENTER}, +}; + } // namespace class SmartLockAuthFactorModelUnittest : public AshTestBase { @@ -157,4 +219,15 @@ EXPECT_EQ(AuthFactorState::kErrorPermanent, model_->GetAuthFactorState()); } +TEST_F(SmartLockAuthFactorModelUnittest, GetLabelAndAccessibleName) { + for (const LabelTestcase& testcase : kLabelTestcases) { + smart_lock_model_->SetSmartLockState(testcase.state); + if (testcase.can_use_pin.has_value()) { + model_->set_can_use_pin(testcase.can_use_pin.value()); + } + EXPECT_EQ(testcase.label_id, model_->GetLabelId()); + EXPECT_EQ(testcase.accessible_name_id, model_->GetAccessibleNameId()); + } +} + } // namespace ash
diff --git a/ash/projector/projector_controller_impl.cc b/ash/projector/projector_controller_impl.cc index 122df382..421ece77 100644 --- a/ash/projector/projector_controller_impl.cc +++ b/ash/projector/projector_controller_impl.cc
@@ -89,6 +89,7 @@ controller->Start(CaptureModeEntryType::kProjector); if (controller->IsActive()) { projector_session_->Start(storage_dir); + client_->MinimizeProjectorApp(); } } }
diff --git a/ash/projector/test/mock_projector_client.h b/ash/projector/test/mock_projector_client.h index 27dd22f..fb806a96 100644 --- a/ash/projector/test/mock_projector_client.h +++ b/ash/projector/test/mock_projector_client.h
@@ -32,6 +32,7 @@ MOCK_METHOD0(ShowSelfieCam, void()); MOCK_METHOD0(CloseSelfieCam, void()); MOCK_CONST_METHOD0(OpenProjectorApp, void()); + MOCK_CONST_METHOD0(MinimizeProjectorApp, void()); MOCK_CONST_METHOD1(OnNewScreencastPreconditionChanged, void(bool)); bool IsSelfieCamVisible() const override;
diff --git a/ash/public/cpp/BUILD.gn b/ash/public/cpp/BUILD.gn index ddc14c6..79d33d1e 100644 --- a/ash/public/cpp/BUILD.gn +++ b/ash/public/cpp/BUILD.gn
@@ -429,6 +429,7 @@ "//mojo/public/cpp/bindings", "//testing/gtest", "//ui/aura:test_support", + "//ui/chromeos/styles:cros_styles_views", "//ui/compositor_extra", "//ui/gfx:test_support", "//ui/views",
diff --git a/ash/public/cpp/holding_space/holding_space_item.cc b/ash/public/cpp/holding_space/holding_space_item.cc index 12b176f..eb7c53e 100644 --- a/ash/public/cpp/holding_space/holding_space_item.cc +++ b/ash/public/cpp/holding_space/holding_space_item.cc
@@ -39,8 +39,10 @@ bool HoldingSpaceItem::operator==(const HoldingSpaceItem& rhs) const { return type_ == rhs.type_ && id_ == rhs.id_ && file_path_ == rhs.file_path_ && file_system_url_ == rhs.file_system_url_ && text_ == rhs.text_ && - secondary_text_ == rhs.secondary_text_ && *image_ == *rhs.image_ && - progress_ == rhs.progress_ && paused_ == rhs.paused_; + secondary_text_ == rhs.secondary_text_ && + secondary_text_color_ == rhs.secondary_text_color_ && + *image_ == *rhs.image_ && progress_ == rhs.progress_ && + paused_ == rhs.paused_; } // static @@ -197,6 +199,15 @@ return true; } +bool HoldingSpaceItem::SetSecondaryTextColor( + const absl::optional<cros_styles::ColorName>& secondary_text_color) { + if (secondary_text_color_ == secondary_text_color) + return false; + + secondary_text_color_ = secondary_text_color; + return true; +} + std::u16string HoldingSpaceItem::GetAccessibleName() const { if (accessible_name_) return accessible_name_.value();
diff --git a/ash/public/cpp/holding_space/holding_space_item.h b/ash/public/cpp/holding_space/holding_space_item.h index e285d74..19df9f4f 100644 --- a/ash/public/cpp/holding_space/holding_space_item.h +++ b/ash/public/cpp/holding_space/holding_space_item.h
@@ -20,6 +20,10 @@ class DictionaryValue; } // namespace base +namespace cros_styles { +enum class ColorName; +} // namespace cros_styles + namespace ash { class HoldingSpaceImage; @@ -123,6 +127,12 @@ // if a change occurred or `false` to indicate no-op. bool SetSecondaryText(const absl::optional<std::u16string>& secondary_text); + // Sets the color for the secondary text that should be shown for the item, + // returning `true` if a change occurred or `false` to indicate no-op. If + // `absl::nullopt` is provided, secondary text color will fallback to default. + bool SetSecondaryTextColor( + const absl::optional<cros_styles::ColorName>& secondary_text_color); + // Returns `accessible_name_`, falling back to a concatenation of primary // and secondary text if absent. std::u16string GetAccessibleName() const; @@ -162,6 +172,10 @@ return secondary_text_; } + const absl::optional<cros_styles::ColorName>& secondary_text_color() const { + return secondary_text_color_; + } + const HoldingSpaceImage& image() const { return *image_; } const base::FilePath& file_path() const { return file_path_; } @@ -198,6 +212,9 @@ // If set, the secondary text that should be shown for the item. absl::optional<std::u16string> secondary_text_; + // If set, the color for the secondary text that should be shown for the item. + absl::optional<cros_styles::ColorName> secondary_text_color_; + // If set, the accessible name that should be used for the item. absl::optional<std::u16string> accessible_name_;
diff --git a/ash/public/cpp/holding_space/holding_space_item_unittest.cc b/ash/public/cpp/holding_space/holding_space_item_unittest.cc index 0d7d097..5382af05 100644 --- a/ash/public/cpp/holding_space/holding_space_item_unittest.cc +++ b/ash/public/cpp/holding_space/holding_space_item_unittest.cc
@@ -16,6 +16,7 @@ #include "base/test/scoped_locale.h" #include "base/values.h" #include "testing/gtest/include/gtest/gtest.h" +#include "ui/chromeos/styles/cros_styles.h" namespace ash { @@ -226,6 +227,34 @@ EXPECT_FALSE(holding_space_item->secondary_text()); } +// Tests setting the secondary text color for each holding space item type. +TEST_P(HoldingSpaceItemTest, SecondaryTextColor) { + // Create a `holding_space_item`. + auto holding_space_item = HoldingSpaceItem::CreateFileBackedItem( + /*type=*/GetParam(), base::FilePath("file_path"), + GURL("filesystem::file_system_url"), + /*image_resolver=*/base::BindOnce(&CreateFakeHoldingSpaceImage)); + + // Initially the secondary text color should be absent. + EXPECT_FALSE(holding_space_item->secondary_text_color()); + + // It should be possible to update secondary text color to a new value. + EXPECT_TRUE(holding_space_item->SetSecondaryTextColor( + cros_styles::ColorName::kTextColorAlert)); + EXPECT_EQ(holding_space_item->secondary_text_color().value(), + cros_styles::ColorName::kTextColorAlert); + + // It should no-op to try to update secondary text color to existing values. + EXPECT_FALSE(holding_space_item->SetSecondaryTextColor( + cros_styles::ColorName::kTextColorAlert)); + EXPECT_EQ(holding_space_item->secondary_text_color().value(), + cros_styles::ColorName::kTextColorAlert); + + // It should be possible to unset secondary text color. + EXPECT_TRUE(holding_space_item->SetSecondaryTextColor(absl::nullopt)); + EXPECT_FALSE(holding_space_item->secondary_text_color()); +} + // Tests setting the text for each holding space item type. TEST_P(HoldingSpaceItemTest, Text) { // Create a `holding_space_item`.
diff --git a/ash/public/cpp/holding_space/holding_space_model.cc b/ash/public/cpp/holding_space/holding_space_model.cc index 7b09803..4194f8e 100644 --- a/ash/public/cpp/holding_space/holding_space_model.cc +++ b/ash/public/cpp/holding_space/holding_space_model.cc
@@ -54,6 +54,14 @@ updated_fields |= HoldingSpaceModelObserver::UpdatedField::kSecondaryText; } + // Update secondary text color. + if (secondary_text_color_) { + if (item_->SetSecondaryTextColor(secondary_text_color_.value())) { + updated_fields |= + HoldingSpaceModelObserver::UpdatedField::kSecondaryTextColor; + } + } + // Update text. if (text_) { if (item_->SetText(text_.value())) @@ -119,6 +127,13 @@ } HoldingSpaceModel::ScopedItemUpdate& +HoldingSpaceModel::ScopedItemUpdate::SetSecondaryTextColor( + const absl::optional<cros_styles::ColorName>& secondary_text_color) { + secondary_text_color_ = secondary_text_color; + return *this; +} + +HoldingSpaceModel::ScopedItemUpdate& HoldingSpaceModel::ScopedItemUpdate::SetText( const absl::optional<std::u16string>& text) { text_ = text;
diff --git a/ash/public/cpp/holding_space/holding_space_model.h b/ash/public/cpp/holding_space/holding_space_model.h index 6a933bf..ed5b483 100644 --- a/ash/public/cpp/holding_space/holding_space_model.h +++ b/ash/public/cpp/holding_space/holding_space_model.h
@@ -23,6 +23,10 @@ class FilePath; } // namespace base +namespace cros_styles { +enum class ColorName; +} // namespace cros_styles + namespace ash { class HoldingSpaceModelObserver; @@ -73,6 +77,11 @@ ScopedItemUpdate& SetSecondaryText( const absl::optional<std::u16string>& secondary_text); + // Sets the color for the secondary text that should be shown for the item + // and returns a reference to `this`. + ScopedItemUpdate& SetSecondaryTextColor( + const absl::optional<cros_styles::ColorName>& secondary_text_color); + // Sets the text that should be shown for the item and returns a reference // to `this`. If absent, the lossy display name of the backing file will be // used. @@ -91,6 +100,8 @@ absl::optional<bool> paused_; absl::optional<HoldingSpaceProgress> progress_; absl::optional<absl::optional<std::u16string>> secondary_text_; + absl::optional<absl::optional<cros_styles::ColorName>> + secondary_text_color_; absl::optional<absl::optional<std::u16string>> text_; bool invalidate_image_ = false; };
diff --git a/ash/public/cpp/holding_space/holding_space_model_observer.h b/ash/public/cpp/holding_space/holding_space_model_observer.h index bcff74a..31b9581 100644 --- a/ash/public/cpp/holding_space/holding_space_model_observer.h +++ b/ash/public/cpp/holding_space/holding_space_model_observer.h
@@ -38,7 +38,8 @@ kPaused = kBackingFile << 1u, kProgress = kPaused << 1u, kSecondaryText = kProgress << 1u, - kText = kSecondaryText << 1u, + kSecondaryTextColor = kSecondaryText << 1u, + kText = kSecondaryTextColor << 1u, }; // Called when an `item` gets updated within the holding space model. The
diff --git a/ash/public/cpp/holding_space/holding_space_model_unittest.cc b/ash/public/cpp/holding_space/holding_space_model_unittest.cc index 3b77dbe..af23106f 100644 --- a/ash/public/cpp/holding_space/holding_space_model_unittest.cc +++ b/ash/public/cpp/holding_space/holding_space_model_unittest.cc
@@ -15,6 +15,7 @@ #include "base/bind.h" #include "base/scoped_observation.h" #include "testing/gtest/include/gtest/gtest.h" +#include "ui/chromeos/styles/cros_styles.h" namespace ash { namespace { @@ -272,6 +273,17 @@ EXPECT_EQ(observation.TakeUpdatedItemCount(), 1); EXPECT_EQ(item_ptr->secondary_text(), u"secondary_text"); + // Update secondary text color. + model() + .UpdateItem(item_ptr->id()) + ->SetSecondaryTextColor(cros_styles::ColorName::kTextColorAlert); + EXPECT_EQ(observation.TakeLastUpdatedItem(), item_ptr); + EXPECT_EQ(observation.TakeLastUpdatedFields(), + UpdatedField::kSecondaryTextColor); + EXPECT_EQ(observation.TakeUpdatedItemCount(), 1); + EXPECT_EQ(item_ptr->secondary_text_color(), + cros_styles::ColorName::kTextColorAlert); + // Update all attributes. updated_file_path = base::FilePath("again_updated_file_path"); updated_file_system_url = GURL("filesystem::again_updated_file_system_url"); @@ -281,6 +293,7 @@ .SetBackingFile(updated_file_path, updated_file_system_url) .SetText(u"updated_text") .SetSecondaryText(u"updated_secondary_text") + .SetSecondaryTextColor(cros_styles::ColorName::kTextColorWarning) .SetPaused(false) .SetProgress( HoldingSpaceProgress(/*current_bytes=*/75, /*total_bytes=*/100)); @@ -288,7 +301,8 @@ EXPECT_EQ(observation.TakeLastUpdatedFields(), UpdatedField::kAccessibleName | UpdatedField::kBackingFile | UpdatedField::kPaused | UpdatedField::kProgress | - UpdatedField::kSecondaryText | UpdatedField::kText); + UpdatedField::kSecondaryText | + UpdatedField::kSecondaryTextColor | UpdatedField::kText); EXPECT_EQ(observation.TakeUpdatedItemCount(), 1); EXPECT_EQ(item_ptr->GetAccessibleName(), u"updated_accessible_name"); EXPECT_EQ(item_ptr->file_path(), updated_file_path); @@ -297,6 +311,8 @@ EXPECT_EQ(item_ptr->progress().GetValue(), 0.75f); EXPECT_EQ(item_ptr->GetText(), u"updated_text"); EXPECT_EQ(item_ptr->secondary_text(), u"updated_secondary_text"); + EXPECT_EQ(item_ptr->secondary_text_color(), + cros_styles::ColorName::kTextColorWarning); } // Verifies that updating items will no-op appropriately. @@ -329,6 +345,7 @@ .SetBackingFile(item_ptr->file_path(), item_ptr->file_system_url()) .SetText(absl::nullopt) .SetSecondaryText(absl::nullopt) + .SetSecondaryTextColor(absl::nullopt) .SetPaused(item_ptr->IsPaused()) .SetProgress(item_ptr->progress()); EXPECT_EQ(observation.TakeUpdatedItemCount(), 0);
diff --git a/ash/public/cpp/projector/projector_client.h b/ash/public/cpp/projector/projector_client.h index 40155d5..3bd432d 100644 --- a/ash/public/cpp/projector/projector_client.h +++ b/ash/public/cpp/projector/projector_client.h
@@ -31,6 +31,8 @@ virtual bool IsDriveFsMounted() const = 0; // Opens Projector SWA. The app by default showing the Projector Gallery view. virtual void OpenProjectorApp() const = 0; + // Minimizes Projector SWA. + virtual void MinimizeProjectorApp() const = 0; // TODO(crbug/1199396): Migrate to IPC after Lacros launch and ash-chrome // deprecation.
diff --git a/ash/public/cpp/wallpaper/wallpaper_info.cc b/ash/public/cpp/wallpaper/wallpaper_info.cc index 3f421eb..6482b80 100644 --- a/ash/public/cpp/wallpaper/wallpaper_info.cc +++ b/ash/public/cpp/wallpaper/wallpaper_info.cc
@@ -43,12 +43,26 @@ WallpaperInfo& WallpaperInfo::operator=(WallpaperInfo&& other) = default; bool WallpaperInfo::operator==(const WallpaperInfo& other) const { - // |asset_id| is skipped on purpose in favor of |unit_id| as wallpapers can - // vary across devices due to their color mode. - return (location == other.location) && (layout == other.layout) && - (type == other.type) && (collection_id == other.collection_id) && - (unit_id == other.unit_id) && - (std::equal(variants.begin(), variants.end(), other.variants.begin())); + // |asset_id| and |location| are skipped on purpose in favor of |unit_id| as + // online wallpapers can vary across devices due to their color mode. Other + // wallpaper types still require location to be equal. + switch (type) { + case WallpaperType::kOnline: + case WallpaperType::kDaily: + return type == other.type && layout == other.layout && + collection_id == other.collection_id && unit_id == other.unit_id && + (std::equal(variants.begin(), variants.end(), + other.variants.begin())); + case WallpaperType::kCustomized: + case WallpaperType::kDefault: + case WallpaperType::kPolicy: + case WallpaperType::kThirdParty: + case WallpaperType::kDevice: + case WallpaperType::kOneShot: + case WallpaperType::kCount: + return type == other.type && layout == other.layout && + location == other.location; + } } bool WallpaperInfo::operator!=(const WallpaperInfo& other) const {
diff --git a/ash/system/holding_space/holding_space_item_chip_view.cc b/ash/system/holding_space/holding_space_item_chip_view.cc index 609feab..eefe3b0 100644 --- a/ash/system/holding_space/holding_space_item_chip_view.cc +++ b/ash/system/holding_space/holding_space_item_chip_view.cc
@@ -7,6 +7,7 @@ #include <algorithm> #include "ash/bubble/bubble_utils.h" +#include "ash/constants/ash_features.h" #include "ash/public/cpp/holding_space/holding_space_client.h" #include "ash/public/cpp/holding_space/holding_space_constants.h" #include "ash/public/cpp/holding_space/holding_space_controller.h" @@ -21,8 +22,10 @@ #include "ash/system/holding_space/holding_space_progress_ring_animation.h" #include "ash/system/holding_space/holding_space_view_delegate.h" #include "base/bind.h" +#include "base/feature_list.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/metadata/metadata_impl_macros.h" +#include "ui/chromeos/styles/cros_styles.h" #include "ui/compositor/layer.h" #include "ui/compositor/layer_owner.h" #include "ui/compositor/paint_recorder.h" @@ -563,8 +566,14 @@ secondary_label_->SetEnabledColor( selected() && multiselect ? GetMultiSelectTextColor() - : AshColorProvider::Get()->GetContentLayerColor( - AshColorProvider::ContentLayerType::kTextColorSecondary)); + : item()->secondary_text_color() + ? cros_styles::ResolveColor( + item()->secondary_text_color().value(), + AshColorProvider::Get()->IsDarkModeEnabled(), + base::FeatureList::IsEnabled( + features::kSemanticColorsDebugOverride)) + : AshColorProvider::Get()->GetContentLayerColor( + AshColorProvider::ContentLayerType::kTextColorSecondary)); secondary_label_->SetVisible(!secondary_label_->GetText().empty()); // Tooltip.
diff --git a/ash/system/status_area_widget_unittest.cc b/ash/system/status_area_widget_unittest.cc index d12baaf..12f160c 100644 --- a/ash/system/status_area_widget_unittest.cc +++ b/ash/system/status_area_widget_unittest.cc
@@ -33,11 +33,9 @@ #include "ash/test/ash_test_base.h" #include "base/callback_helpers.h" #include "base/command_line.h" -#include "chromeos/network/cellular_esim_profile_handler_impl.h" #include "chromeos/network/cellular_metrics_logger.h" #include "chromeos/network/network_handler.h" #include "chromeos/network/network_handler_test_helper.h" -#include "chromeos/network/network_metadata_store.h" #include "components/prefs/testing_pref_service.h" #include "components/session_manager/session_manager_types.h" #include "ui/events/event.h" @@ -277,11 +275,12 @@ void SetUp() override { // Initializing NetworkHandler before ash is more like production. AshTestBase::SetUp(); - chromeos::CellularESimProfileHandlerImpl::RegisterLocalStatePrefs( - local_state_.registry()); - chromeos::NetworkMetadataStore::RegisterPrefs(profile_prefs_.registry()); - chromeos::NetworkHandler::Get()->InitializePrefServices(&profile_prefs_, - &local_state_); + network_handler_test_helper_.RegisterPrefs(profile_prefs_.registry(), + local_state_.registry()); + + network_handler_test_helper_.InitializePrefs(&profile_prefs_, + &local_state_); + // Networking stubs may have asynchronous initialization. base::RunLoop().RunUntilIdle(); }
diff --git a/ash/wallpaper/OWNERS b/ash/wallpaper/OWNERS index 40d483e..85d32470 100644 --- a/ash/wallpaper/OWNERS +++ b/ash/wallpaper/OWNERS
@@ -1,2 +1,3 @@ +cowmoo@chromium.org xdai@chromium.org xiaohuic@chromium.org
diff --git a/ash/wallpaper/wallpaper_controller_unittest.cc b/ash/wallpaper/wallpaper_controller_unittest.cc index 2981fa0..b22179c 100644 --- a/ash/wallpaper/wallpaper_controller_unittest.cc +++ b/ash/wallpaper/wallpaper_controller_unittest.cc
@@ -4035,4 +4035,85 @@ EXPECT_EQ(controller_->GetWallpaperType(), WallpaperType::kOnline); } +TEST_F(WallpaperControllerWallpaperWebUiTest, + HandleWallpaperInfoSyncedForDarkLightWallpapers_NotSynced) { + SimulateUserLogin(account_id_1); + CacheOnlineWallpaper(kDummyUrl); + ClearWallpaperCount(); + + std::vector<OnlineWallpaperVariant> variants; + variants.emplace_back(kAssetId.value(), GURL(kDummyUrl), + backdrop::Image::IMAGE_TYPE_LIGHT_MODE); + variants.emplace_back(kAssetId2.value(), GURL(kDummyUrl2), + backdrop::Image::IMAGE_TYPE_DARK_MODE); + const OnlineWallpaperParams& params = OnlineWallpaperParams( + account_id_1, kAssetId, GURL(kDummyUrl), kDummyCollectionId, + WALLPAPER_LAYOUT_CENTER_CROPPED, + /*preview_mode=*/false, /*from_user=*/true, + /*daily_refresh_enabled=*/false, absl::nullopt, variants); + // local info doesn't have unit_id. + const WallpaperInfo& local_info = WallpaperInfo(params); + PutWallpaperInfoInPrefs(account_id_1, local_info, GetLocalPrefService(), + prefs::kUserWallpaperInfo); + + const OnlineWallpaperParams& params2 = + OnlineWallpaperParams(account_id_1, kAssetId2, GURL(kDummyUrl2), + kDummyCollectionId, WALLPAPER_LAYOUT_CENTER_CROPPED, + /*preview_mode=*/false, /*from_user=*/true, + /*daily_refresh_enabled=*/false, kUnitId, variants); + // synced info tracks dark variant. + const WallpaperInfo& synced_info = WallpaperInfo(params2); + PutWallpaperInfoInPrefs(account_id_1, synced_info, + GetProfilePrefService(account_id_1), + prefs::kSyncableWallpaperInfo); + RunAllTasksUntilIdle(); + + WallpaperInfo actual_info; + EXPECT_TRUE(controller_->GetUserWallpaperInfo(account_id_1, &actual_info)); + EXPECT_EQ(synced_info, actual_info); + // Verify the wallpaper is set. + EXPECT_EQ(1, GetWallpaperCount()); +} + +TEST_F(WallpaperControllerWallpaperWebUiTest, + HandleWallpaperInfoSyncedForDarkLightWallpapers_AlreadySynced) { + SimulateUserLogin(account_id_1); + CacheOnlineWallpaper(kDummyUrl); + ClearWallpaperCount(); + + std::vector<OnlineWallpaperVariant> variants; + variants.emplace_back(kAssetId.value(), GURL(kDummyUrl), + backdrop::Image::IMAGE_TYPE_LIGHT_MODE); + variants.emplace_back(kAssetId2.value(), GURL(kDummyUrl2), + backdrop::Image::IMAGE_TYPE_DARK_MODE); + const OnlineWallpaperParams& params = + OnlineWallpaperParams(account_id_1, kAssetId, GURL(kDummyUrl), + kDummyCollectionId, WALLPAPER_LAYOUT_CENTER_CROPPED, + /*preview_mode=*/false, /*from_user=*/true, + /*daily_refresh_enabled=*/false, kUnitId, variants); + // local info tracks light variant. + const WallpaperInfo& local_info = WallpaperInfo(params); + PutWallpaperInfoInPrefs(account_id_1, local_info, GetLocalPrefService(), + prefs::kUserWallpaperInfo); + + const OnlineWallpaperParams& params2 = + OnlineWallpaperParams(account_id_1, kAssetId2, GURL(kDummyUrl2), + kDummyCollectionId, WALLPAPER_LAYOUT_CENTER_CROPPED, + /*preview_mode=*/false, /*from_user=*/true, + /*daily_refresh_enabled=*/false, kUnitId, variants); + // synced info tracks dark variant. + const WallpaperInfo& synced_info = WallpaperInfo(params2); + PutWallpaperInfoInPrefs(account_id_1, synced_info, + GetProfilePrefService(account_id_1), + prefs::kSyncableWallpaperInfo); + RunAllTasksUntilIdle(); + + WallpaperInfo actual_info; + EXPECT_TRUE(controller_->GetUserWallpaperInfo(account_id_1, &actual_info)); + EXPECT_EQ(local_info, synced_info); + EXPECT_EQ(local_info, actual_info); + // Verify the wallpaper is not set again. + EXPECT_EQ(0, GetWallpaperCount()); +} + } // namespace ash
diff --git a/ash/webui/diagnostics_ui/backend/network_health_provider_unittest.cc b/ash/webui/diagnostics_ui/backend/network_health_provider_unittest.cc index eeb3d7a..89067ad 100644 --- a/ash/webui/diagnostics_ui/backend/network_health_provider_unittest.cc +++ b/ash/webui/diagnostics_ui/backend/network_health_provider_unittest.cc
@@ -14,13 +14,11 @@ #include "base/values.h" #include "chromeos/dbus/shill/shill_ipconfig_client.h" #include "chromeos/login/login_state/login_state.h" -#include "chromeos/network/cellular_esim_profile_handler_impl.h" #include "chromeos/network/managed_network_configuration_handler.h" #include "chromeos/network/network_cert_loader.h" #include "chromeos/network/network_device_handler.h" #include "chromeos/network/network_handler.h" #include "chromeos/network/network_handler_test_helper.h" -#include "chromeos/network/network_metadata_store.h" #include "chromeos/network/network_state_handler.h" #include "chromeos/network/network_type_pattern.h" #include "chromeos/network/onc/network_onc_utils.h" @@ -145,16 +143,13 @@ NetworkCertLoader::Initialize(); network_handler_test_helper_ = std::make_unique<NetworkHandlerTestHelper>(); network_handler_test_helper_->AddDefaultProfiles(); - ClearDevicesAndServices(); + network_handler_test_helper_->RegisterPrefs(user_prefs_.registry(), + local_state_.registry()); PrefProxyConfigTrackerImpl::RegisterProfilePrefs(user_prefs_.registry()); PrefProxyConfigTrackerImpl::RegisterPrefs(local_state_.registry()); - ::onc::RegisterProfilePrefs(user_prefs_.registry()); - ::onc::RegisterPrefs(local_state_.registry()); - chromeos::NetworkMetadataStore::RegisterPrefs(user_prefs_.registry()); - chromeos::NetworkMetadataStore::RegisterPrefs(local_state_.registry()); - chromeos::CellularESimProfileHandlerImpl::RegisterLocalStatePrefs( - local_state_.registry()); - NetworkHandler::Get()->InitializePrefServices(&user_prefs_, &local_state_); + + network_handler_test_helper_->InitializePrefs(&user_prefs_, &local_state_); + ClearDevicesAndServices(); cros_network_config_ = std::make_unique<network_config::CrosNetworkConfig>();
diff --git a/ash/webui/projector_app/projector_app_client.h b/ash/webui/projector_app/projector_app_client.h index 6597116..51b19689 100644 --- a/ash/webui/projector_app/projector_app_client.h +++ b/ash/webui/projector_app/projector_app_client.h
@@ -78,7 +78,7 @@ virtual void AddObserver(Observer* observer) = 0; virtual void RemoveObserver(Observer* observer) = 0; - // Returns the IdentityManager for the primary user profile. + // Returns the IdentityManager for the active user profile. virtual signin::IdentityManager* GetIdentityManager() = 0; // Returns the URLLoaderFactory for the primary user profile.
diff --git a/ash/webui/shimless_rma/backend/shimless_rma_service.cc b/ash/webui/shimless_rma/backend/shimless_rma_service.cc index 497a8d4..bcc45522 100644 --- a/ash/webui/shimless_rma/backend/shimless_rma_service.cc +++ b/ash/webui/shimless_rma/backend/shimless_rma_service.cc
@@ -935,6 +935,14 @@ } } +void ShimlessRmaService::RoFirmwareUpdateProgress( + rmad::UpdateRoFirmwareStatus status) { + last_update_ro_firmware_progress_ = status; + if (update_ro_firmware_observer_.is_bound()) { + update_ro_firmware_observer_->OnUpdateRoFirmwareStatusChanged(status); + } +} + void ShimlessRmaService::ObserveError( ::mojo::PendingRemote<mojom::ErrorObserver> observer) { error_observer_.Bind(std::move(observer)); @@ -1007,6 +1015,15 @@ } } +void ShimlessRmaService::ObserveRoFirmwareUpdateProgress( + ::mojo::PendingRemote<mojom::UpdateRoFirmwareObserver> observer) { + update_ro_firmware_observer_.Bind(std::move(observer)); + if (last_update_ro_firmware_progress_) { + update_ro_firmware_observer_->OnUpdateRoFirmwareStatusChanged( + *last_update_ro_firmware_progress_); + } +} + //////////////////////////////// // Mojom binding. void ShimlessRmaService::BindInterface(
diff --git a/ash/webui/shimless_rma/backend/shimless_rma_service.h b/ash/webui/shimless_rma/backend/shimless_rma_service.h index aaeddb4..9316030f 100644 --- a/ash/webui/shimless_rma/backend/shimless_rma_service.h +++ b/ash/webui/shimless_rma/backend/shimless_rma_service.h
@@ -153,6 +153,8 @@ override; void ObserveFinalizationStatus( ::mojo::PendingRemote<mojom::FinalizationObserver> observer) override; + void ObserveRoFirmwareUpdateProgress( + ::mojo::PendingRemote<mojom::UpdateRoFirmwareObserver> observer) override; void BindInterface( mojo::PendingReceiver<mojom::ShimlessRmaService> pending_receiver); @@ -169,6 +171,7 @@ void HardwareVerificationResult( const rmad::HardwareVerificationResult& result) override; void FinalizationProgress(const rmad::FinalizeStatus& status) override; + void RoFirmwareUpdateProgress(rmad::UpdateRoFirmwareStatus status) override; void OsUpdateProgress(update_engine::Operation operation, double progress); @@ -215,6 +218,8 @@ absl::optional<rmad::HardwareVerificationResult> last_hardware_verification_result_; absl::optional<rmad::FinalizeStatus> last_finalization_progress_; + absl::optional<rmad::UpdateRoFirmwareStatus> + last_update_ro_firmware_progress_; mojo::Remote<mojom::ErrorObserver> error_observer_; mojo::Remote<mojom::OsUpdateObserver> os_update_observer_; @@ -227,6 +232,7 @@ mojo::RemoteSet<mojom::HardwareVerificationStatusObserver> hardware_verification_observers_; mojo::Remote<mojom::FinalizationObserver> finalization_observer_; + mojo::Remote<mojom::UpdateRoFirmwareObserver> update_ro_firmware_observer_; mojo::Receiver<mojom::ShimlessRmaService> receiver_{this}; mojo::Remote<chromeos::network_config::mojom::CrosNetworkConfig>
diff --git a/ash/webui/shimless_rma/backend/shimless_rma_service_unittest.cc b/ash/webui/shimless_rma/backend/shimless_rma_service_unittest.cc index a1f3d3e..66f340b8 100644 --- a/ash/webui/shimless_rma/backend/shimless_rma_service_unittest.cc +++ b/ash/webui/shimless_rma/backend/shimless_rma_service_unittest.cc
@@ -2849,6 +2849,43 @@ EXPECT_EQ(fake_observer.observations.size(), 1UL); } +class FakeUpdateRoFirmwareObserver : public mojom::UpdateRoFirmwareObserver { + public: + void OnUpdateRoFirmwareStatusChanged( + rmad::UpdateRoFirmwareStatus status) override { + observations.push_back(status); + } + + std::vector<rmad::UpdateRoFirmwareStatus> observations; + mojo::Receiver<mojom::UpdateRoFirmwareObserver> receiver{this}; +}; + +TEST_F(ShimlessRmaServiceTest, ObserveUpdateRoFirmwareStatus) { + FakeUpdateRoFirmwareObserver fake_observer; + shimless_rma_provider_->ObserveRoFirmwareUpdateProgress( + fake_observer.receiver.BindNewPipeAndPassRemote()); + base::RunLoop run_loop; + fake_rmad_client_()->TriggerRoFirmwareUpdateProgressObservation( + rmad::UpdateRoFirmwareStatus::RMAD_UPDATE_RO_FIRMWARE_DOWNLOADING); + run_loop.RunUntilIdle(); + EXPECT_EQ(fake_observer.observations.size(), 1UL); + EXPECT_EQ(fake_observer.observations[0], + rmad::UpdateRoFirmwareStatus::RMAD_UPDATE_RO_FIRMWARE_DOWNLOADING); +} + +TEST_F(ShimlessRmaServiceTest, ObserveUpdateRoFirmwareStatusAfterSignal) { + fake_rmad_client_()->TriggerRoFirmwareUpdateProgressObservation( + rmad::UpdateRoFirmwareStatus::RMAD_UPDATE_RO_FIRMWARE_DOWNLOADING); + FakeUpdateRoFirmwareObserver fake_observer; + shimless_rma_provider_->ObserveRoFirmwareUpdateProgress( + fake_observer.receiver.BindNewPipeAndPassRemote()); + base::RunLoop run_loop; + run_loop.RunUntilIdle(); + EXPECT_EQ(fake_observer.observations.size(), 1UL); + EXPECT_EQ(fake_observer.observations[0], + rmad::UpdateRoFirmwareStatus::RMAD_UPDATE_RO_FIRMWARE_DOWNLOADING); +} + class FakeCalibrationObserver : public mojom::CalibrationObserver { public: void OnCalibrationUpdated(
diff --git a/ash/webui/shimless_rma/mojom/BUILD.gn b/ash/webui/shimless_rma/mojom/BUILD.gn index b70ff6a..58cb2085 100644 --- a/ash/webui/shimless_rma/mojom/BUILD.gn +++ b/ash/webui/shimless_rma/mojom/BUILD.gn
@@ -65,6 +65,10 @@ cpp = "::rmad::FinalizeStatus_Status" }, { + mojom = "ash.shimless_rma.mojom.UpdateRoFirmwareStatus" + cpp = "::rmad::UpdateRoFirmwareStatus" + }, + { mojom = "media.mojom.CdmKeyInformation" cpp = "::std::unique_ptr<::media::CdmKeyInformation>" move_only = true
diff --git a/ash/webui/shimless_rma/mojom/shimless_rma.mojom b/ash/webui/shimless_rma/mojom/shimless_rma.mojom index bd490685..2f3f264 100644 --- a/ash/webui/shimless_rma/mojom/shimless_rma.mojom +++ b/ash/webui/shimless_rma/mojom/shimless_rma.mojom
@@ -269,6 +269,22 @@ kCompleteKeepDeviceOpen = 3, }; +// Status of device read only firmware reimaging. +// In some cases device firmware must be re-written from a recovery image for +// device security. +// This must remain in sync with +// UpdateRoFirmwareStatus in //third_party/cros_system_api/dbus/rmad/rmad.proto. +// See shimless_rma_mojom_traits.cc\h. +enum UpdateRoFirmwareStatus { + kUnknown = 0, + kWaitUsb = 1, + kFileNotFound = 2, + kDownloading = 3, + kUpdating = 4, + kRebooting = 5, + kComplete = 6, +}; + // Enumeration of all instructions needed for calibration that require manual // setup. enum CalibrationSetupInstruction { @@ -385,6 +401,13 @@ OnFinalizationUpdated(FinalizationStatus status, float progress); }; +// Implemented by clients to receive status of RO firmware update progress. +interface UpdateRoFirmwareObserver { + // OnUpdateRoFirmwareStatusChanged is called to report progress of RO firmware + // update. + OnUpdateRoFirmwareStatusChanged(UpdateRoFirmwareStatus status); +}; + // Enables clients in the webui to manage the RMA flow. // This API is hosted in the web browser exposed to the Shimless RMA SWA. interface ShimlessRmaService { @@ -714,4 +737,7 @@ pending_remote<HardwareVerificationStatusObserver> observer); // Registers an observer for status of finalization. ObserveFinalizationStatus(pending_remote<FinalizationObserver> observer); + // Registers an observer for status of RO firmware update. + ObserveRoFirmwareUpdateProgress( + pending_remote<UpdateRoFirmwareObserver> observer); };
diff --git a/ash/webui/shimless_rma/mojom/shimless_rma_mojom_traits.cc b/ash/webui/shimless_rma/mojom/shimless_rma_mojom_traits.cc index ff882a7..3f42b24 100644 --- a/ash/webui/shimless_rma/mojom/shimless_rma_mojom_traits.cc +++ b/ash/webui/shimless_rma/mojom/shimless_rma_mojom_traits.cc
@@ -50,6 +50,10 @@ using MojomFinalizationStatus = ash::shimless_rma::mojom::FinalizationStatus; using ProtoFinalizationStatus = rmad::FinalizeStatus_Status; + +using MojomUpdateRoFirmwareStatus = + ash::shimless_rma::mojom::UpdateRoFirmwareStatus; +using ProtoUpdateRoFirmwaretatus = rmad::UpdateRoFirmwareStatus; } // namespace // The rmad state does not map 1:1 with UI app state, the UI handles more states @@ -925,4 +929,61 @@ } return false; } + +// static// static +MojomUpdateRoFirmwareStatus +EnumTraits<MojomUpdateRoFirmwareStatus, ProtoUpdateRoFirmwaretatus>::ToMojom( + ProtoUpdateRoFirmwaretatus step) { + switch (step) { + case ProtoUpdateRoFirmwaretatus::RMAD_UPDATE_RO_FIRMWARE_WAIT_USB: + return MojomUpdateRoFirmwareStatus::kWaitUsb; + case ProtoUpdateRoFirmwaretatus::RMAD_UPDATE_RO_FIRMWARE_FILE_NOT_FOUND: + return MojomUpdateRoFirmwareStatus::kFileNotFound; + case ProtoUpdateRoFirmwaretatus::RMAD_UPDATE_RO_FIRMWARE_DOWNLOADING: + return MojomUpdateRoFirmwareStatus::kDownloading; + case ProtoUpdateRoFirmwaretatus::RMAD_UPDATE_RO_FIRMWARE_UPDATING: + return MojomUpdateRoFirmwareStatus::kUpdating; + case ProtoUpdateRoFirmwaretatus::RMAD_UPDATE_RO_FIRMWARE_REBOOTING: + return MojomUpdateRoFirmwareStatus::kRebooting; + case ProtoUpdateRoFirmwaretatus::RMAD_UPDATE_RO_FIRMWARE_COMPLETE: + return MojomUpdateRoFirmwareStatus::kComplete; + + case ProtoUpdateRoFirmwaretatus::RMAD_UPDATE_RO_FIRMWARE_UNKNOWN: + default: + NOTREACHED(); + return MojomUpdateRoFirmwareStatus::kUnknown; + } + NOTREACHED(); + return MojomUpdateRoFirmwareStatus::kUnknown; +} + +bool EnumTraits<MojomUpdateRoFirmwareStatus, ProtoUpdateRoFirmwaretatus>:: + FromMojom(MojomUpdateRoFirmwareStatus step, + ProtoUpdateRoFirmwaretatus* out) { + switch (step) { + case MojomUpdateRoFirmwareStatus::kWaitUsb: + *out = ProtoUpdateRoFirmwaretatus::RMAD_UPDATE_RO_FIRMWARE_WAIT_USB; + return true; + case MojomUpdateRoFirmwareStatus::kFileNotFound: + *out = ProtoUpdateRoFirmwaretatus::RMAD_UPDATE_RO_FIRMWARE_FILE_NOT_FOUND; + return true; + case MojomUpdateRoFirmwareStatus::kDownloading: + *out = ProtoUpdateRoFirmwaretatus::RMAD_UPDATE_RO_FIRMWARE_DOWNLOADING; + return true; + case MojomUpdateRoFirmwareStatus::kUpdating: + *out = ProtoUpdateRoFirmwaretatus::RMAD_UPDATE_RO_FIRMWARE_UPDATING; + return true; + case MojomUpdateRoFirmwareStatus::kRebooting: + *out = ProtoUpdateRoFirmwaretatus::RMAD_UPDATE_RO_FIRMWARE_REBOOTING; + return true; + case MojomUpdateRoFirmwareStatus::kComplete: + *out = ProtoUpdateRoFirmwaretatus::RMAD_UPDATE_RO_FIRMWARE_COMPLETE; + return true; + case MojomUpdateRoFirmwareStatus::kUnknown: + NOTREACHED(); + return false; + } + NOTREACHED(); + return false; +} } // namespace mojo
diff --git a/ash/webui/shimless_rma/mojom/shimless_rma_mojom_traits.h b/ash/webui/shimless_rma/mojom/shimless_rma_mojom_traits.h index 62c8099..cc6b717 100644 --- a/ash/webui/shimless_rma/mojom/shimless_rma_mojom_traits.h +++ b/ash/webui/shimless_rma/mojom/shimless_rma_mojom_traits.h
@@ -166,6 +166,16 @@ rmad::CalibrationComponentStatus* out); }; +template <> +struct EnumTraits<ash::shimless_rma::mojom::UpdateRoFirmwareStatus, + rmad::UpdateRoFirmwareStatus> { + static ash::shimless_rma::mojom::UpdateRoFirmwareStatus ToMojom( + rmad::UpdateRoFirmwareStatus status); + + static bool FromMojom(ash::shimless_rma::mojom::UpdateRoFirmwareStatus input, + rmad::UpdateRoFirmwareStatus* out); +}; + } // namespace mojo #endif // ASH_WEBUI_SHIMLESS_RMA_MOJOM_SHIMLESS_RMA_MOJOM_TRAITS_H_
diff --git a/ash/webui/shimless_rma/mojom/shimless_rma_mojom_traits_unittest.cc b/ash/webui/shimless_rma/mojom/shimless_rma_mojom_traits_unittest.cc index 48d477d..836ee41 100644 --- a/ash/webui/shimless_rma/mojom/shimless_rma_mojom_traits_unittest.cc +++ b/ash/webui/shimless_rma/mojom/shimless_rma_mojom_traits_unittest.cc
@@ -288,6 +288,26 @@ TestMojoToProto(enums); } +TEST_F(ShimlessRmaMojoToProtoTest, UpdateRoFirmwareStatusMatch) { + constexpr auto enums = base::MakeFixedFlatMap<mojom::UpdateRoFirmwareStatus, + rmad::UpdateRoFirmwareStatus>( + {{mojom::UpdateRoFirmwareStatus::kWaitUsb, + rmad::UpdateRoFirmwareStatus::RMAD_UPDATE_RO_FIRMWARE_WAIT_USB}, + {mojom::UpdateRoFirmwareStatus::kFileNotFound, + rmad::UpdateRoFirmwareStatus::RMAD_UPDATE_RO_FIRMWARE_FILE_NOT_FOUND}, + {mojom::UpdateRoFirmwareStatus::kDownloading, + rmad::UpdateRoFirmwareStatus::RMAD_UPDATE_RO_FIRMWARE_DOWNLOADING}, + {mojom::UpdateRoFirmwareStatus::kUpdating, + rmad::UpdateRoFirmwareStatus::RMAD_UPDATE_RO_FIRMWARE_UPDATING}, + {mojom::UpdateRoFirmwareStatus::kRebooting, + rmad::UpdateRoFirmwareStatus::RMAD_UPDATE_RO_FIRMWARE_REBOOTING}, + {mojom::UpdateRoFirmwareStatus::kComplete, + rmad::UpdateRoFirmwareStatus::RMAD_UPDATE_RO_FIRMWARE_COMPLETE}}); + + TestProtoToMojo(enums); + TestMojoToProto(enums); +} + TEST_F(ShimlessRmaMojoToProtoTest, ProvisioningStatusMatch) { constexpr auto enums = base::MakeFixedFlatMap<mojom::ProvisioningStatus, rmad::ProvisionStatus::Status>(
diff --git a/ash/webui/shimless_rma/resources/fake_shimless_rma_service.js b/ash/webui/shimless_rma/resources/fake_shimless_rma_service.js index fab4fb54..cc92f7c 100644 --- a/ash/webui/shimless_rma/resources/fake_shimless_rma_service.js +++ b/ash/webui/shimless_rma/resources/fake_shimless_rma_service.js
@@ -6,7 +6,7 @@ import {FakeObservables} from 'chrome://resources/ash/common/fake_observables.js'; import {assert} from 'chrome://resources/js/assert.m.js'; -import {CalibrationComponentStatus, CalibrationObserverRemote, CalibrationOverallStatus, CalibrationSetupInstruction, CalibrationStatus, Component, ComponentType, ErrorObserverRemote, FinalizationObserverRemote, FinalizationStatus, HardwareVerificationStatusObserverRemote, HardwareWriteProtectionStateObserverRemote, OsUpdateObserverRemote, OsUpdateOperation, PowerCableStateObserverRemote, ProvisioningObserverRemote, ProvisioningStatus, QrCode, RmadErrorCode, ShimlessRmaServiceInterface, State, StateResult, WriteProtectDisableCompleteAction} from './shimless_rma_types.js'; +import {CalibrationComponentStatus, CalibrationObserverRemote, CalibrationOverallStatus, CalibrationSetupInstruction, CalibrationStatus, Component, ComponentType, ErrorObserverRemote, FinalizationObserverRemote, FinalizationStatus, HardwareVerificationStatusObserverRemote, HardwareWriteProtectionStateObserverRemote, OsUpdateObserverRemote, OsUpdateOperation, PowerCableStateObserverRemote, ProvisioningObserverRemote, ProvisioningStatus, QrCode, RmadErrorCode, ShimlessRmaServiceInterface, State, StateResult, UpdateRoFirmwareObserverRemote, UpdateRoFirmwareStatus, WriteProtectDisableCompleteAction} from './shimless_rma_types.js'; /** @implements {ShimlessRmaServiceInterface} */ export class FakeShimlessRmaService { @@ -39,6 +39,12 @@ this.automaticallyTriggerDisableWriteProtectionObservation_ = false; /** + * Control automatically triggering update RO firmware observations. + * @private {boolean} + */ + this.automaticallyTriggerUpdateRoFirmwareObservation_ = false; + + /** * Control automatically triggering provisioning observations. * @private {boolean} */ @@ -156,7 +162,8 @@ this.setFakePrevState_( state.state, state.canCancel, state.canGoBack, state.error); } - return this.methods_.resolveMethod('transitionPreviousState'); + return this.methods_.resolveMethodWithDelay( + 'transitionPreviousState', this.resolveMethodDelayMs_); } /** @@ -768,6 +775,29 @@ } /** + * Implements ShimlessRmaServiceInterface.ObserveRoFirmwareUpdateProgress. + * @param {!UpdateRoFirmwareObserverRemote} remote + */ + observeRoFirmwareUpdateProgress(remote) { + this.observables_.observe( + 'UpdateRoFirmwareObserver_onUpdateRoFirmwareStatusChanged', + (status) => { + remote.onUpdateRoFirmwareStatusChanged( + /** @type {!UpdateRoFirmwareStatus} */ (status)); + }); + if (this.automaticallyTriggerUpdateRoFirmwareObservation_) { + this.triggerUpdateRoFirmwareObserver(UpdateRoFirmwareStatus.kComplete, 0); + } + } + + /** + * Trigger update ro firmware observations when an observer is added. + */ + automaticallyTriggerUpdateRoFirmwareObservation() { + this.automaticallyTriggerUpdateRoFirmwareObservation_ = true; + } + + /** * Implements ShimlessRmaServiceInterface.ObserveCalibration. * @param {!CalibrationObserverRemote} remote */ @@ -1020,6 +1050,17 @@ } /** + * Causes the update RO firmware observer to fire after a delay. + * @param {!UpdateRoFirmwareStatus} status + * @param {number} delayMs + */ + triggerUpdateRoFirmwareObserver(status, delayMs) { + return this.triggerObserverAfterMs( + 'UpdateRoFirmwareObserver_onUpdateRoFirmwareStatusChanged', status, + delayMs); + } + + /** * Causes the calibration observer to fire after a delay. * @param {!CalibrationComponentStatus} componentStatus * @param {number} delayMs @@ -1236,6 +1277,8 @@ this.observables_ = new FakeObservables(); this.observables_.register('ErrorObserver_onError'); this.observables_.register('OsUpdateObserver_onOsUpdateProgressUpdated'); + this.observables_.register( + 'UpdateRoFirmwareObserver_onUpdateRoFirmwareStatusChanged'); this.observables_.register('CalibrationObserver_onCalibrationUpdated'); this.observables_.register('CalibrationObserver_onCalibrationStepComplete'); this.observables_.register('ProvisioningObserver_onProvisioningUpdated');
diff --git a/ash/webui/shimless_rma/resources/shimless_rma.html b/ash/webui/shimless_rma/resources/shimless_rma.html index 70ecdf94..854b6e4 100644 --- a/ash/webui/shimless_rma/resources/shimless_rma.html +++ b/ash/webui/shimless_rma/resources/shimless_rma.html
@@ -3,10 +3,6 @@ padding: 50px; } - :host([waiting-for-next-response_]) #shimlessRMAContainer { - opacity: .4; - } - .shimless-footer { text-align: right; margin-top: 10px; @@ -30,18 +26,33 @@ margin-right: 5px; } - #busyIcon { + .busy-icon { height: 20px; width: 20px; } - #busyIcon, - #nextButtonCaret { + #nextButtonCaret, + #nextButtonSpinner { margin-inline-start: 5px; } + + #busyStateOverlay { + background-color: white; + display: none; + height: 100vh; + opacity: .4; + position: fixed; + width: 100%; + z-index: 1; + } + + :host([all-buttons-disabled_]) #busyStateOverlay { + display: block; + } </style> <div id="shimlessRMAContainer"> + <div id="busyStateOverlay"></div> <div class="shimless-header"> <cr-button id="back" on-click="onBackButtonClicked_" @@ -65,10 +76,10 @@ <span id="nextButtonLabel"> [[getNextButtonLabel_(currentPage_.buttonNextLabelKey)]] </span> - <paper-spinner-lite id="busyIcon" hidden$="[[!waitingForNextResponse_]]" - active> + <paper-spinner-lite id="nextButtonSpinner" class="busy-icon" + hidden$="[[!nextButtonClicked_]]" active> </paper-spinner-lite> - <span id="nextButtonCaret" hidden$="[[waitingForNextResponse_]]"> + <span id="nextButtonCaret" hidden$="[[nextButtonClicked_]]"> > </span> </cr-button>
diff --git a/ash/webui/shimless_rma/resources/shimless_rma.js b/ash/webui/shimless_rma/resources/shimless_rma.js index 5a18458f..5ad3f7e 100644 --- a/ash/webui/shimless_rma/resources/shimless_rma.js +++ b/ash/webui/shimless_rma/resources/shimless_rma.js
@@ -259,24 +259,24 @@ /** * Used to disable all buttons while waiting for long running mojo API - * calls to complete. + * calls to complete. Also controls the busy state overlay. * TODO(gavindodd): Handle disabling per page buttons. * @protected */ allButtonsDisabled_: { type: Boolean, value: true, + reflectToAttribute: true, }, /** - * True when the Next button is clicked and the page is waiting for the - * response from the RMAD service. + * After the next button is clicked, true until the next state is + * processed. * @protected */ - waitingForNextResponse_: { + nextButtonClicked_: { type: Boolean, value: false, - reflectToAttribute: true, }, }; } @@ -302,6 +302,11 @@ * @private {?Function} */ this.transitionState_ = (e) => { + // If already in a busy state, ignore requests. + if (this.allButtonsDisabled_) { + return; + } + this.allButtonsDisabled_ = true; e.detail().then((stateResult) => this.processStateResult_(stateResult)); }; @@ -406,6 +411,7 @@ showState_(state, canCancel, canGoBack) { const pageInfo = StateComponentMapping[state]; assert(pageInfo); + this.nextButtonClicked_ = false; this.allButtonsDisabled_ = false; pageInfo.buttonCancel = canCancel ? ButtonState.VISIBLE : ButtonState.HIDDEN; @@ -503,16 +509,15 @@ typeof page.onNextButtonClick === 'function', 'onNextButtonClick not a function for ' + this.currentPage_.componentIs); + this.nextButtonClicked_ = true; this.allButtonsDisabled_ = true; - this.waitingForNextResponse_ = true; page.onNextButtonClick() .then((stateResult) => { - this.waitingForNextResponse_ = false; this.processStateResult_(stateResult); }) // TODO(gavindodd): Better error handling. .catch((err) => { - this.waitingForNextResponse_ = false; + this.nextButtonClicked_ = false; this.allButtonsDisabled_ = false; }); }
diff --git a/ash/webui/shimless_rma/resources/shimless_rma_types.js b/ash/webui/shimless_rma/resources/shimless_rma_types.js index f33f254..baa0ee7 100644 --- a/ash/webui/shimless_rma/resources/shimless_rma_types.js +++ b/ash/webui/shimless_rma/resources/shimless_rma_types.js
@@ -56,6 +56,10 @@ export const WriteProtectDisableCompleteAction = ash.shimlessRma.mojom.WriteProtectDisableCompleteAction; +/** @typedef {ash.shimlessRma.mojom.UpdateRoFirmwareStatus} */ +export const UpdateRoFirmwareStatus = + ash.shimlessRma.mojom.UpdateRoFirmwareStatus; + /** * @typedef {ash.shimlessRma.mojom.CalibrationSetupInstruction} */ @@ -142,6 +146,27 @@ ash.shimlessRma.mojom.OsUpdateObserverInterface; /** + * Type alias for UpdateRoFirmwareObserverRemote. + * @typedef {ash.shimlessRma.mojom.UpdateRoFirmwareObserverRemote} + */ +export const UpdateRoFirmwareObserverRemote = + ash.shimlessRma.mojom.UpdateRoFirmwareObserverRemote; + +/** + * Type alias for UpdateRoFirmwareObserverReceiver. + * @typedef {ash.shimlessRma.mojom.UpdateRoFirmwareObserverReceiver} + */ +export const UpdateRoFirmwareObserverReceiver = + ash.shimlessRma.mojom.UpdateRoFirmwareObserverReceiver; + +/** + * Type alias for UpdateRoFirmwareObserverInterface. + * @typedef {ash.shimlessRma.mojom.UpdateRoFirmwareObserverInterface} + */ +export const UpdateRoFirmwareObserverInterface = + ash.shimlessRma.mojom.UpdateRoFirmwareObserverInterface; + +/** * Type alias for CalibrationObserverRemote. * @typedef {ash.shimlessRma.mojom.CalibrationObserverRemote} */
diff --git a/ash/wm/desks/desk.cc b/ash/wm/desks/desk.cc index be5627ae..ae04b63 100644 --- a/ash/wm/desks/desk.cc +++ b/ash/wm/desks/desk.cc
@@ -8,6 +8,7 @@ #include <utility> #include "ash/constants/app_types.h" +#include "ash/public/cpp/desks_templates_delegate.h" #include "ash/public/cpp/shell_window_ids.h" #include "ash/public/cpp/window_properties.h" #include "ash/shell.h" @@ -283,6 +284,14 @@ void Desk::AddWindowToDesk(aura::Window* window) { DCHECK(!base::Contains(windows_, window)); + + // Increment `num_supported_windows_` if the window is supported. + auto* delegate = Shell::Get()->desks_templates_delegate(); + if (delegate && delegate->IsWindowSupportedForDeskTemplate(window) && + !wm::GetTransientParent(window)) { + num_supported_windows_++; + } + windows_.push_back(window); // No need to refresh the mini_views if the destroyed window doesn't show up // there in the first place. Also don't refresh for visible on all desks @@ -305,6 +314,14 @@ void Desk::RemoveWindowFromDesk(aura::Window* window) { DCHECK(base::Contains(windows_, window)); + + // Decrement `num_supported_windows_` if the window was supported. + auto* delegate = Shell::Get()->desks_templates_delegate(); + if (delegate && delegate->IsWindowSupportedForDeskTemplate(window) && + !wm::GetTransientParent(window)) { + num_supported_windows_--; + } + base::Erase(windows_, window); // No need to refresh the mini_views if the destroyed window doesn't show up // there in the first place. Also don't refresh for visible on all desks
diff --git a/ash/wm/desks/desk.h b/ash/wm/desks/desk.h index ceddb9e4..6fdf16d 100644 --- a/ash/wm/desks/desk.h +++ b/ash/wm/desks/desk.h
@@ -90,6 +90,8 @@ last_day_visited_ = last_day_visited; } + int num_supported_windows() const { return num_supported_windows_; } + bool interacted_with_this_week() const { return interacted_with_this_week_; } void set_interacted_with_this_week(bool interacted_with_this_week) { interacted_with_this_week_ = interacted_with_this_week; @@ -244,6 +246,12 @@ int first_day_visited_ = -1; int last_day_visited_ = -1; + // The number of supported windows open on this desk. A window is supported + // for the Desks Templates feature if its app type is supported. Used to + // disable the save desk as templates button if there are no supported windows + // open. + int num_supported_windows_ = 0; + // Tracks whether |this| has been interacted with this week. This value is // reset by the DesksController. bool interacted_with_this_week_ = false;
diff --git a/ash/wm/desks/desks_unittests.cc b/ash/wm/desks/desks_unittests.cc index 96d141a..51396f4 100644 --- a/ash/wm/desks/desks_unittests.cc +++ b/ash/wm/desks/desks_unittests.cc
@@ -4972,6 +4972,31 @@ EXPECT_TRUE(new_desk_button->GetEnabled()); } +TEST_F(DesksTest, AddRemoveSupportedWindows) { + auto* controller = DesksController::Get(); + + // Create a desk other than the default initial desk. + NewDesk(); + + Desk* desk_1 = controller->desks()[0].get(); + + // Create 3 supported windows on desk_1. + auto win0 = CreateAppWindow(gfx::Rect(0, 0, 250, 100)); + auto win1 = CreateAppWindow(gfx::Rect(50, 50, 200, 200)); + auto win2 = CreateAppWindow(gfx::Rect(50, 50, 200, 200)); + + // Expect `num_supported_windows_` to be 3. + EXPECT_EQ(3, desk_1->num_supported_windows()); + + // Close the supported windows. + win0.reset(); + win1.reset(); + win2.reset(); + + // Expect `num_supported_windows_` to be 0. + EXPECT_EQ(0, desk_1->num_supported_windows()); +} + TEST_F(DesksTest, ZeroStateDeskButtonText) { UpdateDisplay("1600x1200"); EnterOverview();
diff --git a/ash/wm/desks/templates/desks_templates_animations.cc b/ash/wm/desks/templates/desks_templates_animations.cc new file mode 100644 index 0000000..b2d22b6 --- /dev/null +++ b/ash/wm/desks/templates/desks_templates_animations.cc
@@ -0,0 +1,38 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ash/wm/desks/templates/desks_templates_animations.h" +#include "ui/compositor/layer.h" +#include "ui/gfx/animation/tween.h" +#include "ui/views/animation/animation_builder.h" +#include "ui/views/view.h" + +// The time duration for widgets to fade in. +constexpr int kFadeInDelay = 0; +constexpr int kFadeInDuration = 100; + +namespace ash { + +// Fade in animation using AnimationBuilder. +void FadeInView(ui::Layer* layer, + int delay_in_ms, + int duration_in_ms, + gfx::Tween::Type tween_type = gfx::Tween::LINEAR) { + views::AnimationBuilder() + .SetPreemptionStrategy( + ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET) + .Once() + .SetDuration(base::TimeDelta()) + .SetOpacity(layer, 0.0f) + .Then() + .SetDuration(base::Milliseconds(duration_in_ms)) + .SetOpacity(layer, 1.0f, tween_type); +} + +void PerformFadeInDesksTemplatesGridView(ui::Layer* layer) { + // TODO(sophiewen): Perform fade out of other overview items. + FadeInView(layer, kFadeInDelay, kFadeInDuration); +} + +} // namespace ash
diff --git a/ash/wm/desks/templates/desks_templates_animations.h b/ash/wm/desks/templates/desks_templates_animations.h new file mode 100644 index 0000000..1c8555f --- /dev/null +++ b/ash/wm/desks/templates/desks_templates_animations.h
@@ -0,0 +1,20 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef ASH_WM_DESKS_TEMPLATES_DESKS_TEMPLATES_ANIMATIONS_H_ +#define ASH_WM_DESKS_TEMPLATES_DESKS_TEMPLATES_ANIMATIONS_H_ + +namespace ui { +class Layer; +} // namespace ui + +namespace ash { + +// Animates the desks templates grid when it is shown, fading out current +// overview items and widgets, and fading in the grid. +void PerformFadeInDesksTemplatesGridView(ui::Layer* layer); + +} // namespace ash + +#endif // ASH_WM_DESKS_TEMPLATES_DESKS_TEMPLATES_ANIMATIONS_H_
diff --git a/ash/wm/desks/templates/desks_templates_unittest.cc b/ash/wm/desks/templates/desks_templates_unittest.cc index 95a3be8b..b9ce0eaf 100644 --- a/ash/wm/desks/templates/desks_templates_unittest.cc +++ b/ash/wm/desks/templates/desks_templates_unittest.cc
@@ -1170,6 +1170,24 @@ ASSERT_EQ(1ul, GetAllEntries().size()); } +// Tests that the save desk as template button is disabled when all windows on +// the desk are unsupported. +TEST_F(DesksTemplatesTest, AllUnsupportedAppsDisablesSaveTemplates) { + auto* root = Shell::Get()->GetPrimaryRootWindow(); + + // Use `CreateTestWindow` instead of `CreateAppWindow`, which by default + // creates a supported window. + auto test_window = CreateTestWindow(); + + EXPECT_EQ(0, DesksController::Get()->active_desk()->num_supported_windows()); + + ToggleOverview(); + + auto* save_template = static_cast<PillButton*>( + GetSaveDeskAsTemplateButtonForRoot(root)->GetContentsView()); + EXPECT_EQ(views::Button::STATE_DISABLED, save_template->GetState()); +} + // Tests the mouse and touch hover behavior on the template item view. TEST_F(DesksTemplatesTest, HoverOnTemplateItemView) { auto test_window = CreateAppWindow();
diff --git a/ash/wm/overview/overview_grid.cc b/ash/wm/overview/overview_grid.cc index c54f96a..dd7cc2b 100644 --- a/ash/wm/overview/overview_grid.cc +++ b/ash/wm/overview/overview_grid.cc
@@ -12,6 +12,7 @@ #include "ash/constants/ash_features.h" #include "ash/frame_throttler/frame_throttling_controller.h" #include "ash/metrics/histogram_macros.h" +#include "ash/public/cpp/desks_templates_delegate.h" #include "ash/public/cpp/metrics_util.h" #include "ash/public/cpp/presentation_time_recorder.h" #include "ash/public/cpp/shelf_config.h" @@ -34,6 +35,7 @@ #include "ash/wm/desks/desks_controller.h" #include "ash/wm/desks/desks_util.h" #include "ash/wm/desks/expanded_desks_bar_button.h" +#include "ash/wm/desks/templates/desks_templates_animations.h" #include "ash/wm/desks/templates/desks_templates_grid_view.h" #include "ash/wm/desks/templates/desks_templates_presenter.h" #include "ash/wm/desks/templates/desks_templates_util.h" @@ -852,7 +854,7 @@ // it will end up being the same and therefore a layout may not be // triggered. This can cause mini views not to show up at all. We must // guarantee that a layout will always occur by invalidating the layout. - // See https://crbug.com/1056371 for more details. + // See crbug.com/1056371 for more details. desks_bar_view_->InvalidateLayout(); desks_widget_->SetBounds(desks_widget_bounds); return true; @@ -1699,6 +1701,13 @@ desks_templates_grid_widget_->Show(); + // Fade in the widget from its current opacity. + // TODO(crbug.com/1277160): Consider adding animate flag to determine whether + // to disable animations. + PerformFadeInDesksTemplatesGridView(desks_templates_grid_widget_->GetLayer()); + + UpdateSaveDeskAsTemplateButton(); + if (was_zero_state) { desks_bar_view_->UpdateNewMiniViews(/*initializing_bar_view=*/false, /*expanded_desks_bar_button=*/true); @@ -1772,6 +1781,10 @@ } void OverviewGrid::UpdateSaveDeskAsTemplateButton() { + // TODO(crbug.com/1275282): The button should be updated whenever the + // overview grid changes, i.e. switches between active desks and/or the + // templates grid. This will be needed when we make it so that switching desks + // keeps us in overview mode. if (!desks_templates_util::AreDesksTemplatesEnabled()) return; @@ -1802,9 +1815,11 @@ save_desk_as_template_widget_->Show(); // Disable the create templates button if the current number of templates has - // reached the max. + // reached the max or the current desk has only unsupported apps. auto* presenter = DesksTemplatesPresenter::Get(); - if (presenter->GetEntryCount() >= presenter->GetMaxEntryCount()) { + auto* desk = DesksController::Get()->active_desk(); + if (presenter->GetEntryCount() >= presenter->GetMaxEntryCount() || + desk->num_supported_windows() == 0) { auto* button = static_cast<PillButton*>( save_desk_as_template_widget_->GetContentsView()); button->SetState(views::Button::STATE_DISABLED);
diff --git a/base/debug/activity_tracker.h b/base/debug/activity_tracker.h index a5066ae7..16590bb 100644 --- a/base/debug/activity_tracker.h +++ b/base/debug/activity_tracker.h
@@ -31,6 +31,7 @@ #include "base/task/sequenced_task_runner.h" #include "base/threading/platform_thread.h" #include "base/threading/thread_local.h" +#include "build/build_config.h" namespace base {
diff --git a/base/logging.h b/base/logging.h index 31b9c94a..c623889 100644 --- a/base/logging.h +++ b/base/logging.h
@@ -18,6 +18,7 @@ #include "base/dcheck_is_on.h" #include "base/scoped_clear_last_error.h" #include "base/strings/string_piece_forward.h" +#include "build/build_config.h" #include "build/chromeos_buildflags.h" #if BUILDFLAG(IS_CHROMEOS_ASH)
diff --git a/base/process/internal_linux.cc b/base/process/internal_linux.cc index cb6ec3b..1e9dcbf 100644 --- a/base/process/internal_linux.cc +++ b/base/process/internal_linux.cc
@@ -19,6 +19,7 @@ #include "base/strings/string_util.h" #include "base/threading/thread_restrictions.h" #include "base/time/time.h" +#include "build/build_config.h" // Not defined on AIX by default. #if defined(OS_AIX)
diff --git a/base/test/gtest_xml_unittest_result_printer.cc b/base/test/gtest_xml_unittest_result_printer.cc index 969ce1a..293bf7f6 100644 --- a/base/test/gtest_xml_unittest_result_printer.cc +++ b/base/test/gtest_xml_unittest_result_printer.cc
@@ -12,6 +12,7 @@ #include "base/test/test_switches.h" #include "base/threading/thread_checker.h" #include "base/time/time.h" +#include "base/time/time_to_iso8601.h" namespace base { @@ -120,19 +121,23 @@ // running when the test binary crashed. Note that we cannot even open the // <testcase> tag here - it requires e.g. run time of the test to be known. fprintf(output_file_.get(), - " <x-teststart name=\"%s\" classname=\"%s\" />\n", - test_info.name(), test_info.test_case_name()); + " <x-teststart name=\"%s\" classname=\"%s\" timestamp=\"%s\" />\n", + test_info.name(), test_info.test_case_name(), + TimeToISO8601(Time::Now()).c_str()); fflush(output_file_); } void XmlUnitTestResultPrinter::OnTestEnd(const testing::TestInfo& test_info) { - fprintf(output_file_.get(), - " <testcase name=\"%s\" status=\"run\" time=\"%.3f\"" - " classname=\"%s\">\n", - test_info.name(), - static_cast<double>(test_info.result()->elapsed_time()) / - Time::kMillisecondsPerSecond, - test_info.test_case_name()); + fprintf( + output_file_.get(), + " <testcase name=\"%s\" status=\"run\" time=\"%.3f\"" + " classname=\"%s\" timestamp=\"%s\">\n", + test_info.name(), + static_cast<double>(test_info.result()->elapsed_time()) / + Time::kMillisecondsPerSecond, + test_info.test_case_name(), + TimeToISO8601(Time::FromJavaTime(test_info.result()->start_timestamp())) + .c_str()); if (test_info.result()->Failed()) { fprintf(output_file_.get(), " <failure message=\"\" type=\"\"></failure>\n");
diff --git a/base/test/gtest_xml_unittest_result_printer_unittest.cc b/base/test/gtest_xml_unittest_result_printer_unittest.cc index 7743ee4fd..c7aeebf 100644 --- a/base/test/gtest_xml_unittest_result_printer_unittest.cc +++ b/base/test/gtest_xml_unittest_result_printer_unittest.cc
@@ -9,6 +9,7 @@ #include "base/files/file_util.h" #include "base/strings/strcat.h" #include "base/test/test_switches.h" +#include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace base { @@ -48,4 +49,38 @@ << expected_content << " not found in " << content; } +class XmlUnitTestResultPrinterTimestampTest : public ::testing::Test { + public: + static void TearDownTestSuite() { + // <testcase ...> should generated after test case finishes. After + // TearDown(). + std::string file_path = + base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( + switches::kTestLauncherOutput); + if (file_path.empty()) { + GTEST_SKIP() << "Test has to run with --" << switches::kTestLauncherOutput + << " switch."; + } + std::string content; + ASSERT_TRUE( + base::ReadFileToString(FilePath::FromUTF8Unsafe(file_path), &content)); + EXPECT_THAT(content, ::testing::ContainsRegex("<testcase.*timestamp=")); + } +}; + +TEST_F(XmlUnitTestResultPrinterTimestampTest, TimestampInXmlFile) { + // <x-teststart ... /> should generated at this point + std::string file_path = + base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( + switches::kTestLauncherOutput); + if (file_path.empty()) { + GTEST_SKIP() << "Test has to run with --" << switches::kTestLauncherOutput + << " switch."; + } + std::string content; + ASSERT_TRUE( + base::ReadFileToString(FilePath::FromUTF8Unsafe(file_path), &content)); + EXPECT_THAT(content, ::testing::ContainsRegex("<x-teststart.*timestamp=")); +} + } // namespace base
diff --git a/base/test/gtest_xml_util.cc b/base/test/gtest_xml_util.cc index e0d30593..fe60626 100644 --- a/base/test/gtest_xml_util.cc +++ b/base/test/gtest_xml_util.cc
@@ -109,6 +109,13 @@ result.elapsed_time = TimeDelta(); + std::string test_timestamp_str; + Time test_timestamp; + if (xml_reader.NodeAttribute("timestamp", &test_timestamp_str) && + Time::FromString(test_timestamp_str.c_str(), &test_timestamp)) { + result.timestamp = test_timestamp; + } + // Assume the test crashed - we can correct that later. result.status = TestResult::TEST_CRASH; @@ -140,6 +147,17 @@ static_cast<int64_t>(strtod(test_time_str.c_str(), nullptr) * Time::kMicrosecondsPerSecond)); + // The timestamp attribute records the local date and time of the test + // execution. It might be missing in the xml generated by older + // version of test launcher or gtest. + // https://github.com/google/googletest/blob/main/docs/advanced.md#generating-an-xml-report + std::string test_timestamp_str; + Time test_timestamp; + if (xml_reader.NodeAttribute("timestamp", &test_timestamp_str) && + Time::FromString(test_timestamp_str.c_str(), &test_timestamp)) { + result.timestamp = test_timestamp; + } + result.status = TestResult::TEST_SUCCESS; if (!results->empty() &&
diff --git a/base/test/launcher/test_launcher.cc b/base/test/launcher/test_launcher.cc index 00e6a81..226c6a4 100644 --- a/base/test/launcher/test_launcher.cc +++ b/base/test/launcher/test_launcher.cc
@@ -310,8 +310,6 @@ TimeDelta timeout, TestLauncherDelegate* delegate, bool* was_timeout) { - TimeTicks start_time(TimeTicks::Now()); - #if defined(OS_POSIX) // Make sure an option we rely on is present - see LaunchChildGTestProcess. DCHECK(options.new_process_group); @@ -511,9 +509,6 @@ GetLiveProcesses()->erase(process.Handle()); } - GetTestLauncherTracer()->RecordProcessExecution( - start_time, TimeTicks::Now() - start_time); - return exit_code; } @@ -526,6 +521,12 @@ bool was_timeout = false; // Exit code of child process. int exit_code; + // Thread ID of the runner. + PlatformThreadId thread_id; + // The sequence number of the child test process executed. + // It's used instead of process id to distinguish processes that process id + // might be reused by OS. + int process_num; }; // Returns the path to a temporary directory within |task_temp_dir| for the @@ -565,6 +566,7 @@ TimeTicks start_time = TimeTicks::Now(); ChildProcessResults result; + result.thread_id = PlatformThread::CurrentId(); ScopedFILE output_file; FilePath output_filename; @@ -648,6 +650,8 @@ #endif } result.elapsed_time = TimeTicks::Now() - start_time; + result.process_num = GetTestLauncherTracer()->RecordProcessExecution( + start_time, result.elapsed_time); return result; } @@ -1049,7 +1053,8 @@ BindOnce(&TestLauncher::ProcessTestResults, Unretained(this), test_names, result_file, process_results.output_file_contents, process_results.elapsed_time, process_results.exit_code, - process_results.was_timeout, + process_results.was_timeout, process_results.thread_id, + process_results.process_num, CountItemsInDirectory(child_temp_dir))); } @@ -1081,6 +1086,8 @@ TimeDelta elapsed_time, int exit_code, bool was_timeout, + PlatformThreadId thread_id, + int process_num, int leaked_items) { std::vector<TestResult> test_results; bool crashed = false; @@ -1159,6 +1166,11 @@ for (auto& i : final_results) { // Fix the output snippet after possible changes to the test result. i.output_snippet = GetTestOutputSnippet(i, output); + // The thread id injected here is the worker thread that launching the child + // testing process, it might be different from the current thread that + // ProcessTestResults. + i.thread_id = thread_id; + i.process_num = process_num; } if (leaked_items)
diff --git a/base/test/launcher/test_launcher.h b/base/test/launcher/test_launcher.h index 94b4046..bba7c8e 100644 --- a/base/test/launcher/test_launcher.h +++ b/base/test/launcher/test_launcher.h
@@ -20,6 +20,7 @@ #include "base/test/gtest_util.h" #include "base/test/launcher/test_result.h" #include "base/test/launcher/test_results_tracker.h" +#include "base/threading/platform_thread.h" #include "base/threading/thread_checker.h" #include "base/time/time.h" #include "base/timer/timer.h" @@ -228,6 +229,8 @@ // EXPECT/ASSERT/DCHECK statements. Test launcher parses that // file to get additional information about test run (status, // error-messages, stack-traces and file/line for failures). + // |thread_id| is the actual worker thread that launching the child process. + // |process_num| is a sequence number of the process executed in the run. // |leaked_items| is the number of files and/or directories remaining in the // child process's temporary directory upon its termination. void ProcessTestResults(const std::vector<std::string>& test_names, @@ -236,6 +239,8 @@ TimeDelta elapsed_time, int exit_code, bool was_timeout, + PlatformThreadId thread_id, + int process_num, int leaked_items); std::vector<std::string> CollectTests();
diff --git a/base/test/launcher/test_launcher_test_utils.cc b/base/test/launcher/test_launcher_test_utils.cc index 18bd962..5796b94 100644 --- a/base/test/launcher/test_launcher_test_utils.cc +++ b/base/test/launcher/test_launcher_test_utils.cc
@@ -64,7 +64,8 @@ bool ValidateTestResult(const Value* iteration_data, const std::string& test_name, const std::string& status, - size_t result_part_count) { + size_t result_part_count, + bool have_running_info) { const Value* results = iteration_data->FindListKey(test_name); if (!results) { ADD_FAILURE() << "Cannot find result"; @@ -84,6 +85,20 @@ if (!ValidateKeyValue(val, "status", status)) return false; + // Verify the keys that only exists when have_running_info, if the test didn't + // run, it wouldn't have these information. + for (auto* key : {"process_num", "thread_id", "timestamp"}) { + bool have_key = val.FindKey(key); + if (have_running_info && !have_key) { + ADD_FAILURE() << "Result must contain '" << key << "' key"; + return false; + } + if (!have_running_info && have_key) { + ADD_FAILURE() << "Result shouldn't contain '" << key << "' key"; + return false; + } + } + const Value* value = val.FindListKey("result_parts"); if (!value) { ADD_FAILURE() << "Result must contain 'result_parts' key";
diff --git a/base/test/launcher/test_launcher_test_utils.h b/base/test/launcher/test_launcher_test_utils.h index aff920a..52831360 100644 --- a/base/test/launcher/test_launcher_test_utils.h +++ b/base/test/launcher/test_launcher_test_utils.h
@@ -30,11 +30,13 @@ int64_t expected_value); // Validate |iteration_data| contains one test result under |test_name| -// with |status|, and |result_part_count| number of result parts. +// with |status|, |result_part_count| number of result parts and additional +// fields that only generated after execution when |have_running_info|. bool ValidateTestResult(const Value* iteration_data, const std::string& test_name, const std::string& status, - size_t result_part_count); + size_t result_part_count, + bool have_running_info = true); // Validate test_locations contains all tests in |test_case_name|. bool ValidateTestLocations(const Value* test_locations,
diff --git a/base/test/launcher/test_launcher_tracer.cc b/base/test/launcher/test_launcher_tracer.cc index 8bc2507..c6a3c46 100644 --- a/base/test/launcher/test_launcher_tracer.cc +++ b/base/test/launcher/test_launcher_tracer.cc
@@ -15,16 +15,18 @@ TestLauncherTracer::~TestLauncherTracer() = default; -void TestLauncherTracer::RecordProcessExecution(TimeTicks start_time, - TimeDelta duration) { +int TestLauncherTracer::RecordProcessExecution(TimeTicks start_time, + TimeDelta duration) { AutoLock lock(lock_); + int process_num = events_.size(); Event event; - event.name = StringPrintf("process #%zu", events_.size()); + event.name = StringPrintf("process #%d", process_num); event.timestamp = start_time; event.duration = duration; event.thread_id = PlatformThread::CurrentId(); events_.push_back(event); + return process_num; } bool TestLauncherTracer::Dump(const FilePath& path) {
diff --git a/base/test/launcher/test_launcher_tracer.h b/base/test/launcher/test_launcher_tracer.h index 7d1441d..f13158a 100644 --- a/base/test/launcher/test_launcher_tracer.h +++ b/base/test/launcher/test_launcher_tracer.h
@@ -28,7 +28,9 @@ ~TestLauncherTracer(); // Records an event corresponding to test process execution. - void RecordProcessExecution(TimeTicks start_time, TimeDelta duration); + // Return the sequence num of the process executed. The sequence num is also + // used as part of the event name been recorded. + int RecordProcessExecution(TimeTicks start_time, TimeDelta duration); // Dumps trace data as JSON. Returns true on success. bool Dump(const FilePath& path) WARN_UNUSED_RESULT;
diff --git a/base/test/launcher/test_launcher_unittest.cc b/base/test/launcher/test_launcher_unittest.cc index 43cee49..9439c748 100644 --- a/base/test/launcher/test_launcher_unittest.cc +++ b/base/test/launcher/test_launcher_unittest.cc
@@ -17,6 +17,7 @@ #include "base/strings/strcat.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" +#include "base/test/gtest_xml_util.h" #include "base/test/launcher/test_launcher_test_utils.h" #include "base/test/launcher/unit_test_launcher.h" #include "base/test/multiprocess_test.h" @@ -832,8 +833,9 @@ EXPECT_EQ(delegate_ptr->GetBatchSize(), 15u); } -// The following 3 tests are disabled as they are meant to only run from -// |RunMockTests| to validate tests launcher output for known results. +// The following 4 tests are disabled as they are meant to only run from +// |RunMockTests| to validate tests launcher output for known results. The tests +// are expected to run in order within a same batch. // Basic test to pass TEST(MockUnitTests, DISABLED_PassTest) { @@ -900,7 +902,51 @@ EXPECT_TRUE(test_launcher_utils::ValidateTestResult( iteration_val, "MockUnitTests.CrashTest", "CRASH", 0u)); EXPECT_TRUE(test_launcher_utils::ValidateTestResult( - iteration_val, "MockUnitTests.NoRunTest", "NOTRUN", 0u)); + iteration_val, "MockUnitTests.NoRunTest", "NOTRUN", 0u, + /*have_running_info=*/false)); +} + +TEST(ProcessGTestOutputTest, RunMockTests) { + ScopedTempDir dir; + CommandLine command_line(CommandLine::ForCurrentProcess()->GetProgram()); + command_line.AppendSwitchASCII("gtest_filter", "MockUnitTests.DISABLED_*"); + + ASSERT_TRUE(dir.CreateUniqueTempDir()); + FilePath path = dir.GetPath().AppendASCII("SaveSummaryResult.xml"); + command_line.AppendSwitchPath("test-launcher-output", path); + command_line.AppendSwitch("gtest_also_run_disabled_tests"); + command_line.AppendSwitch("single-process-tests"); + + std::string output; + GetAppOutputAndError(command_line, &output); + + std::vector<TestResult> test_results; + bool crashed = false; + bool have_test_results = ProcessGTestOutput(path, &test_results, &crashed); + + EXPECT_TRUE(have_test_results); + EXPECT_TRUE(crashed); + ASSERT_EQ(test_results.size(), 3u); + + EXPECT_EQ(test_results[0].full_name, "MockUnitTests.DISABLED_PassTest"); + EXPECT_EQ(test_results[0].status, TestResult::TEST_SUCCESS); + EXPECT_EQ(test_results[0].test_result_parts.size(), 0u); + ASSERT_TRUE(test_results[0].timestamp.has_value()); + EXPECT_GT(*test_results[0].timestamp, Time()); + EXPECT_FALSE(test_results[0].thread_id); + EXPECT_FALSE(test_results[0].process_num); + + EXPECT_EQ(test_results[1].full_name, "MockUnitTests.DISABLED_FailTest"); + EXPECT_EQ(test_results[1].status, TestResult::TEST_FAILURE); + EXPECT_EQ(test_results[1].test_result_parts.size(), 1u); + ASSERT_TRUE(test_results[1].timestamp.has_value()); + EXPECT_GT(*test_results[1].timestamp, Time()); + + EXPECT_EQ(test_results[2].full_name, "MockUnitTests.DISABLED_CrashTest"); + EXPECT_EQ(test_results[2].status, TestResult::TEST_CRASH); + EXPECT_EQ(test_results[2].test_result_parts.size(), 0u); + ASSERT_TRUE(test_results[2].timestamp.has_value()); + EXPECT_GT(*test_results[2].timestamp, Time()); } // TODO(crbug.com/1094369): Enable leaked-child checks on other platforms.
diff --git a/base/test/launcher/test_result.h b/base/test/launcher/test_result.h index bc3cb24..50204b5 100644 --- a/base/test/launcher/test_result.h +++ b/base/test/launcher/test_result.h
@@ -9,7 +9,9 @@ #include <string> #include <vector> +#include "base/threading/platform_thread.h" #include "base/time/time.h" +#include "third_party/abseil-cpp/absl/types/optional.h" namespace base { @@ -96,6 +98,20 @@ Status status; + // Start time of child test process, the field is optional the test could be + // NOT_RUN. + absl::optional<base::Time> timestamp; + + // Thread id of the runner that launching the child process, which is also + // recorded in TestLauncherTracer. + absl::optional<base::PlatformThreadId> thread_id; + + // The process num of child process launched it's recorded as event name in + // TestLauncherTracer. + // It's used instead of process id to distinguish processes that process id + // might be reused by OS. + absl::optional<int> process_num; + // Time it took to run the test. base::TimeDelta elapsed_time;
diff --git a/base/test/launcher/test_results_tracker.cc b/base/test/launcher/test_results_tracker.cc index ba128817..09bdea78 100644 --- a/base/test/launcher/test_results_tracker.cc +++ b/base/test/launcher/test_results_tracker.cc
@@ -18,12 +18,14 @@ #include "base/json/json_writer.h" #include "base/json/string_escape.h" #include "base/logging.h" +#include "base/strings/strcat.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/test/gtest_util.h" #include "base/test/launcher/test_launcher.h" #include "base/test/test_switches.h" #include "base/time/time.h" +#include "base/time/time_to_iso8601.h" #include "base/values.h" namespace base { @@ -140,8 +142,13 @@ for (const TestResult& result : results) { fprintf(out_.get(), " <testcase name=\"%s\" status=\"run\" time=\"%.3f\"" - " classname=\"%s\">\n", + "%s classname=\"%s\">\n", result.GetTestName().c_str(), result.elapsed_time.InSecondsF(), + (result.timestamp + ? StrCat({" timestamp=\"", + FormatTimeAsIso8601(*result.timestamp), "\""}) + .c_str() + : ""), result.GetTestCaseName().c_str()); if (result.status != TestResult::TEST_SUCCESS) { // The actual failure message is not propagated up to here, as it's too @@ -455,6 +462,18 @@ "elapsed_time_ms", static_cast<int>(test_result.elapsed_time.InMilliseconds())); + if (test_result.thread_id) + test_result_value.SetIntKey("thread_id", *test_result.thread_id); + if (test_result.process_num) + test_result_value.SetIntKey("process_num", *test_result.process_num); + if (test_result.timestamp) { + // The timestamp is formatted using TimeToISO8601 instead of + // FormatTimeAsIso8601 here for a better accuracy that the former + // method would include a fraction of second (and the Z suffix). + test_result_value.SetStringKey( + "timestamp", TimeToISO8601(*test_result.timestamp).c_str()); + } + bool lossless_snippet = false; if (IsStringUTF8(test_result.output_snippet)) { test_result_value.SetStringKey("output_snippet",
diff --git a/base/test/launcher/test_results_tracker.h b/base/test/launcher/test_results_tracker.h index 6ae795c8..39f4eff 100644 --- a/base/test/launcher/test_results_tracker.h +++ b/base/test/launcher/test_results_tracker.h
@@ -107,6 +107,10 @@ private: FRIEND_TEST_ALL_PREFIXES(TestResultsTrackerTest, SaveSummaryAsJSONWithLinkInResult); + FRIEND_TEST_ALL_PREFIXES(TestResultsTrackerTest, + SaveSummaryAsJSONWithOutTimestampInResult); + FRIEND_TEST_ALL_PREFIXES(TestResultsTrackerTest, + SaveSummaryAsJSONWithTimestampInResult); void GetTestStatusForIteration(int iteration, TestStatusMap* map) const; template<typename InputIterator>
diff --git a/base/test/launcher/test_results_tracker_unittest.cc b/base/test/launcher/test_results_tracker_unittest.cc index 3d6031a..8ae9314 100644 --- a/base/test/launcher/test_results_tracker_unittest.cc +++ b/base/test/launcher/test_results_tracker_unittest.cc
@@ -6,8 +6,12 @@ #include "base/command_line.h" #include "base/files/file_util.h" +#include "base/time/time.h" +#include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" +using ::testing::HasSubstr; + namespace base { TEST(TestResultsTrackerTest, SaveSummaryAsJSONWithLinkInResult) { @@ -30,4 +34,49 @@ << expected_content << " not found in " << content; } +TEST(TestResultsTrackerTest, SaveSummaryAsJSONWithOutTimestampInResult) { + TestResultsTracker tracker; + TestResult result; + result.full_name = "A.B"; + + TestResultsTracker::AggregateTestResult aggregate_result; + aggregate_result.test_results.push_back(result); + tracker.per_iteration_data_.emplace_back( + TestResultsTracker::PerIterationData()); + tracker.per_iteration_data_.back().results["dummy"] = aggregate_result; + FilePath temp_file; + CreateTemporaryFile(&temp_file); + ASSERT_TRUE(tracker.SaveSummaryAsJSON(temp_file, std::vector<std::string>())); + std::string content; + ASSERT_TRUE(ReadFileToString(temp_file, &content)); + + for (auto* not_expected_content : {"thread_id", "process_num", "timestamp"}) { + EXPECT_THAT(content, ::testing::Not(HasSubstr(not_expected_content))); + } +} + +TEST(TestResultsTrackerTest, SaveSummaryAsJSONWithTimestampInResult) { + TestResultsTracker tracker; + TestResult result; + result.full_name = "A.B"; + result.thread_id = 123; + result.process_num = 456; + result.timestamp = Time::Now(); + + TestResultsTracker::AggregateTestResult aggregate_result; + aggregate_result.test_results.push_back(result); + tracker.per_iteration_data_.emplace_back( + TestResultsTracker::PerIterationData()); + tracker.per_iteration_data_.back().results["dummy"] = aggregate_result; + FilePath temp_file; + CreateTemporaryFile(&temp_file); + ASSERT_TRUE(tracker.SaveSummaryAsJSON(temp_file, std::vector<std::string>())); + std::string content; + ASSERT_TRUE(ReadFileToString(temp_file, &content)); + + EXPECT_THAT(content, HasSubstr(R"raw("thread_id":123)raw")); + EXPECT_THAT(content, HasSubstr(R"raw("process_num":456)raw")); + EXPECT_THAT(content, HasSubstr(R"raw("timestamp":)raw")); +} + } // namespace base
diff --git a/build/android/pylib/local/emulator/avd.py b/build/android/pylib/local/emulator/avd.py index d32fbd9..e637646 100644 --- a/build/android/pylib/local/emulator/avd.py +++ b/build/android/pylib/local/emulator/avd.py
@@ -537,6 +537,7 @@ window=False, writable_system=False, gpu_mode=_DEFAULT_GPU_MODE, + wipe_data=False, debug_tags=None): """Starts the emulator running an instance of the given AVD.""" @@ -552,6 +553,8 @@ '-no-boot-anim', ] + if wipe_data: + emulator_cmd.append('-wipe-data') if read_only: emulator_cmd.append('-read-only') if not snapshot_save:
diff --git a/build/config/fuchsia/generate_runner_scripts.gni b/build/config/fuchsia/generate_runner_scripts.gni index d591eb1..51a9de3 100644 --- a/build/config/fuchsia/generate_runner_scripts.gni +++ b/build/config/fuchsia/generate_runner_scripts.gni
@@ -221,10 +221,6 @@ executable_args += [ "--enable-test-server" ] } - if (defined(invoker.use_cfv2) && invoker.use_cfv2) { - executable_args += [ "--component-version=2" ] - } - if (default_fuchsia_device_node_name != "") { executable_args += [ "--node-name",
diff --git a/build/config/fuchsia/test/OWNERS b/build/config/fuchsia/test/OWNERS index f0bafd9a..3be17de 100644 --- a/build/config/fuchsia/test/OWNERS +++ b/build/config/fuchsia/test/OWNERS
@@ -3,9 +3,5 @@ per-file *.test-cmx=set noparent per-file *.test-cmx=ddorwin@chromium.org per-file *.test-cmx=wez@chromium.org -per-file *.test-cml=set noparent -per-file *.test-cml=ddorwin@chromium.org -per-file *.test-cml=wez@chromium.org # Please prefer the above when possible. per-file *.test-cmx=file://fuchsia/SECURITY_OWNERS -per-file *.test-cml=file://fuchsia/SECURITY_OWNERS
diff --git a/build/config/fuchsia/test/elf_test_runner.shard.test-cml b/build/config/fuchsia/test/elf_test_runner.shard.test-cml deleted file mode 100644 index 63d65fb..0000000 --- a/build/config/fuchsia/test/elf_test_runner.shard.test-cml +++ /dev/null
@@ -1,14 +0,0 @@ -{ - program: { - runner: "elf_test_runner", - }, - capabilities: [ - { protocol: "fuchsia.test.Suite" }, - ], - expose: [ - { - protocol: "fuchsia.test.Suite", - from: "self", - }, - ], -}
diff --git a/build/config/fuchsia/test/minimum_capabilities.test-cml b/build/config/fuchsia/test/minimum_capabilities.test-cml deleted file mode 100644 index a0934c1..0000000 --- a/build/config/fuchsia/test/minimum_capabilities.test-cml +++ /dev/null
@@ -1,52 +0,0 @@ -{ - // Add capability providers. - children: [ - { - name: "intl_property_manager", - url: "fuchsia-pkg://fuchsia.com/intl_property_manager#meta/intl_property_manager.cm", - }, - ], - offer: [ - { - protocol: "fuchsia.logger.LogSink", - from: "parent", - to: [ "#intl_property_manager" ], - } - ], - use: [ - { - storage: "cache", - path: "/cache", - }, - { - storage: "config-data", - rights: [ "r*" ], - path: "/config/data", - }, - { - storage: "custom_artifacts", - rights: [ "rw*" ], - path: "/custom_artifacts", - }, - { - storage: "data", - path: "/data", - }, - { - storage: "tmp", - path: "/tmp", - }, - { - protocol: [ "fuchsia.intl.PropertyProvider" ], - from: "#intl_property_manager", - }, - { - protocol: [ - "fuchsia.boot.ReadOnlyLog", - "fuchsia.logger.LogSink", - "fuchsia.process.Launcher", - "fuchsia.sys.Loader", - ], - }, - ], -}
diff --git a/build/fuchsia/common_args.py b/build/fuchsia/common_args.py index 5e332ee7..ac00fa6 100644 --- a/build/fuchsia/common_args.py +++ b/build/fuchsia/common_args.py
@@ -112,9 +112,6 @@ package_args.add_argument( '--package-name', help='Name of the package to execute, defined in ' + 'package metadata.') - package_args.add_argument('--component-version', - help='Component version of the package to execute', - default='1') emu_args = arg_parser.add_argument_group('emu', 'General emulator arguments') emu_args.add_argument('--cpu-cores',
diff --git a/build/fuchsia/fvdl_target.py b/build/fuchsia/fvdl_target.py index d2172e9..685ba0b 100644 --- a/build/fuchsia/fvdl_target.py +++ b/build/fuchsia/fvdl_target.py
@@ -81,12 +81,10 @@ @staticmethod def RegisterArgs(arg_parser): fvdl_args = arg_parser.add_argument_group('fvdl', 'FVDL arguments') - fvdl_args.add_argument('--without-network', - action='store_false', - dest='with_network', - default=True, - help='Run emulator without emulated nic via ' + - 'tun/tap.') + fvdl_args.add_argument('--with-network', + action='store_true', + default=False, + help='Run emulator with emulated nic via tun/tap.') fvdl_args.add_argument('--custom-image', help='Specify an image used for booting up the ' 'emulator.')
diff --git a/build/fuchsia/linux.sdk.sha1 b/build/fuchsia/linux.sdk.sha1 index 639c8401..9c99855 100644 --- a/build/fuchsia/linux.sdk.sha1 +++ b/build/fuchsia/linux.sdk.sha1
@@ -1 +1 @@ -7.20211207.0.1 +7.20211207.2.1
diff --git a/build/fuchsia/mac.sdk.sha1 b/build/fuchsia/mac.sdk.sha1 index 639c8401..9c99855 100644 --- a/build/fuchsia/mac.sdk.sha1 +++ b/build/fuchsia/mac.sdk.sha1
@@ -1 +1 @@ -7.20211207.0.1 +7.20211207.2.1
diff --git a/build/fuchsia/run_test_package.py b/build/fuchsia/run_test_package.py index aa4e99e..923e4e3 100644 --- a/build/fuchsia/run_test_package.py +++ b/build/fuchsia/run_test_package.py
@@ -114,10 +114,9 @@ del streams_by_fd[fileno] -def _GetComponentUri(package_name, package_component_version): - suffix = 'cm' if package_component_version == '2' else 'cmx' - return 'fuchsia-pkg://fuchsia.com/%s#meta/%s.%s' % (package_name, - package_name, suffix) +def _GetComponentUri(package_name): + return 'fuchsia-pkg://fuchsia.com/%s#meta/%s.cmx' % (package_name, + package_name) class RunTestPackageArgs: @@ -130,15 +129,12 @@ file fetched after the test suite has run. use_run_test_component: If True then the test package will be run hermetically via 'run-test-component', rather than using 'run'. - output_directory: If set, the output directory for CFv2 tests that use - custom artifacts; see fxb/75690. """ def __init__(self): self.code_coverage = False self.test_realm_label = None self.use_run_test_component = False - self.output_directory = None @staticmethod def FromCommonArgs(args): @@ -168,7 +164,7 @@ def RunTestPackage(output_dir, target, package_paths, package_name, - package_component_version, package_args, args): + package_args, args): """Installs the Fuchsia package at |package_path| on the target, executes it with |package_args|, and symbolizes its output. @@ -176,8 +172,6 @@ target: The deployment Target object that will run the package. package_paths: The paths to the .far packages to be installed. package_name: The name of the primary package to run. - package_component_version: The component version of the primary package to - run ("1" or "2"). package_args: The arguments which will be passed to the Fuchsia process. args: RunTestPackageArgs instance configuring how the package will be run. @@ -194,7 +188,6 @@ log_output_thread.start() with target.GetPkgRepo(): - on_target = True start_time = time.time() target.InstallPackage(package_paths) logging.info('Test installed in {:.2f} seconds.'.format(time.time() - @@ -205,23 +198,11 @@ logging.info('Running application.') - component_uri = _GetComponentUri(package_name, package_component_version) - if package_component_version == '2': - ffx = os.path.join(common.SDK_ROOT, 'tools', - common.GetHostArchFromPlatform(), 'ffx') - command = [ - ffx, '--config', 'test.experimental_structured_output=true', 'test', - 'run' - ] - if args.output_directory: - command += ['--output-directory', args.output_directory] - command += [component_uri, '--'] - on_target = False - elif args.code_coverage: - # TODO(crbug.com/1156768): Deprecate runtests. + # TODO(crbug.com/1156768): Deprecate runtests. + if args.code_coverage: # runtests requires specifying an output directory and a double dash # before the argument list. - command = ['runtests', '-o', '/tmp', component_uri] + command = ['runtests', '-o', '/tmp', _GetComponentUri(package_name)] if args.test_realm_label: command += ['--realm-label', args.test_realm_label] command += ['--'] @@ -229,23 +210,16 @@ command = ['run-test-component'] if args.test_realm_label: command += ['--realm-label=%s' % args.test_realm_label] - command.append(component_uri) + command.append(_GetComponentUri(package_name)) command.append('--') else: - command = ['run', component_uri] + command = ['run', _GetComponentUri(package_name)] command.extend(package_args) - if on_target: - process = target.RunCommandPiped(command, - stdin=open(os.devnull, 'r'), - stdout=subprocess.PIPE, - stderr=subprocess.STDOUT) - else: - logging.debug(command) - process = subprocess.Popen(command, - stdin=open(os.devnull, 'r'), - stdout=subprocess.PIPE, - stderr=subprocess.STDOUT) + process = target.RunCommandPiped(command, + stdin=open(os.devnull, 'r'), + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT) # Symbolize klog and systemlog as separate streams. The symbolizer # protocol is stateful, so comingled raw stack dumps can yield
diff --git a/build/fuchsia/start_emulator.py b/build/fuchsia/start_emulator.py index d667d9e..2b6db18a9 100755 --- a/build/fuchsia/start_emulator.py +++ b/build/fuchsia/start_emulator.py
@@ -19,8 +19,7 @@ def main(): parser = argparse.ArgumentParser( description='Launches a long-running emulator that can ' - 'be re-used for multiple test runs.', - conflict_handler='resolve') + 'be re-used for multiple test runs.') AddLongRunningArgs(parser) FvdlTarget.RegisterArgs(parser) AemuTarget.RegisterArgs(parser)
diff --git a/build/fuchsia/test_runner.py b/build/fuchsia/test_runner.py index d01966a..834fdbf 100755 --- a/build/fuchsia/test_runner.py +++ b/build/fuchsia/test_runner.py
@@ -8,7 +8,6 @@ import argparse import os -import shutil import sys import tempfile @@ -22,89 +21,13 @@ TEST_DATA_DIR = '/tmp' TEST_FILTER_PATH = TEST_DATA_DIR + '/test_filter.txt' -TEST_LLVM_PROFILE_DIR = 'llvm-profile' -TEST_PERF_RESULT_FILE = 'test_perf_summary.json' -TEST_RESULT_FILE = 'test_summary.json' +TEST_LLVM_PROFILE_PATH = TEST_DATA_DIR + '/llvm-profile' +TEST_PERF_RESULT_PATH = TEST_DATA_DIR + '/test_perf_summary.json' +TEST_RESULT_PATH = TEST_DATA_DIR + '/test_summary.json' TEST_REALM_NAME = 'chromium_tests' -class TestOutputs(object): - """An abstract base class for extracting outputs generated by a test.""" - - def __init__(self): - pass - - def __enter__(self): - return self - - def __exit__(self, exc_type, exc_val, exc_tb): - return False - - def GetDevicePath(self, path): - """Returns an absolute device-local variant of a path.""" - return '' - - def GetFile(self, glob, destination): - """Places all files/directories matched by a glob into a destination.""" - pass - - -class TargetTestOutputs(TestOutputs): - """A TestOutputs implementation for CFv2 tests, where tests emit files into - /tmp that are retrieved from the device via ssh.""" - - def __init__(self, target, package_name, test_realms): - super(TargetTestOutputs, self).__init__() - self._target = target - self._package_name = package_name - self._test_realms = test_realms - - def GetDevicePath(self, path): - return TEST_DATA_DIR + '/' + path - - def GetFile(self, glob, destination): - """Places all files/directories matched by a glob into a destination.""" - self._target.GetFile(self.GetDevicePath(glob), - destination, - for_package=self._package_name, - for_realms=self._test_realms) - - -class CustomArtifactsTestOutputs(TestOutputs): - """A TestOutputs implementation for CFv2 tests, where tests emit files into - /custom_artifacts that are retrieved from the device automatically via ffx.""" - - def __init__(self): - super(CustomArtifactsTestOutputs, self).__init__() - self._directory_manager = tempfile.TemporaryDirectory() - - def __enter__(self): - self._directory_manager.__enter__() - return self - - def __exit__(self, exc_type, exc_val, exc_tb): - return self._directory_manager.__exit__(exc_type, exc_val, exc_tb) - - def GetDevicePath(self, path): - return '/custom_artifacts/' + path - - def GetOutputDirectory(self): - return self._directory_manager.name - - def GetFile(self, glob, destination): - """Places all files/directories matched by a glob into a destination.""" - shutil.copy( - os.path.join(self._directory_manager.name, 'artifact-0', 'custom-0', - glob), destination) - - -def MakeTestOutputs(component_version, target, package_name, test_realms): - if component_version == '2': - return CustomArtifactsTestOutputs() - return TargetTestOutputs(target, package_name, test_realms) - - def AddTestExecutionArgs(arg_parser): test_args = arg_parser.add_argument_group('testing', 'Test execution arguments') @@ -211,9 +134,6 @@ if not args.out_dir: raise ValueError("out-dir must be specified.") - if args.component_version == "2": - args.use_run_test_component = False - if args.code_coverage and not args.use_run_test_component: raise ValueError('Collecting code coverage info requires using ' 'run-test-component.') @@ -264,6 +184,13 @@ '--test-launcher-retry-limit=' + args.test_launcher_retry_limit) if args.gtest_break_on_failure: child_args.append('--gtest_break_on_failure') + if args.test_launcher_summary_output: + child_args.append('--test-launcher-summary-output=' + TEST_RESULT_PATH) + if args.isolated_script_test_output: + child_args.append('--isolated-script-test-output=' + TEST_RESULT_PATH) + if args.isolated_script_test_perf_output: + child_args.append('--isolated-script-test-perf-output=' + + TEST_PERF_RESULT_PATH) if args.gtest_also_run_disabled_tests: child_args.append('--gtest_also_run_disabled_tests') @@ -277,21 +204,7 @@ test_realms = [TEST_REALM_NAME] try: - with GetDeploymentTargetForArgs(args) as target, \ - MakeTestOutputs(args.component_version, - target, - args.package_name, - test_realms) as test_outputs: - if args.test_launcher_summary_output: - child_args.append('--test-launcher-summary-output=' + - test_outputs.GetDevicePath(TEST_RESULT_FILE)) - if args.isolated_script_test_output: - child_args.append('--isolated-script-test-output=' + - test_outputs.GetDevicePath(TEST_RESULT_FILE)) - if args.isolated_script_test_perf_output: - child_args.append('--isolated-script-test-perf-output=' + - test_outputs.GetDevicePath(TEST_PERF_RESULT_FILE)) - + with GetDeploymentTargetForArgs(args) as target: target.Start() target.StartSystemLog(args.package) @@ -318,11 +231,9 @@ if args.use_run_test_component: run_package_args.test_realm_label = TEST_REALM_NAME run_package_args.use_run_test_component = True - if args.component_version == "2": - run_package_args.output_directory = test_outputs.GetOutputDirectory() returncode = RunTestPackage(args.out_dir, target, args.package, - args.package_name, args.component_version, - child_args, run_package_args) + args.package_name, child_args, + run_package_args) if test_server: test_server.Stop() @@ -330,19 +241,25 @@ if args.code_coverage: # Copy all the files in the profile directory. /* is used instead # of recursively copying due to permission issues for the latter. - test_outputs.GetFile(TEST_LLVM_PROFILE_DIR + '/*', - args.code_coverage_dir) + target.GetFile(TEST_LLVM_PROFILE_PATH + '/*', args.code_coverage_dir) if args.test_launcher_summary_output: - test_outputs.GetFile(TEST_RESULT_FILE, - args.test_launcher_summary_output) + target.GetFile(TEST_RESULT_PATH, + args.test_launcher_summary_output, + for_package=args.package_name, + for_realms=test_realms) if args.isolated_script_test_output: - test_outputs.GetFile(TEST_RESULT_FILE, args.isolated_script_test_output) + target.GetFile(TEST_RESULT_PATH, + args.isolated_script_test_output, + for_package=args.package_name, + for_realms=test_realms) if args.isolated_script_test_perf_output: - test_outputs.GetFile(TEST_PERF_RESULT_FILE, - args.isolated_script_test_perf_output) + target.GetFile(TEST_PERF_RESULT_PATH, + args.isolated_script_test_perf_output, + for_package=args.package_name, + for_realms=test_realms) return returncode
diff --git a/cc/animation/animation_host.cc b/cc/animation/animation_host.cc index 77bd42d..509cf983 100644 --- a/cc/animation/animation_host.cc +++ b/cc/animation/animation_host.cc
@@ -8,6 +8,7 @@ #include <memory> #include <utility> +#include "base/auto_reset.h" #include "base/bind.h" #include "base/callback.h" #include "base/containers/contains.h" @@ -280,9 +281,13 @@ mutator_host_client_->SetMutatorsNeedCommit(); } -void AnimationHost::PushPropertiesTo(MutatorHost* mutator_host_impl) { +void AnimationHost::PushPropertiesTo(MutatorHost* mutator_host_impl, + const PropertyTrees& property_trees) { auto* host_impl = static_cast<AnimationHost*>(mutator_host_impl); + base::AutoReset<const PropertyTrees*> properties(&property_trees_, + &property_trees); + // Update animation counts and whether raf was requested. These explicitly // do not request push properties and are pushed as part of the next commit // when it happens as requesting a commit leads to performance issues: @@ -334,6 +339,9 @@ } void AnimationHost::PushPropertiesToImplThread(AnimationHost* host_impl) { + base::AutoReset<const PropertyTrees*> properties(&host_impl->property_trees_, + property_trees_); + // Sync all animations with impl thread to create ElementAnimations. This // needs to happen before the element animations are synced below. for (auto& kv : id_to_timeline_map_) { @@ -372,6 +380,12 @@ return iter == element_to_animations_map_.end() ? nullptr : iter->second; } +gfx::PointF AnimationHost::GetScrollOffsetForAnimation( + ElementId element_id) const { + DCHECK(property_trees_); + return property_trees_->scroll_tree.current_scroll_offset(element_id); +} + void AnimationHost::SetScrollAnimationDurationForTesting( base::TimeDelta duration) { ScrollOffsetAnimationCurve::SetAnimationDurationForTesting(duration);
diff --git a/cc/animation/animation_host.h b/cc/animation/animation_host.h index 17f2596..027d822 100644 --- a/cc/animation/animation_host.h +++ b/cc/animation/animation_host.h
@@ -70,6 +70,8 @@ scoped_refptr<ElementAnimations> GetElementAnimationsForElementId( ElementId element_id) const; + gfx::PointF GetScrollOffsetForAnimation(ElementId element_id) const; + // Parent LayerTreeHost or LayerTreeHostImpl. MutatorHostClient* mutator_host_client() { return mutator_host_client_; } const MutatorHostClient* mutator_host_client() const { @@ -100,7 +102,8 @@ void SetLayerTreeMutator(std::unique_ptr<LayerTreeMutator> mutator) override; - void PushPropertiesTo(MutatorHost* host_impl) override; + void PushPropertiesTo(MutatorHost* host_impl, + const PropertyTrees& property_trees) override; void SetScrollAnimationDurationForTesting(base::TimeDelta duration) override; bool NeedsTickAnimations() const override; @@ -258,6 +261,9 @@ raw_ptr<MutatorHostClient> mutator_host_client_; + // This is only non-null within the call scope of PushPropertiesTo(). + const PropertyTrees* property_trees_ = nullptr; + // Exactly one of scroll_offset_animations_ and scroll_offset_animations_impl_ // will be non-null for a given AnimationHost instance (the former if // thread_instance_ == ThreadInstance::MAIN, the latter if thread_instance_ ==
diff --git a/cc/animation/animation_host_perftest.cc b/cc/animation/animation_host_perftest.cc index d3f6b788..537a645 100644 --- a/cc/animation/animation_host_perftest.cc +++ b/cc/animation/animation_host_perftest.cc
@@ -120,12 +120,13 @@ } void DoTest(const std::string& test_name) { + PropertyTrees property_trees; timer_.Reset(); do { // Invalidate dirty flags. SetAllTimelinesNeedPushProperties(); SetAllAnimationsNeedPushProperties(); - host()->PushPropertiesTo(host_impl()); + host()->PushPropertiesTo(host_impl(), property_trees); timer_.NextLap(); } while (!timer_.HasTimeLimitExpired());
diff --git a/cc/animation/animation_host_unittest.cc b/cc/animation/animation_host_unittest.cc index 77b3df3..23177392 100644 --- a/cc/animation/animation_host_unittest.cc +++ b/cc/animation/animation_host_unittest.cc
@@ -43,7 +43,7 @@ host_->AddAnimationTimeline(timeline_); timeline_->AttachAnimation(worklet_animation_); - host_->PushPropertiesTo(host_impl_); + host_->PushPropertiesTo(host_impl_, client_.GetPropertyTrees()); timeline_impl_ = host_impl_->GetTimelineById(timeline_id_); worklet_animation_impl_ = ToWorkletAnimation(timeline_impl_->GetAnimationById(cc_id)); @@ -77,20 +77,20 @@ EXPECT_FALSE(host_impl->GetTimelineById(timeline_id)); - host->PushPropertiesTo(host_impl.get()); + host->PushPropertiesTo(host_impl.get(), client_.GetPropertyTrees()); scoped_refptr<AnimationTimeline> timeline_impl = host_impl->GetTimelineById(timeline_id); EXPECT_TRUE(timeline_impl); EXPECT_EQ(timeline_impl->id(), timeline_id); - host->PushPropertiesTo(host_impl.get()); + host->PushPropertiesTo(host_impl.get(), client_.GetPropertyTrees()); EXPECT_EQ(timeline_impl, host_impl->GetTimelineById(timeline_id)); host->RemoveAnimationTimeline(timeline.get()); EXPECT_FALSE(timeline->animation_host()); - host->PushPropertiesTo(host_impl.get()); + host->PushPropertiesTo(host_impl.get(), client_.GetPropertyTrees()); EXPECT_FALSE(host_impl->GetTimelineById(timeline_id)); EXPECT_FALSE(timeline_impl->animation_host()); @@ -114,7 +114,7 @@ host->AddAnimationTimeline(timeline.get()); host_impl->AddAnimationTimeline(timeline_impl.get()); - host->PushPropertiesTo(host_impl.get()); + host->PushPropertiesTo(host_impl.get(), client_.GetPropertyTrees()); EXPECT_TRUE(host->GetTimelineById(timeline_id1)); EXPECT_TRUE(host_impl->GetTimelineById(timeline_id2)); @@ -172,7 +172,7 @@ [this, local_time]() { this->SetOutputState(local_time); })); // Push the opacity animation to the impl thread. - host_->PushPropertiesTo(host_impl_); + host_->PushPropertiesTo(host_impl_, client_.GetPropertyTrees()); host_impl_->ActivateAnimations(nullptr); // Ticking host should cause layer tree mutator to update output state which @@ -206,7 +206,7 @@ AddOpacityTransitionToAnimation(worklet_animation_.get(), duration, start_opacity, end_opacity, true); - host_->PushPropertiesTo(host_impl_); + host_->PushPropertiesTo(host_impl_, client_.GetPropertyTrees()); host_impl_->ActivateAnimations(nullptr); EXPECT_CALL(*mock_mutator, MutateRef(_)); @@ -231,7 +231,7 @@ AddOpacityTransitionToAnimation(worklet_animation_.get(), duration, start_opacity, end_opacity, true); - host_->PushPropertiesTo(host_impl_); + host_->PushPropertiesTo(host_impl_, client_.GetPropertyTrees()); host_impl_->ActivateAnimations(nullptr); EXPECT_CALL(*mock_mutator, MutateRef(_)).Times(1); @@ -425,7 +425,7 @@ EXPECT_FALSE(host_impl->HasCanvasInvalidation()); EXPECT_FALSE(host_impl->HasJSAnimation()); - host->PushPropertiesTo(host_impl.get()); + host->PushPropertiesTo(host_impl.get(), client_.GetPropertyTrees()); EXPECT_TRUE(host_impl->HasCanvasInvalidation()); EXPECT_TRUE(host_impl->HasJSAnimation()); }
diff --git a/cc/animation/animation_unittest.cc b/cc/animation/animation_unittest.cc index 2464b30..9f62ffc7 100644 --- a/cc/animation/animation_unittest.cc +++ b/cc/animation/animation_unittest.cc
@@ -15,6 +15,7 @@ #include "cc/animation/keyframe_effect.h" #include "cc/test/animation_test_common.h" #include "cc/test/animation_timelines_test_common.h" +#include "cc/trees/property_tree.h" namespace cc { namespace { @@ -38,7 +39,7 @@ EXPECT_TRUE(timeline_->needs_push_properties()); EXPECT_FALSE(animation_->keyframe_effect()->needs_push_properties()); - host_->PushPropertiesTo(host_impl_); + host_->PushPropertiesTo(host_impl_, client_.GetPropertyTrees()); EXPECT_FALSE(GetImplKeyframeEffectForLayerId(element_id_)); @@ -59,7 +60,7 @@ EXPECT_EQ(animation_->keyframe_effect()->element_id(), element_id_); CheckKeyframeEffectTimelineNeedsPushProperties(true); - host_->PushPropertiesTo(host_impl_); + host_->PushPropertiesTo(host_impl_, client_.GetPropertyTrees()); EXPECT_EQ(animation_impl_->keyframe_effect(), GetImplKeyframeEffectForLayerId(element_id_)); @@ -73,7 +74,7 @@ EXPECT_FALSE(animation_->keyframe_effect()->element_id()); CheckKeyframeEffectTimelineNeedsPushProperties(true); - host_->PushPropertiesTo(host_impl_); + host_->PushPropertiesTo(host_impl_, client_.GetPropertyTrees()); EXPECT_FALSE(GetImplKeyframeEffectForLayerId(element_id_)); EXPECT_FALSE(animation_impl_->element_animations()); @@ -86,7 +87,7 @@ EXPECT_FALSE(animation_->keyframe_effect()->element_id()); EXPECT_TRUE(timeline_->needs_push_properties()); EXPECT_FALSE(animation_->keyframe_effect()->needs_push_properties()); - host_->PushPropertiesTo(host_impl_); + host_->PushPropertiesTo(host_impl_, client_.GetPropertyTrees()); CheckKeyframeEffectTimelineNeedsPushProperties(false); } @@ -132,7 +133,7 @@ animation_->AttachElement(element_id_); CheckKeyframeEffectTimelineNeedsPushProperties(true); - host_->PushPropertiesTo(host_impl_); + host_->PushPropertiesTo(host_impl_, client_.GetPropertyTrees()); CheckKeyframeEffectTimelineNeedsPushProperties(false); const float start_value = .7f; @@ -148,7 +149,7 @@ end_opacity, false); CheckKeyframeEffectTimelineNeedsPushProperties(true); - host_->PushPropertiesTo(host_impl_); + host_->PushPropertiesTo(host_impl_, client_.GetPropertyTrees()); CheckKeyframeEffectTimelineNeedsPushProperties(false); EXPECT_TRUE(host_->HasInvalidationAnimation()); EXPECT_TRUE(host_->HasNativePropertyAnimation()); @@ -165,7 +166,7 @@ animation_->AttachElement(element_id_); CheckKeyframeEffectTimelineNeedsPushProperties(true); - host_->PushPropertiesTo(host_impl_); + host_->PushPropertiesTo(host_impl_, client_.GetPropertyTrees()); CheckKeyframeEffectTimelineNeedsPushProperties(false); const float start_value = .7f; @@ -176,7 +177,7 @@ end_value); CheckKeyframeEffectTimelineNeedsPushProperties(true); - host_->PushPropertiesTo(host_impl_); + host_->PushPropertiesTo(host_impl_, client_.GetPropertyTrees()); CheckKeyframeEffectTimelineNeedsPushProperties(false); EXPECT_TRUE(host_->HasInvalidationAnimation()); EXPECT_FALSE(host_->HasNativePropertyAnimation()); @@ -193,7 +194,7 @@ animation_->AttachElement(element_id_); CheckKeyframeEffectTimelineNeedsPushProperties(true); - host_->PushPropertiesTo(host_impl_); + host_->PushPropertiesTo(host_impl_, client_.GetPropertyTrees()); CheckKeyframeEffectTimelineNeedsPushProperties(false); const float start_opacity = .7f; @@ -204,7 +205,7 @@ end_opacity, false); CheckKeyframeEffectTimelineNeedsPushProperties(true); - host_->PushPropertiesTo(host_impl_); + host_->PushPropertiesTo(host_impl_, client_.GetPropertyTrees()); CheckKeyframeEffectTimelineNeedsPushProperties(false); EXPECT_FALSE(host_->HasInvalidationAnimation()); EXPECT_TRUE(host_->HasNativePropertyAnimation()); @@ -221,7 +222,7 @@ animation_->AttachElement(element_id_); CheckKeyframeEffectTimelineNeedsPushProperties(true); - host_->PushPropertiesTo(host_impl_); + host_->PushPropertiesTo(host_impl_, client_.GetPropertyTrees()); CheckKeyframeEffectTimelineNeedsPushProperties(false); const float start_opacity = .7f; @@ -249,7 +250,7 @@ end_invert); CheckKeyframeEffectTimelineNeedsPushProperties(true); - host_->PushPropertiesTo(host_impl_); + host_->PushPropertiesTo(host_impl_, client_.GetPropertyTrees()); CheckKeyframeEffectTimelineNeedsPushProperties(false); EXPECT_FALSE(client_.IsPropertyMutated(element_id_, ElementListType::ACTIVE, @@ -350,7 +351,7 @@ AddAnimatedTransformToAnimation(animation2.get(), duration, transform_x, transform_y); - host_->PushPropertiesTo(host_impl_); + host_->PushPropertiesTo(host_impl_, client_.GetPropertyTrees()); host_impl_->ActivateAnimations(nullptr); EXPECT_FALSE(delegate1.started()); @@ -432,7 +433,7 @@ ->HasAnyAnimationTargetingProperty(TargetProperty::OPACITY)); EXPECT_TRUE(animation_->keyframe_effect()->needs_push_properties()); - host_->PushPropertiesTo(host_impl_); + host_->PushPropertiesTo(host_impl_, client_.GetPropertyTrees()); EXPECT_FALSE(client_.IsPropertyMutated(element_id_, ElementListType::ACTIVE, TargetProperty::OPACITY)); @@ -497,7 +498,7 @@ timeline_->AttachAnimation(animation_); animation_->AttachElement(element_id_); - host_->PushPropertiesTo(host_impl_); + host_->PushPropertiesTo(host_impl_, client_.GetPropertyTrees()); timeline_impl_ = host_impl_->GetTimelineById(timeline_id_); EXPECT_TRUE(timeline_impl_); @@ -519,7 +520,7 @@ EXPECT_EQ(animation_impl_->keyframe_effect()->element_id(), element_id_); CheckKeyframeEffectTimelineNeedsPushProperties(false); - const ElementId new_element_id(NextTestLayerId()); + const ElementId new_element_id(element_id_.GetStableId() + 1); animation_->DetachElement(); animation_->AttachElement(new_element_id); @@ -529,7 +530,7 @@ EXPECT_EQ(animation_->keyframe_effect()->element_id(), new_element_id); CheckKeyframeEffectTimelineNeedsPushProperties(true); - host_->PushPropertiesTo(host_impl_); + host_->PushPropertiesTo(host_impl_, client_.GetPropertyTrees()); EXPECT_EQ(animation_impl_->keyframe_effect(), GetImplKeyframeEffectForLayerId(new_element_id));
diff --git a/cc/animation/element_animations.cc b/cc/animation/element_animations.cc index dc50436..00602a4 100644 --- a/cc/animation/element_animations.cc +++ b/cc/animation/element_animations.cc
@@ -544,12 +544,8 @@ } gfx::PointF ElementAnimations::ScrollOffsetForAnimation() const { - if (animation_host_) { - DCHECK(animation_host_->mutator_host_client()); - return animation_host_->mutator_host_client()->GetScrollOffsetForAnimation( - element_id()); - } - + if (animation_host_) + return animation_host_->GetScrollOffsetForAnimation(element_id()); return gfx::PointF(); }
diff --git a/cc/animation/element_animations_unittest.cc b/cc/animation/element_animations_unittest.cc index 16ac81da..d68ba61 100644 --- a/cc/animation/element_animations_unittest.cc +++ b/cc/animation/element_animations_unittest.cc
@@ -262,7 +262,7 @@ gfx::PointF provider_initial_value(150.f, 300.f); gfx::PointF target_value(300.f, 200.f); - client_impl_.SetScrollOffsetForAnimation(provider_initial_value); + client_.SetScrollOffsetForAnimation(provider_initial_value, element_id_); // Animation with initial value set. std::unique_ptr<ScrollOffsetAnimationCurve> curve_fixed( @@ -901,7 +901,7 @@ keyframe_model->set_needs_synchronized_start_time(true); animation_->AddKeyframeModel(std::move(keyframe_model)); - client_impl_.SetScrollOffsetForAnimation(initial_value); + client_.SetScrollOffsetForAnimation(initial_value, element_id_); PushProperties(); animation_impl_->ActivateKeyframeModels(); EXPECT_TRUE(animation_impl_->GetKeyframeModel(TargetProperty::SCROLL_OFFSET)); @@ -1074,7 +1074,7 @@ keyframe_model->set_needs_synchronized_start_time(true); animation_->AddKeyframeModel(std::move(keyframe_model)); - client_.SetScrollOffsetForAnimation(initial_value); + client_.SetScrollOffsetForAnimation(initial_value, element_id_); PushProperties(); animation_impl_->ActivateKeyframeModels(); EXPECT_TRUE(animation_impl_->GetKeyframeModel(TargetProperty::SCROLL_OFFSET));
diff --git a/cc/input/threaded_input_handler.cc b/cc/input/threaded_input_handler.cc index 246e829..9cf134a8 100644 --- a/cc/input/threaded_input_handler.cc +++ b/cc/input/threaded_input_handler.cc
@@ -559,14 +559,14 @@ // Otherwise, the compositor-thread is the 'scrolling thread'. // TODO(crbug.com/1060712): We should also count 'main thread' as the // 'scrolling thread' if the layer being scrolled has scroll-event handlers. - FrameSequenceMetrics::ThreadType scrolling_thread; + FrameInfo::SmoothEffectDrivingThread scrolling_thread; switch (scroll_start_state) { case ScrollBeginThreadState::kScrollingOnCompositor: - scrolling_thread = FrameSequenceMetrics::ThreadType::kCompositor; + scrolling_thread = FrameInfo::SmoothEffectDrivingThread::kCompositor; break; case ScrollBeginThreadState::kScrollingOnMain: case ScrollBeginThreadState::kScrollingOnCompositorBlockedOnMain: - scrolling_thread = FrameSequenceMetrics::ThreadType::kMain; + scrolling_thread = FrameInfo::SmoothEffectDrivingThread::kMain; break; } compositor_delegate_.GetImplDeprecated().frame_trackers().StartScrollSequence(
diff --git a/cc/layers/layer_unittest.cc b/cc/layers/layer_unittest.cc index bf4d4d09..9dd45b42 100644 --- a/cc/layers/layer_unittest.cc +++ b/cc/layers/layer_unittest.cc
@@ -1639,7 +1639,8 @@ EXPECT_FALSE(host_impl_.animation_host()->CurrentFrameHadRAF()); EXPECT_FALSE(host_impl_.animation_host()->HasSmilAnimation()); EXPECT_FALSE(animation_host_->needs_push_properties()); - animation_host_->PushPropertiesTo(host_impl_.animation_host()); + animation_host_->PushPropertiesTo(host_impl_.animation_host(), + *layer_tree_host_->property_trees()); EXPECT_TRUE(host_impl_.animation_host()->CurrentFrameHadRAF()); EXPECT_TRUE(host_impl_.animation_host()->HasSmilAnimation()); }
diff --git a/cc/metrics/compositor_frame_reporter.cc b/cc/metrics/compositor_frame_reporter.cc index f564f27..e3f6fb42 100644 --- a/cc/metrics/compositor_frame_reporter.cc +++ b/cc/metrics/compositor_frame_reporter.cc
@@ -544,7 +544,7 @@ const viz::BeginFrameArgs& args, bool should_report_metrics, SmoothThread smooth_thread, - FrameSequenceMetrics::ThreadType scrolling_thread, + FrameInfo::SmoothEffectDrivingThread scrolling_thread, int layer_tree_host_id, const GlobalMetricsTrackers& trackers) : should_report_metrics_(should_report_metrics), @@ -557,7 +557,14 @@ global_trackers_.dropped_frame_counter->OnBeginFrame( args, IsScrollActive(active_trackers_)); DCHECK(IsScrollActive(active_trackers_) || - scrolling_thread_ == FrameSequenceMetrics::ThreadType::kUnknown); + scrolling_thread_ == FrameInfo::SmoothEffectDrivingThread::kUnknown); + if (scrolling_thread_ == FrameInfo::SmoothEffectDrivingThread::kCompositor) { + DCHECK(smooth_thread_ == SmoothThread::kSmoothCompositor || + smooth_thread_ == SmoothThread::kSmoothBoth); + } else if (scrolling_thread_ == FrameInfo::SmoothEffectDrivingThread::kMain) { + DCHECK(smooth_thread_ == SmoothThread::kSmoothMain || + smooth_thread_ == SmoothThread::kSmoothBoth); + } } std::unique_ptr<CompositorFrameReporter> @@ -1080,14 +1087,14 @@ } reporter->set_affects_smoothness(info.IsDroppedAffectingSmoothness()); ChromeFrameReporter::ScrollState scroll_state; - switch (scrolling_thread_) { - case FrameSequenceMetrics::ThreadType::kMain: + switch (info.scroll_thread) { + case FrameInfo::SmoothEffectDrivingThread::kMain: scroll_state = ChromeFrameReporter::SCROLL_MAIN_THREAD; break; - case FrameSequenceMetrics::ThreadType::kCompositor: + case FrameInfo::SmoothEffectDrivingThread::kCompositor: scroll_state = ChromeFrameReporter::SCROLL_COMPOSITOR_THREAD; break; - case FrameSequenceMetrics::ThreadType::kUnknown: + case FrameInfo::SmoothEffectDrivingThread::kUnknown: scroll_state = ChromeFrameReporter::SCROLL_NONE; break; } @@ -1416,6 +1423,18 @@ info.final_state = final_state; info.smooth_thread = smooth_thread_; info.has_missing_content = has_missing_content_; + + if (!stage_history_.empty()) { + const auto& stage = stage_history_.back(); + if (stage.stage_type == StageType::kTotalLatency) { + DCHECK_EQ(frame_termination_time_ - args_.frame_time, + stage.end_time - stage.start_time); + info.total_latency = frame_termination_time_ - args_.frame_time; + } + } + + info.scroll_thread = scrolling_thread_; + return info; }
diff --git a/cc/metrics/compositor_frame_reporter.h b/cc/metrics/compositor_frame_reporter.h index 9511365..9239b5cb 100644 --- a/cc/metrics/compositor_frame_reporter.h +++ b/cc/metrics/compositor_frame_reporter.h
@@ -229,7 +229,7 @@ const viz::BeginFrameArgs& args, bool should_report_metrics, SmoothThread smooth_thread, - FrameSequenceMetrics::ThreadType scrolling_thread, + FrameInfo::SmoothEffectDrivingThread scrolling_thread, int layer_tree_host_id, const GlobalMetricsTrackers& trackers); ~CompositorFrameReporter(); @@ -402,7 +402,7 @@ FrameTerminationStatus::kUnknown; const ActiveTrackers active_trackers_; - const FrameSequenceMetrics::ThreadType scrolling_thread_; + const FrameInfo::SmoothEffectDrivingThread scrolling_thread_; // Indicates if work on Impl frame is finished. bool did_finish_impl_frame_ = false;
diff --git a/cc/metrics/compositor_frame_reporter_unittest.cc b/cc/metrics/compositor_frame_reporter_unittest.cc index c3e61ca..de005ae8 100644 --- a/cc/metrics/compositor_frame_reporter_unittest.cc +++ b/cc/metrics/compositor_frame_reporter_unittest.cc
@@ -111,7 +111,7 @@ ActiveTrackers(), viz::BeginFrameArgs(), /*should_report_metrics=*/true, CompositorFrameReporter::SmoothThread::kSmoothBoth, - FrameSequenceMetrics::ThreadType::kUnknown, + FrameInfo::SmoothEffectDrivingThread::kUnknown, /*layer_tree_host_id=*/1, trackers); reporter->set_tick_clock(&test_tick_clock_); return reporter;
diff --git a/cc/metrics/compositor_frame_reporting_controller.cc b/cc/metrics/compositor_frame_reporting_controller.cc index 8e9c68b..d069b53 100644 --- a/cc/metrics/compositor_frame_reporting_controller.cc +++ b/cc/metrics/compositor_frame_reporting_controller.cc
@@ -70,11 +70,16 @@ void CompositorFrameReportingController::ProcessSkippedFramesIfNecessary( const viz::BeginFrameArgs& args) { - if (previous_frame_.IsValid() && - previous_frame_.frame_id.source_id == args.frame_id.source_id) { - CreateReportersForDroppedFrames(previous_frame_, args); + const auto& previous_frame = last_started_compositor_frame_.args; + if (previous_frame.IsValid() && + previous_frame.frame_id.source_id == args.frame_id.source_id) { + CreateReportersForDroppedFrames(previous_frame, args); } - previous_frame_ = args; + + last_started_compositor_frame_.args = args; + last_started_compositor_frame_.scrolling_thread = scrolling_thread_; + last_started_compositor_frame_.active_trackers = active_trackers_; + last_started_compositor_frame_.smooth_thread = GetSmoothThread(); } void CompositorFrameReportingController::WillBeginImplFrame( @@ -125,10 +130,22 @@ } else { // In this case we have already submitted the ImplFrame, but we received // beginMain frame before next BeginImplFrame (Not reached the ImplFrame - // deadline yet). So will start a new reporter at BeginMainFrame. + // deadline yet). So will start a new reporter at BeginMainFrame, and use + // the state(s) from the ImplFrame where necessary. + auto scrolling_thread = scrolling_thread_; + auto active_trackers = active_trackers_; + auto smooth_thread = GetSmoothThread(); + if (args.frame_id == last_started_compositor_frame_.args.frame_id) { + // TODO(1277547): Instead of replacing all current information with the + // older information from when the impl-frame started, merge the two sets + // of information that makes sense. + scrolling_thread = last_started_compositor_frame_.scrolling_thread; + active_trackers = last_started_compositor_frame_.active_trackers; + smooth_thread = last_started_compositor_frame_.smooth_thread; + } auto reporter = std::make_unique<CompositorFrameReporter>( - active_trackers_, args, should_report_metrics_, GetSmoothThread(), - scrolling_thread_, layer_tree_host_id_, global_trackers_); + active_trackers, args, should_report_metrics_, smooth_thread, + scrolling_thread, layer_tree_host_id_, global_trackers_); reporter->set_tick_clock(tick_clock_); reporter->StartStage(StageType::kSendBeginMainFrameToCommit, Now()); reporters_[PipelineStage::kBeginMainFrame] = std::move(reporter); @@ -522,7 +539,7 @@ now); } } - previous_frame_ = {}; + last_started_compositor_frame_ = {}; } void CompositorFrameReportingController::NotifyReadyToCommit( @@ -545,19 +562,19 @@ } void CompositorFrameReportingController::SetScrollingThread( - FrameSequenceMetrics::ThreadType thread) { + FrameInfo::SmoothEffectDrivingThread thread) { scrolling_thread_ = thread; } void CompositorFrameReportingController::SetThreadAffectsSmoothness( - FrameSequenceMetrics::ThreadType thread_type, + FrameInfo::SmoothEffectDrivingThread thread_type, bool affects_smoothness) { auto current_smooth_thread = GetSmoothThread(); - if (thread_type == FrameSequenceMetrics::ThreadType::kCompositor) { + if (thread_type == FrameInfo::SmoothEffectDrivingThread::kCompositor) { is_compositor_thread_driving_smoothness_ = affects_smoothness; } else { - DCHECK_EQ(thread_type, FrameSequenceMetrics::ThreadType::kMain); + DCHECK_EQ(thread_type, FrameInfo::SmoothEffectDrivingThread::kMain); is_main_thread_driving_smoothness_ = affects_smoothness; } @@ -710,7 +727,7 @@ auto reporter = std::make_unique<CompositorFrameReporter>( active_trackers_, args, should_report_metrics_, GetSmoothThreadAtTime(timestamp), - FrameSequenceMetrics::ThreadType::kUnknown, layer_tree_host_id_, + FrameInfo::SmoothEffectDrivingThread::kUnknown, layer_tree_host_id_, global_trackers_); reporter->set_tick_clock(tick_clock_); reporter->StartStage(StageType::kBeginImplFrameToSendBeginMainFrame,
diff --git a/cc/metrics/compositor_frame_reporting_controller.h b/cc/metrics/compositor_frame_reporting_controller.h index 05369f603d..998a787 100644 --- a/cc/metrics/compositor_frame_reporting_controller.h +++ b/cc/metrics/compositor_frame_reporting_controller.h
@@ -83,10 +83,11 @@ void AddActiveTracker(FrameSequenceTrackerType type); void RemoveActiveTracker(FrameSequenceTrackerType type); - void SetScrollingThread(FrameSequenceMetrics::ThreadType thread); + void SetScrollingThread(FrameInfo::SmoothEffectDrivingThread thread); - void SetThreadAffectsSmoothness(FrameSequenceMetrics::ThreadType thread_type, - bool affects_smoothness); + void SetThreadAffectsSmoothness( + FrameInfo::SmoothEffectDrivingThread thread_type, + bool affects_smoothness); bool is_main_thread_driving_smoothness() const { return is_main_thread_driving_smoothness_; } @@ -164,8 +165,8 @@ bool next_activate_has_invalidation_ = false; ActiveTrackers active_trackers_; - FrameSequenceMetrics::ThreadType scrolling_thread_ = - FrameSequenceMetrics::ThreadType::kUnknown; + FrameInfo::SmoothEffectDrivingThread scrolling_thread_ = + FrameInfo::SmoothEffectDrivingThread::kUnknown; bool is_compositor_thread_driving_smoothness_ = false; bool is_main_thread_driving_smoothness_ = false; @@ -189,8 +190,18 @@ // must outlive the objects in |submitted_compositor_frames_|. base::circular_deque<SubmittedCompositorFrame> submitted_compositor_frames_; - // The latest frame that was started. - viz::BeginFrameArgs previous_frame_; + // Contains information about the latest frame that was started, and the state + // during that frame. This is used to process skipped frames, as well as + // making sure a CompositorFrameReporter object for a delayed main-frame is + // created with the correct state. + struct { + viz::BeginFrameArgs args; + FrameInfo::SmoothEffectDrivingThread scrolling_thread = + FrameInfo::SmoothEffectDrivingThread::kUnknown; + ActiveTrackers active_trackers; + CompositorFrameReporter::SmoothThread smooth_thread = + CompositorFrameReporter::SmoothThread::kSmoothNone; + } last_started_compositor_frame_; base::TimeTicks begin_main_frame_start_time_; @@ -212,6 +223,7 @@ // interval of last begin frame args. base::TimeDelta last_interval_; }; + } // namespace cc #endif // CC_METRICS_COMPOSITOR_FRAME_REPORTING_CONTROLLER_H_
diff --git a/cc/metrics/compositor_frame_reporting_controller_unittest.cc b/cc/metrics/compositor_frame_reporting_controller_unittest.cc index d64f719..e0c8522 100644 --- a/cc/metrics/compositor_frame_reporting_controller_unittest.cc +++ b/cc/metrics/compositor_frame_reporting_controller_unittest.cc
@@ -1692,7 +1692,8 @@ TEST_F(CompositorFrameReportingControllerTest, SkippedFramesFromDisplayCompositorHaveSmoothThread) { - auto thread_type_compositor = FrameSequenceMetrics::ThreadType::kCompositor; + auto thread_type_compositor = + FrameInfo::SmoothEffectDrivingThread::kCompositor; reporting_controller_.SetThreadAffectsSmoothness(thread_type_compositor, true); dropped_counter_.OnFcpReceived(); @@ -1832,7 +1833,7 @@ TEST_F(CompositorFrameReportingControllerTest, NewMainThreadUpdateNotReportedAsDropped) { - auto thread_type_main = FrameSequenceMetrics::ThreadType::kMain; + auto thread_type_main = FrameInfo::SmoothEffectDrivingThread::kMain; reporting_controller_.SetThreadAffectsSmoothness(thread_type_main, /*affects_smoothness=*/true); dropped_counter_.OnFcpReceived();
diff --git a/cc/metrics/frame_info.cc b/cc/metrics/frame_info.cc index ed8c28ec..7c9703c7 100644 --- a/cc/metrics/frame_info.cc +++ b/cc/metrics/frame_info.cc
@@ -4,6 +4,8 @@ #include "cc/metrics/frame_info.h" +#include <algorithm> + namespace cc { namespace { @@ -49,6 +51,10 @@ } void FrameInfo::MergeWith(const FrameInfo& info) { + // The |scroll_thread| information cannot change once the frame starts. So + // it should not need to be updated during merge. + DCHECK_EQ(scroll_thread, info.scroll_thread); + if (info.has_missing_content) has_missing_content = true; if (info.final_state == FrameFinalState::kDropped) @@ -67,6 +73,8 @@ } else { smooth_thread = SmoothThread::kSmoothNone; } + + total_latency = std::max(total_latency, info.total_latency); } } // namespace cc
diff --git a/cc/metrics/frame_info.h b/cc/metrics/frame_info.h index a1bd0fc..36721c86 100644 --- a/cc/metrics/frame_info.h +++ b/cc/metrics/frame_info.h
@@ -5,6 +5,7 @@ #ifndef CC_METRICS_FRAME_INFO_H_ #define CC_METRICS_FRAME_INFO_H_ +#include "base/time/time.h" #include "cc/cc_export.h" namespace cc { @@ -44,8 +45,16 @@ }; SmoothThread smooth_thread = SmoothThread::kSmoothNone; + enum class SmoothEffectDrivingThread { kMain, kCompositor, kUnknown }; + SmoothEffectDrivingThread scroll_thread = SmoothEffectDrivingThread::kUnknown; + bool has_missing_content = false; + // The total latency for the frame. If the frame had to be 'split' (i.e. + // compositor-thread update and main-thread updates were presented in separate + // frames), then this contains the maximum latency of the two updates. + base::TimeDelta total_latency; + bool IsDroppedAffectingSmoothness() const; void MergeWith(const FrameInfo& info); };
diff --git a/cc/metrics/frame_sequence_metrics.cc b/cc/metrics/frame_sequence_metrics.cc index b5a1767..2ab455c 100644 --- a/cc/metrics/frame_sequence_metrics.cc +++ b/cc/metrics/frame_sequence_metrics.cc
@@ -19,22 +19,24 @@ namespace cc { +using SmoothEffectDrivingThread = FrameInfo::SmoothEffectDrivingThread; + bool ShouldReportForAnimation(FrameSequenceTrackerType sequence_type, - FrameSequenceMetrics::ThreadType thread_type) { + SmoothEffectDrivingThread thread_type) { if (sequence_type == FrameSequenceTrackerType::kCompositorAnimation) - return thread_type == FrameSequenceMetrics::ThreadType::kCompositor; + return thread_type == SmoothEffectDrivingThread::kCompositor; if (sequence_type == FrameSequenceTrackerType::kMainThreadAnimation || sequence_type == FrameSequenceTrackerType::kJSAnimation) - return thread_type == FrameSequenceMetrics::ThreadType::kMain; + return thread_type == SmoothEffectDrivingThread::kMain; return false; } bool ShouldReportForInteraction( FrameSequenceTrackerType sequence_type, - FrameSequenceMetrics::ThreadType reporting_thread_type, - FrameSequenceMetrics::ThreadType metrics_effective_thread_type) { + SmoothEffectDrivingThread reporting_thread_type, + SmoothEffectDrivingThread metrics_effective_thread_type) { // For scrollbar/touch/wheel scroll, the slower thread is the one we want to // report. For pinch-zoom, it's the compositor-thread. if (sequence_type == FrameSequenceTrackerType::kScrollbarScroll || @@ -43,8 +45,7 @@ return reporting_thread_type == metrics_effective_thread_type; if (sequence_type == FrameSequenceTrackerType::kPinchZoom) - return reporting_thread_type == - FrameSequenceMetrics::ThreadType::kCompositor; + return reporting_thread_type == SmoothEffectDrivingThread::kCompositor; return false; } @@ -59,11 +60,11 @@ static_cast<int>(FrameSequenceTrackerType::kMaxType) + 1; constexpr int kMaximumHistogramIndex = 3 * kBuiltinSequenceNum; -int GetIndexForMetric(FrameSequenceMetrics::ThreadType thread_type, +int GetIndexForMetric(SmoothEffectDrivingThread thread_type, FrameSequenceTrackerType type) { - if (thread_type == FrameSequenceMetrics::ThreadType::kMain) + if (thread_type == SmoothEffectDrivingThread::kMain) return static_cast<int>(type); - if (thread_type == FrameSequenceMetrics::ThreadType::kCompositor) + if (thread_type == SmoothEffectDrivingThread::kCompositor) return static_cast<int>(type) + kBuiltinSequenceNum; return static_cast<int>(type) + 2 * kBuiltinSequenceNum; } @@ -100,13 +101,13 @@ FrameSequenceMetrics::FrameSequenceMetrics(FrameSequenceTrackerType type, ThroughputUkmReporter* ukm_reporter) : type_(type), throughput_ukm_reporter_(ukm_reporter) { - ThreadType thread_type = GetEffectiveThread(); + SmoothEffectDrivingThread thread_type = GetEffectiveThread(); // Only construct |jank_reporter_| if it has a valid tracker and thread type. // For scrolling tracker types, |jank_reporter_| may be constructed later in // SetScrollingThread(). - if (thread_type == ThreadType::kCompositor || - thread_type == ThreadType::kMain) { + if (thread_type == SmoothEffectDrivingThread::kCompositor || + thread_type == SmoothEffectDrivingThread::kMain) { jank_reporter_ = std::make_unique<JankMetrics>(type, thread_type); } } @@ -118,15 +119,16 @@ ReportMetrics(); } -void FrameSequenceMetrics::SetScrollingThread(ThreadType scrolling_thread) { +void FrameSequenceMetrics::SetScrollingThread( + SmoothEffectDrivingThread scrolling_thread) { DCHECK(type_ == FrameSequenceTrackerType::kTouchScroll || type_ == FrameSequenceTrackerType::kWheelScroll || type_ == FrameSequenceTrackerType::kScrollbarScroll); - DCHECK_EQ(scrolling_thread_, ThreadType::kUnknown); + DCHECK_EQ(scrolling_thread_, SmoothEffectDrivingThread::kUnknown); scrolling_thread_ = scrolling_thread; DCHECK(!jank_reporter_); - DCHECK_NE(scrolling_thread, ThreadType::kUnknown); + DCHECK_NE(scrolling_thread, SmoothEffectDrivingThread::kUnknown); jank_reporter_ = std::make_unique<JankMetrics>(type_, scrolling_thread); } @@ -135,19 +137,18 @@ custom_reporter_ = std::move(custom_reporter); } -FrameSequenceMetrics::ThreadType FrameSequenceMetrics::GetEffectiveThread() - const { +SmoothEffectDrivingThread FrameSequenceMetrics::GetEffectiveThread() const { switch (type_) { case FrameSequenceTrackerType::kCompositorAnimation: case FrameSequenceTrackerType::kPinchZoom: case FrameSequenceTrackerType::kVideo: - return ThreadType::kCompositor; + return SmoothEffectDrivingThread::kCompositor; case FrameSequenceTrackerType::kMainThreadAnimation: case FrameSequenceTrackerType::kRAF: case FrameSequenceTrackerType::kCanvasAnimation: case FrameSequenceTrackerType::kJSAnimation: - return ThreadType::kMain; + return SmoothEffectDrivingThread::kMain; case FrameSequenceTrackerType::kTouchScroll: case FrameSequenceTrackerType::kScrollbarScroll: @@ -155,12 +156,12 @@ return scrolling_thread_; case FrameSequenceTrackerType::kCustom: - return ThreadType::kMain; + return SmoothEffectDrivingThread::kMain; case FrameSequenceTrackerType::kMaxType: NOTREACHED(); } - return ThreadType::kUnknown; + return SmoothEffectDrivingThread::kUnknown; } void FrameSequenceMetrics::Merge( @@ -229,9 +230,9 @@ } const bool main_report = ThroughputData::CanReportHistogram( - this, ThreadType::kMain, main_throughput_); + this, SmoothEffectDrivingThread::kMain, main_throughput_); const bool compositor_report = ThroughputData::CanReportHistogram( - this, ThreadType::kCompositor, impl_throughput_); + this, SmoothEffectDrivingThread::kCompositor, impl_throughput_); absl::optional<int> impl_throughput_percent_dropped; absl::optional<int> impl_throughput_percent_missed; @@ -242,44 +243,42 @@ if (compositor_report) { impl_throughput_percent_dropped = ThroughputData::ReportDroppedFramePercentHistogram( - this, ThreadType::kCompositor, - GetIndexForMetric(FrameSequenceMetrics::ThreadType::kCompositor, - type_), + this, SmoothEffectDrivingThread::kCompositor, + GetIndexForMetric(SmoothEffectDrivingThread::kCompositor, type_), impl_throughput_); impl_throughput_percent_missed = ThroughputData::ReportMissedDeadlineFramePercentHistogram( - this, ThreadType::kCompositor, - GetIndexForMetric(FrameSequenceMetrics::ThreadType::kCompositor, - type_), + this, SmoothEffectDrivingThread::kCompositor, + GetIndexForMetric(SmoothEffectDrivingThread::kCompositor, type_), impl_throughput_); } if (main_report) { main_throughput_percent_dropped = ThroughputData::ReportDroppedFramePercentHistogram( - this, ThreadType::kMain, - GetIndexForMetric(FrameSequenceMetrics::ThreadType::kMain, type_), + this, SmoothEffectDrivingThread::kMain, + GetIndexForMetric(SmoothEffectDrivingThread::kMain, type_), main_throughput_); main_throughput_percent_missed = ThroughputData::ReportMissedDeadlineFramePercentHistogram( - this, ThreadType::kMain, - GetIndexForMetric(FrameSequenceMetrics::ThreadType::kMain, type_), + this, SmoothEffectDrivingThread::kMain, + GetIndexForMetric(SmoothEffectDrivingThread::kMain, type_), main_throughput_); } // Report for the 'scrolling thread' for the scrolling interactions. - if (scrolling_thread_ != ThreadType::kUnknown) { + if (scrolling_thread_ != SmoothEffectDrivingThread::kUnknown) { absl::optional<int> scrolling_thread_throughput_dropped; absl::optional<int> scrolling_thread_throughput_missed; switch (scrolling_thread_) { - case ThreadType::kCompositor: + case SmoothEffectDrivingThread::kCompositor: scrolling_thread_throughput_dropped = impl_throughput_percent_dropped; scrolling_thread_throughput_missed = impl_throughput_percent_missed; break; - case ThreadType::kMain: + case SmoothEffectDrivingThread::kMain: scrolling_thread_throughput_dropped = main_throughput_percent_dropped; scrolling_thread_throughput_missed = main_throughput_percent_missed; break; - case ThreadType::kUnknown: + case SmoothEffectDrivingThread::kUnknown: NOTREACHED(); break; } @@ -337,12 +336,12 @@ // Report the jank metrics if (jank_reporter_) { if (jank_reporter_->thread_type() == - FrameSequenceMetrics::ThreadType::kCompositor && + SmoothEffectDrivingThread::kCompositor && impl_throughput_.frames_expected >= kMinFramesForThroughputMetric) { DCHECK_EQ(jank_reporter_->thread_type(), this->GetEffectiveThread()); jank_reporter_->ReportJankMetrics(impl_throughput_.frames_expected); } else if (jank_reporter_->thread_type() == - FrameSequenceMetrics::ThreadType::kMain && + SmoothEffectDrivingThread::kMain && main_throughput_.frames_expected >= kMinFramesForThroughputMetric) { DCHECK_EQ(jank_reporter_->thread_type(), this->GetEffectiveThread()); @@ -357,11 +356,10 @@ main_throughput_ = {}; } -void FrameSequenceMetrics::ComputeJank( - FrameSequenceMetrics::ThreadType thread_type, - uint32_t frame_token, - base::TimeTicks presentation_time, - base::TimeDelta frame_interval) { +void FrameSequenceMetrics::ComputeJank(SmoothEffectDrivingThread thread_type, + uint32_t frame_token, + base::TimeTicks presentation_time, + base::TimeDelta frame_interval) { if (!jank_reporter_) return; @@ -371,7 +369,7 @@ } void FrameSequenceMetrics::NotifySubmitForJankReporter( - FrameSequenceMetrics::ThreadType thread_type, + SmoothEffectDrivingThread thread_type, uint32_t frame_token, uint32_t sequence_number) { if (!jank_reporter_) @@ -382,7 +380,7 @@ } void FrameSequenceMetrics::NotifyNoUpdateForJankReporter( - FrameSequenceMetrics::ThreadType thread_type, + SmoothEffectDrivingThread thread_type, uint32_t sequence_number, base::TimeDelta frame_interval) { if (!jank_reporter_) @@ -394,20 +392,20 @@ bool FrameSequenceMetrics::ThroughputData::CanReportHistogram( FrameSequenceMetrics* metrics, - ThreadType thread_type, + SmoothEffectDrivingThread thread_type, const ThroughputData& data) { const auto sequence_type = metrics->type(); DCHECK_LT(sequence_type, FrameSequenceTrackerType::kMaxType); // All video frames are compositor thread only. if (sequence_type == FrameSequenceTrackerType::kVideo && - thread_type == ThreadType::kMain) + thread_type == SmoothEffectDrivingThread::kMain) return false; // RAF and CanvasAnimation are main thread only. if ((sequence_type == FrameSequenceTrackerType::kRAF || sequence_type == FrameSequenceTrackerType::kCanvasAnimation) && - thread_type == ThreadType::kCompositor) + thread_type == SmoothEffectDrivingThread::kCompositor) return false; if (data.frames_expected < kMinFramesForThroughputMetric) @@ -424,7 +422,7 @@ int FrameSequenceMetrics::ThroughputData::ReportDroppedFramePercentHistogram( FrameSequenceMetrics* metrics, - ThreadType thread_type, + SmoothEffectDrivingThread thread_type, int metric_index, const ThroughputData& data) { const auto sequence_type = metrics->type(); @@ -483,9 +481,9 @@ } } - const char* thread_name = thread_type == ThreadType::kCompositor - ? "CompositorThread" - : "MainThread"; + const char* thread_name = + thread_type == SmoothEffectDrivingThread::kCompositor ? "CompositorThread" + : "MainThread"; STATIC_HISTOGRAM_POINTER_GROUP( GetThroughputHistogramName(sequence_type, thread_name), metric_index, kMaximumHistogramIndex, Add(percent), @@ -496,10 +494,11 @@ } int FrameSequenceMetrics::ThroughputData:: - ReportMissedDeadlineFramePercentHistogram(FrameSequenceMetrics* metrics, - ThreadType thread_type, - int metric_index, - const ThroughputData& data) { + ReportMissedDeadlineFramePercentHistogram( + FrameSequenceMetrics* metrics, + SmoothEffectDrivingThread thread_type, + int metric_index, + const ThroughputData& data) { const auto sequence_type = metrics->type(); DCHECK_LT(sequence_type, FrameSequenceTrackerType::kMaxType); @@ -544,9 +543,9 @@ percent); } - const char* thread_name = thread_type == ThreadType::kCompositor - ? "CompositorThread" - : "MainThread"; + const char* thread_name = + thread_type == SmoothEffectDrivingThread::kCompositor ? "CompositorThread" + : "MainThread"; STATIC_HISTOGRAM_POINTER_GROUP( GetMissedDeadlineHistogramName(sequence_type, thread_name), metric_index, kMaximumHistogramIndex, Add(percent), @@ -560,9 +559,9 @@ FrameSequenceMetrics::ThroughputData::ToTracedValue( const ThroughputData& impl, const ThroughputData& main, - ThreadType effective_thread) { + SmoothEffectDrivingThread effective_thread) { auto dict = std::make_unique<base::trace_event::TracedValue>(); - if (effective_thread == ThreadType::kMain) { + if (effective_thread == SmoothEffectDrivingThread::kMain) { dict->SetInteger("main-frames-produced", main.frames_produced); dict->SetInteger("main-frames-expected", main.frames_expected); dict->SetInteger("main-frames-ontime", main.frames_ontime);
diff --git a/cc/metrics/frame_sequence_metrics.h b/cc/metrics/frame_sequence_metrics.h index 9c50073d..a64a8b6e 100644 --- a/cc/metrics/frame_sequence_metrics.h +++ b/cc/metrics/frame_sequence_metrics.h
@@ -12,6 +12,7 @@ #include "base/memory/raw_ptr.h" #include "base/trace_event/traced_value.h" #include "cc/cc_export.h" +#include "cc/metrics/frame_info.h" namespace cc { class ThroughputUkmReporter; @@ -71,28 +72,28 @@ FrameSequenceMetrics(const FrameSequenceMetrics&) = delete; FrameSequenceMetrics& operator=(const FrameSequenceMetrics&) = delete; - enum class ThreadType { kMain, kCompositor, kUnknown }; - struct ThroughputData { static std::unique_ptr<base::trace_event::TracedValue> ToTracedValue( const ThroughputData& impl, const ThroughputData& main, - ThreadType effective_thred); + FrameInfo::SmoothEffectDrivingThread effective_thred); - static bool CanReportHistogram(FrameSequenceMetrics* metrics, - ThreadType thread_type, - const ThroughputData& data); + static bool CanReportHistogram( + FrameSequenceMetrics* metrics, + FrameInfo::SmoothEffectDrivingThread thread_type, + const ThroughputData& data); // Returns the dropped throughput in percent - static int ReportDroppedFramePercentHistogram(FrameSequenceMetrics* metrics, - ThreadType thread_type, - int metric_index, - const ThroughputData& data); + static int ReportDroppedFramePercentHistogram( + FrameSequenceMetrics* metrics, + FrameInfo::SmoothEffectDrivingThread thread_type, + int metric_index, + const ThroughputData& data); // Returns the missed deadline throughput in percent static int ReportMissedDeadlineFramePercentHistogram( FrameSequenceMetrics* metrics, - ThreadType thread_type, + FrameInfo::SmoothEffectDrivingThread thread_type, int metric_index, const ThroughputData& data); @@ -142,7 +143,7 @@ #endif }; - void SetScrollingThread(ThreadType thread); + void SetScrollingThread(FrameInfo::SmoothEffectDrivingThread thread); struct CustomReportData { uint32_t frames_expected = 0; @@ -155,7 +156,7 @@ // Returns the 'effective thread' for the metrics (i.e. the thread most // relevant for this metric). - ThreadType GetEffectiveThread() const; + FrameInfo::SmoothEffectDrivingThread GetEffectiveThread() const; void Merge(std::unique_ptr<FrameSequenceMetrics> metrics); bool HasEnoughDataForReporting() const; @@ -181,17 +182,18 @@ void AdoptTrace(FrameSequenceMetrics* adopt_from); void AdvanceTrace(base::TimeTicks timestamp); - void ComputeJank(FrameSequenceMetrics::ThreadType thread_type, + void ComputeJank(FrameInfo::SmoothEffectDrivingThread thread_type, uint32_t frame_token, base::TimeTicks presentation_time, base::TimeDelta frame_interval); - void NotifySubmitForJankReporter(FrameSequenceMetrics::ThreadType thread_type, - uint32_t frame_token, - uint32_t sequence_number); + void NotifySubmitForJankReporter( + FrameInfo::SmoothEffectDrivingThread thread_type, + uint32_t frame_token, + uint32_t sequence_number); void NotifyNoUpdateForJankReporter( - FrameSequenceMetrics::ThreadType thread_type, + FrameInfo::SmoothEffectDrivingThread thread_type, uint32_t sequence_number, base::TimeDelta frame_interval); @@ -218,7 +220,8 @@ ThroughputData impl_throughput_; ThroughputData main_throughput_; - ThreadType scrolling_thread_ = ThreadType::kUnknown; + FrameInfo::SmoothEffectDrivingThread scrolling_thread_ = + FrameInfo::SmoothEffectDrivingThread::kUnknown; // Tracks the number of produced frames that had some amount of // checkerboarding, and how many frames showed such checkerboarded frames. @@ -231,12 +234,12 @@ }; bool ShouldReportForAnimation(FrameSequenceTrackerType sequence_type, - FrameSequenceMetrics::ThreadType thread_type); + FrameInfo::SmoothEffectDrivingThread thread_type); bool ShouldReportForInteraction( FrameSequenceTrackerType sequence_type, - FrameSequenceMetrics::ThreadType reporting_thread_type, - FrameSequenceMetrics::ThreadType metrics_effective_thread_type); + FrameInfo::SmoothEffectDrivingThread reporting_thread_type, + FrameInfo::SmoothEffectDrivingThread metrics_effective_thread_type); } // namespace cc
diff --git a/cc/metrics/frame_sequence_metrics_unittest.cc b/cc/metrics/frame_sequence_metrics_unittest.cc index 1be96a3..cbef003 100644 --- a/cc/metrics/frame_sequence_metrics_unittest.cc +++ b/cc/metrics/frame_sequence_metrics_unittest.cc
@@ -39,14 +39,14 @@ #if DCHECK_IS_ON() TEST(FrameSequenceMetricsTest, ScrollingThreadMergeMetrics) { FrameSequenceMetrics first(FrameSequenceTrackerType::kTouchScroll, nullptr); - first.SetScrollingThread(FrameSequenceMetrics::ThreadType::kCompositor); + first.SetScrollingThread(FrameInfo::SmoothEffectDrivingThread::kCompositor); first.impl_throughput().frames_expected = 20; first.impl_throughput().frames_produced = 10; first.impl_throughput().frames_ontime = 10; auto second = std::make_unique<FrameSequenceMetrics>( FrameSequenceTrackerType::kTouchScroll, nullptr); - second->SetScrollingThread(FrameSequenceMetrics::ThreadType::kMain); + second->SetScrollingThread(FrameInfo::SmoothEffectDrivingThread::kMain); second->main_throughput().frames_expected = 50; second->main_throughput().frames_produced = 10; second->main_throughput().frames_ontime = 10; @@ -212,7 +212,7 @@ base::HistogramTester histograms; auto metrics = setup(); EXPECT_TRUE(metrics->HasEnoughDataForReporting()); - metrics->SetScrollingThread(FrameSequenceMetrics::ThreadType::kMain); + metrics->SetScrollingThread(FrameInfo::SmoothEffectDrivingThread::kMain); metrics->ReportMetrics(); histograms.ExpectTotalCount(metric, 1u); EXPECT_THAT(histograms.GetAllSamples(metric), @@ -224,7 +224,8 @@ base::HistogramTester histograms; auto metrics = setup(); EXPECT_TRUE(metrics->HasEnoughDataForReporting()); - metrics->SetScrollingThread(FrameSequenceMetrics::ThreadType::kCompositor); + metrics->SetScrollingThread( + FrameInfo::SmoothEffectDrivingThread::kCompositor); metrics->ReportMetrics(); histograms.ExpectTotalCount(metric, 1u); EXPECT_THAT(histograms.GetAllSamples(metric),
diff --git a/cc/metrics/frame_sequence_tracker.cc b/cc/metrics/frame_sequence_tracker.cc index 2622ea3b..4ea0d0a 100644 --- a/cc/metrics/frame_sequence_tracker.cc +++ b/cc/metrics/frame_sequence_tracker.cc
@@ -42,7 +42,7 @@ } // namespace -using ThreadType = FrameSequenceMetrics::ThreadType; +using ThreadType = FrameInfo::SmoothEffectDrivingThread; // In the |TRACKER_TRACE_STREAM|, we mod the numbers such as frame sequence // number, or frame token, such that the debug string is not too long. @@ -291,7 +291,7 @@ TRACKER_TRACE_STREAM << "s(" << frame_token % kDebugStrMod << ")"; had_impl_frame_submitted_between_commits_ = true; metrics()->NotifySubmitForJankReporter( - FrameSequenceMetrics::ThreadType::kCompositor, frame_token, + FrameInfo::SmoothEffectDrivingThread::kCompositor, frame_token, ack.frame_id.sequence_number); const bool main_changes_after_sequence_started = @@ -316,7 +316,7 @@ kDebugStrMod << ")"; metrics()->NotifySubmitForJankReporter( - FrameSequenceMetrics::ThreadType::kMain, frame_token, + FrameInfo::SmoothEffectDrivingThread::kMain, frame_token, origin_args.frame_id.sequence_number); last_submitted_main_sequence_ = origin_args.frame_id.sequence_number; @@ -389,7 +389,7 @@ << TRACKER_DCHECK_MSG; --impl_throughput().frames_expected; metrics()->NotifyNoUpdateForJankReporter( - FrameSequenceMetrics::ThreadType::kCompositor, + FrameInfo::SmoothEffectDrivingThread::kCompositor, args.frame_id.sequence_number, args.interval); #if DCHECK_IS_ON() ++impl_throughput().frames_processed; @@ -485,7 +485,7 @@ metrics()->AdvanceTrace(feedback.timestamp); } - metrics()->ComputeJank(FrameSequenceMetrics::ThreadType::kCompositor, + metrics()->ComputeJank(FrameInfo::SmoothEffectDrivingThread::kCompositor, frame_token, feedback.timestamp, vsync_interval); } @@ -506,7 +506,7 @@ metrics()->AdvanceTrace(feedback.timestamp); } - metrics()->ComputeJank(FrameSequenceMetrics::ThreadType::kMain, + metrics()->ComputeJank(FrameInfo::SmoothEffectDrivingThread::kMain, frame_token, feedback.timestamp, vsync_interval); } if (main_frames_.size() < size_before_erase) { @@ -634,8 +634,8 @@ last_no_main_damage_sequence_ = args.frame_id.sequence_number; --main_throughput().frames_expected; metrics()->NotifyNoUpdateForJankReporter( - FrameSequenceMetrics::ThreadType::kMain, args.frame_id.sequence_number, - args.interval); + FrameInfo::SmoothEffectDrivingThread::kMain, + args.frame_id.sequence_number, args.interval); DCHECK_GE(main_throughput().frames_expected, main_frames_.size()) << TRACKER_DCHECK_MSG;
diff --git a/cc/metrics/frame_sequence_tracker_collection.cc b/cc/metrics/frame_sequence_tracker_collection.cc index e1d59ec..8549ccd 100644 --- a/cc/metrics/frame_sequence_tracker_collection.cc +++ b/cc/metrics/frame_sequence_tracker_collection.cc
@@ -18,7 +18,7 @@ namespace { -using ThreadType = FrameSequenceMetrics::ThreadType; +using ThreadType = FrameInfo::SmoothEffectDrivingThread; bool IsScrollType(FrameSequenceTrackerType type) { return type == FrameSequenceTrackerType::kTouchScroll || @@ -45,7 +45,7 @@ FrameSequenceTracker* FrameSequenceTrackerCollection::StartSequenceInternal( FrameSequenceTrackerType type, - FrameSequenceMetrics::ThreadType scrolling_thread) { + FrameInfo::SmoothEffectDrivingThread scrolling_thread) { DCHECK_NE(FrameSequenceTrackerType::kCustom, type); if (is_single_threaded_) return nullptr; @@ -98,7 +98,7 @@ FrameSequenceTracker* FrameSequenceTrackerCollection::StartScrollSequence( FrameSequenceTrackerType type, - FrameSequenceMetrics::ThreadType scrolling_thread) { + FrameInfo::SmoothEffectDrivingThread scrolling_thread) { DCHECK(IsScrollType(type)); return StartSequenceInternal(type, scrolling_thread); } @@ -360,7 +360,7 @@ // The frame sequence is still active, so create a new tracker to keep // tracking this sequence. - if (thread_type != FrameSequenceMetrics::ThreadType::kUnknown) { + if (thread_type != FrameInfo::SmoothEffectDrivingThread::kUnknown) { DCHECK(IsScrollType(tracker_type)); StartScrollSequence(tracker_type, thread_type); } else {
diff --git a/cc/metrics/frame_sequence_tracker_collection.h b/cc/metrics/frame_sequence_tracker_collection.h index 04d5a51..b74f8ef 100644 --- a/cc/metrics/frame_sequence_tracker_collection.h +++ b/cc/metrics/frame_sequence_tracker_collection.h
@@ -55,7 +55,7 @@ FrameSequenceTracker* StartSequence(FrameSequenceTrackerType type); FrameSequenceTracker* StartScrollSequence( FrameSequenceTrackerType type, - FrameSequenceMetrics::ThreadType scrolling_thread); + FrameInfo::SmoothEffectDrivingThread scrolling_thread); // Schedules |tracker| for destruction. This is preferred instead of outright // desrtruction of the tracker, since this ensures that the actual tracker @@ -125,7 +125,7 @@ FrameSequenceTracker* StartSequenceInternal( FrameSequenceTrackerType type, - FrameSequenceMetrics::ThreadType scrolling_thread); + FrameInfo::SmoothEffectDrivingThread scrolling_thread); void RecreateTrackers(const viz::BeginFrameArgs& args); // Destroy the trackers that are ready to be terminated. @@ -153,7 +153,7 @@ // The callsite can use the type to manipulate the tracker. base::flat_map< - std::pair<FrameSequenceTrackerType, FrameSequenceMetrics::ThreadType>, + std::pair<FrameSequenceTrackerType, FrameInfo::SmoothEffectDrivingThread>, std::unique_ptr<FrameSequenceTracker>> frame_trackers_; @@ -170,7 +170,7 @@ compositor_frame_reporting_controller_; base::flat_map< - std::pair<FrameSequenceTrackerType, FrameSequenceMetrics::ThreadType>, + std::pair<FrameSequenceTrackerType, FrameInfo::SmoothEffectDrivingThread>, std::unique_ptr<FrameSequenceMetrics>> accumulated_metrics_;
diff --git a/cc/metrics/frame_sequence_tracker_unittest.cc b/cc/metrics/frame_sequence_tracker_unittest.cc index 8e18fb985..cb3c6d72 100644 --- a/cc/metrics/frame_sequence_tracker_unittest.cc +++ b/cc/metrics/frame_sequence_tracker_unittest.cc
@@ -51,12 +51,12 @@ compositor_frame_reporting_controller_.get()) { tracker_ = collection_.StartScrollSequence( FrameSequenceTrackerType::kTouchScroll, - FrameSequenceMetrics::ThreadType::kCompositor); + FrameInfo::SmoothEffectDrivingThread::kCompositor); } ~FrameSequenceTrackerTest() override = default; - void CreateNewTracker(FrameSequenceMetrics::ThreadType thread_type = - FrameSequenceMetrics::ThreadType::kCompositor) { + void CreateNewTracker(FrameInfo::SmoothEffectDrivingThread thread_type = + FrameInfo::SmoothEffectDrivingThread::kCompositor) { tracker_ = collection_.StartScrollSequence( FrameSequenceTrackerType::kTouchScroll, thread_type); } @@ -109,13 +109,15 @@ // Check whether a type of tracker exists in |frame_trackers_| or not. bool TrackerExists(FrameSequenceTrackerType type) const { - auto key = std::make_pair(type, FrameSequenceMetrics::ThreadType::kUnknown); + auto key = + std::make_pair(type, FrameInfo::SmoothEffectDrivingThread::kUnknown); if (type == FrameSequenceTrackerType::kTouchScroll || type == FrameSequenceTrackerType::kWheelScroll || type == FrameSequenceTrackerType::kScrollbarScroll) { - key = std::make_pair(type, FrameSequenceMetrics::ThreadType::kCompositor); + key = std::make_pair(type, + FrameInfo::SmoothEffectDrivingThread::kCompositor); if (!collection_.frame_trackers_.contains(key)) - key = std::make_pair(type, FrameSequenceMetrics::ThreadType::kMain); + key = std::make_pair(type, FrameInfo::SmoothEffectDrivingThread::kMain); } return collection_.frame_trackers_.contains(key); } @@ -725,7 +727,7 @@ } TEST_F(FrameSequenceTrackerTest, ScrollingThreadMetricMainThread) { - CreateNewTracker(FrameSequenceMetrics::ThreadType::kMain); + CreateNewTracker(FrameInfo::SmoothEffectDrivingThread::kMain); // Start with a bunch of frames so that the metric does get reported at the // end of the test. @@ -1729,7 +1731,7 @@ GenerateSequence(first_sequence); collection_.StopSequence(FrameSequenceTrackerType::kTouchScroll); - CreateNewTracker(FrameSequenceMetrics::ThreadType::kCompositor); + CreateNewTracker(FrameInfo::SmoothEffectDrivingThread::kCompositor); const char second_sequence[] = "b(81)s(3)e(81,0)P(3)b(101)s(4)e(101,0)P(4)"; GenerateSequence(second_sequence); collection_.StopSequence(FrameSequenceTrackerType::kTouchScroll); @@ -1750,7 +1752,7 @@ GenerateSequence(compscroll_sequence); collection_.StopSequence(FrameSequenceTrackerType::kTouchScroll); - CreateNewTracker(FrameSequenceMetrics::ThreadType::kMain); + CreateNewTracker(FrameInfo::SmoothEffectDrivingThread::kMain); const char mainscroll_sequence[] = "b(81)s(3)e(81,0)P(3)b(101)s(4)e(101,0)P(4)"; GenerateSequence(mainscroll_sequence);
diff --git a/cc/metrics/jank_metrics.cc b/cc/metrics/jank_metrics.cc index 2ae7f7c..499f2d66 100644 --- a/cc/metrics/jank_metrics.cc +++ b/cc/metrics/jank_metrics.cc
@@ -29,18 +29,19 @@ constexpr base::TimeDelta kStaleHistogramMax = base::Milliseconds(1000); constexpr int kStaleHistogramBucketCount = 200; -constexpr bool IsValidJankThreadType(FrameSequenceMetrics::ThreadType type) { - return type == FrameSequenceMetrics::ThreadType::kCompositor || - type == FrameSequenceMetrics::ThreadType::kMain; +constexpr bool IsValidJankThreadType( + FrameInfo::SmoothEffectDrivingThread type) { + return type == FrameInfo::SmoothEffectDrivingThread::kCompositor || + type == FrameInfo::SmoothEffectDrivingThread::kMain; } -const char* GetJankThreadTypeName(FrameSequenceMetrics::ThreadType type) { +const char* GetJankThreadTypeName(FrameInfo::SmoothEffectDrivingThread type) { DCHECK(IsValidJankThreadType(type)); switch (type) { - case FrameSequenceMetrics::ThreadType::kCompositor: + case FrameInfo::SmoothEffectDrivingThread::kCompositor: return "Compositor"; - case FrameSequenceMetrics::ThreadType::kMain: + case FrameInfo::SmoothEffectDrivingThread::kMain: return "Main"; default: NOTREACHED(); @@ -48,13 +49,13 @@ } } -int GetIndexForJankMetric(FrameSequenceMetrics::ThreadType thread_type, +int GetIndexForJankMetric(FrameInfo::SmoothEffectDrivingThread thread_type, FrameSequenceTrackerType type) { DCHECK(IsValidJankThreadType(thread_type)); - if (thread_type == FrameSequenceMetrics::ThreadType::kMain) + if (thread_type == FrameInfo::SmoothEffectDrivingThread::kMain) return static_cast<int>(type); - DCHECK_EQ(thread_type, FrameSequenceMetrics::ThreadType::kCompositor); + DCHECK_EQ(thread_type, FrameInfo::SmoothEffectDrivingThread::kCompositor); return static_cast<int>(type) + kBuiltinSequenceNum; } @@ -84,7 +85,7 @@ } // namespace JankMetrics::JankMetrics(FrameSequenceTrackerType tracker_type, - FrameSequenceMetrics::ThreadType effective_thread) + FrameInfo::SmoothEffectDrivingThread effective_thread) : tracker_type_(tracker_type), effective_thread_(effective_thread) { DCHECK(IsValidJankThreadType(effective_thread)); }
diff --git a/cc/metrics/jank_metrics.h b/cc/metrics/jank_metrics.h index 91ca7fa3d..7f8c9d4 100644 --- a/cc/metrics/jank_metrics.h +++ b/cc/metrics/jank_metrics.h
@@ -25,7 +25,7 @@ class CC_EXPORT JankMetrics { public: JankMetrics(FrameSequenceTrackerType tracker_type, - FrameSequenceMetrics::ThreadType effective_thread); + FrameInfo::SmoothEffectDrivingThread effective_thread); ~JankMetrics(); JankMetrics(const JankMetrics&) = delete; @@ -55,7 +55,7 @@ int jank_count() const { return jank_count_; } base::TimeDelta max_staleness() const { return max_staleness_; } - FrameSequenceMetrics::ThreadType thread_type() const { + FrameInfo::SmoothEffectDrivingThread thread_type() const { return effective_thread_; } @@ -65,7 +65,7 @@ // The thread that contributes to the janks detected by the current // JankMetrics object. - const FrameSequenceMetrics::ThreadType effective_thread_; + const FrameInfo::SmoothEffectDrivingThread effective_thread_; // Number of janks detected. int jank_count_ = 0;
diff --git a/cc/metrics/jank_metrics_unittest.cc b/cc/metrics/jank_metrics_unittest.cc index 43c8e0d..7f52436 100644 --- a/cc/metrics/jank_metrics_unittest.cc +++ b/cc/metrics/jank_metrics_unittest.cc
@@ -137,8 +137,8 @@ base::HistogramTester histogram_tester; FrameSequenceTrackerType tracker_type = FrameSequenceTrackerType::kCompositorAnimation; - FrameSequenceMetrics::ThreadType thread_type = - FrameSequenceMetrics::ThreadType::kCompositor; + FrameInfo::SmoothEffectDrivingThread thread_type = + FrameInfo::SmoothEffectDrivingThread::kCompositor; JankMetrics jank_reporter{tracker_type, thread_type}; // One Jank; there are no no-update frames. The fluctuation in presentation of @@ -196,8 +196,8 @@ base::HistogramTester histogram_tester; FrameSequenceTrackerType tracker_type = FrameSequenceTrackerType::kMainThreadAnimation; - FrameSequenceMetrics::ThreadType thread_type = - FrameSequenceMetrics::ThreadType::kMain; + FrameInfo::SmoothEffectDrivingThread thread_type = + FrameInfo::SmoothEffectDrivingThread::kMain; JankMetrics jank_reporter{tracker_type, thread_type}; // There are only 1 jank because of a no-update frame. @@ -249,8 +249,8 @@ TEST_F(JankMetricsTest, VideoManyJanksOver300ExpectedFrames) { base::HistogramTester histogram_tester; FrameSequenceTrackerType tracker_type = FrameSequenceTrackerType::kVideo; - FrameSequenceMetrics::ThreadType thread_type = - FrameSequenceMetrics::ThreadType::kCompositor; + FrameInfo::SmoothEffectDrivingThread thread_type = + FrameInfo::SmoothEffectDrivingThread::kCompositor; JankMetrics jank_reporter{tracker_type, thread_type}; // 7 janks. @@ -297,8 +297,8 @@ base::HistogramTester histogram_tester; FrameSequenceTrackerType tracker_type = FrameSequenceTrackerType::kWheelScroll; - FrameSequenceMetrics::ThreadType thread_type = - FrameSequenceMetrics::ThreadType::kMain; + FrameInfo::SmoothEffectDrivingThread thread_type = + FrameInfo::SmoothEffectDrivingThread::kMain; JankMetrics jank_reporter{tracker_type, thread_type}; SimulateFrameSequence(&jank_reporter, @@ -348,8 +348,8 @@ base::HistogramTester histogram_tester; FrameSequenceTrackerType tracker_type = FrameSequenceTrackerType::kWheelScroll; - FrameSequenceMetrics::ThreadType thread_type = - FrameSequenceMetrics::ThreadType::kCompositor; + FrameInfo::SmoothEffectDrivingThread thread_type = + FrameInfo::SmoothEffectDrivingThread::kCompositor; JankMetrics jank_reporter{tracker_type, thread_type}; // Two janks; there are no no-update frames. The fluctuations in presentation @@ -404,8 +404,8 @@ base::HistogramTester histogram_tester; FrameSequenceTrackerType tracker_type = FrameSequenceTrackerType::kTouchScroll; - FrameSequenceMetrics::ThreadType thread_type = - FrameSequenceMetrics::ThreadType::kCompositor; + FrameInfo::SmoothEffectDrivingThread thread_type = + FrameInfo::SmoothEffectDrivingThread::kCompositor; JankMetrics jank_reporter{tracker_type, thread_type}; @@ -463,8 +463,8 @@ TEST_F(JankMetricsTest, RAFMergeJanks) { base::HistogramTester histogram_tester; FrameSequenceTrackerType tracker_type = FrameSequenceTrackerType::kRAF; - FrameSequenceMetrics::ThreadType thread_type = - FrameSequenceMetrics::ThreadType::kMain; + FrameInfo::SmoothEffectDrivingThread thread_type = + FrameInfo::SmoothEffectDrivingThread::kMain; JankMetrics jank_reporter{tracker_type, thread_type}; std::unique_ptr<JankMetrics> other_reporter = @@ -522,8 +522,8 @@ TEST_F(JankMetricsTest, CustomNotReported) { base::HistogramTester histogram_tester; FrameSequenceTrackerType tracker_type = FrameSequenceTrackerType::kCustom; - FrameSequenceMetrics::ThreadType thread_type = - FrameSequenceMetrics::ThreadType::kMain; + FrameInfo::SmoothEffectDrivingThread thread_type = + FrameInfo::SmoothEffectDrivingThread::kMain; JankMetrics jank_reporter{tracker_type, thread_type}; // There should be 4 janks, but the jank reporter does not track or report @@ -558,8 +558,8 @@ base::HistogramTester histogram_tester; FrameSequenceTrackerType tracker_type = FrameSequenceTrackerType::kCompositorAnimation; - FrameSequenceMetrics::ThreadType thread_type = - FrameSequenceMetrics::ThreadType::kCompositor; + FrameInfo::SmoothEffectDrivingThread thread_type = + FrameInfo::SmoothEffectDrivingThread::kCompositor; JankMetrics jank_reporter{tracker_type, thread_type}; // One jank at E. The long delay of 100 frames between b and c is considered @@ -624,8 +624,8 @@ base::HistogramTester histogram_tester; FrameSequenceTrackerType tracker_type = FrameSequenceTrackerType::kCompositorAnimation; - FrameSequenceMetrics::ThreadType thread_type = - FrameSequenceMetrics::ThreadType::kCompositor; + FrameInfo::SmoothEffectDrivingThread thread_type = + FrameInfo::SmoothEffectDrivingThread::kCompositor; JankMetrics jank_reporter{tracker_type, thread_type}; // Two janks at D and E. The long delay of 99 no-update frames does not
diff --git a/cc/metrics/throughput_ukm_reporter.cc b/cc/metrics/throughput_ukm_reporter.cc index b11ef1f..077e9592 100644 --- a/cc/metrics/throughput_ukm_reporter.cc +++ b/cc/metrics/throughput_ukm_reporter.cc
@@ -37,13 +37,13 @@ samples_to_next_event_[static_cast<int>(type)] = kNumberOfSamplesToReport; if (impl_throughput_percent) { ukm_manager_->RecordThroughputUKM( - type, FrameSequenceMetrics::ThreadType::kCompositor, + type, FrameInfo::SmoothEffectDrivingThread::kCompositor, impl_throughput_percent.value()); } if (main_throughput_percent) { - ukm_manager_->RecordThroughputUKM(type, - FrameSequenceMetrics::ThreadType::kMain, - main_throughput_percent.value()); + ukm_manager_->RecordThroughputUKM( + type, FrameInfo::SmoothEffectDrivingThread::kMain, + main_throughput_percent.value()); } } DCHECK_GT(samples_to_next_event_[static_cast<int>(type)], 0u);
diff --git a/cc/test/animation_timelines_test_common.cc b/cc/test/animation_timelines_test_common.cc index b34c41b..0b12e25 100644 --- a/cc/test/animation_timelines_test_common.cc +++ b/cc/test/animation_timelines_test_common.cc
@@ -176,13 +176,9 @@ } void TestHostClient::SetScrollOffsetForAnimation( - const gfx::PointF& scroll_offset) { - scroll_offset_ = scroll_offset; -} - -gfx::PointF TestHostClient::GetScrollOffsetForAnimation( - ElementId element_id) const { - return scroll_offset_; + const gfx::PointF& scroll_offset, + ElementId element_id) { + property_trees_.scroll_tree.SetScrollOffset(element_id, scroll_offset); } void TestHostClient::RegisterElementId(ElementId element_id, @@ -417,11 +413,9 @@ host_impl_(nullptr), timeline_id_(AnimationIdProvider::NextTimelineId()), animation_id_(AnimationIdProvider::NextAnimationId()), - next_test_layer_id_(0) { + element_id_(1) { host_ = client_.host(); host_impl_ = client_impl_.host(); - - element_id_ = ElementId(NextTestLayerId()); } AnimationTimelinesTest::~AnimationTimelinesTest() = default; @@ -469,7 +463,7 @@ } void AnimationTimelinesTest::CreateImplTimelineAndAnimation() { - host_->PushPropertiesTo(host_impl_); + host_->PushPropertiesTo(host_impl_, client_.GetPropertyTrees()); GetImplTimelineAndAnimationByID(); } @@ -525,11 +519,6 @@ : nullptr; } -int AnimationTimelinesTest::NextTestLayerId() { - next_test_layer_id_++; - return next_test_layer_id_; -} - bool AnimationTimelinesTest::CheckKeyframeEffectTimelineNeedsPushProperties( bool needs_push_properties) const { DCHECK(animation_); @@ -553,7 +542,7 @@ } void AnimationTimelinesTest::PushProperties() { - host_->PushPropertiesTo(host_impl_); + host_->PushPropertiesTo(host_impl_, client_.GetPropertyTrees()); } } // namespace cc
diff --git a/cc/test/animation_timelines_test_common.h b/cc/test/animation_timelines_test_common.h index cd29937..801ff36d 100644 --- a/cc/test/animation_timelines_test_common.h +++ b/cc/test/animation_timelines_test_common.h
@@ -14,6 +14,7 @@ #include "cc/animation/keyframe_model.h" #include "cc/paint/filter_operations.h" #include "cc/trees/mutator_host_client.h" +#include "cc/trees/property_tree.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/gfx/animation/keyframe/target_property.h" #include "ui/gfx/geometry/point_f.h" @@ -150,8 +151,9 @@ void ScrollOffsetAnimationFinished() override {} - void SetScrollOffsetForAnimation(const gfx::PointF& scroll_offset); - gfx::PointF GetScrollOffsetForAnimation(ElementId element_id) const override; + void SetScrollOffsetForAnimation(const gfx::PointF& scroll_offset, + ElementId element_id); + const PropertyTrees& GetPropertyTrees() const { return property_trees_; } void NotifyAnimationWorkletStateChange(AnimationWorkletMutationState state, ElementListType tree_type) override {} @@ -226,8 +228,8 @@ ElementIdToTestLayer layers_in_active_tree_; ElementIdToTestLayer layers_in_pending_tree_; - gfx::PointF scroll_offset_; bool mutators_need_commit_; + PropertyTrees property_trees_; }; class TestAnimationDelegate : public AnimationDelegate { @@ -297,8 +299,6 @@ KeyframeEffect* GetKeyframeEffectForElementId(ElementId element_id); KeyframeEffect* GetImplKeyframeEffectForLayerId(ElementId element_id); - int NextTestLayerId(); - bool CheckKeyframeEffectTimelineNeedsPushProperties( bool needs_push_properties) const; @@ -314,8 +314,6 @@ const int animation_id_; ElementId element_id_; - int next_test_layer_id_; - scoped_refptr<AnimationTimeline> timeline_; scoped_refptr<Animation> animation_; scoped_refptr<ElementAnimations> element_animations_;
diff --git a/cc/test/fake_layer_tree_host.cc b/cc/test/fake_layer_tree_host.cc index 855d5b00..a77fd17 100644 --- a/cc/test/fake_layer_tree_host.cc +++ b/cc/test/fake_layer_tree_host.cc
@@ -98,7 +98,8 @@ active_tree()->SetPropertyTrees(*property_trees()); TreeSynchronizer::PushLayerProperties( *pending_commit_state(), thread_unsafe_commit_state(), active_tree()); - mutator_host()->PushPropertiesTo(host_impl_->mutator_host()); + mutator_host()->PushPropertiesTo(host_impl_->mutator_host(), + *property_trees()); active_tree()->property_trees()->scroll_tree.PushScrollUpdatesFromMainThread( property_trees(), active_tree(), @@ -116,7 +117,8 @@ pending_tree()->SetPropertyTrees(*property_trees()); TreeSynchronizer::PushLayerProperties( *pending_commit_state(), thread_unsafe_commit_state(), pending_tree()); - mutator_host()->PushPropertiesTo(host_impl_->mutator_host()); + mutator_host()->PushPropertiesTo(host_impl_->mutator_host(), + *property_trees()); pending_tree()->property_trees()->scroll_tree.PushScrollUpdatesFromMainThread( property_trees(), pending_tree(),
diff --git a/cc/test/layer_tree_impl_test_base.cc b/cc/test/layer_tree_impl_test_base.cc index 9c33938..cf68d64b 100644 --- a/cc/test/layer_tree_impl_test_base.cc +++ b/cc/test/layer_tree_impl_test_base.cc
@@ -58,7 +58,8 @@ timeline_ = AnimationTimeline::Create(timeline_id); animation_host_->AddAnimationTimeline(timeline_); // Create impl-side instance. - animation_host_->PushPropertiesTo(host_impl()->animation_host()); + animation_host_->PushPropertiesTo(host_impl()->animation_host(), + *host_->property_trees()); timeline_impl_ = host_impl()->animation_host()->GetTimelineById(timeline_id); }
diff --git a/cc/test/mock_mutator_host.h b/cc/test/mock_mutator_host.h index 63bfc13a..bbf1c165 100644 --- a/cc/test/mock_mutator_host.h +++ b/cc/test/mock_mutator_host.h
@@ -27,7 +27,9 @@ MOCK_METHOD1(SetMutatorHostClient, void(MutatorHostClient* client)); MOCK_METHOD1(SetLayerTreeMutator, void(std::unique_ptr<LayerTreeMutator> mutator)); - MOCK_METHOD1(PushPropertiesTo, void(MutatorHost* host_impl)); + MOCK_METHOD2(PushPropertiesTo, + void(MutatorHost* host_impl, + const PropertyTrees& property_trees)); MOCK_METHOD1(SetScrollAnimationDurationForTesting, void(base::TimeDelta duration)); MOCK_CONST_METHOD0(NeedsTickAnimations, bool());
diff --git a/cc/trees/layer_tree_host.cc b/cc/trees/layer_tree_host.cc index cb2ac7e..0d37c85 100644 --- a/cc/trees/layer_tree_host.cc +++ b/cc/trees/layer_tree_host.cc
@@ -1696,11 +1696,6 @@ property_trees()->MaximumAnimationScaleChanged(element_id, maximum_scale); } -gfx::PointF LayerTreeHost::GetScrollOffsetForAnimation( - ElementId element_id) const { - return property_trees()->scroll_tree.current_scroll_offset(element_id); -} - void LayerTreeHost::QueueImageDecode(const PaintImage& image, base::OnceCallback<void(bool)> callback) { TRACE_EVENT0("cc", "LayerTreeHost::QueueImageDecode");
diff --git a/cc/trees/layer_tree_host.h b/cc/trees/layer_tree_host.h index 5f59935..65b4a5c 100644 --- a/cc/trees/layer_tree_host.h +++ b/cc/trees/layer_tree_host.h
@@ -762,7 +762,6 @@ PaintWorkletInput::PropertyValue property_value) override {} void ScrollOffsetAnimationFinished() override {} - gfx::PointF GetScrollOffsetForAnimation(ElementId element_id) const override; void NotifyAnimationWorkletStateChange(AnimationWorkletMutationState state, ElementListType tree_type) override {}
diff --git a/cc/trees/layer_tree_host_impl.cc b/cc/trees/layer_tree_host_impl.cc index dcc2d99..8f20031e 100644 --- a/cc/trees/layer_tree_host_impl.cc +++ b/cc/trees/layer_tree_host_impl.cc
@@ -471,7 +471,7 @@ if (is_ui) { dropped_frame_counter_.EnableReporForUI(); compositor_frame_reporting_controller_->SetThreadAffectsSmoothness( - FrameSequenceMetrics::ThreadType::kMain, true); + FrameInfo::SmoothEffectDrivingThread::kMain, true); } #endif // BUILDFLAG(IS_CHROMEOS_ASH) @@ -5025,16 +5025,6 @@ } } -gfx::PointF LayerTreeHostImpl::GetScrollOffsetForAnimation( - ElementId element_id) const { - if (active_tree()) { - return active_tree()->property_trees()->scroll_tree.current_scroll_offset( - element_id); - } - - return gfx::PointF(); -} - bool LayerTreeHostImpl::CommitToActiveTree() const { return settings_.commit_to_active_tree; }
diff --git a/cc/trees/layer_tree_host_impl.h b/cc/trees/layer_tree_host_impl.h index 5e53e84..0a76f24 100644 --- a/cc/trees/layer_tree_host_impl.h +++ b/cc/trees/layer_tree_host_impl.h
@@ -470,7 +470,6 @@ PaintWorkletInput::PropertyValue property_value) override; void ScrollOffsetAnimationFinished() override; - gfx::PointF GetScrollOffsetForAnimation(ElementId element_id) const override; void NotifyAnimationWorkletStateChange(AnimationWorkletMutationState state, ElementListType tree_type) override;
diff --git a/cc/trees/layer_tree_impl.cc b/cc/trees/layer_tree_impl.cc index af8ed31..71a4179 100644 --- a/cc/trees/layer_tree_impl.cc +++ b/cc/trees/layer_tree_impl.cc
@@ -614,7 +614,8 @@ TRACE_EVENT0("cc", "LayerTreeHost::AnimationHost::PushProperties"); DCHECK(mutator_host()); - unsafe_state.mutator_host->PushPropertiesTo(mutator_host()); + unsafe_state.mutator_host->PushPropertiesTo(mutator_host(), + unsafe_state.property_trees); if (IsActiveTree() && property_trees()->changed) { if (unsafe_state.root_layer) {
diff --git a/cc/trees/mutator_host.h b/cc/trees/mutator_host.h index 90d8cd8..86c536bf 100644 --- a/cc/trees/mutator_host.h +++ b/cc/trees/mutator_host.h
@@ -21,6 +21,7 @@ class MutatorEvents; class MutatorHostClient; class LayerTreeMutator; +class PropertyTrees; class ScrollTree; // Used as the return value of GetAnimationScales() to indicate that there is @@ -55,7 +56,8 @@ virtual void SetLayerTreeMutator( std::unique_ptr<LayerTreeMutator> mutator) = 0; - virtual void PushPropertiesTo(MutatorHost* host_impl) = 0; + virtual void PushPropertiesTo(MutatorHost* host_impl, + const PropertyTrees& property_trees) = 0; virtual void SetScrollAnimationDurationForTesting( base::TimeDelta duration) = 0;
diff --git a/cc/trees/mutator_host_client.h b/cc/trees/mutator_host_client.h index 560f8cf..a9fa96a 100644 --- a/cc/trees/mutator_host_client.h +++ b/cc/trees/mutator_host_client.h
@@ -66,8 +66,6 @@ float maximum_scale) = 0; virtual void ScrollOffsetAnimationFinished() = 0; - virtual gfx::PointF GetScrollOffsetForAnimation( - ElementId element_id) const = 0; virtual void NotifyAnimationWorkletStateChange( AnimationWorkletMutationState state,
diff --git a/cc/trees/ukm_manager.cc b/cc/trees/ukm_manager.cc index 7eecacb..eb814d7 100644 --- a/cc/trees/ukm_manager.cc +++ b/cc/trees/ukm_manager.cc
@@ -98,11 +98,11 @@ void UkmManager::RecordThroughputUKM( FrameSequenceTrackerType tracker_type, - FrameSequenceMetrics::ThreadType thread_type, + FrameInfo::SmoothEffectDrivingThread thread_type, int64_t throughput) const { ukm::builders::Graphics_Smoothness_PercentDroppedFrames builder(source_id_); switch (thread_type) { - case FrameSequenceMetrics::ThreadType::kMain: { + case FrameInfo::SmoothEffectDrivingThread::kMain: { switch (tracker_type) { #define CASE_FOR_MAIN_THREAD_TRACKER(name) \ case FrameSequenceTrackerType::k##name: \ @@ -127,7 +127,7 @@ break; } - case FrameSequenceMetrics::ThreadType::kCompositor: { + case FrameInfo::SmoothEffectDrivingThread::kCompositor: { switch (tracker_type) { #define CASE_FOR_COMPOSITOR_THREAD_TRACKER(name) \ case FrameSequenceTrackerType::k##name: \ @@ -149,7 +149,7 @@ break; } - case FrameSequenceMetrics::ThreadType::kUnknown: + case FrameInfo::SmoothEffectDrivingThread::kUnknown: NOTREACHED(); break; }
diff --git a/cc/trees/ukm_manager.h b/cc/trees/ukm_manager.h index b4fdf3f..1345e248 100644 --- a/cc/trees/ukm_manager.h +++ b/cc/trees/ukm_manager.h
@@ -48,7 +48,7 @@ void AddCheckerboardedImages(int num_of_checkerboarded_images); void RecordThroughputUKM(FrameSequenceTrackerType tracker_type, - FrameSequenceMetrics::ThreadType thread_type, + FrameInfo::SmoothEffectDrivingThread thread_type, int64_t throughput) const; void RecordAggregateThroughput(AggregationType aggregation_type, int64_t throughput_percent) const;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/infobar/AutofillSaveCardInfoBar.java b/chrome/android/java/src/org/chromium/chrome/browser/infobar/AutofillSaveCardInfoBar.java index 5b457c01..9da3949 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/infobar/AutofillSaveCardInfoBar.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/infobar/AutofillSaveCardInfoBar.java
@@ -21,7 +21,6 @@ import org.chromium.base.annotations.NativeMethods; import org.chromium.chrome.R; import org.chromium.chrome.browser.autofill.LegalMessageLine; -import org.chromium.chrome.browser.flags.ChromeFeatureList; import org.chromium.components.browser_ui.widget.RoundedCornerImageView; import org.chromium.components.infobars.ConfirmInfoBar; import org.chromium.components.infobars.InfoBarControlLayout; @@ -188,9 +187,7 @@ control.addDescription(text); } - if (ChromeFeatureList.isEnabled( - ChromeFeatureList.AUTOFILL_ENABLE_SAVE_CARD_INFO_BAR_ACCOUNT_INDICATION_FOOTER) - && mAccountFooterEmail != null && mAccountFooterAvatar != null) { + if (mAccountFooterEmail != null && mAccountFooterAvatar != null) { Resources res = layout.getResources(); int smallIconSize = res.getDimensionPixelSize(R.dimen.infobar_small_icon_size); int padding = res.getDimensionPixelOffset(R.dimen.infobar_padding);
diff --git a/chrome/app/DEPS b/chrome/app/DEPS index 5ea568c926..4e68c46 100644 --- a/chrome/app/DEPS +++ b/chrome/app/DEPS
@@ -38,6 +38,7 @@ "+content/public/browser/browser_main_runner.h", "+content/public/common", "+extensions/common/constants.h", + "+headless/app/headless_shell_switches.h", "+headless/public", "+media/base/media_switches.h", "+native_client/src/trusted/service_runtime/osx",
diff --git a/chrome/app/chrome_main.cc b/chrome/app/chrome_main.cc index c4f0d0ca..cf8f5825 100644 --- a/chrome/app/chrome_main.cc +++ b/chrome/app/chrome_main.cc
@@ -17,6 +17,7 @@ #include "chrome/common/profiler/main_thread_stack_sampling_profiler.h" #include "content/public/app/content_main.h" #include "content/public/common/content_switches.h" +#include "headless/app/headless_shell_switches.h" #include "headless/public/headless_shell.h" #include "ui/gfx/switches.h" @@ -120,7 +121,7 @@ base::CommandLine::Init(params.argc, params.argv); #endif // defined(OS_WIN) base::CommandLine::Init(0, nullptr); - const base::CommandLine* command_line(base::CommandLine::ForCurrentProcess()); + base::CommandLine* command_line(base::CommandLine::ForCurrentProcess()); ALLOW_UNUSED_LOCAL(command_line); #if defined(OS_WIN) @@ -147,8 +148,12 @@ } else { #if defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_MAC) || \ defined(OS_WIN) - if (command_line->HasSwitch(switches::kHeadless)) + if (command_line->HasSwitch(switches::kHeadless)) { +#if BUILDFLAG(GOOGLE_CHROME_BRANDING) + command_line->AppendSwitch(::headless::switches::kEnableCrashReporter); +#endif return headless::HeadlessShellMain(std::move(params)); + } #endif // defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_MAC) || // defined(OS_WIN) }
diff --git a/chrome/app/chromeos_strings.grdp b/chrome/app/chromeos_strings.grdp index 94f591a..69fe8410 100644 --- a/chrome/app/chromeos_strings.grdp +++ b/chrome/app/chromeos_strings.grdp
@@ -819,10 +819,10 @@ Available devices </message> <message name="IDS_BLUETOOTH_PAIRING_PAIRING_NO_AVAILABLE_DEVICES" desc="Bluetooth pairing dialog: Title for the list of Bluetooth devices when no devices are available for pairing."> - No devices found + No devices found nearby </message> <message name="IDS_BLUETOOTH_PAIRING_LEARN_MORE" desc="Bluetooth pairing dialog: Message informing the user on what actions to take in order to see a device in the list of available devices."> - Make sure your Bluetooth device is in pairing mode and nearby. <ph name="BEGIN_LINK_LEARN_MORE"><a target="_blank" href="$1"></ph>Learn more<ph name="END_LINK_LEARN_MORE"></a></ph> + Make sure your Bluetooth device is in pairing mode and nearby. Only pair with devices you trust. <ph name="BEGIN_LINK_LEARN_MORE"><a target="_blank" href="$1"></ph>Learn more<ph name="END_LINK_LEARN_MORE"></a></ph> </message> <message name="IDS_BLUETOOTH_PAIRING_ENTER_PIN" desc="Bluetooth pairing dialog: Message displayed informing the user to enter a PIN in other to complete device pairing."> Enter PIN to pair with <ph name="DEVICE_NAME">$1<ex>Nexus S</ex></ph> @@ -3872,7 +3872,7 @@ 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" desc="Message in the consolidated consent screen to opt-in for metrics for a child 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. + 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" desc="Message in the consolidated consent screen to opt-in for metrics when ARC is disabled."> Help improve Chrome and ChromeOS features and performance by automatically sending crash reports as well as diagnostic and usage data to Google.
diff --git a/chrome/app/chromeos_strings_grdp/IDS_BLUETOOTH_PAIRING_LEARN_MORE.png.sha1 b/chrome/app/chromeos_strings_grdp/IDS_BLUETOOTH_PAIRING_LEARN_MORE.png.sha1 index 26ef596..2647f964 100644 --- a/chrome/app/chromeos_strings_grdp/IDS_BLUETOOTH_PAIRING_LEARN_MORE.png.sha1 +++ b/chrome/app/chromeos_strings_grdp/IDS_BLUETOOTH_PAIRING_LEARN_MORE.png.sha1
@@ -1 +1 @@ -8d1f9d06d780e3c976582188c01d19bd7f9fb4f9 \ No newline at end of file +8f5f4fc0ca39f4c016c6dec3aa059da424b3613a \ No newline at end of file
diff --git a/chrome/app/chromeos_strings_grdp/IDS_BLUETOOTH_PAIRING_PAIRING_NO_AVAILABLE_DEVICES.png.sha1 b/chrome/app/chromeos_strings_grdp/IDS_BLUETOOTH_PAIRING_PAIRING_NO_AVAILABLE_DEVICES.png.sha1 index ee7d053..5d36c6ab 100644 --- a/chrome/app/chromeos_strings_grdp/IDS_BLUETOOTH_PAIRING_PAIRING_NO_AVAILABLE_DEVICES.png.sha1 +++ b/chrome/app/chromeos_strings_grdp/IDS_BLUETOOTH_PAIRING_PAIRING_NO_AVAILABLE_DEVICES.png.sha1
@@ -1 +1 @@ -f823e10167a89137bb01243eb7592b97e6f1b34f \ No newline at end of file +4f18bd8e11c9319cc110ffb64aa397543b1d4aa3 \ No newline at end of file
diff --git a/chrome/app/generated_resources.grd b/chrome/app/generated_resources.grd index e587ae34..dcac1852 100644 --- a/chrome/app/generated_resources.grd +++ b/chrome/app/generated_resources.grd
@@ -11452,6 +11452,9 @@ <message name="IDS_WEBAUTHN_CABLEV2_2ND_FACTOR_DESCRIPTION" desc="The contents of a dialog shown when the user tries to sign-in using a phone as a security key, or tries to register their phone as a security key for a future sign-in. A security key is traditionally a small USB device that is touched to confirm a sign-in (e.g. a gNubby) and, in this context, the phone is replacing the need for a separate device. The placeholder for the notification title will be replaced with the string that will appear in the notification on the phone. These messages are 4300134428943426639 and 581442427601260656."> <ph name="WEBSITE"><ex>accounts.google.com</ex>$1</ph> sent a notification to your phone. To confirm it's you, tap the “<ph name="NOTIFICATIONTITLE"><ex>Verify with this phone</ex>$2</ph>” notification and follow the steps. </message> + <message name="IDS_WEBAUTHN_CABLEV2_ADD_PHONE" desc="The label on a button-like element in a list of options. Clicking this causes Chrome to show a QR code that the user can scan with their phone to use that phone for signing into a website. Here 'phone' is used as a short hand for smartphone."> + Add a new phone + </message> <message name="IDS_WEBAUTHN_CABLE_ACTIVATE_DESCRIPTION_SHORT" desc="Second line of text in an item letting the user know that they can use their phone as a security key. The user needs to check their phone and respond to a notification that will ask them to press a button on the phone's screen to confirm that they're logging in."> Unlock your phone and confirm it's you
diff --git a/chrome/app/generated_resources_grd/IDS_WEBAUTHN_CABLEV2_ADD_PHONE.png.sha1 b/chrome/app/generated_resources_grd/IDS_WEBAUTHN_CABLEV2_ADD_PHONE.png.sha1 new file mode 100644 index 0000000..59eca98 --- /dev/null +++ b/chrome/app/generated_resources_grd/IDS_WEBAUTHN_CABLEV2_ADD_PHONE.png.sha1
@@ -0,0 +1 @@ +3f19b4f5479ff3238a0307cbaf61b1d8ed868e89 \ No newline at end of file
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index 6cf2117..ce0b1ab8 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -101,7 +101,7 @@ #include "components/flags_ui/flags_ui_metrics.h" #include "components/flags_ui/flags_ui_switches.h" #include "components/heavy_ad_intervention/heavy_ad_features.h" -#include "components/history_clusters/core/memories_features.h" +#include "components/history_clusters/core/features.h" #include "components/invalidation/impl/invalidation_switches.h" #include "components/language/core/common/language_experiments.h" #include "components/lens/lens_features.h"
diff --git a/chrome/browser/android/autofill_assistant/client_android.cc b/chrome/browser/android/autofill_assistant/client_android.cc index 63a9784..5819ff6 100644 --- a/chrome/browser/android/autofill_assistant/client_android.cc +++ b/chrome/browser/android/autofill_assistant/client_android.cc
@@ -100,7 +100,7 @@ ClientAndroid::ClientAndroid( content::WebContents* web_contents, const base::android::JavaRef<jobject>& jdependencies) - : web_contents_(web_contents), + : content::WebContentsUserData<ClientAndroid>(*web_contents), jdependencies_(jdependencies), java_object_(Java_AutofillAssistantClient_Constructor( AttachCurrentThread(), @@ -205,7 +205,7 @@ auto* other_web_contents = content::WebContents::FromJavaWebContents(jother_web_contents); - DCHECK_NE(other_web_contents, web_contents_); + DCHECK_NE(other_web_contents, GetWebContents()); ClientAndroid* other_client = ClientAndroid::FromWebContents(other_web_contents); @@ -248,7 +248,7 @@ base::android::ScopedJavaGlobalRef<jobject> scoped_jcallback(env, jcallback); controller_->Track( ui_controller_android_utils::CreateTriggerContext( - env, web_contents_, jexperiment_ids, jparameter_names, + env, GetWebContents(), jexperiment_ids, jparameter_names, jparameter_values, /* jdevice_only_parameter_names= */ base::android::JavaParamRef<jobjectArray>(nullptr), /* jdevice_only_parameter_values= */ @@ -357,7 +357,7 @@ base::android::ConvertJavaStringToUTF8(env, jaction_name); auto trigger_context = ui_controller_android_utils::CreateTriggerContext( - env, web_contents_, jexperiment_ids, jparameter_names, + env, GetWebContents(), jexperiment_ids, jparameter_names, jparameter_values, /* jdevice_only_parameter_names= */ base::android::JavaParamRef<jobjectArray>(nullptr), /* jdevice_only_parameter_values= */ @@ -434,7 +434,7 @@ const base::android::JavaRef<jobject>& joverlay_coordinator) { if (!ui_controller_android_) { ui_controller_android_ = UiControllerAndroid::CreateFromWebContents( - web_contents_, jdependencies_, joverlay_coordinator); + GetWebContents(), jdependencies_, joverlay_coordinator); if (!ui_controller_android_) { // The activity is not or not yet in a mode where attaching the UI is // possible. @@ -448,7 +448,7 @@ !ui_controller_android_->IsAttachedTo(controller_.get()))) { if (!controller_) CreateController(nullptr, absl::nullopt); - ui_controller_android_->Attach(web_contents_, this, controller_.get()); + ui_controller_android_->Attach(GetWebContents(), this, controller_.get()); } } @@ -470,7 +470,7 @@ std::string ClientAndroid::GetChromeSignedInEmailAddress() const { CoreAccountInfo account_info = IdentityManagerFactory::GetForProfile( - Profile::FromBrowserContext(web_contents_->GetBrowserContext())) + Profile::FromBrowserContext(GetWebContents()->GetBrowserContext())) ->GetPrimaryAccountInfo(signin::ConsentLevel::kSync); return account_info.email; } @@ -523,8 +523,8 @@ WebsiteLoginManager* ClientAndroid::GetWebsiteLoginManager() const { if (!website_login_manager_) { website_login_manager_ = std::make_unique<WebsiteLoginManagerImpl>( - ChromePasswordManagerClient::FromWebContents(web_contents_), - web_contents_); + ChromePasswordManagerClient::FromWebContents(GetWebContents()), + GetWebContents()); } return website_login_manager_.get(); } @@ -569,7 +569,11 @@ } content::WebContents* ClientAndroid::GetWebContents() const { - return web_contents_; + // While a const_cast is not ideal. The Autofill API uses const in various + // spots and the content public API doesn't have const accessors. So the const + // cast is the lesser of two evils. + return const_cast<content::WebContents*>( + &content::WebContentsUserData<ClientAndroid>::GetWebContents()); } void ClientAndroid::RecordDropOut(Metrics::DropOutReason reason) { @@ -653,11 +657,12 @@ content::TtsController::GetInstance()); } controller_ = std::make_unique<Controller>( - web_contents_, /* client= */ this, base::DefaultTickClock::GetInstance(), - RuntimeManagerImpl::GetForWebContents(web_contents_)->GetWeakPtr(), + GetWebContents(), /* client= */ this, + base::DefaultTickClock::GetInstance(), + RuntimeManagerImpl::GetForWebContents(GetWebContents())->GetWeakPtr(), std::move(service), std::move(tts_controller), ukm::UkmRecorder::Get(), AnnotateDomModelServiceFactory::GetInstance()->GetForBrowserContext( - web_contents_->GetBrowserContext())); + GetWebContents()->GetBrowserContext())); controller_->SetStatusMessage(status_message); if (progress_bar_config) { controller_->SetStepProgressBarConfiguration(*progress_bar_config);
diff --git a/chrome/browser/android/autofill_assistant/client_android.h b/chrome/browser/android/autofill_assistant/client_android.h index cba6d86..6232dca4 100644 --- a/chrome/browser/android/autofill_assistant/client_android.h +++ b/chrome/browser/android/autofill_assistant/client_android.h
@@ -172,7 +172,6 @@ WEB_CONTENTS_USER_DATA_KEY_DECL(); - raw_ptr<content::WebContents> web_contents_; const base::android::ScopedJavaGlobalRef<jobject> jdependencies_; base::android::ScopedJavaGlobalRef<jobject> java_object_;
diff --git a/chrome/browser/android/autofill_assistant/starter_android.cc b/chrome/browser/android/autofill_assistant/starter_android.cc index ec47601..70c9e75 100644 --- a/chrome/browser/android/autofill_assistant/starter_android.cc +++ b/chrome/browser/android/autofill_assistant/starter_android.cc
@@ -38,7 +38,7 @@ } StarterAndroid::StarterAndroid(content::WebContents* web_contents) - : web_contents_(web_contents), + : content::WebContentsUserData<StarterAndroid>(*web_contents), website_login_manager_(std::make_unique<WebsiteLoginManagerImpl>( ChromePasswordManagerClient::FromWebContents(web_contents), web_contents)) {} @@ -50,8 +50,8 @@ java_object_ = base::android::ScopedJavaGlobalRef<jobject>(jcaller); starter_ = std::make_unique<Starter>( - web_contents_, this, ukm::UkmRecorder::Get(), - RuntimeManagerImpl::GetForWebContents(web_contents_)->GetWeakPtr(), + &GetWebContents(), this, ukm::UkmRecorder::Get(), + RuntimeManagerImpl::GetForWebContents(&GetWebContents())->GetWeakPtr(), base::DefaultTickClock::GetInstance()); } @@ -217,7 +217,8 @@ } bool StarterAndroid::GetIsCustomTab() const { - return ui_controller_android_utils::IsCustomTab(web_contents_); + return ui_controller_android_utils::IsCustomTab( + const_cast<content::WebContents*>(&GetWebContents())); } bool StarterAndroid::GetIsTabCreatedByGSA() const { @@ -259,8 +260,9 @@ const base::android::JavaRef<jstring>& jinitial_url) { DCHECK(starter_); auto trigger_context = ui_controller_android_utils::CreateTriggerContext( - env, web_contents_, jexperiment_ids, jparameter_names, jparameter_values, - jdevice_only_parameter_names, jdevice_only_parameter_values, + env, &GetWebContents(), jexperiment_ids, jparameter_names, + jparameter_values, jdevice_only_parameter_names, + jdevice_only_parameter_values, /* onboarding_shown = */ false, /* is_direct_action = */ false, jinitial_url); @@ -272,8 +274,8 @@ std::unique_ptr<TriggerContext> trigger_context, const absl::optional<TriggerScriptProto>& trigger_script) { CreateJavaDependenciesIfNecessary(); - ClientAndroid::CreateForWebContents(web_contents_, java_dependencies_); - auto* client_android = ClientAndroid::FromWebContents(web_contents_); + ClientAndroid::CreateForWebContents(&GetWebContents(), java_dependencies_); + auto* client_android = ClientAndroid::FromWebContents(&GetWebContents()); DCHECK(client_android); JNIEnv* env = base::android::AttachCurrentThread(); @@ -286,7 +288,8 @@ } bool StarterAndroid::IsRegularScriptRunning() const { - auto* client_android = ClientAndroid::FromWebContents(web_contents_); + const auto* client_android = + ClientAndroid::FromWebContents(&GetWebContents()); if (!client_android) { return false; } @@ -294,7 +297,8 @@ } bool StarterAndroid::IsRegularScriptVisible() const { - auto* client_android = ClientAndroid::FromWebContents(web_contents_); + const auto* client_android = + ClientAndroid::FromWebContents(&GetWebContents()); if (!client_android) { return false; }
diff --git a/chrome/browser/android/autofill_assistant/starter_android.h b/chrome/browser/android/autofill_assistant/starter_android.h index c6b7c1b..94501de3 100644 --- a/chrome/browser/android/autofill_assistant/starter_android.h +++ b/chrome/browser/android/autofill_assistant/starter_android.h
@@ -119,7 +119,6 @@ void CreateJavaDependenciesIfNecessary(); WEB_CONTENTS_USER_DATA_KEY_DECL(); - raw_ptr<content::WebContents> web_contents_; std::unique_ptr<Starter> starter_; base::android::ScopedJavaGlobalRef<jobject> java_object_; base::android::ScopedJavaGlobalRef<jobject> java_dependencies_;
diff --git a/chrome/browser/ash/file_manager/copy_or_move_io_task.cc b/chrome/browser/ash/file_manager/copy_or_move_io_task.cc index 02958a2..ebf186b 100644 --- a/chrome/browser/ash/file_manager/copy_or_move_io_task.cc +++ b/chrome/browser/ash/file_manager/copy_or_move_io_task.cc
@@ -320,8 +320,9 @@ // should do the same. storage::FileSystemOperation::CopyOrMoveOptionSet options = storage::FileSystemOperation::CopyOrMoveOptionSet( + storage::FileSystemOperation::CopyOrMoveOption::kPreserveLastModified, storage::FileSystemOperation::CopyOrMoveOption:: - kPreserveLastModified); + kRemovePartiallyCopiedFilesOnError); // To ensure progress updates, force cross-filesystem I/O operations when the // source and the destination are on different volumes, or between My files // and Downloads.
diff --git a/chrome/browser/ash/login/screens/app_downloading_screen.cc b/chrome/browser/ash/login/screens/app_downloading_screen.cc index da2d4e44..0ed5ad2 100644 --- a/chrome/browser/ash/login/screens/app_downloading_screen.cc +++ b/chrome/browser/ash/login/screens/app_downloading_screen.cc
@@ -32,6 +32,11 @@ view_->Bind(nullptr); } +void AppDownloadingScreen::OnViewDestroyed(AppDownloadingScreenView* view) { + if (view_ == view) + view_ = nullptr; +} + void AppDownloadingScreen::ShowImpl() { // Show the screen. view_->Show();
diff --git a/chrome/browser/ash/login/screens/app_downloading_screen.h b/chrome/browser/ash/login/screens/app_downloading_screen.h index 90e81111..ed4449dc 100644 --- a/chrome/browser/ash/login/screens/app_downloading_screen.h +++ b/chrome/browser/ash/login/screens/app_downloading_screen.h
@@ -32,6 +32,10 @@ exit_callback_ = exit_callback; } + // This method is called, when view is being destroyed. Note, if model + // is destroyed earlier then it has to call SetModel(NULL). + void OnViewDestroyed(AppDownloadingScreenView* view); + protected: // BaseScreen: void ShowImpl() override; @@ -39,7 +43,7 @@ void OnUserAction(const std::string& action_id) override; private: - AppDownloadingScreenView* const view_; + AppDownloadingScreenView* view_; base::RepeatingClosure exit_callback_; };
diff --git a/chrome/browser/ash/net/network_diagnostics/captive_portal_routine_unittest.cc b/chrome/browser/ash/net/network_diagnostics/captive_portal_routine_unittest.cc index 66120b79..6d306b20 100644 --- a/chrome/browser/ash/net/network_diagnostics/captive_portal_routine_unittest.cc +++ b/chrome/browser/ash/net/network_diagnostics/captive_portal_routine_unittest.cc
@@ -9,7 +9,6 @@ #include "chromeos/network/network_cert_loader.h" #include "chromeos/network/network_configuration_handler.h" #include "chromeos/network/network_handler.h" -#include "chromeos/network/network_metadata_store.h" #include "chromeos/network/network_profile_handler.h" #include "chromeos/network/onc/network_onc_utils.h" #include "chromeos/network/proxy/ui_proxy_config_service.h"
diff --git a/chrome/browser/ash/net/network_diagnostics/dns_resolver_present_routine_unittest.cc b/chrome/browser/ash/net/network_diagnostics/dns_resolver_present_routine_unittest.cc index ad22af7..604b23b 100644 --- a/chrome/browser/ash/net/network_diagnostics/dns_resolver_present_routine_unittest.cc +++ b/chrome/browser/ash/net/network_diagnostics/dns_resolver_present_routine_unittest.cc
@@ -13,7 +13,6 @@ #include "chromeos/network/network_cert_loader.h" #include "chromeos/network/network_configuration_handler.h" #include "chromeos/network/network_handler.h" -#include "chromeos/network/network_metadata_store.h" #include "chromeos/network/network_profile_handler.h" #include "chromeos/network/onc/network_onc_utils.h" #include "chromeos/network/proxy/ui_proxy_config_service.h"
diff --git a/chrome/browser/ash/net/network_diagnostics/gateway_can_be_pinged_routine_unittest.cc b/chrome/browser/ash/net/network_diagnostics/gateway_can_be_pinged_routine_unittest.cc index e8e312a..36d80fd 100644 --- a/chrome/browser/ash/net/network_diagnostics/gateway_can_be_pinged_routine_unittest.cc +++ b/chrome/browser/ash/net/network_diagnostics/gateway_can_be_pinged_routine_unittest.cc
@@ -12,7 +12,6 @@ #include "chromeos/network/network_cert_loader.h" #include "chromeos/network/network_configuration_handler.h" #include "chromeos/network/network_handler.h" -#include "chromeos/network/network_metadata_store.h" #include "chromeos/network/network_profile_handler.h" #include "chromeos/network/onc/network_onc_utils.h" #include "chromeos/network/proxy/ui_proxy_config_service.h"
diff --git a/chrome/browser/ash/net/network_diagnostics/network_diagnostics_unittest.cc b/chrome/browser/ash/net/network_diagnostics/network_diagnostics_unittest.cc index 01fdeb9..5917bb4 100644 --- a/chrome/browser/ash/net/network_diagnostics/network_diagnostics_unittest.cc +++ b/chrome/browser/ash/net/network_diagnostics/network_diagnostics_unittest.cc
@@ -15,7 +15,6 @@ #include "chromeos/network/network_cert_loader.h" #include "chromeos/network/network_configuration_handler.h" #include "chromeos/network/network_handler.h" -#include "chromeos/network/network_metadata_store.h" #include "chromeos/network/network_profile_handler.h" #include "chromeos/network/onc/network_onc_utils.h" #include "chromeos/network/proxy/ui_proxy_config_service.h"
diff --git a/chrome/browser/ash/net/rollback_network_config/rollback_network_config_unittest.cc b/chrome/browser/ash/net/rollback_network_config/rollback_network_config_unittest.cc index ac651e1..1084e44 100644 --- a/chrome/browser/ash/net/rollback_network_config/rollback_network_config_unittest.cc +++ b/chrome/browser/ash/net/rollback_network_config/rollback_network_config_unittest.cc
@@ -21,10 +21,8 @@ #include "chrome/test/base/testing_profile_manager.h" #include "chromeos/dbus/session_manager/fake_session_manager_client.h" #include "chromeos/login/login_state/login_state.h" -#include "chromeos/network/cellular_esim_profile_handler_impl.h" #include "chromeos/network/managed_network_configuration_handler.h" #include "chromeos/network/network_handler_test_helper.h" -#include "chromeos/network/network_metadata_store.h" #include "chromeos/network/network_state.h" #include "chromeos/network/network_state_handler.h" #include "chromeos/tpm/stub_install_attributes.h" @@ -309,13 +307,10 @@ void RegisterAndSetUpPrefs() { PrefProxyConfigTrackerImpl::RegisterProfilePrefs(user_prefs_.registry()); PrefProxyConfigTrackerImpl::RegisterPrefs(local_state_.registry()); - ::onc::RegisterProfilePrefs(user_prefs_.registry()); - ::onc::RegisterPrefs(local_state_.registry()); - chromeos::NetworkMetadataStore::RegisterPrefs(user_prefs_.registry()); - chromeos::NetworkMetadataStore::RegisterPrefs(local_state_.registry()); - chromeos::CellularESimProfileHandlerImpl::RegisterLocalStatePrefs( - local_state_.registry()); - NetworkHandler::Get()->InitializePrefServices(&user_prefs_, &local_state_); + network_handler_test_helper_.RegisterPrefs(user_prefs_.registry(), + local_state_.registry()); + + network_handler_test_helper_.InitializePrefs(&user_prefs_, &local_state_); } void SetUp() override { SetEmptyDevicePolicy(); }
diff --git a/chrome/browser/ash/policy/networking/euicc_status_uploader_unittest.cc b/chrome/browser/ash/policy/networking/euicc_status_uploader_unittest.cc index 00d34fd..4d346d3 100644 --- a/chrome/browser/ash/policy/networking/euicc_status_uploader_unittest.cc +++ b/chrome/browser/ash/policy/networking/euicc_status_uploader_unittest.cc
@@ -10,7 +10,6 @@ #include "base/test/values_test_util.h" #include "chrome/test/base/testing_browser_process.h" #include "chromeos/dbus/shill/shill_manager_client.h" -#include "chromeos/network/cellular_esim_profile_handler_impl.h" #include "chromeos/network/managed_network_configuration_handler.h" #include "chromeos/network/network_handler_test_helper.h" #include "chromeos/network/network_ui_data.h" @@ -137,10 +136,8 @@ helper_ = std::make_unique<ash::NetworkHandlerTestHelper>(); EuiccStatusUploader::RegisterLocalStatePrefs(local_state_.registry()); - chromeos::CellularESimProfileHandlerImpl::RegisterLocalStatePrefs( - local_state_.registry()); - chromeos::NetworkHandler::Get()->InitializePrefServices(nullptr, - &local_state_); + helper_->RegisterPrefs(nullptr, local_state_.registry()); + helper_->InitializePrefs(nullptr, &local_state_); } std::unique_ptr<EuiccStatusUploader> CreateStatusUploader() {
diff --git a/chrome/browser/ash/remote_apps/remote_apps_manager_browsertest.cc b/chrome/browser/ash/remote_apps/remote_apps_manager_browsertest.cc index 2ef50bdd..6b60992a 100644 --- a/chrome/browser/ash/remote_apps/remote_apps_manager_browsertest.cc +++ b/chrome/browser/ash/remote_apps/remote_apps_manager_browsertest.cc
@@ -459,6 +459,39 @@ EXPECT_EQ(std::string(), item2->folder_id()); } +// Verifies that folders are not removed after user moves all but single item +// from them. +IN_PROC_BROWSER_TEST_F(RemoteAppsManagerBrowsertest, + DontRemoveSingleItemFolders) { + // Folder has id kId1. + manager_->AddFolder("folder_name", /*add_to_front=*/false); + + // App has id kId2. + AddAppAndWaitForIconChange(kId2, "name", kId1, GURL("icon_url"), + CreateTestIcon(32, SK_ColorRED), + /*add_to_front=*/false); + // App has id kId3. + AddAppAndWaitForIconChange(kId3, "name2", kId1, GURL("icon_url2"), + CreateTestIcon(32, SK_ColorBLUE), + /*add_to_front=*/false); + + ash::AppListItem* folder_item = GetAppListItem(kId1); + EXPECT_EQ(2u, folder_item->ChildItemCount()); + EXPECT_TRUE(folder_item->FindChildItem(kId2)); + EXPECT_TRUE(folder_item->FindChildItem(kId3)); + + // Move kId2 item to root app list. + ash::AppListItem* item1 = GetAppListItem(kId2); + ASSERT_TRUE(item1); + ash::AppListModelProvider::Get()->model()->MoveItemToRootAt( + item1, folder_item->position().CreateBefore()); + + ASSERT_EQ(folder_item, GetAppListItem(kId1)); + EXPECT_EQ(1u, folder_item->ChildItemCount()); + EXPECT_FALSE(folder_item->FindChildItem(kId2)); + EXPECT_TRUE(folder_item->FindChildItem(kId3)); +} + IN_PROC_BROWSER_TEST_F(RemoteAppsManagerBrowsertest, AddToFront) { // Folder has id kId1. manager_->AddFolder("folder_name", /*add_to_front=*/false);
diff --git a/chrome/browser/autofill/address_accessory_controller_impl.cc b/chrome/browser/autofill/address_accessory_controller_impl.cc index 5071f62e..c805e446 100644 --- a/chrome/browser/autofill/address_accessory_controller_impl.cc +++ b/chrome/browser/autofill/address_accessory_controller_impl.cc
@@ -129,7 +129,7 @@ const AccessorySheetField& selection) { // Since the data we fill is scoped to the profile and not to a frame, we can // fill the focused frame - we basically behave like a keyboard here. - content::RenderFrameHost* rfh = web_contents_->GetFocusedFrame(); + content::RenderFrameHost* rfh = GetWebContents().GetFocusedFrame(); if (!rfh) return; autofill::ContentAutofillDriver* driver = @@ -143,7 +143,7 @@ void AddressAccessoryControllerImpl::OnOptionSelected( AccessoryAction selected_action) { if (selected_action == AccessoryAction::MANAGE_ADDRESSES) { - autofill::ShowAutofillProfileSettings(web_contents_); + autofill::ShowAutofillProfileSettings(&GetWebContents()); return; } NOTREACHED() << "Unhandled selected action: " @@ -161,7 +161,7 @@ if (!personal_data_manager_) { personal_data_manager_ = autofill::PersonalDataManagerFactory::GetForProfile( - Profile::FromBrowserContext(web_contents_->GetBrowserContext())); + Profile::FromBrowserContext(GetWebContents().GetBrowserContext())); personal_data_manager_->AddObserver(this); } absl::optional<AccessorySheetData> data = GetSheetData(); @@ -200,14 +200,15 @@ AddressAccessoryControllerImpl::AddressAccessoryControllerImpl( content::WebContents* web_contents, base::WeakPtr<ManualFillingController> mf_controller) - : web_contents_(web_contents), + : content::WebContentsUserData<AddressAccessoryControllerImpl>( + *web_contents), mf_controller_(std::move(mf_controller)), personal_data_manager_(nullptr) {} base::WeakPtr<ManualFillingController> AddressAccessoryControllerImpl::GetManualFillingController() { if (!mf_controller_) - mf_controller_ = ManualFillingController::GetOrCreate(web_contents_); + mf_controller_ = ManualFillingController::GetOrCreate(&GetWebContents()); DCHECK(mf_controller_); return mf_controller_; }
diff --git a/chrome/browser/autofill/address_accessory_controller_impl.h b/chrome/browser/autofill/address_accessory_controller_impl.h index 8683f3c6..bd0dacf 100644 --- a/chrome/browser/autofill/address_accessory_controller_impl.h +++ b/chrome/browser/autofill/address_accessory_controller_impl.h
@@ -70,9 +70,6 @@ // |web_contents_|. The lazy initialization allows injecting mocks for tests. base::WeakPtr<ManualFillingController> GetManualFillingController(); - // The tab for which this class is scoped. - raw_ptr<content::WebContents> web_contents_; - // The observer to notify if available suggestions change. FillingSourceObserver source_observer_;
diff --git a/chrome/browser/autofill/credit_card_accessory_controller_impl.cc b/chrome/browser/autofill/credit_card_accessory_controller_impl.cc index e26271e..4c20762 100644 --- a/chrome/browser/autofill/credit_card_accessory_controller_impl.cc +++ b/chrome/browser/autofill/credit_card_accessory_controller_impl.cc
@@ -150,7 +150,7 @@ CreditCardAccessoryControllerImpl::GetSheetData() const { // Note that also GetManager() can return nullptr. autofill::BrowserAutofillManager* autofill_manager = - web_contents_->GetFocusedFrame() ? GetManager() : nullptr; + GetWebContents().GetFocusedFrame() ? GetManager() : nullptr; std::vector<UserInfo> info_to_add; bool allow_filling = autofill_manager && @@ -207,7 +207,7 @@ void CreditCardAccessoryControllerImpl::OnFillingTriggered( FieldGlobalId focused_field_id, const AccessorySheetField& selection) { - content::RenderFrameHost* rfh = web_contents_->GetFocusedFrame(); + content::RenderFrameHost* rfh = GetWebContents().GetFocusedFrame(); if (!rfh) return; // Without focused frame, driver and manager will be undefined. if (!GetDriver() || !GetManager()) { @@ -256,7 +256,7 @@ void CreditCardAccessoryControllerImpl::OnOptionSelected( AccessoryAction selected_action) { if (selected_action == AccessoryAction::MANAGE_CREDIT_CARDS) { - autofill::ShowAutofillCreditCardSettings(web_contents_); + autofill::ShowAutofillCreditCardSettings(&GetWebContents()); return; } NOTREACHED() << "Unhandled selected action: " @@ -317,7 +317,7 @@ const std::u16string& cvc) { if (result != CreditCardFetchResult::kSuccess) return; - content::RenderFrameHost* rfh = web_contents_->GetFocusedFrame(); + content::RenderFrameHost* rfh = GetWebContents().GetFocusedFrame(); if (!rfh || !last_focused_field_id_ || last_focused_field_id_.frame_token != autofill::LocalFrameToken(rfh->GetFrameToken().value())) { @@ -351,11 +351,11 @@ CreditCardAccessoryControllerImpl::CreditCardAccessoryControllerImpl( content::WebContents* web_contents) - : web_contents_(web_contents), + : content::WebContentsUserData<CreditCardAccessoryControllerImpl>( + *web_contents), personal_data_manager_( autofill::PersonalDataManagerFactory::GetForProfile( - Profile::FromBrowserContext( - web_contents_->GetBrowserContext()))) { + Profile::FromBrowserContext(web_contents->GetBrowserContext()))) { if (personal_data_manager_) personal_data_manager_->AddObserver(this); } @@ -366,7 +366,8 @@ PersonalDataManager* personal_data_manager, autofill::BrowserAutofillManager* af_manager, autofill::AutofillDriver* af_driver) - : web_contents_(web_contents), + : content::WebContentsUserData<CreditCardAccessoryControllerImpl>( + *web_contents), mf_controller_(mf_controller), personal_data_manager_(personal_data_manager), af_manager_for_testing_(af_manager), @@ -377,7 +378,7 @@ std::vector<CreditCardAccessoryControllerImpl::CardOrVirtualCard> CreditCardAccessoryControllerImpl::GetAllCreditCards() const { - if (!web_contents_->GetFocusedFrame() || !personal_data_manager_) + if (!GetWebContents().GetFocusedFrame() || !personal_data_manager_) return std::vector<CardOrVirtualCard>(); std::vector<CardOrVirtualCard> cards; @@ -395,7 +396,7 @@ std::vector<const CachedServerCardInfo*> CreditCardAccessoryControllerImpl::GetUnmaskedCreditCards() const { - if (!web_contents_->GetFocusedFrame()) + if (!GetWebContents().GetFocusedFrame()) return std::vector<const CachedServerCardInfo*>(); autofill::BrowserAutofillManager* autofill_manager = GetManager(); if (!autofill_manager || !autofill_manager->credit_card_access_manager()) @@ -421,7 +422,7 @@ std::vector<const AutofillOfferData*> CreditCardAccessoryControllerImpl::GetPromoCodeOffers() const { autofill::BrowserAutofillManager* autofill_manager = GetManager(); - if (!web_contents_->GetFocusedFrame() || !personal_data_manager_ || + if (!GetWebContents().GetFocusedFrame() || !personal_data_manager_ || !autofill_manager) return std::vector<const AutofillOfferData*>(); @@ -434,30 +435,40 @@ base::WeakPtr<ManualFillingController> CreditCardAccessoryControllerImpl::GetManualFillingController() { if (!mf_controller_) - mf_controller_ = ManualFillingController::GetOrCreate(web_contents_); + mf_controller_ = ManualFillingController::GetOrCreate(&GetWebContents()); DCHECK(mf_controller_); return mf_controller_; } autofill::AutofillDriver* CreditCardAccessoryControllerImpl::GetDriver() { - DCHECK(web_contents_->GetFocusedFrame()); + DCHECK(GetWebContents().GetFocusedFrame()); return af_driver_for_testing_ ? af_driver_for_testing_.get() : autofill::ContentAutofillDriver::GetForRenderFrameHost( - web_contents_->GetFocusedFrame()); + GetWebContents().GetFocusedFrame()); } autofill::BrowserAutofillManager* CreditCardAccessoryControllerImpl::GetManager() const { - DCHECK(web_contents_->GetFocusedFrame()); + DCHECK(GetWebContents().GetFocusedFrame()); if (af_manager_for_testing_) return af_manager_for_testing_; autofill::ContentAutofillDriver* driver = autofill::ContentAutofillDriver::GetForRenderFrameHost( - web_contents_->GetFocusedFrame()); + GetWebContents().GetFocusedFrame()); return driver ? driver->browser_autofill_manager() : nullptr; } +content::WebContents& CreditCardAccessoryControllerImpl::GetWebContents() + const { + // While a const_cast is not ideal. The Autofill API uses const in various + // spots and the content public API doesn't have const accessors. So the const + // cast is the lesser of two evils. + return const_cast<content::WebContents&>( + content::WebContentsUserData< + CreditCardAccessoryControllerImpl>::GetWebContents()); +} + WEB_CONTENTS_USER_DATA_KEY_IMPL(CreditCardAccessoryControllerImpl); } // namespace autofill
diff --git a/chrome/browser/autofill/credit_card_accessory_controller_impl.h b/chrome/browser/autofill/credit_card_accessory_controller_impl.h index cf1c64dd..3957347 100644 --- a/chrome/browser/autofill/credit_card_accessory_controller_impl.h +++ b/chrome/browser/autofill/credit_card_accessory_controller_impl.h
@@ -87,7 +87,8 @@ autofill::AutofillDriver* GetDriver(); autofill::BrowserAutofillManager* GetManager() const; - raw_ptr<content::WebContents> web_contents_; + content::WebContents& GetWebContents() const; + base::WeakPtr<ManualFillingController> mf_controller_; const raw_ptr<PersonalDataManager> personal_data_manager_; raw_ptr<autofill::BrowserAutofillManager> af_manager_for_testing_ = nullptr;
diff --git a/chrome/browser/autofill/manual_filling_controller_impl.cc b/chrome/browser/autofill/manual_filling_controller_impl.cc index 7561f93..6bf1633 100644 --- a/chrome/browser/autofill/manual_filling_controller_impl.cc +++ b/chrome/browser/autofill/manual_filling_controller_impl.cc
@@ -139,7 +139,7 @@ TRACE_EVENT0("passwords", "ManualFillingControllerImpl::NotifyFocusedInputChanged"); autofill::LocalFrameToken frame_token; - if (content::RenderFrameHost* rfh = web_contents_->GetFocusedFrame()) { + if (content::RenderFrameHost* rfh = GetWebContents().GetFocusedFrame()) { frame_token = autofill::LocalFrameToken(rfh->GetFrameToken().value()); } last_focused_field_id_ = {frame_token, focused_field_id}; @@ -246,7 +246,10 @@ } gfx::NativeView ManualFillingControllerImpl::container_view() const { - return web_contents_->GetNativeView(); + // While a const_cast is not ideal. The Autofill API uses const in various + // spots and the content public API doesn't have const accessors. So the const + // cast is the lesser of two evils. + return const_cast<content::WebContents&>(GetWebContents()).GetNativeView(); } // Returns a weak pointer for this object. @@ -256,7 +259,7 @@ } void ManualFillingControllerImpl::Initialize() { - DCHECK(FromWebContents(web_contents_)) << "Don't call from constructor!"; + DCHECK(FromWebContents(&GetWebContents())) << "Don't call from constructor!"; RegisterObserverForAllowedSources(); if (address_controller_) address_controller_->RefreshSuggestions(); @@ -264,12 +267,11 @@ ManualFillingControllerImpl::ManualFillingControllerImpl( content::WebContents* web_contents) - : web_contents_(web_contents) { - if (PasswordAccessoryController::AllowedForWebContents(web_contents_)) { - pwd_controller_ = - ChromePasswordManagerClient::FromWebContents(web_contents_) - ->GetOrCreatePasswordAccessory() - ->AsWeakPtr(); + : content::WebContentsUserData<ManualFillingControllerImpl>(*web_contents) { + if (PasswordAccessoryController::AllowedForWebContents(web_contents)) { + pwd_controller_ = ChromePasswordManagerClient::FromWebContents(web_contents) + ->GetOrCreatePasswordAccessory() + ->AsWeakPtr(); DCHECK(pwd_controller_); } if (AddressAccessoryController::AllowedForWebContents(web_contents)) { @@ -293,7 +295,7 @@ base::WeakPtr<AddressAccessoryController> address_controller, base::WeakPtr<CreditCardAccessoryController> cc_controller, std::unique_ptr<ManualFillingViewInterface> view) - : web_contents_(web_contents), + : content::WebContentsUserData<ManualFillingControllerImpl>(*web_contents), pwd_controller_(std::move(pwd_controller)), address_controller_(std::move(address_controller)), cc_controller_(std::move(cc_controller)),
diff --git a/chrome/browser/autofill/manual_filling_controller_impl.h b/chrome/browser/autofill/manual_filling_controller_impl.h index ee37f7b..6a10b34 100644 --- a/chrome/browser/autofill/manual_filling_controller_impl.h +++ b/chrome/browser/autofill/manual_filling_controller_impl.h
@@ -139,9 +139,6 @@ AccessoryController* GetControllerForAction( autofill::AccessoryAction action) const; - // The tab for which this class is scoped. - raw_ptr<content::WebContents> web_contents_ = nullptr; - // This set contains sources to be shown to the user. base::flat_set<FillingSource> available_sources_; @@ -165,7 +162,7 @@ // member so the view can be created in the constructor with a fully set up // controller instance. std::unique_ptr<ManualFillingViewInterface> view_ = - ManualFillingViewInterface::Create(this, web_contents_); + ManualFillingViewInterface::Create(this, &GetWebContents()); base::WeakPtrFactory<ManualFillingControllerImpl> weak_factory_{this};
diff --git a/chrome/browser/browser_process_impl.cc b/chrome/browser/browser_process_impl.cc index 3a1bf72..eeb32e6 100644 --- a/chrome/browser/browser_process_impl.cc +++ b/chrome/browser/browser_process_impl.cc
@@ -622,9 +622,11 @@ if (metrics) { metrics->RecordStartOfSessionEnd(); #if !BUILDFLAG(IS_CHROMEOS_ASH) - // MetricsService lazily writes to prefs, force it to write now. - // On ChromeOS, chrome gets killed when hangs, so no need to - // commit metrics::prefs::kStabilitySessionEndCompleted change immediately. + // The MetricsService may update Local State prefs in memory without + // writing the updated prefs to disk, so schedule a Local State write now. + // + // Do not schedule a write on ChromeOS because writing to disk multiple + // times during shutdown was causing shutdown problems. See crbug/302578. local_state_->CommitPendingWrite(base::OnceClosure(), rundown_counter->GetRundownClosure()); #endif
diff --git a/chrome/browser/chrome_browser_interface_binders.cc b/chrome/browser/chrome_browser_interface_binders.cc index 576df7b..092eb4e4 100644 --- a/chrome/browser/chrome_browser_interface_binders.cc +++ b/chrome/browser/chrome_browser_interface_binders.cc
@@ -154,7 +154,7 @@ #include "chrome/browser/ui/webui/tab_search/tab_search_ui.h" #include "chrome/browser/ui/webui/whats_new/whats_new_ui.h" #include "chrome/common/webui_url_constants.h" -#include "components/history_clusters/core/memories_features.h" +#include "components/history_clusters/core/features.h" #include "components/search/ntp_features.h" #include "media/base/media_switches.h" #include "media/mojo/mojom/speech_recognition_service.mojom.h"
diff --git a/chrome/browser/enterprise/connectors/common.cc b/chrome/browser/enterprise/connectors/common.cc index 6464f377..e7c5970 100644 --- a/chrome/browser/enterprise/connectors/common.cc +++ b/chrome/browser/enterprise/connectors/common.cc
@@ -40,6 +40,8 @@ return kOnFileDownloadedPref; case AnalysisConnector::FILE_ATTACHED: return kOnFileAttachedPref; + case AnalysisConnector::PRINT: + return kOnPrintPref; case AnalysisConnector::ANALYSIS_CONNECTOR_UNSPECIFIED: NOTREACHED() << "Using unspecified analysis connector"; return ""; @@ -68,6 +70,8 @@ return kOnFileDownloadedScopePref; case AnalysisConnector::FILE_ATTACHED: return kOnFileAttachedScopePref; + case AnalysisConnector::PRINT: + return kOnPrintScopePref; case AnalysisConnector::ANALYSIS_CONNECTOR_UNSPECIFIED: NOTREACHED() << "Using unspecified analysis connector"; return "";
diff --git a/chrome/browser/enterprise/connectors/connectors_manager.cc b/chrome/browser/enterprise/connectors/connectors_manager.cc index d0610810..039b032 100644 --- a/chrome/browser/enterprise/connectors/connectors_manager.cc +++ b/chrome/browser/enterprise/connectors/connectors_manager.cc
@@ -286,6 +286,7 @@ StartObservingPref(AnalysisConnector::FILE_ATTACHED); StartObservingPref(AnalysisConnector::FILE_DOWNLOADED); StartObservingPref(AnalysisConnector::BULK_DATA_ENTRY); + StartObservingPref(AnalysisConnector::PRINT); StartObservingPref(ReportingConnector::SECURITY_EVENT); StartObservingPref(FileSystemConnector::SEND_DOWNLOAD_TO_CLOUD); }
diff --git a/chrome/browser/enterprise/connectors/connectors_manager_unittest.cc b/chrome/browser/enterprise/connectors/connectors_manager_unittest.cc index 7d2c9bf..cb2c2c0 100644 --- a/chrome/browser/enterprise/connectors/connectors_manager_unittest.cc +++ b/chrome/browser/enterprise/connectors/connectors_manager_unittest.cc
@@ -31,7 +31,7 @@ constexpr AnalysisConnector kAllAnalysisConnectors[] = { AnalysisConnector::FILE_DOWNLOADED, AnalysisConnector::FILE_ATTACHED, - AnalysisConnector::BULK_DATA_ENTRY}; + AnalysisConnector::BULK_DATA_ENTRY, AnalysisConnector::PRINT}; constexpr ReportingConnector kAllReportingConnectors[] = { ReportingConnector::SECURITY_EVENT};
diff --git a/chrome/browser/enterprise/connectors/connectors_service.cc b/chrome/browser/enterprise/connectors/connectors_service.cc index 507f36a..337c6218 100644 --- a/chrome/browser/enterprise/connectors/connectors_service.cc +++ b/chrome/browser/enterprise/connectors/connectors_service.cc
@@ -393,6 +393,7 @@ ConnectorScopePref(AnalysisConnector::FILE_ATTACHED), ConnectorScopePref(AnalysisConnector::FILE_DOWNLOADED), ConnectorScopePref(AnalysisConnector::BULK_DATA_ENTRY), + ConnectorScopePref(AnalysisConnector::PRINT), ConnectorScopePref(ReportingConnector::SECURITY_EVENT)}) { absl::optional<DmToken> dm_token = GetDmToken(scope_pref); if (dm_token.has_value()) {
diff --git a/chrome/browser/enterprise/connectors/connectors_service_browsertest.cc b/chrome/browser/enterprise/connectors/connectors_service_browsertest.cc index 425c29a9..3906e0204 100644 --- a/chrome/browser/enterprise/connectors/connectors_service_browsertest.cc +++ b/chrome/browser/enterprise/connectors/connectors_service_browsertest.cc
@@ -444,7 +444,7 @@ , ConnectorsServiceAnalysisProfileBrowserTest, testing::Combine( - testing::Values(FILE_ATTACHED, FILE_DOWNLOADED, BULK_DATA_ENTRY), + testing::Values(FILE_ATTACHED, FILE_DOWNLOADED, BULK_DATA_ENTRY, PRINT), testing::Values(ManagementStatus::AFFILIATED, ManagementStatus::UNAFFILIATED, ManagementStatus::UNMANAGED)));
diff --git a/chrome/browser/enterprise/connectors/connectors_service_unittest.cc b/chrome/browser/enterprise/connectors/connectors_service_unittest.cc index 514a6fa..93a9949 100644 --- a/chrome/browser/enterprise/connectors/connectors_service_unittest.cc +++ b/chrome/browser/enterprise/connectors/connectors_service_unittest.cc
@@ -140,11 +140,10 @@ .empty()); } -INSTANTIATE_TEST_CASE_P(, - ConnectorsServiceAnalysisNoFeatureTest, - testing::Values(FILE_ATTACHED, - FILE_DOWNLOADED, - BULK_DATA_ENTRY)); +INSTANTIATE_TEST_CASE_P( + , + ConnectorsServiceAnalysisNoFeatureTest, + testing::Values(FILE_ATTACHED, FILE_DOWNLOADED, BULK_DATA_ENTRY, PRINT)); // Tests to make sure getting reporting settings work with both the feature flag // and the OnSecurityEventEnterpriseConnector policy. The parameter for these
diff --git a/chrome/browser/extensions/api/declarative_net_request/declarative_net_request_browsertest.cc b/chrome/browser/extensions/api/declarative_net_request/declarative_net_request_browsertest.cc index fe926c1..cfd03a7 100644 --- a/chrome/browser/extensions/api/declarative_net_request/declarative_net_request_browsertest.cc +++ b/chrome/browser/extensions/api/declarative_net_request/declarative_net_request_browsertest.cc
@@ -184,7 +184,8 @@ feature_list_.InitWithFeatures( /*enabled_features=*/ {blink::features::kInterestGroupStorage, - blink::features::kAdInterestGroupAPI, blink::features::kFledge}, + blink::features::kAdInterestGroupAPI, blink::features::kFledge, + blink::features::kFencedFrames}, /*disabled_features=*/ {}); net::test_server::RegisterDefaultHandlers(embedded_test_server());
diff --git a/chrome/browser/extensions/api/networking_private/networking_private_chromeos_apitest.cc b/chrome/browser/extensions/api/networking_private/networking_private_chromeos_apitest.cc index 50fbc4a..a400bc9 100644 --- a/chrome/browser/extensions/api/networking_private/networking_private_chromeos_apitest.cc +++ b/chrome/browser/extensions/api/networking_private/networking_private_chromeos_apitest.cc
@@ -28,13 +28,11 @@ #include "chromeos/dbus/shill/shill_service_client.h" #include "chromeos/dbus/userdataauth/cryptohome_misc_client.h" #include "chromeos/dbus/userdataauth/userdataauth_client.h" -#include "chromeos/network/cellular_esim_profile_handler_impl.h" #include "chromeos/network/cellular_metrics_logger.h" #include "chromeos/network/managed_network_configuration_handler.h" #include "chromeos/network/network_certificate_handler.h" #include "chromeos/network/network_handler.h" #include "chromeos/network/network_handler_test_helper.h" -#include "chromeos/network/network_metadata_store.h" #include "chromeos/network/network_state.h" #include "chromeos/network/network_state_handler.h" #include "chromeos/network/network_type_pattern.h" @@ -396,17 +394,13 @@ base::Value("third_party_provider_extension_id")); profile_test()->AddService(kUser1ProfilePath, "stub_vpn2"); - chromeos::CellularESimProfileHandlerImpl::RegisterLocalStatePrefs( - local_state_.registry()); PrefProxyConfigTrackerImpl::RegisterProfilePrefs(user_prefs_.registry()); PrefProxyConfigTrackerImpl::RegisterPrefs(local_state_.registry()); - ::onc::RegisterProfilePrefs(user_prefs_.registry()); - ::onc::RegisterPrefs(local_state_.registry()); - chromeos::NetworkMetadataStore::RegisterPrefs(user_prefs_.registry()); - chromeos::NetworkMetadataStore::RegisterPrefs(local_state_.registry()); + network_handler_test_helper_->RegisterPrefs(user_prefs_.registry(), + local_state_.registry()); - chromeos::NetworkHandler::Get()->InitializePrefServices(&user_prefs_, - &local_state_); + network_handler_test_helper_->InitializePrefs(&user_prefs_, &local_state_); + content::RunAllPendingInMessageLoop(); }
diff --git a/chrome/browser/flag-metadata.json b/chrome/browser/flag-metadata.json index f5505b1..3d15ff83 100644 --- a/chrome/browser/flag-metadata.json +++ b/chrome/browser/flag-metadata.json
@@ -127,12 +127,12 @@ { "name": "android-detailed-language-settings", "owners": [ "perrier", "chrome-language@google.com" ], - "expiry_milestone": 99 + "expiry_milestone": 101 }, { "name": "android-force-app-language-prompt", "owners": [ "perrier", "chrome-language@google.com" ], - "expiry_milestone": 99 + "expiry_milestone": 101 }, { "name": "android-picture-in-picture-api", @@ -714,7 +714,7 @@ { "name": "chrome-sharing-hub-launch-adjacent", "owners": [ "skare", "chrome-sharing-eng@google.com" ], - "expiry_milestone": 97 + "expiry_milestone": 100 }, { "name": "chrome-tips-in-main-menu", @@ -1081,11 +1081,6 @@ "expiry_milestone": 105 }, { - "name": "default-user-agent", - "owners": [ "gambard", "bling-flags@google.com" ], - "expiry_milestone": 100 - }, - { "name": "default-wkwebview-context-menu", "owners": [ "gambard", "bling-flags@google.com" ], "expiry_milestone": 100 @@ -1110,12 +1105,12 @@ { "name": "desktop-detailed-language-settings", "owners": [ "chrome-language@google.com" ], - "expiry_milestone": 97 + "expiry_milestone": 101 }, { "name": "desktop-restructured-language-settings", "owners": [ "chrome-language@google.com" ], - "expiry_milestone": 97 + "expiry_milestone": 101 }, { "name": "destroy-profile-on-browser-close", @@ -2431,7 +2426,7 @@ "name": "enable-palm-suppression", "owners": [ "robsc", "napper", "hcutts", "chromeos-tango@google.com" ], // Added feature, for testing. expiry deep in future. - "expiry_milestone": 95 + "expiry_milestone": 116 }, { "name": "enable-palm-tool-type-palm", @@ -4762,7 +4757,7 @@ "name": "restore-session-from-cache", "owners": [ "justincohen", "gambard", "bling-flags@google.com" ], // Needed for manual testing of native session restore flow on iOS. - "expiry_milestone": 97 + "expiry_milestone": 101 }, { "name": "restrict-gamepad-access", @@ -4941,7 +4936,7 @@ { "name": "share-context-menu", "owners": [ "ellyjones", "chrome-sharing-eng@google.com" ], - "expiry_milestone": 97 + "expiry_milestone": 100 }, { "name": "share-usage-ranking", @@ -5467,7 +5462,7 @@ { "name": "url-blocklist-ios", "owners": [ "michaeldo", "rohitrao", "bling-flags@google.com" ], - "expiry_milestone": 90 + "expiry_milestone": 101 }, { "name": "use-angle",
diff --git a/chrome/browser/flags/android/chrome_feature_list.cc b/chrome/browser/flags/android/chrome_feature_list.cc index 430a8da..72b2304 100644 --- a/chrome/browser/flags/android/chrome_feature_list.cc +++ b/chrome/browser/flags/android/chrome_feature_list.cc
@@ -81,8 +81,6 @@ const base::Feature* const kFeaturesExposedToJava[] = { &autofill::features::kAutofillAddressProfileSavePromptNicknameSupport, &autofill::features::kAutofillCreditCardAuthentication, - &autofill::features::kAutofillEnablePasswordInfoBarAccountIndicationFooter, - &autofill::features::kAutofillEnableSaveCardInfoBarAccountIndicationFooter, &autofill::features::kAutofillKeyboardAccessory, &autofill::features::kAutofillManualFallbackAndroid, &autofill::features::kAutofillRefreshStyleAndroid,
diff --git a/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/ChromeFeatureList.java b/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/ChromeFeatureList.java index f0c690df..46960e1d 100644 --- a/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/ChromeFeatureList.java +++ b/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/ChromeFeatureList.java
@@ -206,10 +206,6 @@ "AutofillCreditCardAuthentication"; public static final String AUTOFILL_ENABLE_GOOGLE_ISSUED_CARD = "AutofillEnableGoogleIssuedCard"; - public static final String AUTOFILL_ENABLE_PASSWORD_INFO_BAR_ACCOUNT_INDICATION_FOOTER = - "AutofillEnablePasswordInfoBarAccountIndicationFooter"; - public static final String AUTOFILL_ENABLE_SAVE_CARD_INFO_BAR_ACCOUNT_INDICATION_FOOTER = - "AutofillEnableSaveCardInfoBarAccountIndicationFooter"; public static final String AUTOFILL_ENABLE_SUPPORT_FOR_HONORIFIC_PREFIXES = "AutofillEnableSupportForHonorificPrefixes"; public static final String AUTOFILL_ENABLE_SUPPORT_FOR_MORE_STRUCTURE_IN_ADDRESSES =
diff --git a/chrome/browser/history_clusters/history_clusters_metrics_browsertest.cc b/chrome/browser/history_clusters/history_clusters_metrics_browsertest.cc index 3012f47..10d82d2 100644 --- a/chrome/browser/history_clusters/history_clusters_metrics_browsertest.cc +++ b/chrome/browser/history_clusters/history_clusters_metrics_browsertest.cc
@@ -22,7 +22,7 @@ #include "chrome/common/webui_url_constants.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" -#include "components/history_clusters/core/memories_features.h" +#include "components/history_clusters/core/features.h" #include "components/ukm/test_ukm_recorder.h" #include "components/variations/active_field_trials.h" #include "content/public/browser/navigation_handle.h"
diff --git a/chrome/browser/history_clusters/history_clusters_tab_helper_unittest.cc b/chrome/browser/history_clusters/history_clusters_tab_helper_unittest.cc index 6112296..fea36fa 100644 --- a/chrome/browser/history_clusters/history_clusters_tab_helper_unittest.cc +++ b/chrome/browser/history_clusters/history_clusters_tab_helper_unittest.cc
@@ -23,8 +23,8 @@ #include "components/history/core/browser/history_service.h" #include "components/history/core/browser/history_types.h" #include "components/history/core/test/history_service_test_util.h" +#include "components/history_clusters/core/features.h" #include "components/history_clusters/core/history_clusters_service_test_api.h" -#include "components/history_clusters/core/memories_features.h" #include "components/keyed_service/core/service_access_type.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_observer.h"
diff --git a/chrome/browser/media/webrtc/webrtc_event_log_manager_common.cc b/chrome/browser/media/webrtc/webrtc_event_log_manager_common.cc index c441afb..372714b 100644 --- a/chrome/browser/media/webrtc/webrtc_event_log_manager_common.cc +++ b/chrome/browser/media/webrtc/webrtc_event_log_manager_common.cc
@@ -1043,7 +1043,7 @@ // cases (e.g. on Chrome OS). Although currently this should be covered by the // other checks, let's explicitly check to anticipate edge cases and make the // requirement explicit. - if (profile->IsOffTheRecord() || profile->IsSupervised()) { + if (profile->IsOffTheRecord() || profile->IsChild()) { return false; }
diff --git a/chrome/browser/media/webrtc/webrtc_event_log_manager_unittest.cc b/chrome/browser/media/webrtc/webrtc_event_log_manager_unittest.cc index 74dd78f..3e4ad39 100644 --- a/chrome/browser/media/webrtc/webrtc_event_log_manager_unittest.cc +++ b/chrome/browser/media/webrtc/webrtc_event_log_manager_unittest.cc
@@ -41,6 +41,7 @@ #include "chrome/browser/media/webrtc/webrtc_event_log_manager_unittest_helpers.h" #include "chrome/browser/policy/profile_policy_connector.h" #include "chrome/browser/prefs/browser_prefs.h" +#include "chrome/browser/supervised_user/supervised_user_constants.h" #include "chrome/common/chrome_features.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" @@ -707,7 +708,9 @@ profile_builder.OverridePolicyConnectorIsManagedForTesting( is_managed_profile); if (is_supervised) { - profile_builder.SetSupervisedUserId("id"); +#if BUILDFLAG(ENABLE_SUPERVISED_USERS) + profile_builder.SetSupervisedUserId(supervised_users::kChildAccountSUID); +#endif } std::unique_ptr<TestingProfile> profile = profile_builder.Build(); @@ -4052,16 +4055,15 @@ // TODO(crbug.com/1035829): Figure out whether this can be resolved by tweaking // the test setup or whether the Active Directory services need to be adapted // for easy testing. +#if BUILDFLAG(IS_CHROMEOS_ASH) TEST_F(WebRtcEventLogManagerTestPolicy, ManagedProfileDoesNotAllowRemoteLoggingForSupervisedProfiles) { SetUp(true); // Feature generally enabled (kill-switch not engaged). const bool allow_remote_logging = false; -#if BUILDFLAG(IS_CHROMEOS_ASH) std::unique_ptr<user_manager::ScopedUserManager> scoped_user_manager = GetScopedUserManager(user_manager::USER_TYPE_CHILD); -#endif auto browser_context = CreateBrowserContextWithCustomSupervision( "name", true /* is_managed_profile */, @@ -4075,6 +4077,7 @@ ASSERT_TRUE(OnPeerConnectionSessionIdSet(key)); EXPECT_EQ(StartRemoteLogging(key), allow_remote_logging); } +#endif #if !defined(OS_ANDROID) && !BUILDFLAG(IS_CHROMEOS_ASH) TEST_F(WebRtcEventLogManagerTestPolicy,
diff --git a/chrome/browser/optimization_guide/page_content_annotations_service_browsertest.cc b/chrome/browser/optimization_guide/page_content_annotations_service_browsertest.cc index ba923371..69a2ad87 100644 --- a/chrome/browser/optimization_guide/page_content_annotations_service_browsertest.cc +++ b/chrome/browser/optimization_guide/page_content_annotations_service_browsertest.cc
@@ -302,17 +302,6 @@ 1); #endif - PageContentAnnotationsService* service = - PageContentAnnotationsServiceFactory::GetForProfile(browser()->profile()); - -#if BUILDFLAG(BUILD_WITH_TFLITE_LIB) - absl::optional<int64_t> model_version = service->GetPageTopicsModelVersion(); - EXPECT_TRUE(model_version.has_value()); - EXPECT_EQ(123, *model_version); -#else - EXPECT_FALSE(service->GetPageTopicsModelVersion().has_value()); -#endif - #if BUILDFLAG(BUILD_WITH_TFLITE_LIB) RetryForHistogramUntilCountReached(
diff --git a/chrome/browser/password_manager/android/password_accessory_controller_impl.cc b/chrome/browser/password_manager/android/password_accessory_controller_impl.cc index 05621016..6c28a0d 100644 --- a/chrome/browser/password_manager/android/password_accessory_controller_impl.cc +++ b/chrome/browser/password_manager/android/password_accessory_controller_impl.cc
@@ -130,7 +130,7 @@ // Prevent crashing by returning a nullopt if no field was focused yet or if // the frame was (possibly temporarily) unfocused. This signals to the caller // that no sheet is available right now. - if (web_contents_->GetFocusedFrame() == nullptr) + if (GetWebContents().GetFocusedFrame() == nullptr) return absl::nullopt; if (!last_focused_field_info_) return absl::nullopt; @@ -319,7 +319,7 @@ } if (selected_action == autofill::AccessoryAction::MANAGE_PASSWORDS) { password_manager_launcher::ShowPasswordSettings( - web_contents_, + &GetWebContents(), password_manager::ManagePasswordsReferrer::kPasswordsAccessorySheet); return; } @@ -362,7 +362,7 @@ // Prevent crashing by not acting at all if frame became unfocused at any // point. The next time a focus event happens, this will be called again and // ensure we show correct data. - if (web_contents_->GetFocusedFrame() == nullptr) + if (GetWebContents().GetFocusedFrame() == nullptr) return; url::Origin origin = GetFocusedFrameOrigin(); if (origin.opaque()) @@ -403,7 +403,7 @@ void PasswordAccessoryControllerImpl::OnGenerationRequested( autofill::password_generation::PasswordGenerationType type) { PasswordGenerationController* pwd_generation_controller = - PasswordGenerationController::GetIfExisting(web_contents_); + PasswordGenerationController::GetIfExisting(&GetWebContents()); DCHECK(pwd_generation_controller); pwd_generation_controller->OnGenerationRequested(type); @@ -423,7 +423,8 @@ base::WeakPtr<ManualFillingController> mf_controller, password_manager::PasswordManagerClient* password_client, PasswordDriverSupplierForFocusedFrame driver_supplier) - : web_contents_(web_contents), + : content::WebContentsUserData<PasswordAccessoryControllerImpl>( + *web_contents), credential_cache_(credential_cache), mf_controller_(std::move(mf_controller)), password_client_(password_client), @@ -483,18 +484,18 @@ base::WeakPtr<ManualFillingController> PasswordAccessoryControllerImpl::GetManualFillingController() { if (!mf_controller_) - mf_controller_ = ManualFillingController::GetOrCreate(web_contents_); + mf_controller_ = ManualFillingController::GetOrCreate(&GetWebContents()); DCHECK(mf_controller_); return mf_controller_; } url::Origin PasswordAccessoryControllerImpl::GetFocusedFrameOrigin() const { - if (web_contents_->GetFocusedFrame() == nullptr) { + if (GetWebContents().GetFocusedFrame() == nullptr) { LOG(DFATAL) << "Tried to get retrieve origin without focused " "frame."; return url::Origin(); // Nonce! } - return web_contents_->GetFocusedFrame()->GetLastCommittedOrigin(); + return GetWebContents().GetFocusedFrame()->GetLastCommittedOrigin(); } void PasswordAccessoryControllerImpl::ShowAllPasswords() { @@ -510,7 +511,7 @@ // TODO(crbug.com/1104132): Update the controller with the last focused field. all_passords_bottom_sheet_controller_ = std::make_unique<AllPasswordsBottomSheetController>( - web_contents_, password_client_->GetProfilePasswordStore(), + &GetWebContents(), password_client_->GetProfilePasswordStore(), base::BindOnce( &PasswordAccessoryControllerImpl::AllPasswordsSheetDismissed, base::Unretained(this)), @@ -549,7 +550,7 @@ return; // Never fill across different origins! } password_manager::PasswordManagerDriver* driver = - driver_supplier_.Run(web_contents_.get()); + driver_supplier_.Run(&GetWebContents()); if (!driver) return; driver->FillIntoFocusedField(selection.is_obfuscated(), @@ -565,11 +566,20 @@ return security_level_for_testing_ == security_state::SECURE; } - SecurityStateTabHelper::CreateForWebContents(web_contents_); + SecurityStateTabHelper::CreateForWebContents(&GetWebContents()); SecurityStateTabHelper* helper = - SecurityStateTabHelper::FromWebContents(web_contents_); + SecurityStateTabHelper::FromWebContents(&GetWebContents()); return helper && helper->GetSecurityLevel() == security_state::SECURE; } +content::WebContents& PasswordAccessoryControllerImpl::GetWebContents() const { + // While a const_cast is not ideal. The Autofill API uses const in various + // spots and the content public API doesn't have const accessors. So the const + // cast is the lesser of two evils. + return const_cast<content::WebContents&>( + content::WebContentsUserData< + PasswordAccessoryControllerImpl>::GetWebContents()); +} + WEB_CONTENTS_USER_DATA_KEY_IMPL(PasswordAccessoryControllerImpl);
diff --git a/chrome/browser/password_manager/android/password_accessory_controller_impl.h b/chrome/browser/password_manager/android/password_accessory_controller_impl.h index 931b16d..91d07c2 100644 --- a/chrome/browser/password_manager/android/password_accessory_controller_impl.h +++ b/chrome/browser/password_manager/android/password_accessory_controller_impl.h
@@ -182,8 +182,7 @@ // the Bottom Sheet view is destroyed. void AllPasswordsSheetDismissed(); - // The tab for which this class is scoped. - raw_ptr<content::WebContents> web_contents_ = nullptr; + content::WebContents& GetWebContents() const; // Keeps track of credentials which are stored for all origins in this tab. raw_ptr<password_manager::CredentialCache> credential_cache_ = nullptr;
diff --git a/chrome/browser/password_manager/android/password_infobar_utils.cc b/chrome/browser/password_manager/android/password_infobar_utils.cc index 2df7f34..b69fb4c 100644 --- a/chrome/browser/password_manager/android/password_infobar_utils.cc +++ b/chrome/browser/password_manager/android/password_infobar_utils.cc
@@ -16,13 +16,7 @@ absl::optional<AccountInfo> GetAccountInfoForPasswordInfobars(Profile* profile, bool is_syncing) { DCHECK(profile); - if (!base::FeatureList::IsEnabled( - autofill::features:: - kAutofillEnablePasswordInfoBarAccountIndicationFooter) || - !is_syncing || - !base::FeatureList::IsEnabled( - autofill::features:: - kAutofillEnableInfoBarAccountIndicationFooterForSyncUsers)) { + if (!is_syncing) { return absl::nullopt; } signin::IdentityManager* identity_manager = @@ -31,17 +25,8 @@ identity_manager->GetPrimaryAccountId(signin::ConsentLevel::kSync); AccountInfo account_info = identity_manager->FindExtendedAccountInfoByAccountId(account_id); - bool is_single_account_user = - identity_manager->GetAccountsWithRefreshTokens().size() == 1; - bool should_show_account_footer = - (!is_single_account_user || - base::FeatureList::IsEnabled( - autofill::features:: - kAutofillEnableInfoBarAccountIndicationFooterForSingleAccountUsers)) && - !account_info.IsEmpty(); - - return should_show_account_footer + return !account_info.IsEmpty() ? absl::make_optional<AccountInfo>(account_info) : absl::nullopt; }
diff --git a/chrome/browser/password_manager/android/password_infobar_utils.h b/chrome/browser/password_manager/android/password_infobar_utils.h index 1131526..ba71760 100644 --- a/chrome/browser/password_manager/android/password_infobar_utils.h +++ b/chrome/browser/password_manager/android/password_infobar_utils.h
@@ -12,6 +12,9 @@ namespace password_manager { +// TODO(crbug.com/1277513): These functions should return a non-optional +// AccountInfo, since AccountInfo itself already supports an "empty" state. + absl::optional<AccountInfo> GetAccountInfoForPasswordInfobars(Profile* profile, bool is_syncing);
diff --git a/chrome/browser/prefs/browser_prefs.cc b/chrome/browser/prefs/browser_prefs.cc index c54e06e..8834b6ac 100644 --- a/chrome/browser/prefs/browser_prefs.cc +++ b/chrome/browser/prefs/browser_prefs.cc
@@ -676,6 +676,10 @@ "Availability.Prober.cache.IsolatedPrerenderTLSCanaryCheck"; const char kAvailabilityProberDNSCanaryCheck[] = "Availability.Prober.cache.IsolatedPrerenderDNSCanaryCheck"; +const char kStabilityIncompleteSessionEndCount[] = + "user_experience_metrics.stability.incomplete_session_end_count"; +const char kStabilitySessionEndCompleted[] = + "user_experience_metrics.stability.session_end_completed"; // Register local state used only for migration (clearing or moving to a new // key). @@ -717,6 +721,9 @@ registry->RegisterStringPref(kPrivacyBudgetActiveSurfaces, std::string()); registry->RegisterStringPref(kPrivacyBudgetRetiredSurfaces, std::string()); registry->RegisterUint64Pref(kPrivacyBudgetSeed, 0u); + + registry->RegisterIntegerPref(kStabilityIncompleteSessionEndCount, 0); + registry->RegisterBooleanPref(kStabilitySessionEndCompleted, true); } // Register prefs used only for migration (clearing or moving to a new key). @@ -1455,7 +1462,6 @@ // Please don't delete the preceding line. It is used by PRESUBMIT.py. #if BUILDFLAG(IS_CHROMEOS_ASH) - // Added 12/2020. local_state->ClearPref(kFirstRunTrialGroup); local_state->ClearPref(kLocalSearchServiceSyncMetricsDailySample); @@ -1500,6 +1506,10 @@ // Added 10/2021. local_state->ClearPref(kTabStripStackedLayout); + // Added 12/2021. + local_state->ClearPref(kStabilityIncompleteSessionEndCount); + local_state->ClearPref(kStabilitySessionEndCompleted); + // Please don't delete the following line. It is used by PRESUBMIT.py. // END_MIGRATE_OBSOLETE_LOCAL_STATE_PREFS }
diff --git a/chrome/browser/push_messaging/push_messaging_notification_manager_unittest.cc b/chrome/browser/push_messaging/push_messaging_notification_manager_unittest.cc index e90ab669..7b6b466 100644 --- a/chrome/browser/push_messaging/push_messaging_notification_manager_unittest.cc +++ b/chrome/browser/push_messaging/push_messaging_notification_manager_unittest.cc
@@ -14,6 +14,8 @@ #include "url/gurl.h" #if BUILDFLAG(IS_CHROMEOS_ASH) +#include <memory> + #include "chrome/browser/ash/android_sms/fake_android_sms_app_manager.h" #include "chromeos/services/multidevice_setup/public/cpp/fake_multidevice_setup_client.h" #endif @@ -58,20 +60,19 @@ TEST_F(PushMessagingNotificationManagerTest, SkipEnforceUserVisibleOnlyRequirementsForAndroidMessages) { GURL app_url("https://example.com/test/"); - auto* fake_android_sms_app_manager = - new ash::android_sms::FakeAndroidSmsAppManager(); + auto fake_android_sms_app_manager = + std::make_unique<ash::android_sms::FakeAndroidSmsAppManager>(); fake_android_sms_app_manager->SetInstalledAppUrl(app_url); - chromeos::multidevice_setup::FakeMultiDeviceSetupClient* - fake_multidevice_setup_client = - new chromeos::multidevice_setup::FakeMultiDeviceSetupClient(); + auto fake_multidevice_setup_client = std::make_unique< + chromeos::multidevice_setup::FakeMultiDeviceSetupClient>(); fake_multidevice_setup_client->SetFeatureState( chromeos::multidevice_setup::mojom::Feature::kMessages, chromeos::multidevice_setup::mojom::FeatureState::kEnabledByUser); PushMessagingNotificationManager manager(profile()); - manager.SetTestMultiDeviceSetupClient(fake_multidevice_setup_client); - manager.SetTestAndroidSmsAppManager(fake_android_sms_app_manager); + manager.SetTestMultiDeviceSetupClient(fake_multidevice_setup_client.get()); + manager.SetTestAndroidSmsAppManager(fake_android_sms_app_manager.get()); bool was_called = false; manager.EnforceUserVisibleOnlyRequirements(
diff --git a/chrome/browser/resources/new_tab_page/realbox/realbox_dropdown.html b/chrome/browser/resources/new_tab_page/realbox/realbox_dropdown.html index c8792bb..f13e784 100644 --- a/chrome/browser/resources/new_tab_page/realbox/realbox_dropdown.html +++ b/chrome/browser/resources/new_tab_page/realbox/realbox_dropdown.html
@@ -48,6 +48,7 @@ .header cr-icon-button { --cr-icon-button-fill-color: var(--search-box-icon, var(--google-grey-refresh-700)); + --cr-icon-button-focus-outline-color: var(--google-blue-600); --cr-icon-button-icon-size: 16px; --cr-icon-button-margin-start: 0; --cr-icon-button-size: 24px; @@ -60,27 +61,17 @@ } .header:focus-within:not(:focus) cr-icon-button { - --cr-icon-button-fill-color: var(--search-box-icon-selected, var(--google-grey-refresh-700)); + --cr-icon-button-fill-color: var(--search-box-icon-selected, var(--google-grey-refresh-700)); } - ntp-realbox-match:hover, - .header:hover { + ntp-realbox-match:-webkit-any(:hover, :focus-within, .selected), + .header:-webkit-any(:hover, :focus-within) { background-color: var(--search-box-results-bg-hovered, rgba(var(--google-grey-900-rgb), .1)); } - ntp-realbox-match:-webkit-any(:focus-within, .selected), - .header:focus-within:not(:focus) { - background-color: var(--search-box-results-bg-selected, rgba(var(--google-grey-900-rgb), .16)); - color: var(--search-box-results-text-selected, var(--google-grey-900)); - } - @media (forced-colors: active) { - ntp-realbox-match:hover, - .header:hover { - background-color: Highlight; - } - ntp-realbox-match:-webkit-any(:focus-within, .selected), - .header:focus-within:not(:focus) { + ntp-realbox-match:-webkit-any(:hover, :focus-within, .selected), + .header:-webkit-any(:hover, :focus-within) { background-color: Highlight; } }
diff --git a/chrome/browser/resources/new_tab_page/realbox/realbox_dropdown.js b/chrome/browser/resources/new_tab_page/realbox/realbox_dropdown.js index 02daa97..5958701 100644 --- a/chrome/browser/resources/new_tab_page/realbox/realbox_dropdown.js +++ b/chrome/browser/resources/new_tab_page/realbox/realbox_dropdown.js
@@ -231,17 +231,15 @@ } this.updateStyles({ - '--search-box-icon': skColorToRgba(this.theme.icon), + '--search-box-icon-selected': + skColorToRgba(assert(this.theme.iconSelected)), + '--search-box-icon': skColorToRgba(assert(this.theme.icon)), '--search-box-results-bg-hovered': skColorToRgba(assert(this.theme.resultsBgHovered)), - '--search-box-results-bg-selected': - skColorToRgba(assert(this.theme.resultsBgSelected)), '--search-box-results-bg': skColorToRgba(assert(this.theme.resultsBg)), '--search-box-results-dim-selected': skColorToRgba(assert(this.theme.resultsDimSelected)), '--search-box-results-dim': skColorToRgba(assert(this.theme.resultsDim)), - '--search-box-results-text-selected': - skColorToRgba(assert(this.theme.resultsTextSelected)), '--search-box-results-text': skColorToRgba(assert(this.theme.resultsText)), '--search-box-results-url-selected':
diff --git a/chrome/browser/resources/new_tab_page/realbox/realbox_icon.html b/chrome/browser/resources/new_tab_page/realbox/realbox_icon.html index 7226592..f800b04 100644 --- a/chrome/browser/resources/new_tab_page/realbox/realbox_icon.html +++ b/chrome/browser/resources/new_tab_page/realbox/realbox_icon.html
@@ -4,6 +4,7 @@ display: flex; flex-shrink: 0; justify-content: center; + padding-inline-start: 8px; width: 32px; }
diff --git a/chrome/browser/resources/new_tab_page/realbox/realbox_match.html b/chrome/browser/resources/new_tab_page/realbox/realbox_match.html index e88d24b..01a43156 100644 --- a/chrome/browser/resources/new_tab_page/realbox/realbox_match.html +++ b/chrome/browser/resources/new_tab_page/realbox/realbox_match.html
@@ -4,19 +4,20 @@ outline: none; } - #action { - margin-inline-start: 40px; /* icon width + text padding */ + margin-inline-start: 40px; /* icon width + text padding */ } .container { align-items: center; cursor: default; display: flex; + overflow: hidden; padding-bottom: 6px; padding-inline-end: 16px; padding-inline-start: 12px; padding-top: 6px; + position: relative; } .container + .container { @@ -29,6 +30,20 @@ text-overflow: ellipsis; } + #focus-indicator { + background-color: var(--google-blue-600); + border-radius: 3px; + display: none; + height: 100%; + margin-inline-start: -15px; /* -1 * (.container padding + width / 2) */ + position: absolute; + width: 6px; + } + + :host(:-webkit-any(:focus, .selected:not(:focus-within))) #focus-indicator { + display: block; + } + #separator { white-space: pre; } @@ -86,6 +101,7 @@ #remove { --cr-icon-button-active-background-color: rgba(var(--google-grey-900-rgb), .16); --cr-icon-button-fill-color: var(--search-box-icon, var(--google-grey-refresh-700)); + --cr-icon-button-focus-outline-color: var(--google-blue-600); --cr-icon-button-hover-background-color: rgba(var(--google-grey-900-rgb), .1); --cr-icon-button-icon-size: 16px; --cr-icon-button-margin-end: 0; @@ -106,6 +122,7 @@ </style> <div class="container" aria-hidden="true"> + <div id="focus-indicator"></div> <ntp-realbox-icon id="icon" match="[[match]]"></ntp-realbox-icon> <div id="text-container"> <span id="contents" inner-h-t-m-l="[[contentsHtml_]]"></span>
diff --git a/chrome/browser/resources/read_later/side_panel/bookmarks_list.ts b/chrome/browser/resources/read_later/side_panel/bookmarks_list.ts index 8ade8cfc..dec72ac 100644 --- a/chrome/browser/resources/read_later/side_panel/bookmarks_list.ts +++ b/chrome/browser/resources/read_later/side_panel/bookmarks_list.ts
@@ -137,6 +137,16 @@ } this.focusBookmark_(bookmarks[0]!.id); + + // <if expr="is_macosx"> + // On Mac, the hover effect on the dragged item can linger on before the + // user moves the pointer after drop. Reset pointer events on the whole + // list temporarily to reset the effect. + this.style.pointerEvents = 'none'; + setTimeout(() => { + this.style.pointerEvents = 'auto'; + }, 50); + // </if> } /** BookmarksDragDelegate */
diff --git a/chrome/browser/resources/settings/basic_page/basic_page.html b/chrome/browser/resources/settings/basic_page/basic_page.html index fb78a724..21f042f 100644 --- a/chrome/browser/resources/settings/basic_page/basic_page.html +++ b/chrome/browser/resources/settings/basic_page/basic_page.html
@@ -5,29 +5,6 @@ overflow: hidden; } - :host([advanced-toggling-in-progress_]) { - -webkit-tap-highlight-color: transparent; - } - - #advancedToggle { - --ink-color: currentColor; - align-items: center; - background: transparent; - border: none; - box-shadow: none; - color: currentColor; - display: flex; - font-weight: 400; - margin-bottom: 3px; - margin-top: 12px; /* Part of a 48px spacer (33px + 12px + 3px). */ - min-height: 32px; - padding: 0 12px; - } - - :host-context(.focus-outline-visible) #advancedToggle:focus { - outline: auto 5px -webkit-focus-ring-color; - } - #osSettingsBanner { background-color: var(--cr-card-background-color); border-radius: var(--cr-card-border-radius); @@ -35,27 +12,7 @@ margin-top: 21px; } - #toggleContainer { - align-items: center; - color: var(--cr-primary-text-color); - display: flex; - font: inherit; - justify-content: center; - margin-bottom: 0; - margin-top: 0; - padding-bottom: 0; - padding-top: 0; - } - - #toggleSpacer { - padding-top: 33px; /* Part of a 48px spacer (33px + 12px + 3px). */ - } - - iron-icon { - margin-inline-start: 16px; - } - - :host-context([enable-landing-page-redesign]):host(:not([in-search-mode])) settings-section:not([active]) { + :host(:not([in-search-mode])) settings-section:not([active]) { display: none; } </style> @@ -153,19 +110,6 @@ </template> <template is="dom-if" if="[[showAdvancedSettings_(pageVisibility.advancedSettings)]]"> - <template is="dom-if" if="[[showAdvancedToggle_( - inSearchMode, hasExpandedSection_)]]"> - <div id="toggleSpacer"></div> - <h2 id="toggleContainer"> - <cr-button id="advancedToggle" on-click="advancedToggleClicked_" - aria-expanded$="[[boolToString_(advancedToggleExpanded)]]"> - <span>$i18n{advancedPageTitle}</span> - <iron-icon icon="[[getArrowIcon_(advancedToggleExpanded)]]"> - </iron-icon> - </cr-button> - </h2> - </template> - <settings-idle-load id="advancedPageTemplate"> <template> <div id="advancedPage" hidden$="[[!showAdvancedPage_(
diff --git a/chrome/browser/resources/settings/basic_page/basic_page.ts b/chrome/browser/resources/settings/basic_page/basic_page.ts index 56d7765a..07bd17f1 100644 --- a/chrome/browser/resources/settings/basic_page/basic_page.ts +++ b/chrome/browser/resources/settings/basic_page/basic_page.ts
@@ -6,7 +6,6 @@ * @fileoverview * 'settings-basic-page' is the settings page containing the actual settings. */ -import 'chrome://resources/cr_elements/cr_button/cr_button.m.js'; import 'chrome://resources/cr_elements/hidden_style_css.m.js'; import 'chrome://resources/cr_elements/shared_style_css.m.js'; import 'chrome://resources/cr_elements/shared_vars_css.m.js'; @@ -33,7 +32,7 @@ // </if> import {assert} from 'chrome://resources/js/assert.m.js'; -import {beforeNextRender, html, microTask, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; +import {beforeNextRender, html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {SettingsIdleLoadElement} from '../controls/settings_idle_load.js'; import {loadTimeData} from '../i18n_setup.js'; @@ -112,6 +111,16 @@ }, }, + /** + * Whether a search operation is in progress or previous search + * results are being displayed. + */ + inSearchMode: { + type: Boolean, + value: false, + reflectToAttribute: true, + }, + advancedToggleExpanded: { type: Boolean, value: false, @@ -161,6 +170,7 @@ } pageVisibility: PageVisibility; + inSearchMode: boolean; advancedToggleExpanded: boolean; private hasExpandedSection_: boolean; private showResetProfileBanner_: boolean; @@ -348,43 +358,6 @@ new CustomEvent(eventName, {bubbles: true, composed: true, detail})); } - private advancedToggleClicked_() { - if (this.advancedTogglingInProgress_) { - return; - } - - this.advancedTogglingInProgress_ = true; - const toggle = - this.shadowRoot!.querySelector('#toggleContainer') as HTMLElement; - if (!this.advancedToggleExpanded) { - this.advancedToggleExpanded = true; - microTask.run(() => { - this.getIdleLoad_().then(() => { - this.fire_('scroll-to-top', { - top: toggle.offsetTop, - callback: () => { - this.advancedTogglingInProgress_ = false; - } - }); - }); - }); - } else { - this.fire_('scroll-to-bottom', { - bottom: toggle.offsetTop + toggle.offsetHeight + 24, - callback: () => { - this.advancedToggleExpanded = false; - this.advancedTogglingInProgress_ = false; - } - }); - } - } - - private showAdvancedToggle_( - inSearchMode: boolean, hasExpandedSection: boolean): boolean { - return !inSearchMode && !hasExpandedSection && - !loadTimeData.getBoolean('enableLandingPageRedesign'); - } - /** * @return Whether to show the basic page, taking into account both routing * and search state. @@ -410,14 +383,6 @@ private showAdvancedSettings_(visibility?: boolean): boolean { return visibility !== false; } - - private getArrowIcon_(opened: boolean): string { - return opened ? 'cr:arrow-drop-up' : 'cr:arrow-drop-down'; - } - - private boolToString_(bool: boolean): string { - return bool.toString(); - } } declare global {
diff --git a/chrome/browser/resources/settings/route.ts b/chrome/browser/resources/settings/route.ts index 37933d4..486e717 100644 --- a/chrome/browser/resources/settings/route.ts +++ b/chrome/browser/resources/settings/route.ts
@@ -16,6 +16,8 @@ r.CLEAR_BROWSER_DATA = r.PRIVACY.createChild('/clearBrowserData'); r.CLEAR_BROWSER_DATA.isNavigableDialog = true; + r.SAFETY_CHECK = r.PRIVACY.createSection('/safetyCheck', 'safetyCheck'); + if (loadTimeData.getBoolean('privacyReviewEnabled')) { r.PRIVACY_REVIEW = r.PRIVACY.createChild('review'); } @@ -140,12 +142,6 @@ if (visibility.privacy !== false) { r.PRIVACY = r.BASIC.createSection('/privacy', 'privacy'); addPrivacyChildRoutes(r); - - if (loadTimeData.getBoolean('enableLandingPageRedesign')) { - r.SAFETY_CHECK = r.PRIVACY.createSection('/safetyCheck', 'safetyCheck'); - } else { - r.SAFETY_CHECK = r.BASIC.createSection('/safetyCheck', 'safetyCheck'); - } } // <if expr="not chromeos and not lacros">
diff --git a/chrome/browser/resources/settings/settings.html b/chrome/browser/resources/settings/settings.html index 50cb169..da9d882 100644 --- a/chrome/browser/resources/settings/settings.html +++ b/chrome/browser/resources/settings/settings.html
@@ -1,6 +1,5 @@ <!doctype html> <html dir="$i18n{textdirection}" lang="$i18n{language}" class="loading" - $i18n{enableLandingPageRedesignAttribute} $i18n{enableBrandingUpdateAttribute}> <head> <meta charset="utf-8">
diff --git a/chrome/browser/resources/settings/settings_main/settings_main.html b/chrome/browser/resources/settings/settings_main/settings_main.html index fdb63425..f689ddf 100644 --- a/chrome/browser/resources/settings/settings_main/settings_main.html +++ b/chrome/browser/resources/settings/settings_main/settings_main.html
@@ -1,12 +1,4 @@ <style include="cr-shared-style cr-hidden-style settings-shared"> - #overscroll { - margin-top: 64px; - } - - .showing-subpage ~ #overscroll { - display: none; - } - #noSearchResults { margin-top: 80px; text-align: center; @@ -46,7 +38,6 @@ class="cr-centered-card-container" prefs="{{prefs}}" page-visibility="[[pageVisibility]]" - on-showing-section="onShowingSection_" on-subpage-expand="onShowingSubpage_" on-showing-main-page="onShowingMainPage_" in-search-mode="[[inSearchMode_]]" @@ -59,4 +50,3 @@ prefs="{{prefs}}"> </settings-about-page> </template> - <div id="overscroll" style="padding-bottom: [[overscroll_]]px"></div>
diff --git a/chrome/browser/resources/settings/settings_main/settings_main.ts b/chrome/browser/resources/settings/settings_main/settings_main.ts index 676e89b..6a5d4fe8 100644 --- a/chrome/browser/resources/settings/settings_main/settings_main.ts +++ b/chrome/browser/resources/settings/settings_main/settings_main.ts
@@ -35,12 +35,6 @@ settings: boolean, }; -export interface SettingsMainElement { - $: { - overscroll: HTMLElement, - }; -} - const SettingsMainElementBase = RouteObserverMixin(PolymerElement) as {new (): PolymerElement & RouteObserverMixinInterface}; @@ -68,11 +62,6 @@ notify: true, }, - overscroll_: { - type: Number, - observer: 'overscrollChanged_', - }, - /** * Controls which main pages are displayed via dom-ifs, based on the * current route. @@ -114,51 +103,12 @@ } advancedToggleExpanded: boolean; - private overscroll_: number; private showPages_: MainPageVisibility; private inSearchMode_: boolean; private showNoResultsFound_: boolean; private showingSubpage_: boolean; toolbarSpinnerActive: boolean; pageVisibility: PageVisibility; - private boundScroll_: (() => void)|null = null; - - private overscrollChanged_() { - assert(!loadTimeData.getBoolean('enableLandingPageRedesign')); - if (!this.overscroll_ && this.boundScroll_) { - this.offsetParent!.removeEventListener('scroll', this.boundScroll_); - window.removeEventListener('resize', this.boundScroll_); - this.boundScroll_ = null; - } else if (this.overscroll_ && !this.boundScroll_) { - this.boundScroll_ = () => { - if (!this.showingSubpage_) { - this.setOverscroll_(0); - } - }; - this.offsetParent!.addEventListener('scroll', this.boundScroll_); - window.addEventListener('resize', this.boundScroll_); - } - } - - /** - * Sets the overscroll padding. Never forces a scroll, i.e., always leaves - * any currently visible overflow as-is. - * @param opt_minHeight The minimum overscroll height needed. - */ - private setOverscroll_(opt_minHeight?: number) { - const scroller = this.offsetParent; - if (!scroller) { - return; - } - const overscroll = this.$.overscroll; - const visibleBottom = scroller.scrollTop + scroller.clientHeight; - const overscrollBottom = overscroll.offsetTop + overscroll.scrollHeight; - // How much of the overscroll is visible (may be negative). - const visibleOverscroll = - overscroll.scrollHeight - (overscrollBottom - visibleBottom); - this.overscroll_ = - Math.max(opt_minHeight || 0, Math.ceil(visibleOverscroll)); - } /** * Updates the hidden state of the about and settings pages based on the @@ -186,27 +136,6 @@ } /** - * A handler for the 'showing-section' event fired from settings-basic-page, - * indicating that a section should be scrolled into view as a result of a - * navigation. - */ - private onShowingSection_(e: CustomEvent<HTMLElement>) { - assert(!loadTimeData.getBoolean('enableLandingPageRedesign')); - - const section = e.detail; - // Calculate the height that the overscroll padding should be set to, so - // that the given section is displayed at the top of the viewport. - // Find the distance from the section's top to the overscroll. - const sectionTop = - (section.offsetParent as HTMLElement).offsetTop + section.offsetTop; - const distance = this.$.overscroll.offsetTop - sectionTop; - const overscroll = Math.max(0, this.offsetParent!.clientHeight - distance); - this.setOverscroll_(overscroll); - section.scrollIntoView(); - section.focus(); - } - - /** * @return A promise indicating that searching finished. */ searchContents(query: string): Promise<void> {
diff --git a/chrome/browser/resources/settings/settings_menu/settings_menu.html b/chrome/browser/resources/settings/settings_menu/settings_menu.html index e31d300..cb96e9cf 100644 --- a/chrome/browser/resources/settings/settings_menu/settings_menu.html +++ b/chrome/browser/resources/settings/settings_menu/settings_menu.html
@@ -118,16 +118,6 @@ $i18n{autofillPageTitle} <paper-ripple></paper-ripple> </a> - <template is="dom-if" if="[[!enableLandingPageRedesign_]]"> - <a role="menuitem" href="/safetyCheck" - hidden="[[!pageVisibility.safetyCheck]]" - id="safetyCheck" - class="cr-nav-menu-item"> - <iron-icon icon="settings20:safety-check"></iron-icon> - $i18n{safetyCheckSectionTitle} - <paper-ripple></paper-ripple> - </a> - </template> <a role="menuitem" href="/privacy" hidden="[[!pageVisibility.privacy]]" class="cr-nav-menu-item">
diff --git a/chrome/browser/resources/settings/settings_menu/settings_menu.ts b/chrome/browser/resources/settings/settings_menu/settings_menu.ts index f6c0336..3af5385 100644 --- a/chrome/browser/resources/settings/settings_menu/settings_menu.ts +++ b/chrome/browser/resources/settings/settings_menu/settings_menu.ts
@@ -23,7 +23,6 @@ import {IronSelectorElement} from 'chrome://resources/polymer/v3_0/iron-selector/iron-selector.js'; import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; -import {loadTimeData} from '../i18n_setup.js'; import {PageVisibility} from '../page_visibility.js'; import {Route, RouteObserverMixin, RouteObserverMixinInterface, Router} from '../router.js'; @@ -62,18 +61,11 @@ * Dictionary defining page visibility. */ pageVisibility: Object, - - enableLandingPageRedesign_: { - type: Boolean, - value: () => loadTimeData.getBoolean('enableLandingPageRedesign'), - }, - }; } advancedOpened: boolean; pageVisibility: PageVisibility; - private enableLandingPageRedesign_: boolean; currentRouteChanged(newRoute: Route) { // Focus the initially selected path.
diff --git a/chrome/browser/resources/settings/settings_page/main_page_mixin.ts b/chrome/browser/resources/settings/settings_page/main_page_mixin.ts index d01d80d4..3f644879 100644 --- a/chrome/browser/resources/settings/settings_page/main_page_mixin.ts +++ b/chrome/browser/resources/settings/settings_page/main_page_mixin.ts
@@ -70,22 +70,6 @@ const superClassBase = BaseMixin(superClass); class MainPageMixin extends superClassBase { - static get properties() { - return { - /** - * Whether a search operation is in progress or previous search - * results are being displayed. - */ - inSearchMode: { - type: Boolean, - value: false, - observer: 'inSearchModeChanged_', - reflectToAttribute: true, - }, - }; - } - - inSearchMode: boolean; scroller: HTMLElement|null = null; private validTransitions_: Map<RouteState, Set<RouteState>>; private lastScrollTop_: number = 0; @@ -139,31 +123,6 @@ return false; } - private inSearchModeChanged_(_current: boolean, previous: boolean) { - if (loadTimeData.getBoolean('enableLandingPageRedesign')) { - // No need to deal with overscroll, as only one section is shown at - // any given time. - return; - } - - // Ignore 1st occurrence which happens while the element is being - // initialized. - if (previous === undefined) { - return; - } - - if (!this.inSearchMode) { - const route = Router.getInstance().getCurrentRoute(); - if (this.containsRoute(route) && - classifyRoute(route) === RouteState.SECTION) { - // Re-fire the showing-section event to trigger settings-main - // recalculation of the overscroll, now that sections are not - // hidden-by-search. - this.fire('showing-section', this.getSection(route.section)); - } - } - } - private shouldExpandAdvanced_(route: Route): boolean { const routes = Router.getInstance().getRoutes() as MinimumRoutes; return this.tagName === 'SETTINGS-BASIC-PAGE' && routes.ADVANCED && @@ -271,15 +230,6 @@ }); } - private scrollToSection_(route: Route) { - this.ensureSectionForRoute_(route).then(section => { - if (!this.inSearchMode) { - this.fire('showing-section', section); - } - this.fire('show-container'); - }); - } - /** * Shows the section(s) corresponding to |newRoute| and hides the * previously |active| section(s), if any. @@ -348,104 +298,6 @@ const newState = transition[1]; assert(this.validTransitions_.get(oldState)!.has(newState)); - loadTimeData.getBoolean('enableLandingPageRedesign') ? - this.processTransitionRedesign_( - oldRoute, newRoute, oldState, newState) : - this.processTransition_(oldRoute, newRoute, oldState, newState); - } - - private processTransition_( - oldRoute: Route|null, newRoute: Route, oldState: RouteState, - newState: RouteState) { - if (oldState === RouteState.TOP_LEVEL) { - if (newState === RouteState.SECTION) { - this.scrollToSection_(newRoute); - } else if (newState === RouteState.SUBPAGE) { - this.enterSubpage_(newRoute); - } - // Nothing to do here for the case of RouteState.DIALOG or - // TOP_LEVEL. The latter happens when navigating from '/?search=foo' - // to '/' (clearing search results). - return; - } - - if (oldState === RouteState.SECTION) { - if (newState === RouteState.SECTION) { - this.scrollToSection_(newRoute); - } else if (newState === RouteState.SUBPAGE) { - this.enterSubpage_(newRoute); - } else if (newState === RouteState.TOP_LEVEL) { - this.scroller!.scrollTop = 0; - } - // Nothing to do here for the case of RouteState.DIALOG. - return; - } - - if (oldState === RouteState.SUBPAGE) { - if (newState === RouteState.SECTION) { - this.enterMainPage_(oldRoute!); - - // Scroll to the corresponding section, only if the user - // explicitly navigated to a section (via the menu). - if (!Router.getInstance().lastRouteChangeWasPopstate()) { - this.scrollToSection_(newRoute); - } - } else if (newState === RouteState.SUBPAGE) { - // Handle case where the two subpages belong to - // different sections, but are linked to each other. For example - // /storage and /accounts (in ChromeOS). - if (!oldRoute!.contains(newRoute) && - !newRoute.contains(oldRoute!)) { - this.enterMainPage_(oldRoute!).then(() => { - this.enterSubpage_(newRoute); - }); - return; - } - - // Handle case of subpage to sub-subpage navigation. - if (oldRoute!.contains(newRoute)) { - this.scroller!.scrollTop = 0; - return; - } - // When going from a sub-subpage to its parent subpage, scroll - // position is automatically restored, because we focus the - // sub-subpage entry point. - } else if (newState === RouteState.TOP_LEVEL) { - this.enterMainPage_(oldRoute!); - } else if (newState === RouteState.DIALOG) { - // The only known case currently for such a transition is from - // /syncSetup to /signOut. - this.enterMainPage_(oldRoute!); - } - return; - } - - if (oldState === RouteState.INITIAL) { - if (newState === RouteState.SECTION) { - this.scrollToSection_(newRoute); - } else if (newState === RouteState.SUBPAGE) { - this.enterSubpage_(newRoute); - } - // Nothing to do here for the case of RouteState.DIALOG and - // TOP_LEVEL. - return; - } - - if (oldState === RouteState.DIALOG) { - if (newState === RouteState.SUBPAGE) { - // The only known case currently for such a transition is from - // /signOut to /syncSetup. - this.enterSubpage_(newRoute); - } - // Nothing to do for all other cases. - } - - // Nothing to do for when oldState === RouteState.DIALOG. - } - - private processTransitionRedesign_( - oldRoute: Route|null, newRoute: Route, oldState: RouteState, - newState: RouteState) { if (oldState === RouteState.TOP_LEVEL) { if (newState === RouteState.SECTION) { this.switchToSections_(newRoute);
diff --git a/chrome/browser/safe_browsing/cloud_content_scanning/binary_upload_service.cc b/chrome/browser/safe_browsing/cloud_content_scanning/binary_upload_service.cc index 2322061..22ebf758 100644 --- a/chrome/browser/safe_browsing/cloud_content_scanning/binary_upload_service.cc +++ b/chrome/browser/safe_browsing/cloud_content_scanning/binary_upload_service.cc
@@ -737,6 +737,9 @@ case enterprise_connectors::BULK_DATA_ENTRY: connector = "OnBulkDataEntry"; break; + case enterprise_connectors::PRINT: + connector = "OnPrint"; + break; case enterprise_connectors::ANALYSIS_CONNECTOR_UNSPECIFIED: break; } @@ -874,7 +877,8 @@ ANALYSIS_CONNECTOR_UNSPECIFIED, enterprise_connectors::AnalysisConnector::FILE_DOWNLOADED, enterprise_connectors::AnalysisConnector::FILE_ATTACHED, - enterprise_connectors::AnalysisConnector::BULK_DATA_ENTRY}) { + enterprise_connectors::AnalysisConnector::BULK_DATA_ENTRY, + enterprise_connectors::AnalysisConnector::PRINT}) { TokenAndConnector token_and_connector = {dm_token, connector}; can_upload_enterprise_data_[token_and_connector] = authorized; }
diff --git a/chrome/browser/safe_browsing/cloud_content_scanning/binary_upload_service_unittest.cc b/chrome/browser/safe_browsing/cloud_content_scanning/binary_upload_service_unittest.cc index 06d04c6..69b11d33 100644 --- a/chrome/browser/safe_browsing/cloud_content_scanning/binary_upload_service_unittest.cc +++ b/chrome/browser/safe_browsing/cloud_content_scanning/binary_upload_service_unittest.cc
@@ -609,7 +609,8 @@ ANALYSIS_CONNECTOR_UNSPECIFIED, enterprise_connectors::AnalysisConnector::BULK_DATA_ENTRY, enterprise_connectors::AnalysisConnector::FILE_ATTACHED, - enterprise_connectors::AnalysisConnector::FILE_DOWNLOADED}) { + enterprise_connectors::AnalysisConnector::FILE_DOWNLOADED, + enterprise_connectors::AnalysisConnector::PRINT}) { service_->IsAuthorized(GURL(), base::BindOnce([](bool authorized) { EXPECT_TRUE(authorized); }),
diff --git a/chrome/browser/safe_browsing/cloud_content_scanning/deep_scanning_browsertest_base.cc b/chrome/browser/safe_browsing/cloud_content_scanning/deep_scanning_browsertest_base.cc index 2882de9..810f67a 100644 --- a/chrome/browser/safe_browsing/cloud_content_scanning/deep_scanning_browsertest_base.cc +++ b/chrome/browser/safe_browsing/cloud_content_scanning/deep_scanning_browsertest_base.cc
@@ -87,6 +87,8 @@ enterprise_connectors::FILE_DOWNLOADED); ClearAnalysisConnector(browser()->profile()->GetPrefs(), enterprise_connectors::BULK_DATA_ENTRY); + ClearAnalysisConnector(browser()->profile()->GetPrefs(), + enterprise_connectors::PRINT); SetOnSecurityEventReporting(browser()->profile()->GetPrefs(), false); }
diff --git a/chrome/browser/safe_browsing/settings_reset_prompt/settings_reset_prompt_model_browsertest_win.cc b/chrome/browser/safe_browsing/settings_reset_prompt/settings_reset_prompt_model_browsertest_win.cc index 4e5d47d6..f4f7d5e4 100644 --- a/chrome/browser/safe_browsing/settings_reset_prompt/settings_reset_prompt_model_browsertest_win.cc +++ b/chrome/browser/safe_browsing/settings_reset_prompt/settings_reset_prompt_model_browsertest_win.cc
@@ -176,9 +176,8 @@ const base::ListValue* url_list = GetPrefs()->GetList(prefs::kURLsToRestoreOnStartup); ASSERT_EQ(url_list->GetList().size(), 1U); - std::string url_text; - ASSERT_TRUE(url_list->GetString(0, &url_text)); - ASSERT_EQ(GURL(url_text), GURL(startup_url)); + ASSERT_TRUE(url_list->GetList()[0].is_string()); + ASSERT_EQ(GURL(url_list->GetList()[0].GetString()), GURL(startup_url)); } void LoadManifest(const std::string& manifest,
diff --git a/chrome/browser/safe_browsing/settings_reset_prompt/settings_reset_prompt_model_unittest.cc b/chrome/browser/safe_browsing/settings_reset_prompt/settings_reset_prompt_model_unittest.cc index 2203d97..4bec3a8 100644 --- a/chrome/browser/safe_browsing/settings_reset_prompt/settings_reset_prompt_model_unittest.cc +++ b/chrome/browser/safe_browsing/settings_reset_prompt/settings_reset_prompt_model_unittest.cc
@@ -14,6 +14,7 @@ #include "base/memory/raw_ptr.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" +#include "build/build_config.h" #include "chrome/browser/extensions/extension_service_test_base.h" #include "chrome/browser/prefs/session_startup_pref.h" #include "chrome/browser/profile_resetter/profile_resetter_test_base.h" @@ -56,9 +57,9 @@ if (!list) return false; - for (size_t i = 0; i < list->GetList().size(); ++i) { - std::string url_text; - if (list->GetString(i, &url_text) && url == url_text) + for (const base::Value& i : list->GetList()) { + const std::string* url_text = i.GetIfString(); + if (url_text && url == *url_text) return true; } return false;
diff --git a/chrome/browser/spellchecker/spellcheck_service_browsertest.cc b/chrome/browser/spellchecker/spellcheck_service_browsertest.cc index 83cda5a..4c03e6e9 100644 --- a/chrome/browser/spellchecker/spellcheck_service_browsertest.cc +++ b/chrome/browser/spellchecker/spellcheck_service_browsertest.cc
@@ -745,6 +745,12 @@ if (!spellcheck::WindowsVersionSupportsSpellchecker()) return; + // This test specifically covers the case where spellcheck delayed + // initialization is not enabled, so return early if it is. Other tests + // cover the case where delayed initialization is enabled. + if (base::FeatureList::IsEnabled(spellcheck::kWinDelaySpellcheckServiceInit)) + return; + ASSERT_TRUE(spellcheck::UseBrowserSpellChecker()); // Note that the base class forces dictionary sync to not be performed, which
diff --git a/chrome/browser/ui/android/autofill/internal/BUILD.gn b/chrome/browser/ui/android/autofill/internal/BUILD.gn index 533010e..2689356f 100644 --- a/chrome/browser/ui/android/autofill/internal/BUILD.gn +++ b/chrome/browser/ui/android/autofill/internal/BUILD.gn
@@ -16,8 +16,12 @@ "java/src/org/chromium/chrome/browser/ui/autofill/AuthenticatorSelectionDialogBridge.java", "java/src/org/chromium/chrome/browser/ui/autofill/AutofillErrorDialogBridge.java", "java/src/org/chromium/chrome/browser/ui/autofill/AutofillProgressDialogBridge.java", - "java/src/org/chromium/chrome/browser/ui/autofill/OtpVerificationDialog.java", "java/src/org/chromium/chrome/browser/ui/autofill/OtpVerificationDialogBridge.java", + "java/src/org/chromium/chrome/browser/ui/autofill/OtpVerificationDialogCoordinator.java", + "java/src/org/chromium/chrome/browser/ui/autofill/OtpVerificationDialogMediator.java", + "java/src/org/chromium/chrome/browser/ui/autofill/OtpVerificationDialogProperties.java", + "java/src/org/chromium/chrome/browser/ui/autofill/OtpVerificationDialogView.java", + "java/src/org/chromium/chrome/browser/ui/autofill/OtpVerificationDialogViewBinder.java", "java/src/org/chromium/chrome/browser/ui/autofill/data/AuthenticatorOption.java", "java/src/org/chromium/chrome/browser/ui/autofill/data/CardUnmaskChallengeOptionType.java", ]
diff --git a/chrome/browser/ui/android/autofill/internal/java/res/layout/otp_verification_dialog.xml b/chrome/browser/ui/android/autofill/internal/java/res/layout/otp_verification_dialog.xml index 819ca06..7b4a8a0 100644 --- a/chrome/browser/ui/android/autofill/internal/java/res/layout/otp_verification_dialog.xml +++ b/chrome/browser/ui/android/autofill/internal/java/res/layout/otp_verification_dialog.xml
@@ -2,7 +2,7 @@ <!-- Copyright 2021 The Chromium Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. --> -<RelativeLayout +<org.chromium.chrome.browser.ui.autofill.OtpVerificationDialogView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"> @@ -44,4 +44,4 @@ android:layout_height="wrap_content" android:layout_width="wrap_content" android:visibility="gone"/> -</RelativeLayout> +</org.chromium.chrome.browser.ui.autofill.OtpVerificationDialogView>
diff --git a/chrome/browser/ui/android/autofill/internal/java/src/org/chromium/chrome/browser/ui/autofill/OtpVerificationDialog.java b/chrome/browser/ui/android/autofill/internal/java/src/org/chromium/chrome/browser/ui/autofill/OtpVerificationDialog.java deleted file mode 100644 index fd1d95f..0000000 --- a/chrome/browser/ui/android/autofill/internal/java/src/org/chromium/chrome/browser/ui/autofill/OtpVerificationDialog.java +++ /dev/null
@@ -1,199 +0,0 @@ -// Copyright 2021 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package org.chromium.chrome.browser.ui.autofill; -import android.content.Context; -import android.os.Handler; -import android.text.Editable; -import android.text.SpannableString; -import android.text.TextWatcher; -import android.text.method.LinkMovementMethod; -import android.view.LayoutInflater; -import android.view.View; -import android.widget.EditText; -import android.widget.TextView; - -import androidx.core.content.res.ResourcesCompat; - -import org.chromium.chrome.browser.ui.autofill.internal.R; -import org.chromium.ui.modaldialog.DialogDismissalCause; -import org.chromium.ui.modaldialog.ModalDialogManager; -import org.chromium.ui.modaldialog.ModalDialogProperties; -import org.chromium.ui.modelutil.PropertyModel; -import org.chromium.ui.text.NoUnderlineClickableSpan; -import org.chromium.ui.text.SpanApplier; -import org.chromium.ui.text.SpanApplier.SpanInfo; - -/** Dialog shown to the user for credit card unmasking using OTP-based verification. */ -public class OtpVerificationDialog { - private static final int ANIMATION_DURATION_MS = 250; - - /** Interface for the caller to be notified of user actions. */ - public interface Listener { - /** - * Notify that the user clicked on the positive button after entering the otp. - * - * @param otp The OTP entered by the user. - */ - void onConfirm(String otp); - /** Notify that a new otp was requested by the user. */ - void onNewOtpRequested(); - /** Notify the caller that the dialog was dismissed. */ - void onDialogDismissed(); - } - - private final ModalDialogProperties.Controller mModalDialogController = - new ModalDialogProperties.Controller() { - @Override - public void onClick(PropertyModel model, int buttonType) { - switch (buttonType) { - case ModalDialogProperties.ButtonType.POSITIVE: - mListener.onConfirm(mOtpEditText.getText().toString()); - showProgressBarOverlay(); - break; - case ModalDialogProperties.ButtonType.NEGATIVE: - mModalDialogManager.dismissDialog( - model, DialogDismissalCause.NEGATIVE_BUTTON_CLICKED); - break; - } - } - - @Override - public void onDismiss(PropertyModel model, int dismissalCause) { - mListener.onDialogDismissed(); - } - }; - - private TextWatcher mOtpTextWatcher = new TextWatcher() { - @Override - public void onTextChanged(CharSequence s, int start, int before, int count) { - // Hide the error message view if it is visible, as the user is editing the OTP. - mOtpErrorMessageTextView.setVisibility(View.GONE); - // Disable the positive button if the length of the text is not equal to the OTP length. - mDialogModel.set( - ModalDialogProperties.POSITIVE_BUTTON_DISABLED, s.length() != mOtpLength); - } - @Override - public void beforeTextChanged(CharSequence s, int start, int count, int after) {} - - @Override - public void afterTextChanged(Editable s) {} - }; - - private final Context mContext; - private final Listener mListener; - private final ModalDialogManager mModalDialogManager; - private View mProgressBarOverlayView; - private View mOtpVerificationDialogContents; - private EditText mOtpEditText; - private TextView mOtpErrorMessageTextView; - private TextView mOtpResendMessageTextView; - private PropertyModel mDialogModel; - private int mOtpLength; - - public OtpVerificationDialog( - Context context, Listener listener, ModalDialogManager modalDialogManager) { - this.mContext = context; - this.mListener = listener; - this.mModalDialogManager = modalDialogManager; - } - - /** - * Show the OtpVerification dialog. - * - * @param otpLength The expected length of the OTP input field. - */ - public void show(int otpLength) { - mOtpLength = otpLength; - View view = LayoutInflater.from(mContext).inflate(R.layout.otp_verification_dialog, null); - mOtpEditText = view.findViewById(R.id.otp_input); - mOtpErrorMessageTextView = view.findViewById(R.id.otp_error_message); - mOtpResendMessageTextView = view.findViewById(R.id.otp_resend_message); - mOtpVerificationDialogContents = view.findViewById(R.id.otp_verification_dialog_contents); - mProgressBarOverlayView = view.findViewById(R.id.progress_bar_overlay); - - mOtpEditText.setHint(mContext.getResources().getString( - R.string.autofill_payments_otp_verification_dialog_otp_input_hint, otpLength)); - mOtpEditText.addTextChangedListener(mOtpTextWatcher); - mOtpErrorMessageTextView.setVisibility(View.GONE); - - mOtpResendMessageTextView.setText(getOtpResendMessage()); - mOtpResendMessageTextView.setMovementMethod(LinkMovementMethod.getInstance()); - - mDialogModel = buildDialogModel(view); - mModalDialogManager.showDialog(mDialogModel, ModalDialogManager.ModalDialogType.TAB); - } - - private PropertyModel buildDialogModel(View customView) { - return new PropertyModel.Builder(ModalDialogProperties.ALL_KEYS) - .with(ModalDialogProperties.CONTROLLER, mModalDialogController) - .with(ModalDialogProperties.CUSTOM_VIEW, customView) - .with(ModalDialogProperties.TITLE, - mContext.getResources().getString( - R.string.autofill_payments_otp_verification_dialog_title)) - .with(ModalDialogProperties.TITLE_ICON, - ResourcesCompat.getDrawable(mContext.getResources(), - R.drawable.google_pay_with_divider, mContext.getTheme())) - .with(ModalDialogProperties.NEGATIVE_BUTTON_TEXT, - mContext.getResources().getString( - R.string.autofill_payments_otp_verification_dialog_negative_button_label)) - .with(ModalDialogProperties.POSITIVE_BUTTON_TEXT, - mContext.getResources().getString( - R.string.autofill_payments_otp_verification_dialog_positive_button_label)) - .with(ModalDialogProperties.POSITIVE_BUTTON_DISABLED, true) - .build(); - } - - private SpannableString getOtpResendMessage() { - return SpanApplier.applySpans( - mContext.getResources().getString( - R.string.autofill_payments_otp_verification_dialog_cant_find_code_message), - new SpanInfo("<link>", "</link>", - new NoUnderlineClickableSpan(mContext.getResources(), textView -> { - mOtpEditText.getText().clear(); - mListener.onNewOtpRequested(); - }))); - } - - /** Show an error message for the submitted otp. */ - public void showOtpErrorMessage(String errorMessage) { - hideProgressBarOverlay(); - mOtpErrorMessageTextView.setVisibility(View.VISIBLE); - mOtpErrorMessageTextView.setText(errorMessage); - mDialogModel.set(ModalDialogProperties.POSITIVE_BUTTON_DISABLED, true); - } - - /** Dismiss the dialog if is already showing. */ - public void dismissDialog() { - mModalDialogManager.dismissDialog(mDialogModel, DialogDismissalCause.DISMISSED_BY_NATIVE); - } - - /** Show confirmation message */ - public void showConfirmationAndDismissDialog(String confirmationMessage) { - if (mProgressBarOverlayView != null) { - mProgressBarOverlayView.findViewById(R.id.progress_bar).setVisibility(View.GONE); - mProgressBarOverlayView.findViewById(R.id.confirmation_icon) - .setVisibility(View.VISIBLE); - ((TextView) mProgressBarOverlayView.findViewById(R.id.progress_bar_message)) - .setText(confirmationMessage); - } - Runnable dismissRunnable = () -> dismissDialog(); - new Handler().postDelayed(dismissRunnable, ANIMATION_DURATION_MS); - } - - private void showProgressBarOverlay() { - mProgressBarOverlayView.setVisibility(View.VISIBLE); - mProgressBarOverlayView.setAlpha(0f); - mProgressBarOverlayView.animate().alpha(1f).setDuration(ANIMATION_DURATION_MS); - mOtpVerificationDialogContents.animate().alpha(0f).setDuration(ANIMATION_DURATION_MS); - mDialogModel.set(ModalDialogProperties.POSITIVE_BUTTON_DISABLED, true); - } - - private void hideProgressBarOverlay() { - mProgressBarOverlayView.setVisibility(View.GONE); - mProgressBarOverlayView.animate().alpha(0f).setDuration(ANIMATION_DURATION_MS); - mOtpVerificationDialogContents.animate().alpha(1f).setDuration(ANIMATION_DURATION_MS); - mDialogModel.set(ModalDialogProperties.POSITIVE_BUTTON_DISABLED, false); - } -}
diff --git a/chrome/browser/ui/android/autofill/internal/java/src/org/chromium/chrome/browser/ui/autofill/OtpVerificationDialogBridge.java b/chrome/browser/ui/android/autofill/internal/java/src/org/chromium/chrome/browser/ui/autofill/OtpVerificationDialogBridge.java index 55cab10..5305554e 100644 --- a/chrome/browser/ui/android/autofill/internal/java/src/org/chromium/chrome/browser/ui/autofill/OtpVerificationDialogBridge.java +++ b/chrome/browser/ui/android/autofill/internal/java/src/org/chromium/chrome/browser/ui/autofill/OtpVerificationDialogBridge.java
@@ -5,8 +5,10 @@ package org.chromium.chrome.browser.ui.autofill; import android.content.Context; +import android.os.Build.VERSION_CODES; import androidx.annotation.Nullable; +import androidx.annotation.RequiresApi; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; @@ -15,21 +17,39 @@ import org.chromium.ui.modaldialog.ModalDialogManager; /** - * JNI glue for the {@link OtpVerificationDialog}. This allows the native code to show/dismiss the - * OTP verification dialog and also show an error message when OTP verification fails. + * JNI glue for the {@link OtpVerificationDialogView}. This allows the native code to show/dismiss + * the OTP verification dialog and also show an error message when OTP verification fails. */ @JNINamespace("autofill") -public class OtpVerificationDialogBridge implements OtpVerificationDialog.Listener { +class OtpVerificationDialogBridge implements OtpVerificationDialogCoordinator.Delegate { private final long mNativeOtpVerificationDialogView; - private final Context mContext; - private final ModalDialogManager mModalDialogManager; - private OtpVerificationDialog mOtpVerificationDialog; + private OtpVerificationDialogCoordinator mDialogCoordinator; - public OtpVerificationDialogBridge(long nativeOtpVerificationDialogView, Context context, + OtpVerificationDialogBridge(long nativeOtpVerificationDialogView, Context context, ModalDialogManager modalDialogManager) { this.mNativeOtpVerificationDialogView = nativeOtpVerificationDialogView; - this.mModalDialogManager = modalDialogManager; - this.mContext = context; + mDialogCoordinator = + OtpVerificationDialogCoordinator.create(context, modalDialogManager, this); + } + + /** + * Create an instance of the {@link OtpVerificationDialogBridge} that can be used by the native + * code to call different actions on. + * + * @param nativeOtpVerificationDialogView The pointer to the native object. + * @param windowAndroid The current {@link WindowAndroid} object. + */ + @CalledByNative + @Nullable + static OtpVerificationDialogBridge create( + long nativeOtpVerificationDialogView, WindowAndroid windowAndroid) { + Context context = windowAndroid.getActivity().get(); + ModalDialogManager modalDialogManager = windowAndroid.getModalDialogManager(); + if (context == null || modalDialogManager == null) { + return null; + } + return new OtpVerificationDialogBridge( + nativeOtpVerificationDialogView, context, modalDialogManager); } @Override @@ -48,36 +68,15 @@ } /** - * Create an instance of the {@link OtpVerificationDialogBridge} that can be used by the native - * code to call different actions on. - * - * @param nativeOtpVerificationDialogView The pointer to the native object. - * @param windowAndroid The current {@link WindowAndroid} object. - * @return - */ - @CalledByNative - @Nullable - public static OtpVerificationDialogBridge create( - long nativeOtpVerificationDialogView, WindowAndroid windowAndroid) { - Context context = windowAndroid.getActivity().get(); - ModalDialogManager modalDialogManager = windowAndroid.getModalDialogManager(); - if (context == null || modalDialogManager == null) { - return null; - } - return new OtpVerificationDialogBridge( - nativeOtpVerificationDialogView, context, modalDialogManager); - } - - /** * Show the OTP verification dialog to allow the user to input an OTP. * * @param otpLength The expected length of the OTP. This is used for showing a hint in the input * field as well as some basic error handling. */ + @RequiresApi(api = VERSION_CODES.N) @CalledByNative - public void showDialog(int otpLength) { - mOtpVerificationDialog = new OtpVerificationDialog(mContext, this, mModalDialogManager); - mOtpVerificationDialog.show(otpLength); + void showDialog(int otpLength) { + mDialogCoordinator.show(otpLength); } /** @@ -85,22 +84,23 @@ * * @param errorMessage The error message to be displayed below the OTP input field. */ + @RequiresApi(api = VERSION_CODES.N) @CalledByNative - public void showOtpErrorMessage(String errorMessage) { - mOtpVerificationDialog.showOtpErrorMessage(errorMessage); + void showOtpErrorMessage(String errorMessage) { + mDialogCoordinator.showOtpErrorMessage(errorMessage); } /** * Dismiss the dialog if it is already showing. */ @CalledByNative - public void dismissDialog() { - mOtpVerificationDialog.dismissDialog(); + void dismissDialog() { + mDialogCoordinator.dismissDialog(); } @CalledByNative - public void showConfirmationAndDismissDialog(String confirmationMessage) { - mOtpVerificationDialog.showConfirmationAndDismissDialog(confirmationMessage); + void showConfirmationAndDismissDialog(String confirmationMessage) { + mDialogCoordinator.showConfirmationAndDismissDialog(confirmationMessage); } @NativeMethods
diff --git a/chrome/browser/ui/android/autofill/internal/java/src/org/chromium/chrome/browser/ui/autofill/OtpVerificationDialogCoordinator.java b/chrome/browser/ui/android/autofill/internal/java/src/org/chromium/chrome/browser/ui/autofill/OtpVerificationDialogCoordinator.java new file mode 100644 index 0000000..ae01c2499 --- /dev/null +++ b/chrome/browser/ui/android/autofill/internal/java/src/org/chromium/chrome/browser/ui/autofill/OtpVerificationDialogCoordinator.java
@@ -0,0 +1,169 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.ui.autofill; + +import static org.chromium.chrome.browser.ui.autofill.OtpVerificationDialogProperties.ALL_KEYS; +import static org.chromium.chrome.browser.ui.autofill.OtpVerificationDialogProperties.EDIT_TEXT_HINT; +import static org.chromium.chrome.browser.ui.autofill.OtpVerificationDialogProperties.OTP_LENGTH; + +import android.content.Context; +import android.os.Build.VERSION_CODES; +import android.view.LayoutInflater; +import android.view.View; + +import androidx.annotation.RequiresApi; +import androidx.annotation.VisibleForTesting; +import androidx.core.content.res.ResourcesCompat; + +import org.chromium.chrome.browser.ui.autofill.internal.R; +import org.chromium.ui.modaldialog.ModalDialogManager; +import org.chromium.ui.modaldialog.ModalDialogProperties; +import org.chromium.ui.modelutil.PropertyModel; +import org.chromium.ui.modelutil.PropertyModelChangeProcessor; + +import java.util.Optional; + +/** The coordinator for the OTP Verification Dialog. Manages the sub-component objects. **/ +class OtpVerificationDialogCoordinator { + /** Interface for the caller to be notified of user actions. */ + interface Delegate { + /** + * Notify that the user clicked on the positive button after entering the otp. + * + * @param otp The OTP entered by the user. + */ + void onConfirm(String otp); + /** Notify that a new otp was requested by the user. */ + void onNewOtpRequested(); + /** Notify the caller that the dialog was dismissed. */ + void onDialogDismissed(); + } + + private final OtpVerificationDialogMediator mMediator; + private final Context mContext; + private final OtpVerificationDialogView mDialogView; + + /** + * Creates the {@link OtpVerificationDialogCoordinator}. + * + * @param context The context of the window where the dialog will be displayed. + * @param modalDialogManager The modal dialog manager of the window where the dialog will be + * displayed. + * @param delegate The delegate to be called with results of interaction. + */ + static OtpVerificationDialogCoordinator create( + Context context, ModalDialogManager modalDialogManager, Delegate delegate) { + OtpVerificationDialogView otpVerificationDialogView = + (OtpVerificationDialogView) LayoutInflater.from(context).inflate( + org.chromium.chrome.browser.ui.autofill.internal.R.layout + .otp_verification_dialog, + null); + return new OtpVerificationDialogCoordinator( + context, modalDialogManager, otpVerificationDialogView, delegate); + } + + /** + * Internal constructor for {@link OtpVerificationDialogCoordinator}. Used by tests to inject + * parameters. External code should use OtpVerificationDialogCoordinator#create. + * + * @param context The context for accessing resources. + * @param modalDialogManager The ModalDialogManager to display the dialog. + * @param dialogView The custom view with dialog content. + * @param delegate The delegate to be called with results of interaction. + */ + @VisibleForTesting + OtpVerificationDialogCoordinator(Context context, ModalDialogManager modalDialogManager, + OtpVerificationDialogView dialogView, Delegate delegate) { + mContext = context; + mDialogView = dialogView; + mMediator = new OtpVerificationDialogMediator( + modalDialogManager, getModalDialogModelBuilder(dialogView), delegate); + } + + /** + * Show the OtpVerification dialog. + * + * @param otpLength The expected length of the OTP input field. + */ + @RequiresApi(api = VERSION_CODES.N) + void show(int otpLength) { + PropertyModel otpVerificationDialogModel = buildOtpVerificationDialogModel(otpLength); + PropertyModelChangeProcessor.create( + otpVerificationDialogModel, mDialogView, OtpVerificationDialogViewBinder::bind); + mMediator.show(otpVerificationDialogModel); + } + + /** + * Show an error message for the submitted otp. + * + * @param errorMessage The string that is displayed in the error message. + */ + @RequiresApi(api = VERSION_CODES.N) + void showOtpErrorMessage(String errorMessage) { + mMediator.showOtpErrorMessage(Optional.of(errorMessage)); + } + + /** Dismiss the dialog if it is already showing. */ + void dismissDialog() { + mMediator.dismissDialog(); + } + + /** + * Show the confirmation message and dismiss the dialog. This is called once we receive a + * successful server response when the user enters an OTP into the edit text field and clicks + * accept. + * + * @param confirmationMessage The confirmation message to be shown. + */ + void showConfirmationAndDismissDialog(String confirmationMessage) { + mMediator.showConfirmationAndDismissDialog(confirmationMessage); + } + + /** + * Builds the dialog view model. + * + * @param otpLength The only non-static state of the dialog, needs to be passed in so that it + * can be added to the model. + */ + @RequiresApi(api = VERSION_CODES.N) + private PropertyModel buildOtpVerificationDialogModel(int otpLength) { + return new PropertyModel.Builder(ALL_KEYS) + .with(OTP_LENGTH, otpLength) + .with(EDIT_TEXT_HINT, + mContext.getResources().getString( + R.string.autofill_payments_otp_verification_dialog_otp_input_hint, + otpLength)) + .build(); + } + + /** + * Gets the dialog model builder. {@link OtpVerificationDialogMediator} implements the + * controller, so the final model will be finished being built in the Mediator. + * + * @param customView The view for the dialog model. + */ + private PropertyModel.Builder getModalDialogModelBuilder(View customView) { + return new PropertyModel.Builder(ModalDialogProperties.ALL_KEYS) + .with(ModalDialogProperties.CUSTOM_VIEW, customView) + .with(ModalDialogProperties.TITLE, + mContext.getResources().getString( + org.chromium.chrome.browser.ui.autofill.internal.R.string + .autofill_payments_otp_verification_dialog_title)) + .with(ModalDialogProperties.TITLE_ICON, + ResourcesCompat.getDrawable(mContext.getResources(), + org.chromium.chrome.browser.ui.autofill.internal.R.drawable + .google_pay_with_divider, + mContext.getTheme())) + .with(ModalDialogProperties.NEGATIVE_BUTTON_TEXT, + mContext.getResources().getString( + org.chromium.chrome.browser.ui.autofill.internal.R.string + .autofill_payments_otp_verification_dialog_negative_button_label)) + .with(ModalDialogProperties.POSITIVE_BUTTON_TEXT, + mContext.getResources().getString( + org.chromium.chrome.browser.ui.autofill.internal.R.string + .autofill_payments_otp_verification_dialog_positive_button_label)) + .with(ModalDialogProperties.POSITIVE_BUTTON_DISABLED, true); + } +}
diff --git a/chrome/browser/ui/android/autofill/internal/java/src/org/chromium/chrome/browser/ui/autofill/OtpVerificationDialogMediator.java b/chrome/browser/ui/android/autofill/internal/java/src/org/chromium/chrome/browser/ui/autofill/OtpVerificationDialogMediator.java new file mode 100644 index 0000000..cd88be4 --- /dev/null +++ b/chrome/browser/ui/android/autofill/internal/java/src/org/chromium/chrome/browser/ui/autofill/OtpVerificationDialogMediator.java
@@ -0,0 +1,143 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.ui.autofill; + +import static org.chromium.chrome.browser.ui.autofill.OtpVerificationDialogProperties.DELAY_BETWEEN_CONFIRMATION_SHOWN_AND_DISMISSAL_MS; +import static org.chromium.chrome.browser.ui.autofill.OtpVerificationDialogProperties.EDIT_TEXT; +import static org.chromium.chrome.browser.ui.autofill.OtpVerificationDialogProperties.OTP_ERROR_MESSAGE; +import static org.chromium.chrome.browser.ui.autofill.OtpVerificationDialogProperties.OTP_LENGTH; +import static org.chromium.chrome.browser.ui.autofill.OtpVerificationDialogProperties.SHOW_CONFIRMATION; +import static org.chromium.chrome.browser.ui.autofill.OtpVerificationDialogProperties.SHOW_PROGRESS_BAR_OVERLAY; +import static org.chromium.chrome.browser.ui.autofill.OtpVerificationDialogProperties.VIEW_DELEGATE; + +import android.os.Build.VERSION_CODES; +import android.os.Handler; + +import androidx.annotation.RequiresApi; + +import org.chromium.chrome.browser.ui.autofill.OtpVerificationDialogCoordinator.Delegate; +import org.chromium.ui.modaldialog.DialogDismissalCause; +import org.chromium.ui.modaldialog.ModalDialogManager; +import org.chromium.ui.modaldialog.ModalDialogProperties; +import org.chromium.ui.modelutil.PropertyModel; + +import java.util.Optional; + +class OtpVerificationDialogMediator + implements ModalDialogProperties.Controller, OtpVerificationDialogProperties.ViewDelegate { + private final ModalDialogManager mModalDialogManager; + private PropertyModel mModalDialogModel; + private Delegate mDelegate; + private PropertyModel mOtpVerificationDialogModel; + + OtpVerificationDialogMediator(ModalDialogManager modalDialogManager, + PropertyModel.Builder dialogModelBuilder, Delegate delegate) { + mModalDialogManager = modalDialogManager; + mModalDialogModel = dialogModelBuilder.with(ModalDialogProperties.CONTROLLER, this).build(); + mDelegate = delegate; + } + + @Override + public void onDismiss(PropertyModel model, int dismissalCause) { + mDelegate.onDialogDismissed(); + } + + @RequiresApi(api = VERSION_CODES.N) + @Override + public void onClick(PropertyModel model, int buttonType) { + switch (buttonType) { + case ModalDialogProperties.ButtonType.POSITIVE: + Optional<CharSequence> editTextOptional = + mOtpVerificationDialogModel.get(EDIT_TEXT); + // Safety check, this should always be true. + if (editTextOptional.isPresent()) { + showProgressBarOverlay(); + mDelegate.onConfirm(editTextOptional.get().toString()); + } + break; + case ModalDialogProperties.ButtonType.NEGATIVE: + mModalDialogManager.dismissDialog( + model, DialogDismissalCause.NEGATIVE_BUTTON_CLICKED); + break; + } + } + + @RequiresApi(api = VERSION_CODES.N) + @Override + public void onTextChanged(CharSequence s) { + mModalDialogModel.set(ModalDialogProperties.POSITIVE_BUTTON_DISABLED, + s.length() != mOtpVerificationDialogModel.get(OTP_LENGTH)); + mOtpVerificationDialogModel.set(OTP_ERROR_MESSAGE, Optional.empty()); + mOtpVerificationDialogModel.set(EDIT_TEXT, Optional.of(s)); + } + + @RequiresApi(api = VERSION_CODES.N) + @Override + public void onResendLinkClicked() { + clearEditText(); + onNewOtpRequested(); + } + + /** + * Show the OtpVerification dialog. + * + * @param dialogViewModel The model for the dialog view. + */ + void show(PropertyModel dialogViewModel) { + setDialogViewModel(dialogViewModel); + mModalDialogManager.showDialog(mModalDialogModel, ModalDialogManager.ModalDialogType.TAB); + } + + /** Dismiss the dialog if is already showing. */ + void dismissDialog() { + mModalDialogManager.dismissDialog( + mModalDialogModel, DialogDismissalCause.DISMISSED_BY_NATIVE); + } + + /** Clear the text in the Edit Text field. */ + @RequiresApi(api = VERSION_CODES.N) + void clearEditText() { + mOtpVerificationDialogModel.set(EDIT_TEXT, Optional.empty()); + } + + /** + * Shows the progress bar overlay for the dialog. This method is called once the users clicks + * the accept button. + */ + void showProgressBarOverlay() { + mOtpVerificationDialogModel.set(SHOW_PROGRESS_BAR_OVERLAY, true); + mModalDialogModel.set(ModalDialogProperties.POSITIVE_BUTTON_DISABLED, true); + } + + /** Show an error message for the submitted otp. */ + @RequiresApi(api = VERSION_CODES.N) + void showOtpErrorMessage(Optional<String> errorMessage) { + mOtpVerificationDialogModel.set(SHOW_PROGRESS_BAR_OVERLAY, false); + mOtpVerificationDialogModel.set(OTP_ERROR_MESSAGE, errorMessage); + mModalDialogModel.set(ModalDialogProperties.POSITIVE_BUTTON_DISABLED, true); + } + + /** + * Shows the confirmation message and dismisses the dialog. This method is called when the + * server returns a success response after the user clicked the accept button. + * + * @param confirmationMessage The confirmation message that gets shown on successful server + * response. + */ + void showConfirmationAndDismissDialog(String confirmationMessage) { + mOtpVerificationDialogModel.set(SHOW_CONFIRMATION, confirmationMessage); + new Handler().postDelayed( + this::dismissDialog, DELAY_BETWEEN_CONFIRMATION_SHOWN_AND_DISMISSAL_MS); + } + + void onNewOtpRequested() { + mDelegate.onNewOtpRequested(); + } + + private void setDialogViewModel(PropertyModel dialogViewModel) { + mOtpVerificationDialogModel = dialogViewModel; + mOtpVerificationDialogModel.set(VIEW_DELEGATE, this); + } +}
diff --git a/chrome/browser/ui/android/autofill/internal/java/src/org/chromium/chrome/browser/ui/autofill/OtpVerificationDialogProperties.java b/chrome/browser/ui/android/autofill/internal/java/src/org/chromium/chrome/browser/ui/autofill/OtpVerificationDialogProperties.java new file mode 100644 index 0000000..7f5e23a --- /dev/null +++ b/chrome/browser/ui/android/autofill/internal/java/src/org/chromium/chrome/browser/ui/autofill/OtpVerificationDialogProperties.java
@@ -0,0 +1,62 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.ui.autofill; + +import org.chromium.ui.modelutil.PropertyKey; +import org.chromium.ui.modelutil.PropertyModel.ReadableIntPropertyKey; +import org.chromium.ui.modelutil.PropertyModel.ReadableObjectPropertyKey; +import org.chromium.ui.modelutil.PropertyModel.WritableBooleanPropertyKey; +import org.chromium.ui.modelutil.PropertyModel.WritableObjectPropertyKey; + +import java.util.Optional; + +class OtpVerificationDialogProperties { + /** Interface for the mediator to be notified of view actions. */ + interface ViewDelegate { + /** + * Notifies the mediator of a text changed event in the edit text field. + * + * @param s The current text in the edit text field. + */ + void onTextChanged(CharSequence s); + /** + * Notifies the mediator that the resend link was clicked. + */ + void onResendLinkClicked(); + } + + static final int ANIMATION_DURATION_MS = 250; + static final int DELAY_BETWEEN_CONFIRMATION_SHOWN_AND_DISMISSAL_MS = 250; + + static final ReadableIntPropertyKey OTP_LENGTH = new ReadableIntPropertyKey(); + + static final ReadableObjectPropertyKey<String> EDIT_TEXT_HINT = + new ReadableObjectPropertyKey<>(); + + static final WritableObjectPropertyKey<ViewDelegate> VIEW_DELEGATE = + new WritableObjectPropertyKey<>(); + + // |EDIT_TEXT| is a one-to-one mapping of the edit text on the dialog. Empty |EDIT_TEXT| + // indicates that there should be no edit text shown on the dialog, while + // |OTP_ERROR_MESSAGE| with a value indicates that value should be displayed on the dialog. + static final WritableObjectPropertyKey<Optional<CharSequence>> EDIT_TEXT = + new WritableObjectPropertyKey<>(); + + // |OTP_ERROR_MESSAGE| is a one-to-one mapping of the error message on the dialog. Empty + // |OTP_ERROR_MESSAGE| indicates that there should be no error message shown on the dialog, + // while |OTP_ERROR_MESSAGE| with a value indicates that value should be displayed on the + // dialog. + static final WritableObjectPropertyKey<Optional<String>> OTP_ERROR_MESSAGE = + new WritableObjectPropertyKey<>(); + + static final WritableObjectPropertyKey<String> SHOW_CONFIRMATION = + new WritableObjectPropertyKey<>(); + + static final WritableBooleanPropertyKey SHOW_PROGRESS_BAR_OVERLAY = + new WritableBooleanPropertyKey(); + + static final PropertyKey[] ALL_KEYS = {OTP_LENGTH, EDIT_TEXT, EDIT_TEXT_HINT, VIEW_DELEGATE, + OTP_ERROR_MESSAGE, SHOW_CONFIRMATION, SHOW_PROGRESS_BAR_OVERLAY}; +}
diff --git a/chrome/browser/ui/android/autofill/internal/java/src/org/chromium/chrome/browser/ui/autofill/OtpVerificationDialogTest.java b/chrome/browser/ui/android/autofill/internal/java/src/org/chromium/chrome/browser/ui/autofill/OtpVerificationDialogTest.java index 56c505d..865a2520 100644 --- a/chrome/browser/ui/android/autofill/internal/java/src/org/chromium/chrome/browser/ui/autofill/OtpVerificationDialogTest.java +++ b/chrome/browser/ui/android/autofill/internal/java/src/org/chromium/chrome/browser/ui/autofill/OtpVerificationDialogTest.java
@@ -10,6 +10,7 @@ import android.text.SpannableString; import android.text.style.ClickableSpan; +import android.view.LayoutInflater; import android.view.View; import android.widget.EditText; import android.widget.TextView; @@ -30,19 +31,23 @@ import org.chromium.ui.modaldialog.ModalDialogProperties; import org.chromium.ui.modelutil.PropertyModel; +import java.util.Optional; + /** - * Unit tests for {@link OtpVerificationDialog}. + * Unit tests for {@link OtpVerificationDialogView}. */ @RunWith(BaseRobolectricTestRunner.class) public class OtpVerificationDialogTest { private static final String ERROR_MESSAGE = "Error message"; private static final String VALID_OTP = "123456"; - private OtpVerificationDialog mOtpVerificationDialog; + private OtpVerificationDialogView mOtpVerificationDialogView; private FakeModalDialogManager mModalDialogManager; + private OtpVerificationDialogCoordinator mOtpVerificationDialogCoordinator; @Mock - private OtpVerificationDialog.Listener mListener; + private OtpVerificationDialogCoordinator.Delegate mDelegate; + private class FakeModalDialogManager extends ModalDialogManager { private PropertyModel mShownDialogModel; @@ -75,15 +80,19 @@ public void setUp() { MockitoAnnotations.initMocks(this); mModalDialogManager = new FakeModalDialogManager(); - mOtpVerificationDialog = new OtpVerificationDialog( - ApplicationProvider.getApplicationContext(), mListener, mModalDialogManager); + mOtpVerificationDialogView = (OtpVerificationDialogView) LayoutInflater + .from(ApplicationProvider.getApplicationContext()) + .inflate(R.layout.otp_verification_dialog, null); + mOtpVerificationDialogCoordinator = + new OtpVerificationDialogCoordinator(ApplicationProvider.getApplicationContext(), + mModalDialogManager, mOtpVerificationDialogView, mDelegate); } @Test public void testDefaultState() { int otpLength = 6; - mOtpVerificationDialog.show(otpLength); + mOtpVerificationDialogCoordinator.show(otpLength); PropertyModel model = mModalDialogManager.getShownDialogModel(); View view = model.get(ModalDialogProperties.CUSTOM_VIEW); @@ -101,9 +110,8 @@ @Test public void testShowHideErrorMessage() { - mOtpVerificationDialog.show(/*otpLength= */ 6); - - mOtpVerificationDialog.showOtpErrorMessage(ERROR_MESSAGE); + mOtpVerificationDialogCoordinator.show(/*otpLength=*/6); + mOtpVerificationDialogView.showOtpErrorMessage(Optional.of(ERROR_MESSAGE)); PropertyModel model = mModalDialogManager.getShownDialogModel(); View view = model.get(ModalDialogProperties.CUSTOM_VIEW); @@ -120,7 +128,7 @@ @Test public void testPositiveButtonDisabledState() { - mOtpVerificationDialog.show(/*otpLength= */ 6); + mOtpVerificationDialogCoordinator.show(/*otpLength=*/6); PropertyModel model = mModalDialogManager.getShownDialogModel(); View view = model.get(ModalDialogProperties.CUSTOM_VIEW); @@ -141,7 +149,7 @@ @Test public void testOtpSubmission() { - mOtpVerificationDialog.show(/*otpLength= */ 6); + mOtpVerificationDialogCoordinator.show(/*otpLength=*/6); PropertyModel model = mModalDialogManager.getShownDialogModel(); View view = model.get(ModalDialogProperties.CUSTOM_VIEW); EditText otpInputEditText = (EditText) view.findViewById(R.id.otp_input); @@ -150,7 +158,7 @@ mModalDialogManager.clickPositiveButton(); // Verify that the listener is called with the text entered in the OTP input field. - verify(mListener, times(1)).onConfirm(VALID_OTP); + verify(mDelegate, times(1)).onConfirm(VALID_OTP); // Verify that the progress bar is shown. assertThat(view.findViewById(R.id.progress_bar_overlay).getVisibility()) .isEqualTo(View.VISIBLE); @@ -158,7 +166,7 @@ @Test public void testGetNewCode() { - mOtpVerificationDialog.show(/*otpLength= */ 6); + mOtpVerificationDialogCoordinator.show(/*otpLength=*/6); PropertyModel model = mModalDialogManager.getShownDialogModel(); View view = model.get(ModalDialogProperties.CUSTOM_VIEW); TextView otpResendMessageTextView = (TextView) view.findViewById(R.id.otp_resend_message); @@ -168,16 +176,16 @@ getNewCodeSpan.onClick(otpResendMessageTextView); - verify(mListener, times(1)).onNewOtpRequested(); + verify(mDelegate, times(1)).onNewOtpRequested(); } @Test public void testDialogDismissal() { - mOtpVerificationDialog.show(/*otpLength= */ 6); + mOtpVerificationDialogCoordinator.show(/*otpLength=*/6); mModalDialogManager.dismissDialog(mModalDialogManager.getShownDialogModel(), DialogDismissalCause.NEGATIVE_BUTTON_CLICKED); - verify(mListener, times(1)).onDialogDismissed(); + verify(mDelegate, times(1)).onDialogDismissed(); } }
diff --git a/chrome/browser/ui/android/autofill/internal/java/src/org/chromium/chrome/browser/ui/autofill/OtpVerificationDialogView.java b/chrome/browser/ui/android/autofill/internal/java/src/org/chromium/chrome/browser/ui/autofill/OtpVerificationDialogView.java new file mode 100644 index 0000000..03aeada --- /dev/null +++ b/chrome/browser/ui/android/autofill/internal/java/src/org/chromium/chrome/browser/ui/autofill/OtpVerificationDialogView.java
@@ -0,0 +1,164 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.ui.autofill; + +import static org.chromium.chrome.browser.ui.autofill.OtpVerificationDialogProperties.ANIMATION_DURATION_MS; + +import android.content.Context; +import android.os.Build.VERSION_CODES; +import android.text.Editable; +import android.text.SpannableString; +import android.text.TextWatcher; +import android.text.method.LinkMovementMethod; +import android.util.AttributeSet; +import android.view.View; +import android.widget.EditText; +import android.widget.RelativeLayout; +import android.widget.TextView; + +import androidx.annotation.RequiresApi; + +import org.chromium.chrome.browser.ui.autofill.OtpVerificationDialogProperties.ViewDelegate; +import org.chromium.chrome.browser.ui.autofill.internal.R; +import org.chromium.ui.text.NoUnderlineClickableSpan; +import org.chromium.ui.text.SpanApplier; +import org.chromium.ui.text.SpanApplier.SpanInfo; + +import java.util.Optional; + +/** Dialog shown to the user for credit card unmasking using OTP-based verification. */ +public class OtpVerificationDialogView extends RelativeLayout { + private View mProgressBarOverlayView; + private View mOtpVerificationDialogViewContents; + private EditText mOtpEditText; + private TextView mOtpErrorMessageTextView; + private TextView mOtpResendMessageTextView; + + public OtpVerificationDialogView(Context context, AttributeSet attrs) { + super(context, attrs); + } + + @Override + protected void onFinishInflate() { + super.onFinishInflate(); + mProgressBarOverlayView = findViewById(R.id.progress_bar_overlay); + mProgressBarOverlayView.setVisibility(View.GONE); + mOtpVerificationDialogViewContents = findViewById(R.id.otp_verification_dialog_contents); + mOtpEditText = findViewById(R.id.otp_input); + mOtpErrorMessageTextView = findViewById(R.id.otp_error_message); + mOtpErrorMessageTextView.setVisibility(View.GONE); + mOtpResendMessageTextView = findViewById(R.id.otp_resend_message); + mOtpResendMessageTextView.setMovementMethod(LinkMovementMethod.getInstance()); + } + + /** + * Sets the edit text hint, which lets the user know how many digits are in the OTP. + * + * @param editTextHint The edit text hint, this hint will be dynamic based on the length of the + * OTP. + */ + void setEditTextHint(String editTextHint) { + mOtpEditText.setHint(editTextHint); + } + + void clearEditText() { + mOtpEditText.getText().clear(); + } + + /** + * Updates the necessary views and the model once a viewDelegate is received. + * + * @param viewDelegate The view delegate for this specific view. + */ + @RequiresApi(api = VERSION_CODES.N) + void setViewDelegate(ViewDelegate viewDelegate) { + mOtpEditText.addTextChangedListener(buildTextWatcher(viewDelegate)); + mOtpResendMessageTextView.setText(buildOtpResendMessageLink(getContext(), viewDelegate)); + } + + /** + * Fades in the progress bar overlay for the dialog. This method is called once the users clicks + * the accept button. + */ + void fadeInProgressBarOverlay() { + mProgressBarOverlayView.setVisibility(View.VISIBLE); + mProgressBarOverlayView.setAlpha(0f); + mProgressBarOverlayView.animate().alpha(1f).setDuration(ANIMATION_DURATION_MS); + mOtpVerificationDialogViewContents.animate().alpha(0f).setDuration(ANIMATION_DURATION_MS); + } + + /** + * Fades out the progress bar overlay for the dialog. This method is called if the user receives + * an error after submitting an OTP. + */ + void fadeOutProgressBarOverlay() { + mProgressBarOverlayView.setVisibility(View.GONE); + mProgressBarOverlayView.animate().alpha(0f).setDuration(ANIMATION_DURATION_MS); + mOtpVerificationDialogViewContents.animate().alpha(1f).setDuration(ANIMATION_DURATION_MS); + } + + /** + * Show an error message for the submitted OTP. This method is called once we receive an + * unsuccessful server response after the user submits an OTP, and the errorMessage lets the + * user know why the OTP was unsuccessful. + * + * @param errorMessage The error message that gets displayed to the user. Can be empty, + * indicating there should be no error message shown on the dialog (so we hide it). + */ + @RequiresApi(api = VERSION_CODES.N) + void showOtpErrorMessage(Optional<String> errorMessage) { + mOtpErrorMessageTextView.setVisibility(View.VISIBLE); + mOtpErrorMessageTextView.setText(errorMessage.get()); + } + + /** + * Hides the OTP error message. This method is called when the user changes the text in the + * edit text field while an OTP error message is showing. + */ + void hideOtpErrorMessage() { + mOtpErrorMessageTextView.setVisibility(View.GONE); + } + + /** + * Show a confirmation message for the submitted OTP. This method is called once we receive a + * successful server response after the user submits an OTP. + * + * @param confirmationMessage The confirmation message displayed to the user. + */ + void showConfirmation(String confirmationMessage) { + assert mProgressBarOverlayView != null : "mProgressBarOverlayView is null."; + mProgressBarOverlayView.findViewById(R.id.progress_bar).setVisibility(View.GONE); + mProgressBarOverlayView.findViewById(R.id.confirmation_icon).setVisibility(View.VISIBLE); + ((TextView) mProgressBarOverlayView.findViewById(R.id.progress_bar_message)) + .setText(confirmationMessage); + } + + private TextWatcher buildTextWatcher(ViewDelegate viewDelegate) { + return new TextWatcher() { + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + viewDelegate.onTextChanged(s); + } + + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) {} + + @Override + public void afterTextChanged(Editable s) {} + }; + } + + /** Builds Otp Resend Message Link **/ + @RequiresApi(api = VERSION_CODES.N) + private SpannableString buildOtpResendMessageLink(Context context, ViewDelegate viewDelegate) { + return SpanApplier.applySpans( + context.getResources().getString( + org.chromium.chrome.browser.ui.autofill.internal.R.string + .autofill_payments_otp_verification_dialog_cant_find_code_message), + new SpanInfo("<link>", "</link>", + new NoUnderlineClickableSpan(context.getResources(), + textView -> { viewDelegate.onResendLinkClicked(); }))); + } +}
diff --git a/chrome/browser/ui/android/autofill/internal/java/src/org/chromium/chrome/browser/ui/autofill/OtpVerificationDialogViewBinder.java b/chrome/browser/ui/android/autofill/internal/java/src/org/chromium/chrome/browser/ui/autofill/OtpVerificationDialogViewBinder.java new file mode 100644 index 0000000..f5babba --- /dev/null +++ b/chrome/browser/ui/android/autofill/internal/java/src/org/chromium/chrome/browser/ui/autofill/OtpVerificationDialogViewBinder.java
@@ -0,0 +1,55 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.ui.autofill; + +import static org.chromium.chrome.browser.ui.autofill.OtpVerificationDialogProperties.EDIT_TEXT; +import static org.chromium.chrome.browser.ui.autofill.OtpVerificationDialogProperties.EDIT_TEXT_HINT; +import static org.chromium.chrome.browser.ui.autofill.OtpVerificationDialogProperties.OTP_ERROR_MESSAGE; +import static org.chromium.chrome.browser.ui.autofill.OtpVerificationDialogProperties.SHOW_CONFIRMATION; +import static org.chromium.chrome.browser.ui.autofill.OtpVerificationDialogProperties.SHOW_PROGRESS_BAR_OVERLAY; +import static org.chromium.chrome.browser.ui.autofill.OtpVerificationDialogProperties.VIEW_DELEGATE; + +import android.os.Build.VERSION_CODES; + +import androidx.annotation.RequiresApi; + +import org.chromium.ui.modelutil.PropertyKey; +import org.chromium.ui.modelutil.PropertyModel; + +import java.util.Optional; + +/** Class responsible for binding the model and the view in OTP Verification Dialog. **/ +class OtpVerificationDialogViewBinder { + private OtpVerificationDialogViewBinder() {} + + @RequiresApi(api = VERSION_CODES.N) + static void bind( + PropertyModel model, OtpVerificationDialogView dialogView, PropertyKey propertyKey) { + if (propertyKey.equals(EDIT_TEXT)) { + if (!model.get(EDIT_TEXT).isPresent()) { + dialogView.clearEditText(); + } + } else if (propertyKey.equals(EDIT_TEXT_HINT)) { + dialogView.setEditTextHint(model.get(EDIT_TEXT_HINT)); + } else if (propertyKey.equals(VIEW_DELEGATE)) { + dialogView.setViewDelegate(model.get(VIEW_DELEGATE)); + } else if (propertyKey.equals(OTP_ERROR_MESSAGE)) { + Optional<String> errorMessage = model.get(OTP_ERROR_MESSAGE); + if (errorMessage.isPresent()) { + dialogView.showOtpErrorMessage(errorMessage); + } else { + dialogView.hideOtpErrorMessage(); + } + } else if (propertyKey.equals(SHOW_CONFIRMATION)) { + dialogView.showConfirmation(model.get(SHOW_CONFIRMATION)); + } else if (propertyKey.equals(SHOW_PROGRESS_BAR_OVERLAY)) { + if (model.get(SHOW_PROGRESS_BAR_OVERLAY)) { + dialogView.fadeInProgressBarOverlay(); + } else { + dialogView.fadeOutProgressBarOverlay(); + } + } + } +}
diff --git a/chrome/browser/ui/app_list/app_list_model_builder.cc b/chrome/browser/ui/app_list/app_list_model_builder.cc index 11086e8e..9f2e909 100644 --- a/chrome/browser/ui/app_list/app_list_model_builder.cc +++ b/chrome/browser/ui/app_list/app_list_model_builder.cc
@@ -64,13 +64,13 @@ void AppListModelBuilder::RemoveApp(const std::string& id, bool unsynced_change) { + // The parameter `is_uninstall` is true because the item is removed due to + // local app uninstallation rather than sync. if (!unsynced_change && service_) { - service_->RemoveUninstalledItem(id); + service_->RemoveItem(id, /*is_unistall=*/true); return; } - // The parameter `is_uninstall` is true because the item is removed due to - // local app uninstallation rather than sync. model_updater_->RemoveItem(id, /*is_uninstall=*/true); }
diff --git a/chrome/browser/ui/app_list/app_list_sort_unittest.cc b/chrome/browser/ui/app_list/app_list_sort_unittest.cc index 87d6898..bc64532 100644 --- a/chrome/browser/ui/app_list/app_list_sort_unittest.cc +++ b/chrome/browser/ui/app_list/app_list_sort_unittest.cc
@@ -855,7 +855,7 @@ // Trigger item removal from the local device by app list syncable service or // the model updater depending on the test param. if (uninstall_through_service_) { - app_list_syncable_service()->RemoveUninstalledItem(kItemId4); + app_list_syncable_service()->RemoveItem(kItemId4, /*is_uninstall=*/true); } else { // Default apps uninstallation could bypass app list syncable service. // Therefore remove the item through `model_updater` to verify this
diff --git a/chrome/browser/ui/app_list/app_list_syncable_service.cc b/chrome/browser/ui/app_list/app_list_syncable_service.cc index c50c7e5..028cc9e 100644 --- a/chrome/browser/ui/app_list/app_list_syncable_service.cc +++ b/chrome/browser/ui/app_list/app_list_syncable_service.cc
@@ -231,8 +231,7 @@ const AppListSyncableService::SyncItem& folder_item) { if (folder_item.item_type != sync_pb::AppListSpecifics::TYPE_FOLDER) return false; - return (folder_item.item_id == ash::kOemFolderId || - folder_item.item_id == ash::kCrostiniFolderId); + return folder_item.is_persistent_folder; } // Updates `target` if `target` is different from a valid new value. Returns @@ -674,9 +673,10 @@ std::vector<std::string> ids_to_be_deleted; for (auto iter = sync_items_.begin(); iter != sync_items_.end();) { SyncItem* sync_item = (iter++)->second.get(); - if (RemoveOnlyChildOutOfUserCreatedFolderIfNecessary(sync_item)) { + const std::string id = sync_item->item_id; + if (RemoveOnlyChildOutOfUserCreatedFolderIfNecessary(id)) { // Remember the id of the folder item to be deleted. - ids_to_be_deleted.push_back(sync_item->item_id); + ids_to_be_deleted.push_back(id); } } @@ -707,7 +707,14 @@ } bool AppListSyncableService::RemoveOnlyChildOutOfUserCreatedFolderIfNecessary( - SyncItem* sync_item) { + const std::string& item_id) { + if (ash::features::IsProductivityLauncherEnabled()) + return false; + + SyncItem* sync_item = FindSyncItem(item_id); + if (!sync_item) + return false; + SyncItem* child_item = GetOnlyChildOfUserCreatedFolder(sync_item); if (!child_item) return false; @@ -923,7 +930,7 @@ return; } std::string app_item_folder_id = app_item->folder_id(); - std::string sync_item_orignial_parent_id = sync_item->parent_id; + std::string sync_item_original_parent_id = sync_item->parent_id; bool changed = UpdateSyncItemFromAppItem(app_item, sync_item); if (!changed) { DVLOG(2) << this << " - Update: SYNC NO CHANGE: " << sync_item->ToString(); @@ -935,10 +942,10 @@ // If the |app_item| is moved out from a user created folder, check if // its original folder becomes a single sync item folder. Clean it up if // it does. - if (!sync_item_orignial_parent_id.empty() && - app_item_folder_id != sync_item_orignial_parent_id) { - SyncItem* original_folder_item = FindSyncItem(sync_item_orignial_parent_id); - RemoveOnlyChildOutOfUserCreatedFolderIfNecessary(original_folder_item); + if (!sync_item_original_parent_id.empty() && + app_item_folder_id != sync_item_original_parent_id) { + RemoveOnlyChildOutOfUserCreatedFolderIfNecessary( + sync_item_original_parent_id); } PruneRedundantPageBreakItems(); @@ -999,16 +1006,17 @@ return app_item->item_ordinal.CreateAfter(); } -void AppListSyncableService::RemoveItem(const std::string& id) { - RemoveSyncItem(id); - model_updater_->RemoveItem(id, /*is_uninstall=*/false); - PruneEmptySyncFolders(); - PruneRedundantPageBreakItems(); -} +void AppListSyncableService::RemoveItem(const std::string& id, + bool is_uninstall) { + SyncItem* item = FindSyncItem(id); + const std::string parent_id = item ? item->parent_id : std::string(); -void AppListSyncableService::RemoveUninstalledItem(const std::string& id) { RemoveSyncItem(id); - model_updater_->RemoveItem(id, /*is_uninstall=*/true); + model_updater_->RemoveItem(id, is_uninstall); + + if (is_uninstall && !parent_id.empty()) + RemoveOnlyChildOutOfUserCreatedFolderIfNecessary(parent_id); + PruneEmptySyncFolders(); PruneRedundantPageBreakItems(); } @@ -1725,6 +1733,14 @@ SetIconColorIfChanged(app_item->icon_color(), &sync_item->item_color); } + if (sync_item->is_persistent_folder != app_item->is_persistent()) { + DCHECK(!sync_item->is_persistent_folder); + sync_item->is_persistent_folder = app_item->is_persistent(); + // Do not mark the item as changed - the persistent value is not expected to + // be persisted to local state, nor synced. Also, it's expected to be set as + // part of folder item creation flow, so no further processing should be + // necessary. + } return changed; }
diff --git a/chrome/browser/ui/app_list/app_list_syncable_service.h b/chrome/browser/ui/app_list/app_list_syncable_service.h index 2be42fc1a..76dc626 100644 --- a/chrome/browser/ui/app_list/app_list_syncable_service.h +++ b/chrome/browser/ui/app_list/app_list_syncable_service.h
@@ -70,6 +70,13 @@ syncer::StringOrdinal item_pin_ordinal; ash::IconColor item_color; + // Indicates whether the item represents a persistent folder - i.e. a folder + // that was not created explicitly by a user, and which should not be + // removed if it's left with a single child. + // Unlike other properties, this value is not persisted to local state, nor + // synced. It reflects the associated ChromeAppListItem state. + bool is_persistent_folder = false; + std::string ToString() const; }; @@ -131,11 +138,9 @@ // updates the existing sync item instead. void AddItem(std::unique_ptr<ChromeAppListItem> app_item); - // Removes sync item matching |id|. - void RemoveItem(const std::string& id); - - // Removes sync item matching |id| after item uninstall. - void RemoveUninstalledItem(const std::string& id); + // Removes sync item matching |id|. |is_uninstall| indicates whether the item + // was removed due to an app uninstall. + void RemoveItem(const std::string& id, bool is_uninstall); // Returns the default position for the OEM folder. syncer::StringOrdinal GetDefaultOemFolderPosition() const; @@ -346,7 +351,8 @@ // child item in it, the child item will be removed out of the folder and // place at the same location of its original folder. // Otherwise, return false, no change will be made. - bool RemoveOnlyChildOutOfUserCreatedFolderIfNecessary(SyncItem* sync_item); + bool RemoveOnlyChildOutOfUserCreatedFolderIfNecessary( + const std::string& item_id); // Returns true if extension service is ready. bool IsExtensionServiceReady() const;
diff --git a/chrome/browser/ui/app_list/app_list_syncable_service_unittest.cc b/chrome/browser/ui/app_list/app_list_syncable_service_unittest.cc index 4b1eb2c0..371edeb 100644 --- a/chrome/browser/ui/app_list/app_list_syncable_service_unittest.cc +++ b/chrome/browser/ui/app_list/app_list_syncable_service_unittest.cc
@@ -826,7 +826,7 @@ ASSERT_TRUE(GetSyncItem(kItemId2)); // Remove one of the child item, the folder still has one item in it. - app_list_syncable_service()->RemoveItem(kItemId1); + app_list_syncable_service()->RemoveItem(kItemId1, /*is_uninstall=*/false); content::RunAllTasksUntilIdle(); ASSERT_TRUE(GetSyncItem(kFolderItemId)); @@ -834,7 +834,7 @@ ASSERT_TRUE(GetSyncItem(kItemId2)); // Remove the other child item, the empty folder should be removed as well. - app_list_syncable_service()->RemoveItem(kItemId2); + app_list_syncable_service()->RemoveItem(kItemId2, /*is_uninstall=*/false); content::RunAllTasksUntilIdle(); ASSERT_FALSE(GetSyncItem(kFolderItemId)); @@ -1099,7 +1099,7 @@ ASSERT_TRUE(GetSyncItem(kPageBreakItemId5)); // Remove a item, which triggers removing redundant "page break" items. - app_list_syncable_service()->RemoveItem(kItemId1); + app_list_syncable_service()->RemoveItem(kItemId1, /*is_uninstall=*/false); content::RunAllTasksUntilIdle(); ASSERT_FALSE(GetSyncItem(kPageBreakItemId1)); @@ -1838,14 +1838,34 @@ GetModelUpdater()->model_for_test()->MoveItemToRootAt(item_6, target_position); + EXPECT_EQ(GetNamesOfSortedItemsPerPageFromSyncableService(), + std::vector<std::vector<std::string>>( + {{"Item 20", "Item 19", "Item 18", "Item 17", "Item 16", + "Item 15", "Item 14", "Item 13", "Item 12", "Item 11", + "Item 10", "Item 9", "Item 8", "Item 7", "", + "Item 4", "Item 3", "Item 2", "Item 6", "Item 1"}, + {"Item 0"}})); + + // Move item 5 out of folder to the second page, and verify the item on the + // second page fills the empty space left by the folder removal. + // Note that when productivity launcher is enabled, single item folders are + // allowed, so Item 5 is expected to still be in the folder at this point. + ash::AppListItem* item_5 = FindItemForApp(initial_apps[5].get()); + ASSERT_TRUE(item_5); + + ash::AppListItem* item_0 = FindItemForApp(initial_apps[0].get()); + ASSERT_TRUE(item_0); + GetModelUpdater()->model_for_test()->MoveItemToRootAt( + item_5, item_0->position().CreateAfter()); + EXPECT_EQ( GetNamesOfSortedItemsPerPageFromSyncableService(), std::vector<std::vector<std::string>>( {{"Item 20", "Item 19", "Item 18", "Item 17", "Item 16", "Item 15", "Item 14", "Item 13", "Item 12", "Item 11", "Item 10", "Item 9", - "Item 8", "Item 7", "", "Item 5", "Item 4", "Item 3", - "Item 2", "Item 6", "Item 1"}, - {"Item 0"}})); + "Item 8", "Item 7", "", "Item 4", "Item 3", "Item 2", + "Item 6", "Item 1", "Item 0"}, + {"Item 5"}})); } TEST_F(ProductivityLauncherAppListSyncableServiceTest,
diff --git a/chrome/browser/ui/app_list/app_service/app_service_app_model_builder_unittest.cc b/chrome/browser/ui/app_list/app_service/app_service_app_model_builder_unittest.cc index 35d10b6..2660806 100644 --- a/chrome/browser/ui/app_list/app_service/app_service_app_model_builder_unittest.cc +++ b/chrome/browser/ui/app_list/app_service/app_service_app_model_builder_unittest.cc
@@ -787,7 +787,7 @@ id == crostini::kCrostiniTerminalSystemAppId) { continue; } - sync_service_->RemoveItem(id); + sync_service_->RemoveItem(id, /*is_uninstall=*/false); } }
diff --git a/chrome/browser/ui/app_list/chrome_app_list_model_updater.cc b/chrome/browser/ui/app_list/chrome_app_list_model_updater.cc index 8a1e58f..e5962f79 100644 --- a/chrome/browser/ui/app_list/chrome_app_list_model_updater.cc +++ b/chrome/browser/ui/app_list/chrome_app_list_model_updater.cc
@@ -259,14 +259,19 @@ std::string id_copy = id; // The item matched by `id` may be unavailable on the local device. - if (!FindItem(id_copy)) + ash::AppListItem* item = model_.FindItem(id_copy); + if (!item) return; + const std::string parent_id = item->folder_id(); item_manager_->RemoveChromeItem(id_copy); - // Clean the parent folder if any, when item is deleted due to app - // uninstallation rather than sync. - model_.DeleteItem(id_copy, is_uninstall); + model_.DeleteItem(id_copy); + + if (!parent_id.empty() && is_uninstall && + !ash::features::IsProductivityLauncherEnabled()) { + ClearFolderIfItHasSingleChild(parent_id); + } if (is_uninstall) { // When item deletion is triggered by local app uninstallation instead of @@ -752,10 +757,16 @@ } } + const std::string old_folder_id = item->folder_id(); std::unique_ptr<ash::AppListItemMetadata> data = item->CloneMetadata(); data->folder_id = folder_id; data->position = target_position; model_.SetItemMetadata(id, std::move(data)); + + if (!old_folder_id.empty() && + !ash::features::IsProductivityLauncherEnabled()) { + ClearFolderIfItHasSingleChild(old_folder_id); + } } // When user moves a local item to a folder, the user is believed to accept @@ -794,11 +805,17 @@ if (!item) return; + const std::string old_parent = item->folder_id(); + DCHECK(!old_parent.empty()); + std::unique_ptr<ash::AppListItemMetadata> data = item->CloneMetadata(); data->folder_id = ""; data->position = target_position; model_.SetItemMetadata(id, std::move(data)); + if (!ash::features::IsProductivityLauncherEnabled()) + ClearFolderIfItHasSingleChild(old_parent); + sync_model_sanitizer_->SanitizePageBreaksForProductivityLauncher( GetTopLevelItemIds(), /*reset_page_breaks=*/false); } @@ -999,3 +1016,17 @@ ItemChangeType::kUpdate); } } + +void ChromeAppListModelUpdater::ClearFolderIfItHasSingleChild( + const std::string& folder_id) { + ash::AppListFolderItem* folder = model_.FindFolderItem(folder_id); + if (folder && folder->ShouldAutoRemove() && folder->ChildItemCount() == 1) { + ash::AppListItem* single_child = folder->GetChildItemAt(0); + const std::string item_id = single_child->id(); + std::unique_ptr<ash::AppListItemMetadata> metadata = + single_child->CloneMetadata(); + metadata->folder_id = ""; + metadata->position = folder->position(); + model_.SetItemMetadata(item_id, std::move(metadata)); + } +}
diff --git a/chrome/browser/ui/app_list/chrome_app_list_model_updater.h b/chrome/browser/ui/app_list/chrome_app_list_model_updater.h index acd013c..ba9cc2c 100644 --- a/chrome/browser/ui/app_list/chrome_app_list_model_updater.h +++ b/chrome/browser/ui/app_list/chrome_app_list_model_updater.h
@@ -176,6 +176,10 @@ // Commits item positions under the temporary sort. void CommitTemporaryPositions(); + // If folder with the provided ID has a single child, it reparents the child + // to the root app list. + void ClearFolderIfItHasSingleChild(const std::string& folder_id); + // Indicates the profile that the model updater is associated with. Profile* const profile_ = nullptr;
diff --git a/chrome/browser/ui/app_list/test/app_list_syncable_service_test_base.cc b/chrome/browser/ui/app_list/test/app_list_syncable_service_test_base.cc index 37a55f8..bb84811a 100644 --- a/chrome/browser/ui/app_list/test/app_list_syncable_service_test_base.cc +++ b/chrome/browser/ui/app_list/test/app_list_syncable_service_test_base.cc
@@ -40,8 +40,7 @@ AppListModelUpdater* model_updater = GetModelUpdater(); for (std::string& id : existing_item_ids) { - app_list_syncable_service()->RemoveItem(id); - model_updater->RemoveItem(id, /*is_uninstall=*/true); + app_list_syncable_service()->RemoveItem(id, /*is_uninstall=*/true); } // Delete all default page breaks.
diff --git a/chrome/browser/ui/ash/holding_space/holding_space_downloads_delegate.cc b/chrome/browser/ui/ash/holding_space/holding_space_downloads_delegate.cc index ce8b25a2..d3adaa4 100644 --- a/chrome/browser/ui/ash/holding_space/holding_space_downloads_delegate.cc +++ b/chrome/browser/ui/ash/holding_space/holding_space_downloads_delegate.cc
@@ -28,6 +28,7 @@ #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/text/bytes_formatting.h" +#include "ui/chromeos/styles/cros_styles.h" #include "ui/gfx/image/image_skia_operations.h" #include "ui/gfx/paint_vector_icon.h" @@ -58,6 +59,7 @@ // to indicate error. gfx::ImageSkia CreateErrorPlaceholderImageSkia( const gfx::Size& size, + cros_styles::ColorName color_name, const absl::optional<bool>& dark_background) { DCHECK_GE(size.width(), kHoldingSpaceIconSize); DCHECK_GE(size.height(), kHoldingSpaceIconSize); @@ -65,9 +67,14 @@ image_util::CreateEmptyImage(size), gfx::CreateVectorIcon( vector_icons::kErrorOutlineIcon, kHoldingSpaceIconSize, - dark_background.value_or(AshColorProvider::Get()->IsDarkModeEnabled()) - ? gfx::kGoogleRed300 - : gfx::kGoogleRed600)); + cros_styles::ResolveColor( + color_name, + /*is_dark_mode=*/ + dark_background.value_or( + AshColorProvider::Get()->IsDarkModeEnabled()), + /*use_debug_colors=*/ + base::FeatureList::IsEnabled( + features::kSemanticColorsDebugOverride)))); } // Returns the singleton `crosapi::DownloadControllerAsh` if it exists. @@ -170,15 +177,22 @@ absl::optional<std::u16string> GetAccessibleName() const { if (IsComplete(mojo_download_item_.get())) return absl::nullopt; - return l10n_util::GetStringFUTF16( - IsScanning(mojo_download_item_.get()) - ? IDS_ASH_HOLDING_SPACE_IN_PROGRESS_DOWNLOAD_A11Y_NAME_SCANNING - : IsDangerous() || IsMixedContent() - ? IDS_ASH_HOLDING_SPACE_IN_PROGRESS_DOWNLOAD_A11Y_NAME_DANGEROUS - : IsPaused() - ? IDS_ASH_HOLDING_SPACE_IN_PROGRESS_DOWNLOAD_A11Y_NAME_PAUSED - : IDS_ASH_HOLDING_SPACE_IN_PROGRESS_DOWNLOAD_A11Y_NAME, - mojo_download_item_->target_file_path.BaseName().LossyDisplayName()); + + int msg_id = IDS_ASH_HOLDING_SPACE_IN_PROGRESS_DOWNLOAD_A11Y_NAME; + + if (IsScanning(mojo_download_item_.get())) { + msg_id = IDS_ASH_HOLDING_SPACE_IN_PROGRESS_DOWNLOAD_A11Y_NAME_SCANNING; + } else if (IsDangerous() && !MightBeMalicious()) { + msg_id = IDS_ASH_HOLDING_SPACE_IN_PROGRESS_DOWNLOAD_A11Y_NAME_CONFIRM; + } else if (IsDangerous() || IsMixedContent()) { + msg_id = IDS_ASH_HOLDING_SPACE_IN_PROGRESS_DOWNLOAD_A11Y_NAME_DANGEROUS; + } else if (IsPaused()) { + msg_id = IDS_ASH_HOLDING_SPACE_IN_PROGRESS_DOWNLOAD_A11Y_NAME_PAUSED; + } + + const auto& filename = + mojo_download_item_->target_file_path.BaseName().LossyDisplayName(); + return l10n_util::GetStringFUTF16(msg_id, filename); } // Returns the file path associated with the underlying download. @@ -241,6 +255,13 @@ // Returns whether the underlying download is paused. bool IsPaused() const { return mojo_download_item_->is_paused; } + // Returns whether the underlying download might be malicious. + bool MightBeMalicious() const { + return IsDangerous() && mojo_download_item_->danger_type != + crosapi::mojom::DownloadDangerType:: + kDownloadDangerTypeDangerousFile; + } + // Associates this in-progress download with the specified in-progress // `holding_space_item`. NOTE: This association may be performed only once. void SetHoldingSpaceItem(const HoldingSpaceItem* holding_space_item) { @@ -270,7 +291,12 @@ if (in_progress_download && (in_progress_download->IsDangerous() || in_progress_download->IsMixedContent())) { - return CreateErrorPlaceholderImageSkia(size, dark_background); + return CreateErrorPlaceholderImageSkia( + size, /*color_name=*/in_progress_download->IsDangerous() && + !in_progress_download->MightBeMalicious() + ? cros_styles::ColorName::kIconColorWarning + : cros_styles::ColorName::kIconColorAlert, + dark_background); } base::FilePath rewritten_file_path(file_path); @@ -308,6 +334,14 @@ IDS_ASH_HOLDING_SPACE_IN_PROGRESS_DOWNLOAD_SCANNING); } + // In-progress download items which are dangerous but not malicious can be + // kept or discarded by the user via notification. This being the case, such + // items have a special secondary text treatment. + if (IsDangerous() && !MightBeMalicious()) { + return l10n_util::GetStringUTF16( + IDS_ASH_HOLDING_SPACE_IN_PROGRESS_DOWNLOAD_CONFIRM); + } + // In-progress download items which are dangerous or mixed content have a // special secondary text treatment. if (IsDangerous() || IsMixedContent()) { @@ -354,12 +388,40 @@ return secondary_text; } + // Returns the color for the secondary text to display for the underlying + // download. + absl::optional<cros_styles::ColorName> GetSecondaryTextColor() const { + // Only in-progress download items have secondary text. + if (!IsInProgress(mojo_download_item_.get())) + return absl::nullopt; + + // In-progress download items which are being scanned have a special + // secondary text treatment. + if (IsScanning(mojo_download_item_.get())) + return cros_styles::ColorName::kTextColorProminent; + + // In-progress download items which are dangerous but not malicious can be + // kept or discarded by the user via notification. This being the case, such + // items have a special secondary text treatment. + if (IsDangerous() && !MightBeMalicious()) + return cros_styles::ColorName::kTextColorWarning; + + // In-progress download items which are dangerous or mixed content have a + // special secondary text treatment. + if (IsDangerous() || IsMixedContent()) + return cros_styles::ColorName::kTextColorAlert; + + return absl::nullopt; + } + protected: // Updates the `mojo_download_item_` associated with this in-progress // download, notifying `delegate_` of the change in state. Note that invoking // this method may result in the destruction of `this`. void UpdateMojoDownloadItem( crosapi::mojom::DownloadItemPtr mojo_download_item) { + const bool was_dangerous_but_not_malicious = + IsDangerous() && !MightBeMalicious(); const bool was_dangerous_or_mixed_content = IsDangerous() || IsMixedContent(); @@ -370,10 +432,17 @@ return; } + const bool is_dangerous_but_not_malicious = + IsDangerous() && !MightBeMalicious(); + const bool is_dangerous_or_mixed_content = + IsDangerous() || IsMixedContent(); + // Explicitly invalidate the image of the associated holding space item if - // the download is transitioning to/from a dangerous or mixed content state. + // the download is transitioning to/from a state which required an error + // placeholder image. const bool invalidate_image = - was_dangerous_or_mixed_content != (IsDangerous() || IsMixedContent()); + was_dangerous_but_not_malicious != is_dangerous_but_not_malicious || + was_dangerous_or_mixed_content != is_dangerous_or_mixed_content; switch (mojo_download_item_->state) { case crosapi::mojom::DownloadState::kInProgress: @@ -851,6 +920,7 @@ .SetInvalidateImage(invalidate_image) .SetText(in_progress_download->GetText()) .SetSecondaryText(in_progress_download->GetSecondaryText()) + .SetSecondaryTextColor(in_progress_download->GetSecondaryTextColor()) .SetPaused(in_progress_download->IsPaused()) .SetProgress(in_progress_download->GetProgress()); }
diff --git a/chrome/browser/ui/ash/holding_space/holding_space_keyed_service_unittest.cc b/chrome/browser/ui/ash/holding_space/holding_space_keyed_service_unittest.cc index e0ff686..f62c669d 100644 --- a/chrome/browser/ui/ash/holding_space/holding_space_keyed_service_unittest.cc +++ b/chrome/browser/ui/ash/holding_space/holding_space_keyed_service_unittest.cc
@@ -1810,6 +1810,8 @@ int64_t current_received_bytes = 0; int64_t current_total_bytes = 100; bool current_is_dangerous = false; + download::DownloadDangerType current_danger_type = + download::DownloadDangerType::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS; // Create a fake download item and cache a function to update it. std::unique_ptr<content::FakeDownloadItem> fake_download_item = @@ -1823,6 +1825,7 @@ fake_download_item->SetTargetFilePath(current_target_path); fake_download_item->SetTotalBytes(current_total_bytes); fake_download_item->SetIsDangerous(current_is_dangerous); + fake_download_item->SetDangerType(current_danger_type); fake_download_item->NotifyDownloadUpdated(); }; @@ -1961,13 +1964,15 @@ run_loop.Run(); } - // Mark the download as dangerous. + // Mark the download as dangerous and maybe malicious. current_is_dangerous = true; + current_danger_type = download::DownloadDangerType:: + DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT; UpdateFakeDownloadItem(); { - // Because the download has been marked as dangerous, the image should - // represent that the underlying download is in error. + // Because the download has been marked as dangerous and maybe malicious, + // the image should represent that the underlying download is in error. base::RunLoop run_loop; auto image_skia_changed_subscription = model->items()[0]->image().AddImageSkiaChangedCallback( @@ -1991,6 +1996,37 @@ run_loop.Run(); } + // Mark the download as *not* being malicious. + current_danger_type = + download::DownloadDangerType::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE; + UpdateFakeDownloadItem(); + + { + // Because the download has been marked as dangerous but *not* malicious, + // the image should represent that the underlying download is in warning. + base::RunLoop run_loop; + auto image_skia_changed_subscription = + model->items()[0]->image().AddImageSkiaChangedCallback( + base::BindLambdaForTesting([&]() { + gfx::ImageSkia actual_image = + model->items()[0]->image().GetImageSkia(kImageSize, + kDarkBackground); + gfx::ImageSkia expected_image = + gfx::ImageSkiaOperations::CreateSuperimposedImage( + image_util::CreateEmptyImage(kImageSize), + gfx::CreateVectorIcon(vector_icons::kErrorOutlineIcon, + kHoldingSpaceIconSize, + gfx::kGoogleYellow600)); + EXPECT_TRUE(BitmapsAreEqual(actual_image, expected_image)); + run_loop.Quit(); + })); + + // Force a thumbnail request and wait for the `ThumbnailLoader` to finish + // processing the request. + model->items()[0]->image().GetImageSkia(kImageSize, kDarkBackground); + run_loop.Run(); + } + // Complete the download. current_state = download::DownloadItem::COMPLETE; current_path = current_target_path;
diff --git a/chrome/browser/ui/ash/holding_space/holding_space_ui_browsertest.cc b/chrome/browser/ui/ash/holding_space/holding_space_ui_browsertest.cc index eae39bbd..8e3fa8c 100644 --- a/chrome/browser/ui/ash/holding_space/holding_space_ui_browsertest.cc +++ b/chrome/browser/ui/ash/holding_space/holding_space_ui_browsertest.cc
@@ -1557,21 +1557,27 @@ } // Updates whether the specified `in_progress_download` of the appropriate - // type for Ash or Lacros given test parameterization is dangerous or mixed - // content. - void UpdateInProgressDownloadIsDangerousOrMixedContent( + // type for Ash or Lacros given test parameterization is dangerous, mixed + // content, or might be malicious. + void UpdateInProgressDownloadIsDangerousMixedContentOrMightBeMalicious( AshOrLacrosDownload* in_progress_download, bool is_dangerous, - bool is_mixed_content) { + bool is_mixed_content, + bool might_be_malicious) { + ASSERT_TRUE(is_dangerous || !might_be_malicious); switch (GetDownloadTypeToUse()) { case DownloadTypeToUse::kAsh: { auto& in_progress_ash_download = absl::get<0>(*in_progress_download); ON_CALL(*in_progress_ash_download, GetDangerType()) .WillByDefault(testing::Return( - is_dangerous ? download::DownloadDangerType:: - DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE - : download::DownloadDangerType:: - DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS)); + is_dangerous + ? might_be_malicious + ? download::DownloadDangerType:: + DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT + : download::DownloadDangerType:: + DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE + : download::DownloadDangerType:: + DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS)); ON_CALL(*in_progress_ash_download, IsDangerous()) .WillByDefault(testing::Return(is_dangerous)); ON_CALL(*in_progress_ash_download, IsMixedContent()) @@ -1582,8 +1588,11 @@ case DownloadTypeToUse::kLacros: { auto& in_progress_lacros_download = absl::get<1>(*in_progress_download); in_progress_lacros_download->danger_type = - is_dangerous ? crosapi::mojom::DownloadDangerType:: - kDownloadDangerTypeDangerousFile + is_dangerous ? might_be_malicious + ? crosapi::mojom::DownloadDangerType:: + kDownloadDangerTypeMaybeDangerousContent + : crosapi::mojom::DownloadDangerType:: + kDownloadDangerTypeDangerousFile : crosapi::mojom::DownloadDangerType:: kDownloadDangerTypeNotDangerous; in_progress_lacros_download->is_dangerous = is_dangerous; @@ -1952,6 +1961,7 @@ // `0 B` as there is no knowledge of the total number of bytes expected. EXPECT_TRUE(secondary_label->GetVisible()); EXPECT_EQ(secondary_label->GetText(), u"0 B"); + EXPECT_EQ(secondary_label->GetEnabledColor(), gfx::kGoogleGrey400); // The accessible name should indicate that the download is in progress. EXPECT_EQ(GetAccessibleName(download_chips.at(0)), @@ -1969,6 +1979,7 @@ EXPECT_EQ(primary_label->GetText(), target_file_name); EXPECT_TRUE(secondary_label->GetVisible()); WaitForText(secondary_label, u"Paused, 0 B"); + EXPECT_EQ(secondary_label->GetEnabledColor(), gfx::kGoogleGrey400); // The accessible name should indicate that the download is in progress and // that progress is paused. @@ -1986,6 +1997,7 @@ EXPECT_EQ(primary_label->GetText(), target_file_name); EXPECT_TRUE(secondary_label->GetVisible()); WaitForText(secondary_label, u"Paused, 1,024 KB"); + EXPECT_EQ(secondary_label->GetEnabledColor(), gfx::kGoogleGrey400); // The accessible name should indicate that the download is in progress and // that progress is paused. @@ -2003,6 +2015,7 @@ EXPECT_EQ(primary_label->GetText(), target_file_name); EXPECT_TRUE(secondary_label->GetVisible()); WaitForText(secondary_label, u"1,024 KB"); + EXPECT_EQ(secondary_label->GetEnabledColor(), gfx::kGoogleGrey400); // The accessible name should indicate that the download is in progress. EXPECT_EQ(GetAccessibleName(download_chips.at(0)), @@ -2020,6 +2033,7 @@ EXPECT_EQ(primary_label->GetText(), target_file_name); EXPECT_TRUE(secondary_label->GetVisible()); WaitForText(secondary_label, u"1.0/2.0 MB"); + EXPECT_EQ(secondary_label->GetEnabledColor(), gfx::kGoogleGrey400); // The accessible name should indicate that the download is in progress. EXPECT_EQ(GetAccessibleName(download_chips.at(0)), @@ -2037,6 +2051,7 @@ EXPECT_EQ(primary_label->GetText(), target_file_name); EXPECT_TRUE(secondary_label->GetVisible()); WaitForText(secondary_label, u"Paused, 1.0/2.0 MB"); + EXPECT_EQ(secondary_label->GetEnabledColor(), gfx::kGoogleGrey400); // The accessible name should indicate that the download is in progress and // that progress is paused. @@ -2057,6 +2072,7 @@ EXPECT_EQ(primary_label->GetText(), target_file_name); EXPECT_TRUE(secondary_label->GetVisible()); WaitForText(secondary_label, u"Paused, 2.0/2.0 MB"); + EXPECT_EQ(secondary_label->GetEnabledColor(), gfx::kGoogleGrey400); // The accessible name should indicate that the download is in progress and // that progress is paused. @@ -2064,9 +2080,11 @@ base::UTF16ToUTF8(u"Download paused " + target_file_name)); // Mark the download as dangerous. - UpdateInProgressDownloadIsDangerousOrMixedContent(in_progress_download.get(), - /*is_dangerous=*/true, - /*is_mixed_content=*/false); + UpdateInProgressDownloadIsDangerousMixedContentOrMightBeMalicious( + in_progress_download.get(), + /*is_dangerous=*/true, + /*is_mixed_content=*/false, + /*might_be_malicious=*/true); // Because the download is marked as dangerous, that should be indicated in // the `secondary_label` of the holding space item chip view. @@ -2074,6 +2092,7 @@ EXPECT_EQ(primary_label->GetText(), target_file_name); EXPECT_TRUE(secondary_label->GetVisible()); WaitForText(secondary_label, u"Dangerous file"); + EXPECT_EQ(secondary_label->GetEnabledColor(), gfx::kGoogleRed300); // The accessible name should indicate that the download is dangerous. EXPECT_EQ(GetAccessibleName(download_chips.at(0)), @@ -2088,15 +2107,36 @@ EXPECT_EQ(primary_label->GetText(), target_file_name); EXPECT_TRUE(secondary_label->GetVisible()); WaitForText(secondary_label, u"Being scanned"); + EXPECT_EQ(secondary_label->GetEnabledColor(), gfx::kGoogleBlue300); // The accessible name should indicate that the download is being scanning. EXPECT_EQ(GetAccessibleName(download_chips.at(0)), base::UTF16ToUTF8(u"Download being scanned " + target_file_name)); + // Stop scanning and mark that the download is *not* malicious. + UpdateInProgressDownloadIsDangerousMixedContentOrMightBeMalicious( + in_progress_download.get(), /*is_dangerous=*/true, + /*is_mixed_content=*/false, /*might_be_malicious=*/false); + + // Because the download is *not* malicious, the user will be able to keep/ + // discard the download via notification. That should be indicated in the + // `secondary_label` of the holding space item chip view. + EXPECT_TRUE(primary_label->GetVisible()); + EXPECT_EQ(primary_label->GetText(), target_file_name); + EXPECT_TRUE(secondary_label->GetVisible()); + WaitForText(secondary_label, u"Confirm download"); + EXPECT_EQ(secondary_label->GetEnabledColor(), gfx::kGoogleYellow300); + + // The accessible name should indicate that the download must be confirmed. + EXPECT_EQ(GetAccessibleName(download_chips.at(0)), + base::UTF16ToUTF8(u"Confirm download " + target_file_name)); + // Mark the download as safe. - UpdateInProgressDownloadIsDangerousOrMixedContent(in_progress_download.get(), - /*is_dangerous=*/false, - /*is_mixed_content=*/false); + UpdateInProgressDownloadIsDangerousMixedContentOrMightBeMalicious( + in_progress_download.get(), + /*is_dangerous=*/false, + /*is_mixed_content=*/false, + /*might_be_malicious=*/false); // Because the download is no longer marked as dangerous, that should be // indicated in the `secondary_label` of the holding space item chip view. @@ -2104,6 +2144,7 @@ EXPECT_EQ(primary_label->GetText(), target_file_name); EXPECT_TRUE(secondary_label->GetVisible()); WaitForText(secondary_label, u"Paused, 2.0/2.0 MB"); + EXPECT_EQ(secondary_label->GetEnabledColor(), gfx::kGoogleGrey400); // The accessible name should indicate that the download is in progress and // that progress is paused. @@ -2111,9 +2152,11 @@ base::UTF16ToUTF8(u"Download paused " + target_file_name)); // Mark the download as mixed content. - UpdateInProgressDownloadIsDangerousOrMixedContent(in_progress_download.get(), - /*is_dangerous=*/false, - /*is_mixed_content=*/true); + UpdateInProgressDownloadIsDangerousMixedContentOrMightBeMalicious( + in_progress_download.get(), + /*is_dangerous=*/false, + /*is_mixed_content=*/true, + /*might_be_malicious=*/false); // Because the download is marked as mixed content, that should be indicated // in the `secondary_label` of the holding space item chip view. @@ -2121,15 +2164,18 @@ EXPECT_EQ(primary_label->GetText(), target_file_name); EXPECT_TRUE(secondary_label->GetVisible()); WaitForText(secondary_label, u"Dangerous file"); + EXPECT_EQ(secondary_label->GetEnabledColor(), gfx::kGoogleRed300); // The accessible name should indicate that the download is dangerous. EXPECT_EQ(GetAccessibleName(download_chips.at(0)), base::UTF16ToUTF8(u"Download dangerous " + target_file_name)); // Mark the download as *not* mixed content. - UpdateInProgressDownloadIsDangerousOrMixedContent(in_progress_download.get(), - /*is_dangerous=*/false, - /*is_mixed_content=*/false); + UpdateInProgressDownloadIsDangerousMixedContentOrMightBeMalicious( + in_progress_download.get(), + /*is_dangerous=*/false, + /*is_mixed_content=*/false, + /*might_be_malicious=*/false); // Because the download is no longer marked as mixed content, that should be // indicated in the `secondary_label` of the holding space item chip view. @@ -2137,6 +2183,7 @@ EXPECT_EQ(primary_label->GetText(), target_file_name); EXPECT_TRUE(secondary_label->GetVisible()); WaitForText(secondary_label, u"Paused, 2.0/2.0 MB"); + EXPECT_EQ(secondary_label->GetEnabledColor(), gfx::kGoogleGrey400); // The accessible name should indicate that the download is in progress and // that progress is paused. @@ -2150,6 +2197,7 @@ EXPECT_TRUE(primary_label->GetVisible()); EXPECT_EQ(primary_label->GetText(), target_file_name); EXPECT_FALSE(secondary_label->GetVisible()); + EXPECT_EQ(secondary_label->GetEnabledColor(), gfx::kGoogleGrey400); // The accessible name should indicate the target file name. EXPECT_EQ(GetAccessibleName(download_chips.at(0)),
diff --git a/chrome/browser/ui/ash/network/network_state_notifier_unittest.cc b/chrome/browser/ui/ash/network/network_state_notifier_unittest.cc index 96d03b24..8475a5e 100644 --- a/chrome/browser/ui/ash/network/network_state_notifier_unittest.cc +++ b/chrome/browser/ui/ash/network/network_state_notifier_unittest.cc
@@ -18,15 +18,12 @@ #include "chromeos/dbus/hermes/hermes_clients.h" #include "chromeos/dbus/shill/shill_device_client.h" #include "chromeos/dbus/shill/shill_service_client.h" -#include "chromeos/network/cellular_esim_profile_handler_impl.h" #include "chromeos/network/cellular_metrics_logger.h" #include "chromeos/network/network_connect.h" #include "chromeos/network/network_handler.h" #include "chromeos/network/network_handler_test_helper.h" -#include "chromeos/network/network_metadata_store.h" #include "chromeos/network/network_state_handler.h" #include "chromeos/network/network_state_test_helper.h" -#include "chromeos/network/test_cellular_esim_profile_handler.h" #include "components/prefs/testing_pref_service.h" #include "testing/platform_test.h" #include "third_party/cros_system_api/dbus/service_constants.h" @@ -91,11 +88,10 @@ void SetUp() override { BrowserWithTestWindowTest::SetUp(); network_handler_test_helper_ = std::make_unique<NetworkHandlerTestHelper>(); - CellularESimProfileHandlerImpl::RegisterLocalStatePrefs( - local_state_.registry()); - NetworkMetadataStore::RegisterPrefs(user_prefs_.registry()); - NetworkMetadataStore::RegisterPrefs(local_state_.registry()); - NetworkHandler::Get()->InitializePrefServices(&user_prefs_, &local_state_); + network_handler_test_helper_->RegisterPrefs(user_prefs_.registry(), + local_state_.registry()); + + network_handler_test_helper_->InitializePrefs(&user_prefs_, &local_state_); SetupDefaultShillState(); base::RunLoop().RunUntilIdle();
diff --git a/chrome/browser/ui/ash/projector/pending_screencast_manager.cc b/chrome/browser/ui/ash/projector/pending_screencast_manager.cc index ddc00f8..10c1b28 100644 --- a/chrome/browser/ui/ash/projector/pending_screencast_manager.cc +++ b/chrome/browser/ui/ash/projector/pending_screencast_manager.cc
@@ -35,13 +35,13 @@ path.MatchesExtension(GetMetadataFileExtension()); } -drive::DriveIntegrationService* GetDriveIntegrationServiceForPrimaryProfile() { +drive::DriveIntegrationService* GetDriveIntegrationServiceForActiveProfile() { return drive::DriveIntegrationServiceFactory::FindForProfile( - ProfileManager::GetPrimaryUserProfile()); + ProfileManager::GetActiveUserProfile()); } -drivefs::DriveFsHost* GetDriveFsHostForPrimaryProfile() { - auto* drivefs_integration = GetDriveIntegrationServiceForPrimaryProfile(); +drivefs::DriveFsHost* GetDriveFsHostForActiveProfile() { + auto* drivefs_integration = GetDriveIntegrationServiceForActiveProfile(); return drivefs_integration ? drivefs_integration->GetDriveFsHost() : nullptr; } @@ -132,7 +132,7 @@ session_manager::SessionManager::Get(); if (session_manager) { session_manager->RemoveObserver(this); - auto* drivefs_host = GetDriveFsHostForPrimaryProfile(); + auto* drivefs_host = GetDriveFsHostForActiveProfile(); if (drivefs_host) drivefs_host->RemoveObserver(this); } @@ -173,7 +173,7 @@ base::BindOnce( ProcessAndGenerateNewScreencasts, std::move(pending_webm_or_projector_files), - GetDriveIntegrationServiceForPrimaryProfile()->GetMountPointPath()), + GetDriveIntegrationServiceForActiveProfile()->GetMountPointPath()), base::BindOnce( &PendingSreencastManager::OnProcessAndGenerateNewScreencastsFinished, weak_ptr_factory_.GetWeakPtr())); @@ -185,11 +185,9 @@ } void PendingSreencastManager::OnUserSessionStarted(bool is_primary_user) { - if (!is_primary_user) - return; - auto* drivefs_host = GetDriveFsHostForPrimaryProfile(); + auto* drivefs_host = GetDriveFsHostForActiveProfile(); if (drivefs_host) - GetDriveFsHostForPrimaryProfile()->AddObserver(this); + GetDriveFsHostForActiveProfile()->AddObserver(this); } const std::set<ash::PendingScreencast>&
diff --git a/chrome/browser/ui/ash/projector/pending_screencast_manager_browsertest.cc b/chrome/browser/ui/ash/projector/pending_screencast_manager_browsertest.cc index 456081b..76a1b35d 100644 --- a/chrome/browser/ui/ash/projector/pending_screencast_manager_browsertest.cc +++ b/chrome/browser/ui/ash/projector/pending_screencast_manager_browsertest.cc
@@ -20,6 +20,7 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/ash/projector/projector_app_client_impl.h" +#include "chrome/browser/ui/browser.h" #include "chrome/test/base/in_process_browser_test.h" #include "content/public/test/browser_test.h" #include "content/public/test/test_utils.h" @@ -62,7 +63,8 @@ protected: virtual drive::DriveIntegrationService* CreateDriveIntegrationService( Profile* profile) { - if (!ProfileHelper::IsPrimaryProfile(profile)) + // Ignore non-regular profile. + if (!ProfileHelper::IsRegularProfile(profile)) return nullptr; base::ScopedAllowBlockingForTesting allow_blocking; @@ -81,7 +83,7 @@ drive::DriveIntegrationService* service = drive::DriveIntegrationServiceFactory::FindForProfile( - ProfileManager::GetPrimaryUserProfile()); + browser()->profile()); EXPECT_TRUE(service->IsMounted()); EXPECT_TRUE(base::PathExists(service->GetMountPointPath()));
diff --git a/chrome/browser/ui/ash/projector/projector_app_client_impl.cc b/chrome/browser/ui/ash/projector/projector_app_client_impl.cc index 3cc720a..08d24a5b 100644 --- a/chrome/browser/ui/ash/projector/projector_app_client_impl.cc +++ b/chrome/browser/ui/ash/projector/projector_app_client_impl.cc
@@ -77,15 +77,13 @@ } signin::IdentityManager* ProjectorAppClientImpl::GetIdentityManager() { - Profile* profile = ProfileManager::GetPrimaryUserProfile(); - DCHECK(chromeos::ProfileHelper::IsPrimaryProfile(profile)); + Profile* profile = ProfileManager::GetActiveUserProfile(); return IdentityManagerFactory::GetForProfile(profile); } network::mojom::URLLoaderFactory* ProjectorAppClientImpl::GetUrlLoaderFactory() { - Profile* profile = ProfileManager::GetPrimaryUserProfile(); - DCHECK(chromeos::ProfileHelper::IsPrimaryProfile(profile)); + Profile* profile = ProfileManager::GetActiveUserProfile(); return profile->GetDefaultStoragePartition() ->GetURLLoaderFactoryForBrowserProcess() .get();
diff --git a/chrome/browser/ui/ash/projector/projector_client_impl.cc b/chrome/browser/ui/ash/projector/projector_client_impl.cc index 3624068..0e37780 100644 --- a/chrome/browser/ui/ash/projector/projector_client_impl.cc +++ b/chrome/browser/ui/ash/projector/projector_client_impl.cc
@@ -15,6 +15,7 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/speech/on_device_speech_recognizer.h" +#include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/web_applications/system_web_app_ui_utils.h" #include "chrome/browser/web_applications/system_web_apps/system_web_app_types.h" #include "chromeos/login/login_state/login_state.h" @@ -72,7 +73,7 @@ DCHECK_EQ(speech_recognizer_.get(), nullptr); recognizer_status_ = SPEECH_RECOGNIZER_OFF; speech_recognizer_ = std::make_unique<OnDeviceSpeechRecognizer>( - weak_ptr_factory_.GetWeakPtr(), ProfileManager::GetPrimaryUserProfile(), + weak_ptr_factory_.GetWeakPtr(), ProfileManager::GetActiveUserProfile(), GetLocale(), /*recognition_mode_ime=*/false, /*enable_formatting=*/true); } @@ -84,7 +85,7 @@ void ProjectorClientImpl::ShowSelfieCam() { selfie_cam_bubble_manager_.Show( - ProfileManager::GetPrimaryUserProfile(), + ProfileManager::GetActiveUserProfile(), display::Screen::GetScreen()->GetPrimaryDisplay().work_area()); } @@ -138,7 +139,7 @@ drive::DriveIntegrationService* integration_service = drive::DriveIntegrationServiceFactory::FindForProfile( - ProfileManager::GetPrimaryUserProfile()); + ProfileManager::GetActiveUserProfile()); *result = integration_service->GetMountPointPath(); return true; } @@ -153,17 +154,25 @@ return true; } - auto* profile = ProfileManager::GetPrimaryUserProfile(); + auto* profile = ProfileManager::GetActiveUserProfile(); drive::DriveIntegrationService* integration_service = drive::DriveIntegrationServiceFactory::FindForProfile(profile); return integration_service && integration_service->IsMounted(); } void ProjectorClientImpl::OpenProjectorApp() const { - auto* profile = ProfileManager::GetPrimaryUserProfile(); + auto* profile = ProfileManager::GetActiveUserProfile(); web_app::LaunchSystemWebAppAsync(profile, web_app::SystemAppType::PROJECTOR); } +void ProjectorClientImpl::MinimizeProjectorApp() const { + auto* profile = ProfileManager::GetActiveUserProfile(); + auto* browser = + FindSystemWebAppBrowser(profile, web_app::SystemAppType::PROJECTOR); + if (browser) + browser->window()->Minimize(); +} + void ProjectorClientImpl::OnNewScreencastPreconditionChanged( bool can_start) const { ash::ProjectorAppClient::Get()->OnNewScreencastPreconditionChanged(can_start);
diff --git a/chrome/browser/ui/ash/projector/projector_client_impl.h b/chrome/browser/ui/ash/projector/projector_client_impl.h index a6e76a15..c2fe2c9 100644 --- a/chrome/browser/ui/ash/projector/projector_client_impl.h +++ b/chrome/browser/ui/ash/projector/projector_client_impl.h
@@ -47,6 +47,7 @@ bool GetDriveFsMountPointPath(base::FilePath* result) const override; bool IsDriveFsMounted() const override; void OpenProjectorApp() const override; + void MinimizeProjectorApp() const override; void OnNewScreencastPreconditionChanged(bool can_start) const override; // SpeechRecognizerDelegate:
diff --git a/chrome/browser/ui/ash/projector/projector_client_impl_browsertest.cc b/chrome/browser/ui/ash/projector/projector_client_impl_browsertest.cc index 1af572de6..61b8c59 100644 --- a/chrome/browser/ui/ash/projector/projector_client_impl_browsertest.cc +++ b/chrome/browser/ui/ash/projector/projector_client_impl_browsertest.cc
@@ -14,6 +14,7 @@ #include "chrome/browser/ash/drive/drivefs_test_support.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" +#include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/ui/web_applications/system_web_app_ui_utils.h" #include "chrome/browser/web_applications/system_web_apps/system_web_app_manager.h" @@ -130,6 +131,30 @@ content::PAGE_TYPE_NORMAL); } +IN_PROC_BROWSER_TEST_F(ProjectorClientTest, MinimizeProjectorApp) { + auto* profile = browser()->profile(); + web_app::WebAppProvider::GetForTest(profile) + ->system_web_app_manager() + .InstallSystemAppsForTesting(); + + client()->OpenProjectorApp(); + web_app::FlushSystemWebAppLaunchesForTesting(profile); + + // Verify that Projector App is opened. + Browser* app_browser = + FindSystemWebAppBrowser(profile, web_app::SystemAppType::PROJECTOR); + ASSERT_TRUE(app_browser); + content::WebContents* tab = + app_browser->tab_strip_model()->GetActiveWebContents(); + ASSERT_TRUE(tab); + EXPECT_EQ(tab->GetController().GetVisibleEntry()->GetPageType(), + content::PAGE_TYPE_NORMAL); + + client()->MinimizeProjectorApp(); + // Verify that Projector App is minimized. + EXPECT_TRUE(app_browser->window()->IsMinimized()); +} + IN_PROC_BROWSER_TEST_F(ProjectorClientTest, GetDriveFsMountPointPath) { ASSERT_TRUE(client()->IsDriveFsMounted());
diff --git a/chrome/browser/ui/ash/quick_answers/quick_answers_controller_unittest.cc b/chrome/browser/ui/ash/quick_answers/quick_answers_controller_unittest.cc index 628a713..8356f841 100644 --- a/chrome/browser/ui/ash/quick_answers/quick_answers_controller_unittest.cc +++ b/chrome/browser/ui/ash/quick_answers/quick_answers_controller_unittest.cc
@@ -61,6 +61,10 @@ // first. if (set_visibility) controller()->SetPendingShowQuickAnswers(); + + // Set up a companion menu before creating the QuickAnswersView. + CreateAndShowBasicMenu(); + controller()->MaybeShowQuickAnswers(kDefaultAnchorBoundsInScreen, kDefaultTitle, {}); }
diff --git a/chrome/browser/ui/ash/quick_answers/quick_answers_ui_controller_unittest.cc b/chrome/browser/ui/ash/quick_answers/quick_answers_ui_controller_unittest.cc index 3c5ac19..f875c6c 100644 --- a/chrome/browser/ui/ash/quick_answers/quick_answers_ui_controller_unittest.cc +++ b/chrome/browser/ui/ash/quick_answers/quick_answers_ui_controller_unittest.cc
@@ -43,6 +43,10 @@ TEST_F(QuickAnswersUiControllerTest, TearDownWhileQuickAnswersViewShowing) { EXPECT_FALSE(ui_controller()->is_showing_quick_answers_view()); + + // Set up a companion menu before creating the QuickAnswersView. + CreateAndShowBasicMenu(); + ui_controller()->CreateQuickAnswersView(kDefaultAnchorBoundsInScreen, "default_title", "default_query", /*is_internal=*/false); @@ -51,6 +55,10 @@ TEST_F(QuickAnswersUiControllerTest, TearDownWhileConsentViewShowing) { EXPECT_FALSE(ui_controller()->is_showing_user_consent_view()); + + // Set up a companion menu before creating the QuickAnswersView. + CreateAndShowBasicMenu(); + ui_controller()->CreateUserConsentView(kDefaultAnchorBoundsInScreen, std::u16string(), std::u16string()); EXPECT_TRUE(ui_controller()->is_showing_user_consent_view());
diff --git a/chrome/browser/ui/ash/quick_answers/test/chrome_quick_answers_test_base.cc b/chrome/browser/ui/ash/quick_answers/test/chrome_quick_answers_test_base.cc index 617de2b0..227792a 100644 --- a/chrome/browser/ui/ash/quick_answers/test/chrome_quick_answers_test_base.cc +++ b/chrome/browser/ui/ash/quick_answers/test/chrome_quick_answers_test_base.cc
@@ -7,6 +7,10 @@ #include "ash/session/session_controller_impl.h" #include "ash/shell.h" #include "chrome/browser/ui/ash/quick_answers/quick_answers_controller_impl.h" +#include "ui/base/models/simple_menu_model.h" +#include "ui/views/controls/label.h" +#include "ui/views/controls/menu/menu_runner.h" +#include "ui/views/widget/widget.h" ChromeQuickAnswersTestBase::ChromeQuickAnswersTestBase() = default; @@ -26,5 +30,23 @@ void ChromeQuickAnswersTestBase::TearDown() { quick_answers_controller_.reset(); + // Menu. + menu_parent_.reset(); + menu_runner_.reset(); + menu_model_.reset(); + menu_delegate_.reset(); + ChromeAshTestBase::TearDown(); } + +void ChromeQuickAnswersTestBase::CreateAndShowBasicMenu() { + menu_delegate_ = std::make_unique<views::Label>(); + menu_model_ = std::make_unique<ui::SimpleMenuModel>(menu_delegate_.get()); + menu_model_->AddItem(0, u"Menu item"); + menu_runner_ = std::make_unique<views::MenuRunner>( + menu_model_.get(), views::MenuRunner::CONTEXT_MENU); + menu_parent_ = CreateTestWidget(); + menu_runner_->RunMenuAt(menu_parent_.get(), nullptr, gfx::Rect(), + views::MenuAnchorPosition::kTopLeft, + ui::MENU_SOURCE_MOUSE); +}
diff --git a/chrome/browser/ui/ash/quick_answers/test/chrome_quick_answers_test_base.h b/chrome/browser/ui/ash/quick_answers/test/chrome_quick_answers_test_base.h index e57696cdf..70169ea0 100644 --- a/chrome/browser/ui/ash/quick_answers/test/chrome_quick_answers_test_base.h +++ b/chrome/browser/ui/ash/quick_answers/test/chrome_quick_answers_test_base.h
@@ -11,6 +11,16 @@ class QuickAnswersController; } // namespace ash +namespace ui { +class SimpleMenuModel; +} // namespace ui + +namespace views { +class Label; +class MenuRunner; +class Widget; +} // namespace views + // Helper class for Quick Answers related tests. class ChromeQuickAnswersTestBase : public ChromeAshTestBase { public: @@ -26,7 +36,16 @@ void SetUp() override; void TearDown() override; + protected: + void CreateAndShowBasicMenu(); + private: + // Menu. + std::unique_ptr<views::Label> menu_delegate_; + std::unique_ptr<ui::SimpleMenuModel> menu_model_; + std::unique_ptr<views::MenuRunner> menu_runner_; + std::unique_ptr<views::Widget> menu_parent_; + std::unique_ptr<ash::QuickAnswersController> quick_answers_controller_; };
diff --git a/chrome/browser/ui/ash/quick_answers/ui/quick_answers_view.cc b/chrome/browser/ui/ash/quick_answers/ui/quick_answers_view.cc index 6eda6ac..b23abce 100644 --- a/chrome/browser/ui/ash/quick_answers/ui/quick_answers_view.cc +++ b/chrome/browser/ui/ash/quick_answers/ui/quick_answers_view.cc
@@ -6,7 +6,6 @@ #include "ash/public/cpp/app_list/vector_icons/vector_icons.h" #include "ash/resources/vector_icons/vector_icons.h" -#include "ash/shell.h" #include "base/bind.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/ash/quick_answers/quick_answers_ui_controller.h" @@ -14,9 +13,11 @@ #include "chromeos/components/quick_answers/quick_answers_model.h" #include "chromeos/strings/grit/chromeos_strings.h" #include "chromeos/ui/vector_icons/vector_icons.h" +#include "ui/aura/window.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/metadata/metadata_header_macros.h" #include "ui/base/metadata/metadata_impl_macros.h" +#include "ui/display/screen.h" #include "ui/gfx/paint_vector_icon.h" #include "ui/views/accessibility/view_accessibility.h" #include "ui/views/animation/ink_drop_impl.h" @@ -399,14 +400,11 @@ params.type = views::Widget::InitParams::TYPE_POPUP; params.z_order = ui::ZOrderLevel::kFloatingUIElement; - // Parent the widget depending on the context. + // Parent the widget to the owner of the menu. auto* active_menu_controller = views::MenuController::GetActiveInstance(); - if (active_menu_controller && active_menu_controller->owner()) { - params.parent = active_menu_controller->owner()->GetNativeView(); - params.child = true; - } else { - params.context = Shell::Get()->GetRootWindowForNewWindows(); - } + DCHECK(active_menu_controller && active_menu_controller->owner()); + params.parent = active_menu_controller->owner()->GetNativeView(); + params.child = true; views::Widget* widget = new views::Widget(); widget->Init(std::move(params));
diff --git a/chrome/browser/ui/ash/quick_answers/ui/quick_answers_view_unittest.cc b/chrome/browser/ui/ash/quick_answers/ui/quick_answers_view_unittest.cc index a5e3866..378d6e5 100644 --- a/chrome/browser/ui/ash/quick_answers/ui/quick_answers_view_unittest.cc +++ b/chrome/browser/ui/ash/quick_answers/ui/quick_answers_view_unittest.cc
@@ -6,11 +6,7 @@ #include "chrome/browser/ui/ash/quick_answers/quick_answers_controller_impl.h" #include "chrome/browser/ui/ash/quick_answers/test/chrome_quick_answers_test_base.h" -#include "ui/base/models/simple_menu_model.h" -#include "ui/views/controls/label.h" #include "ui/views/controls/menu/menu_controller.h" -#include "ui/views/controls/menu/menu_runner.h" -#include "ui/views/widget/widget.h" namespace ash { @@ -35,19 +31,11 @@ ChromeQuickAnswersTestBase::SetUp(); anchor_bounds_ = kDefaultAnchorBoundsInScreen; - CreateQuickAnswersView(anchor_bounds_, "default_title", - /*create_menu=*/false); } void TearDown() override { quick_answers_view_.reset(); - // Menu. - menu_parent_.reset(); - menu_runner_.reset(); - menu_model_.reset(); - menu_delegate_.reset(); - ChromeQuickAnswersTestBase::TearDown(); } @@ -60,14 +48,12 @@ // Create a QuickAnswersView instance with custom anchor-bounds and // title-text. void CreateQuickAnswersView(const gfx::Rect anchor_bounds, - const char* title, - bool create_menu) { + const char* title) { // Reset existing view if any. quick_answers_view_.reset(); // Set up a companion menu before creating the QuickAnswersView. - if (create_menu) - CreateAndShowBasicMenu(); + CreateAndShowBasicMenu(); anchor_bounds_ = anchor_bounds; auto* ui_controller = @@ -77,32 +63,15 @@ anchor_bounds_, title, /*is_internal=*/false, ui_controller); } - void CreateAndShowBasicMenu() { - menu_delegate_ = std::make_unique<views::Label>(); - menu_model_ = std::make_unique<ui::SimpleMenuModel>(menu_delegate_.get()); - menu_model_->AddItem(0, u"Menu item"); - menu_runner_ = std::make_unique<views::MenuRunner>( - menu_model_.get(), views::MenuRunner::CONTEXT_MENU); - menu_parent_ = CreateTestWidget(); - menu_runner_->RunMenuAt(menu_parent_.get(), nullptr, gfx::Rect(), - views::MenuAnchorPosition::kTopLeft, - ui::MENU_SOURCE_MOUSE); - } - private: std::unique_ptr<QuickAnswersView> quick_answers_view_; gfx::Rect anchor_bounds_; - - // Menu. - std::unique_ptr<views::Label> menu_delegate_; - std::unique_ptr<ui::SimpleMenuModel> menu_model_; - std::unique_ptr<views::MenuRunner> menu_runner_; - std::unique_ptr<views::Widget> menu_parent_; }; TEST_F(QuickAnswersViewsTest, DefaultLayoutAroundAnchor) { - gfx::Rect view_bounds = view()->GetBoundsInScreen(); gfx::Rect anchor_bounds = GetAnchorBounds(); + CreateQuickAnswersView(anchor_bounds, "default_title"); + gfx::Rect view_bounds = view()->GetBoundsInScreen(); // Vertically aligned with anchor. EXPECT_EQ(view_bounds.x(), anchor_bounds.x()); @@ -118,7 +87,7 @@ // space above it to show the QuickAnswersView. anchor_bounds.set_y(kSmallTop); - CreateQuickAnswersView(anchor_bounds, "title", /*create_menu=*/false); + CreateQuickAnswersView(anchor_bounds, "title"); gfx::Rect view_bounds = view()->GetBoundsInScreen(); // Anchor is positioned above the view. @@ -126,17 +95,7 @@ } TEST_F(QuickAnswersViewsTest, FocusProperties) { - // Not focused by default. - EXPECT_FALSE(view()->HasFocus()); - - // Does not gain focus upon request if no active menu. - CHECK(views::MenuController::GetActiveInstance() == nullptr); - view()->RequestFocus(); - EXPECT_FALSE(view()->HasFocus()); - - // Set up a companion menu before creating a new view. - CreateQuickAnswersView(GetAnchorBounds(), "title", - /*create_menu=*/true); + CreateQuickAnswersView(GetAnchorBounds(), "title"); CHECK(views::MenuController::GetActiveInstance() && views::MenuController::GetActiveInstance()->owner());
diff --git a/chrome/browser/ui/ash/quick_answers/ui/user_consent_view.cc b/chrome/browser/ui/ash/quick_answers/ui/user_consent_view.cc index cbf4abe..90cd9ef 100644 --- a/chrome/browser/ui/ash/quick_answers/ui/user_consent_view.cc +++ b/chrome/browser/ui/ash/quick_answers/ui/user_consent_view.cc
@@ -6,13 +6,14 @@ #include "ash/public/cpp/app_list/vector_icons/vector_icons.h" #include "ash/resources/vector_icons/vector_icons.h" -#include "ash/shell.h" #include "base/bind.h" #include "chrome/browser/ash/accessibility/accessibility_manager.h" #include "chrome/browser/ui/ash/quick_answers/quick_answers_ui_controller.h" #include "chromeos/strings/grit/chromeos_strings.h" #include "chromeos/ui/vector_icons/vector_icons.h" +#include "ui/aura/window.h" #include "ui/base/l10n/l10n_util.h" +#include "ui/display/screen.h" #include "ui/events/event_handler.h" #include "ui/gfx/paint_vector_icon.h" #include "ui/views/accessibility/view_accessibility.h" @@ -331,14 +332,11 @@ params.type = views::Widget::InitParams::TYPE_POPUP; params.z_order = ui::ZOrderLevel::kFloatingUIElement; - // Parent the widget depending on the context. + // Parent the widget to the owner of the menu. auto* active_menu_controller = views::MenuController::GetActiveInstance(); - if (active_menu_controller && active_menu_controller->owner()) { - params.parent = active_menu_controller->owner()->GetNativeView(); - params.child = true; - } else { - params.context = Shell::Get()->GetRootWindowForNewWindows(); - } + DCHECK(active_menu_controller && active_menu_controller->owner()); + params.parent = active_menu_controller->owner()->GetNativeView(); + params.child = true; views::Widget* widget = new views::Widget(); widget->Init(std::move(params));
diff --git a/chrome/browser/ui/autofill/chrome_autofill_client.cc b/chrome/browser/ui/autofill/chrome_autofill_client.cc index 51c20c7..73f14a8 100644 --- a/chrome/browser/ui/autofill/chrome_autofill_client.cc +++ b/chrome/browser/ui/autofill/chrome_autofill_client.cc
@@ -544,30 +544,11 @@ /*local_save_card_callback=*/{}); return; } - bool sync_disabled_wallet_transport_enabled = - GetPersonalDataManager()->GetSyncSigninState() == - autofill::AutofillSyncSigninState::kSignedInAndWalletSyncTransportEnabled; - AccountInfo account_info; - // AccountInfo data should be passed down only if the following conditions are - // satisfied: - // 1) Sync is off or the - // kAutofillEnableInfoBarAccountIndicationFooterForSyncUsers flag is on. - // 2) User has multiple accounts or the - // kAutofillEnableInfoBarAccountIndicationFooterForSingleAccountUsers is on. - if ((sync_disabled_wallet_transport_enabled || - base::FeatureList::IsEnabled( - features:: - kAutofillEnableInfoBarAccountIndicationFooterForSyncUsers)) && - (IsMultipleAccountUser() || - base::FeatureList::IsEnabled( - features:: - kAutofillEnableInfoBarAccountIndicationFooterForSingleAccountUsers))) { - signin::IdentityManager* identity_manager = - IdentityManagerFactory::GetForProfile(GetProfile()); - account_info = identity_manager->FindExtendedAccountInfo( - identity_manager->GetPrimaryAccountInfo(signin::ConsentLevel::kSignin)); - } + signin::IdentityManager* identity_manager = + IdentityManagerFactory::GetForProfile(GetProfile()); + AccountInfo account_info = identity_manager->FindExtendedAccountInfo( + identity_manager->GetPrimaryAccountInfo(signin::ConsentLevel::kSignin)); infobars::ContentInfoBarManager::FromWebContents(web_contents()) ->AddInfoBar(CreateSaveCardInfoBarMobile( std::make_unique<AutofillSaveCardInfoBarDelegateMobile>(
diff --git a/chrome/browser/ui/toolbar/toolbar_actions_model.cc b/chrome/browser/ui/toolbar/toolbar_actions_model.cc index 7db872ae..9afdb4ef 100644 --- a/chrome/browser/ui/toolbar/toolbar_actions_model.cc +++ b/chrome/browser/ui/toolbar/toolbar_actions_model.cc
@@ -226,6 +226,11 @@ return controller; } +const std::string& ToolbarActionsModel::GetExtensionName( + const ActionId& action_id) const { + return extension_registry_->enabled_extensions().GetByID(action_id)->name(); +} + bool ToolbarActionsModel::IsActionPinned(const ActionId& action_id) const { return base::Contains(pinned_action_ids_, action_id); }
diff --git a/chrome/browser/ui/toolbar/toolbar_actions_model.h b/chrome/browser/ui/toolbar/toolbar_actions_model.h index 9c3d2c5c..49a9265 100644 --- a/chrome/browser/ui/toolbar/toolbar_actions_model.h +++ b/chrome/browser/ui/toolbar/toolbar_actions_model.h
@@ -112,6 +112,9 @@ std::unique_ptr<extensions::ExtensionMessageBubbleController> GetExtensionMessageBubbleController(Browser* browser); + // Returns the extension name corresponding to the `action_id`. + const std::string& GetExtensionName(const ActionId& action_id) const; + // Returns true if the action is pinned to the toolbar. bool IsActionPinned(const ActionId& action_id) const;
diff --git a/chrome/browser/ui/views/extensions/extensions_tabbed_menu_view.cc b/chrome/browser/ui/views/extensions/extensions_tabbed_menu_view.cc index e603bf2b..508ee82 100644 --- a/chrome/browser/ui/views/extensions/extensions_tabbed_menu_view.cc +++ b/chrome/browser/ui/views/extensions/extensions_tabbed_menu_view.cc
@@ -5,24 +5,71 @@ #include "chrome/browser/ui/views/extensions/extensions_tabbed_menu_view.h" #include "base/feature_list.h" +#include "base/i18n/case_conversion.h" +#include "base/strings/utf_string_conversions.h" +#include "chrome/browser/ui/browser.h" +#include "chrome/browser/ui/toolbar/toolbar_action_view_controller.h" #include "chrome/browser/ui/ui_features.h" +#include "chrome/browser/ui/views/extensions/extensions_menu_item_view.h" +#include "chrome/browser/ui/views/extensions/extensions_toolbar_container.h" #include "chrome/grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/views/accessibility/view_accessibility.h" +#include "ui/views/controls/scroll_view.h" #include "ui/views/controls/tabbed_pane/tabbed_pane.h" #include "ui/views/layout/box_layout.h" #include "ui/views/layout/layout_provider.h" +#include "ui/views/view_utils.h" namespace { ExtensionsTabbedMenuView* g_extensions_dialog = nullptr; + +// Adds a new tab in `tabbed_pane` at `index` with the given `title` and +// `contents`. +void CreateTab(raw_ptr<views::TabbedPane> tabbed_pane, + size_t index, + int title_string_id, + std::unique_ptr<views::View> contents) { + // This is set so that the extensions menu doesn't fall outside the monitor in + // a maximized window in 1024x768. See https://crbug.com/1096630. + // TODO(pbos): Consider making this dynamic and handled by views. Ideally we + // wouldn't ever pop up so that they pop outside the screen. + constexpr int kMaxExtensionButtonsHeightDp = 448; + auto scroll_view = std::make_unique<views::ScrollView>(); + scroll_view->ClipHeightTo(0, kMaxExtensionButtonsHeightDp); + scroll_view->SetDrawOverflowIndicator(false); + scroll_view->SetHorizontalScrollBarMode( + views::ScrollView::ScrollBarMode::kDisabled); + scroll_view->SetContents(std::move(contents)); + + tabbed_pane->AddTabAtIndex(index, l10n_util::GetStringUTF16(title_string_id), + std::move(scroll_view)); +} + +// A helper method to convert to an ExtensionsMenuItemView. This cannot be used +// to *determine* if a view is an ExtensionsMenuItemView (it should only be used +// when the view is known to be one). It is only used as an extra measure to +// prevent bad static casts. +ExtensionsMenuItemView* GetAsMenuItemView(views::View* view) { + DCHECK(views::IsViewClass<ExtensionsMenuItemView>(view)); + return static_cast<ExtensionsMenuItemView*>(view); +} + } // namespace ExtensionsTabbedMenuView::ExtensionsTabbedMenuView( views::View* anchor_view, - ExtensionsToolbarButton::ButtonType button_type) + Browser* browser, + ExtensionsContainer* extensions_container, + ExtensionsToolbarButton::ButtonType button_type, + bool allow_pinning) : BubbleDialogDelegateView(anchor_view, - views::BubbleBorder::Arrow::TOP_RIGHT) { + views::BubbleBorder::Arrow::TOP_RIGHT), + browser_(browser), + extensions_container_(extensions_container), + toolbar_model_(ToolbarActionsModel::Get(browser_->profile())), + allow_pinning_(allow_pinning) { // Ensure layer masking is used for the extensions menu to ensure buttons with // layer effects sitting flush with the bottom of the bubble are clipped // appropriately. @@ -45,7 +92,7 @@ SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kVertical)); - CreateTabbedPane(button_type); + Populate(button_type); } ExtensionsTabbedMenuView::~ExtensionsTabbedMenuView() { @@ -55,10 +102,14 @@ // static views::Widget* ExtensionsTabbedMenuView::ShowBubble( views::View* anchor_view, - ExtensionsToolbarButton::ButtonType button_type) { + Browser* browser, + ExtensionsContainer* extensions_container_, + ExtensionsToolbarButton::ButtonType button_type, + bool allow_pining) { DCHECK(!g_extensions_dialog); DCHECK(base::FeatureList::IsEnabled(features::kExtensionsMenuAccessControl)); - g_extensions_dialog = new ExtensionsTabbedMenuView(anchor_view, button_type); + g_extensions_dialog = new ExtensionsTabbedMenuView( + anchor_view, browser, extensions_container_, button_type, allow_pining); views::Widget* widget = views::BubbleDialogDelegateView::CreateBubble(g_extensions_dialog); widget->Show(); @@ -86,6 +137,16 @@ return g_extensions_dialog; } +std::vector<ExtensionsMenuItemView*> +ExtensionsTabbedMenuView::GetInstalledItemsForTesting() const { + std::vector<ExtensionsMenuItemView*> menu_item_views; + if (IsShowing()) { + for (views::View* view : installed_items_->children()) + menu_item_views.push_back(GetAsMenuItemView(view)); + } + return menu_item_views; +} + size_t ExtensionsTabbedMenuView::GetSelectedTabIndex() const { return tabbed_pane_->GetSelectedTabIndex(); } @@ -95,27 +156,59 @@ return std::u16string(); } -void ExtensionsTabbedMenuView::CreateTabbedPane( +void ExtensionsTabbedMenuView::Populate( ExtensionsToolbarButton::ButtonType button_type) { + // The actions for the profile haven't been initialized yet. We'll call in + // again once they have. + if (!toolbar_model_->actions_initialized()) + return; + + DCHECK(children().empty()) << "Populate() can only be called once!"; + tabbed_pane_ = AddChildView(std::make_unique<views::TabbedPane>()); tabbed_pane_->SetFocusBehavior(views::View::FocusBehavior::NEVER); // TODO(crbug.com/1263310): Populate site access tab. - auto permissions_view = std::make_unique<views::View>(); - tabbed_pane_->AddTab( - l10n_util::GetStringUTF16(IDS_EXTENSIONS_MENU_SITE_ACCESS_TAB_TITLE), - std::move(permissions_view)); + CreateTab(tabbed_pane_, 0, IDS_EXTENSIONS_MENU_SITE_ACCESS_TAB_TITLE, + std::make_unique<views::View>()); - // TODO(crbug.com/1263311): Populate extensions installed tab. - auto installed_view = std::make_unique<views::View>(); - tabbed_pane_->AddTab( - l10n_util::GetStringUTF16(IDS_EXTENSIONS_MENU_EXTENSIONS_TAB_TITLE), - std::move(installed_view)); + auto installed_items = std::make_unique<views::View>(); + installed_items->SetLayoutManager(std::make_unique<views::BoxLayout>( + views::BoxLayout::Orientation::kVertical)); + installed_items_ = installed_items.get(); + CreateTab(tabbed_pane_, 1, IDS_EXTENSIONS_MENU_EXTENSIONS_TAB_TITLE, + std::move(installed_items)); + + // Sort action ids based on their extension name. + auto sort_by_name = [this](const ToolbarActionsModel::ActionId a, + const ToolbarActionsModel::ActionId b) { + return base::i18n::ToLower( + base::UTF8ToUTF16(toolbar_model_->GetExtensionName(a))) < + base::i18n::ToLower( + base::UTF8ToUTF16(toolbar_model_->GetExtensionName(b))); + }; + std::vector<std::string> sorted_ids(toolbar_model_->action_ids().begin(), + toolbar_model_->action_ids().end()); + std::sort(sorted_ids.begin(), sorted_ids.end(), sort_by_name); + + for (size_t i = 0; i < sorted_ids.size(); ++i) + CreateAndInsertInstalledExtension(sorted_ids[i], i); // Tabs left to right order is 'site access tab' | 'extensions tab'. tabbed_pane_->SelectTabAt(button_type == ExtensionsToolbarButton::ButtonType::kExtensions); } +void ExtensionsTabbedMenuView::CreateAndInsertInstalledExtension( + const ToolbarActionsModel::ActionId& id, + int index) { + std::unique_ptr<ExtensionActionViewController> controller = + ExtensionActionViewController::Create(id, browser_, + extensions_container_); + auto item = std::make_unique<ExtensionsMenuItemView>( + browser_, std::move(controller), allow_pinning_); + installed_items_->AddChildViewAt(std::move(item), index); +} + BEGIN_METADATA(ExtensionsTabbedMenuView, views::BubbleDialogDelegateView) END_METADATA
diff --git a/chrome/browser/ui/views/extensions/extensions_tabbed_menu_view.h b/chrome/browser/ui/views/extensions/extensions_tabbed_menu_view.h index 724b358..5fed59d 100644 --- a/chrome/browser/ui/views/extensions/extensions_tabbed_menu_view.h +++ b/chrome/browser/ui/views/extensions/extensions_tabbed_menu_view.h
@@ -6,6 +6,8 @@ #define CHROME_BROWSER_UI_VIEWS_EXTENSIONS_EXTENSIONS_TABBED_MENU_VIEW_H_ #include "base/memory/raw_ptr.h" +#include "chrome/browser/ui/extensions/extension_action_view_controller.h" +#include "chrome/browser/ui/toolbar/toolbar_actions_model.h" #include "chrome/browser/ui/views/extensions/extensions_toolbar_button.h" #include "ui/base/metadata/metadata_header_macros.h" #include "ui/views/bubble/bubble_dialog_delegate_view.h" @@ -14,6 +16,9 @@ class TabbedPane; } // namespace views +class ExtensionsMenuItemView; +class ExtensionsContainer; + // ExtensionsTabbedMenuView is the extensions menu dialog with a tabbed pane. // TODO(crbug.com/1263311): Brief explanation of each tabs goal after // implementing them. @@ -21,7 +26,10 @@ public: METADATA_HEADER(ExtensionsTabbedMenuView); ExtensionsTabbedMenuView(views::View* anchor_view, - ExtensionsToolbarButton::ButtonType button_type); + Browser* browser, + ExtensionsContainer* extensions_container, + ExtensionsToolbarButton::ButtonType button_type, + bool allow_pinning); ~ExtensionsTabbedMenuView() override; ExtensionsTabbedMenuView(const ExtensionsTabbedMenuView&) = delete; const ExtensionsTabbedMenuView& operator=(const ExtensionsTabbedMenuView&) = @@ -32,7 +40,10 @@ // shown at a time (outside of tests). static views::Widget* ShowBubble( views::View* anchor_view, - ExtensionsToolbarButton::ButtonType button_type); + Browser* browser, + ExtensionsContainer* extensions_container_, + ExtensionsToolbarButton::ButtonType button_type, + bool allow_pinning); // Returns true if there is currently an ExtensionsTabbedMenuView showing // (across all browsers and profiles). @@ -44,6 +55,10 @@ // Returns the currently-showing ExtensionsTabbedMenuView, if any exists. static ExtensionsTabbedMenuView* GetExtensionsTabbedMenuViewForTesting(); + // Returns the currently-showing extension items in the installed tab, if any + // exists. + std::vector<ExtensionsMenuItemView*> GetInstalledItemsForTesting() const; + // Returns the index of the currently selected tab. size_t GetSelectedTabIndex() const; @@ -53,10 +68,25 @@ private: // Initially creates the tabs and opens the corresponding one based on the // `button_type`. - void CreateTabbedPane(ExtensionsToolbarButton::ButtonType button_type_); + void Populate(ExtensionsToolbarButton::ButtonType button_type_); + + // Adds a menu item in the installed extensions for a newly-added extension. + void CreateAndInsertInstalledExtension( + const ToolbarActionsModel::ActionId& id, + int index); + + Browser* const browser_; + ExtensionsContainer* const extensions_container_; + ToolbarActionsModel* const toolbar_model_; + bool const allow_pinning_; // The view containing the menu's two tabs. raw_ptr<views::TabbedPane> tabbed_pane_ = nullptr; + + // The view containing the installed extension menu items. This is + // separated for easy insertion and iteration of menu items. The children are + // guaranteed to only be ExtensionMenuItemViews. + views::View* installed_items_ = nullptr; }; #endif // CHROME_BROWSER_UI_VIEWS_EXTENSIONS_EXTENSIONS_TABBED_MENU_VIEW_H_
diff --git a/chrome/browser/ui/views/extensions/extensions_tabbed_menu_view_unittest.cc b/chrome/browser/ui/views/extensions/extensions_tabbed_menu_view_unittest.cc index 0de9d46..f0820bd2 100644 --- a/chrome/browser/ui/views/extensions/extensions_tabbed_menu_view_unittest.cc +++ b/chrome/browser/ui/views/extensions/extensions_tabbed_menu_view_unittest.cc
@@ -1,12 +1,59 @@ // Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. + #include "chrome/browser/ui/views/extensions/extensions_tabbed_menu_view.h" #include "base/feature_list.h" +#include "base/test/metrics/user_action_tester.h" +#include "build/build_config.h" #include "chrome/browser/ui/ui_features.h" +#include "chrome/browser/ui/views/extensions/extensions_menu_button.h" +#include "chrome/browser/ui/views/extensions/extensions_menu_item_view.h" #include "chrome/browser/ui/views/extensions/extensions_toolbar_container.h" #include "chrome/browser/ui/views/extensions/extensions_toolbar_unittest.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "ui/views/view_utils.h" + +namespace { + +// A scoper that manages a Browser instance created by BrowserWithTestWindowTest +// beyond the default instance it creates in SetUp. +class AdditionalBrowser { + public: + explicit AdditionalBrowser(std::unique_ptr<Browser> browser) + : browser_(std::move(browser)), + browser_view_(BrowserView::GetBrowserViewForBrowser(browser_.get())) {} + + ~AdditionalBrowser() { + // Tear down `browser_`, similar to TestWithBrowserView::TearDown. + browser_.release(); + browser_view_->GetWidget()->CloseNow(); + } + + ExtensionsToolbarContainer* extensions_container() { + return browser_view_->toolbar()->extensions_container(); + } + + private: + std::unique_ptr<Browser> browser_; + BrowserView* browser_view_; +}; + +std::vector<std::string> GetNamesFromInstalledItems( + std::vector<ExtensionsMenuItemView*> installed_items) { + std::vector<std::string> names; + names.resize(installed_items.size()); + std::transform( + installed_items.begin(), installed_items.end(), names.begin(), + [](ExtensionsMenuItemView* item) { + return base::UTF16ToUTF8(item->primary_action_button_for_testing() + ->label_text_for_testing()); + }); + return names; +} + +} // namespace class ExtensionsTabbedMenuViewUnitTest : public ExtensionsToolbarUnitTest { public: @@ -30,9 +77,28 @@ ExtensionsTabbedMenuView* extensions_tabbed_menu() { return ExtensionsTabbedMenuView::GetExtensionsTabbedMenuViewForTesting(); } + std::vector<ExtensionsMenuItemView*> installed_items() { + return ExtensionsTabbedMenuView::GetExtensionsTabbedMenuViewForTesting() + ->GetInstalledItemsForTesting(); + } + + // Asserts there is exactly 1 menu item and then returns it. + ExtensionsMenuItemView* GetOnlyInstalledMenuItem(); + + // Returns a list of the views of the currently pinned extensions, in order + // from left to right. + std::vector<ToolbarActionView*> GetPinnedExtensionViews(); + + // Returns a list of the names of the currently pinned extensions, in order + // from left to right. + std::vector<std::string> GetPinnedExtensionNames(); + + void ShowTabbedMenu(); void ClickSiteAccessButton(); void ClickExtensionsButton(); + void ClickPinButton(ExtensionsMenuItemView* installed_item); + void ClickContextMenuButton(ExtensionsMenuItemView* installed_item); private: base::test::ScopedFeatureList scoped_feature_list_; @@ -43,6 +109,57 @@ features::kExtensionsMenuAccessControl); } +ExtensionsMenuItemView* +ExtensionsTabbedMenuViewUnitTest::GetOnlyInstalledMenuItem() { + std::vector<ExtensionsMenuItemView*> items = installed_items(); + if (items.size() != 1u) { + ADD_FAILURE() << "Not exactly one item; size is: " << items.size(); + return nullptr; + } + return *items.begin(); +} + +std::vector<ToolbarActionView*> +ExtensionsTabbedMenuViewUnitTest::GetPinnedExtensionViews() { + std::vector<ToolbarActionView*> result; + for (views::View* child : extensions_container()->children()) { + // Ensure we don't downcast the ExtensionsToolbarButton. + if (views::IsViewClass<ToolbarActionView>(child)) { + ToolbarActionView* const action = static_cast<ToolbarActionView*>(child); +#if defined(OS_MAC) + // TODO(crbug.com/1045212): Use IsActionVisibleOnToolbar() because it + // queries the underlying model and not GetVisible(), as that relies on an + // animation running, which is not reliable in unit tests on Mac. + const bool is_visible = extensions_container()->IsActionVisibleOnToolbar( + action->view_controller()); +#else + const bool is_visible = action->GetVisible(); +#endif + if (is_visible) + result.push_back(action); + } + } + return result; +} + +std::vector<std::string> +ExtensionsTabbedMenuViewUnitTest::GetPinnedExtensionNames() { + std::vector<ToolbarActionView*> views = GetPinnedExtensionViews(); + std::vector<std::string> result; + result.resize(views.size()); + std::transform( + views.begin(), views.end(), result.begin(), [](ToolbarActionView* view) { + return base::UTF16ToUTF8(view->view_controller()->GetActionName()); + }); + return result; +} + +void ExtensionsTabbedMenuViewUnitTest::ShowTabbedMenu() { + ExtensionsTabbedMenuView::ShowBubble( + extensions_button(), browser(), extensions_container(), + ExtensionsToolbarButton::ButtonType::kExtensions, true); +} + void ExtensionsTabbedMenuViewUnitTest::ClickSiteAccessButton() { ClickButton(site_access_button()); LayoutContainerIfNecessary(); @@ -53,6 +170,17 @@ LayoutContainerIfNecessary(); } +void ExtensionsTabbedMenuViewUnitTest::ClickPinButton( + ExtensionsMenuItemView* installed_item) { + ClickButton(installed_item->pin_button_for_testing()); + WaitForAnimation(); +} + +void ExtensionsTabbedMenuViewUnitTest::ClickContextMenuButton( + ExtensionsMenuItemView* installed_item) { + ClickButton(installed_item->context_menu_button_for_testing()); +} + TEST_F(ExtensionsTabbedMenuViewUnitTest, ButtonOpensAndClosesCorrespondingTab) { content::WebContentsTester* web_contents_tester = AddWebContentsAndGetTester(); @@ -130,3 +258,151 @@ ClickExtensionsButton(); EXPECT_FALSE(ExtensionsTabbedMenuView::IsShowing()); } + +TEST_F(ExtensionsTabbedMenuViewUnitTest, + InstalledExtensionsAreShownInInstalledTab) { + // To start, there should be no extensions in the menu. + EXPECT_EQ(installed_items().size(), 0u); + + // Add an extension, and verify that it's added to the menu. + constexpr char kExtensionName[] = "Test 1"; + InstallExtension(kExtensionName); + + ShowTabbedMenu(); + + ASSERT_EQ(installed_items().size(), 1u); + EXPECT_EQ(base::UTF16ToUTF8((*installed_items().begin()) + ->primary_action_button_for_testing() + ->label_text_for_testing()), + kExtensionName); +} + +TEST_F(ExtensionsTabbedMenuViewUnitTest, + InstalledTab_InstalledExtensionsAreSorted) { + constexpr char kExtensionZName[] = "Z Extension"; + InstallExtension(kExtensionZName); + constexpr char kExtensionAName[] = "A Extension"; + InstallExtension(kExtensionAName); + constexpr char kExtensionBName[] = "b Extension"; + InstallExtension(kExtensionBName); + constexpr char kExtensionCName[] = "C Extension"; + InstallExtension(kExtensionCName); + + ShowTabbedMenu(); + + std::vector<ExtensionsMenuItemView*> items = installed_items(); + ASSERT_EQ(items.size(), 4u); + + // Basic std::sort would do A,C,Z,b however we want A,b,C,Z + EXPECT_THAT(GetNamesFromInstalledItems(items), + testing::ElementsAre(kExtensionAName, kExtensionBName, + kExtensionCName, kExtensionZName)); +} + +TEST_F(ExtensionsTabbedMenuViewUnitTest, + InstalledTab_PinnedExtensionAppearsInToolbar) { + constexpr char kName[] = "Test Name"; + InstallExtension(kName); + + ShowTabbedMenu(); + + ExtensionsMenuItemView* installed_item = GetOnlyInstalledMenuItem(); + ASSERT_TRUE(installed_item); + ToolbarActionViewController* controller = installed_item->view_controller(); + EXPECT_FALSE(extensions_container()->IsActionVisibleOnToolbar(controller)); + EXPECT_THAT(GetPinnedExtensionNames(), testing::IsEmpty()); + + ClickPinButton(installed_item); + + EXPECT_TRUE(extensions_container()->IsActionVisibleOnToolbar(controller)); + EXPECT_THAT(GetPinnedExtensionNames(), testing::ElementsAre(kName)); + + ClickPinButton(installed_item); // Unpin. + + EXPECT_FALSE(extensions_container()->IsActionVisibleOnToolbar( + installed_item->view_controller())); + EXPECT_THAT(GetPinnedExtensionNames(), testing::IsEmpty()); +} + +TEST_F(ExtensionsTabbedMenuViewUnitTest, + InstalledTab_NewPinnedExtensionAppearsToTheRightOfPinnedExtensions) { + constexpr char kExtensionA[] = "A Extension"; + InstallExtension(kExtensionA); + constexpr char kExtensionB[] = "B Extension"; + InstallExtension(kExtensionB); + constexpr char kExtensionC[] = "C Extension"; + InstallExtension(kExtensionC); + + ShowTabbedMenu(); + + std::vector<ExtensionsMenuItemView*> items = installed_items(); + EXPECT_EQ(items.size(), 3u); + + // Verify the order of the extensions is A,B,C. + ASSERT_THAT(GetNamesFromInstalledItems(items), + testing::ElementsAre(kExtensionA, kExtensionB, kExtensionC)); + + ClickPinButton(items.at(0)); + EXPECT_THAT(GetPinnedExtensionNames(), testing::ElementsAre(kExtensionA)); + + // Pinning a second extension should add it to the right of the current pinned + // extensions. + ClickPinButton(items.at(1)); + EXPECT_THAT(GetPinnedExtensionNames(), + testing::ElementsAre(kExtensionA, kExtensionB)); + + // Pinning a third extension should add it to the right of the current pinned + // extensions. + ClickPinButton(items.at(2)); + EXPECT_THAT(GetPinnedExtensionNames(), + testing::ElementsAre(kExtensionA, kExtensionB, kExtensionC)); + + // Unpinning the middle extension should remove it from the toolbar without + // affecting the order of the other pinned extensions. + ClickPinButton(items.at(1)); + EXPECT_THAT(GetPinnedExtensionNames(), + testing::ElementsAre(kExtensionA, kExtensionC)); + + // Pinning an extension should add it to the right of the current pinned + // extensions, even if it was pinned and unpinned previously. + ClickPinButton(items.at(1)); + EXPECT_THAT(GetPinnedExtensionNames(), + testing::ElementsAre(kExtensionA, kExtensionC, kExtensionB)); +} + +TEST_F(ExtensionsTabbedMenuViewUnitTest, + InstalledTab_PinnedExtensionAppearsInAnotherWindow) { + InstallExtension("Test Name"); + + ShowTabbedMenu(); + + AdditionalBrowser browser2( + CreateBrowser(browser()->profile(), browser()->type(), + /* hosted_app */ false, /* browser_window */ nullptr)); + + ExtensionsMenuItemView* installed_item = GetOnlyInstalledMenuItem(); + ASSERT_TRUE(installed_item); + ClickPinButton(installed_item); + + // Window that was already open gets the pinned extension. + EXPECT_TRUE(browser2.extensions_container()->IsActionVisibleOnToolbar( + installed_item->view_controller())); + + AdditionalBrowser browser3( + CreateBrowser(browser()->profile(), browser()->type(), + /* hosted_app */ false, /* browser_window */ nullptr)); + + // Brand-new window also gets the pinned extension. + EXPECT_TRUE(browser3.extensions_container()->IsActionVisibleOnToolbar( + installed_item->view_controller())); +} + +TEST_F(ExtensionsTabbedMenuViewUnitTest, WindowTitle) { + InstallExtension("Test Extension"); + + ShowTabbedMenu(); + + ExtensionsTabbedMenuView* menu = extensions_tabbed_menu(); + EXPECT_FALSE(menu->GetWindowTitle().empty()); + EXPECT_TRUE(menu->GetAccessibleWindowTitle().empty()); +}
diff --git a/chrome/browser/ui/views/extensions/extensions_toolbar_button.cc b/chrome/browser/ui/views/extensions/extensions_toolbar_button.cc index d62b5dab..ba34dee 100644 --- a/chrome/browser/ui/views/extensions/extensions_toolbar_button.cc +++ b/chrome/browser/ui/views/extensions/extensions_toolbar_button.cc
@@ -151,7 +151,9 @@ base::RecordAction(base::UserMetricsAction("Extensions.Toolbar.MenuOpened")); views::Widget* menu; if (base::FeatureList::IsEnabled(features::kExtensionsMenuAccessControl)) { - menu = ExtensionsTabbedMenuView::ShowBubble(this, button_type_); + menu = ExtensionsTabbedMenuView::ShowBubble( + this, browser_, extensions_container_, button_type_, + extensions_container_->CanShowIconInToolbar()); } else { menu = ExtensionsMenuView::ShowBubble( this, browser_, extensions_container_,
diff --git a/chrome/browser/ui/views/frame/opaque_browser_frame_view.cc b/chrome/browser/ui/views/frame/opaque_browser_frame_view.cc index e2e8736de..6610961 100644 --- a/chrome/browser/ui/views/frame/opaque_browser_frame_view.cc +++ b/chrome/browser/ui/views/frame/opaque_browser_frame_view.cc
@@ -751,12 +751,12 @@ } void OpaqueBrowserFrameView::WindowIconPressed() { -#if defined(OS_LINUX) || defined(OS_CHROMEOS) - // TODO(pbos): Figure out / document why this is Linux only. This needs a - // comment. - views::MenuRunner menu_runner(frame()->GetSystemMenuModel(), - views::MenuRunner::HAS_MNEMONICS); - menu_runner.RunMenuAt( +#if defined(OS_LINUX) + // Chrome OS doesn't show the window icon, and Windows handles this on its own + // due to the hit test being HTSYSMENU. + menu_runner_ = std::make_unique<views::MenuRunner>( + frame()->GetSystemMenuModel(), views::MenuRunner::HAS_MNEMONICS); + menu_runner_->RunMenuAt( browser_view()->GetWidget(), window_icon_->button_controller(), window_icon_->GetBoundsInScreen(), views::MenuAnchorPosition::kTopLeft, ui::MENU_SOURCE_MOUSE);
diff --git a/chrome/browser/ui/views/frame/opaque_browser_frame_view.h b/chrome/browser/ui/views/frame/opaque_browser_frame_view.h index 4c26687..2367652c 100644 --- a/chrome/browser/ui/views/frame/opaque_browser_frame_view.h +++ b/chrome/browser/ui/views/frame/opaque_browser_frame_view.h
@@ -224,6 +224,10 @@ // Background painter for the window frame. std::unique_ptr<views::FrameBackground> frame_background_; +#if defined(OS_LINUX) + std::unique_ptr<views::MenuRunner> menu_runner_; +#endif + // PlaceholderContainer beneath the controls button for PWAs with window // controls overlay display override. raw_ptr<CaptionButtonPlaceholderContainer>
diff --git a/chrome/browser/ui/webauthn/sheet_models.cc b/chrome/browser/ui/webauthn/sheet_models.cc index 53f622e..437ffab 100644 --- a/chrome/browser/ui/webauthn/sheet_models.cc +++ b/chrome/browser/ui/webauthn/sheet_models.cc
@@ -1179,11 +1179,9 @@ } std::u16string AuthenticatorQRSheetModel::GetStepTitle() const { - // TODO: i18n once final strings are ready. - return u"Use your phone"; + return l10n_util::GetStringUTF16(IDS_WEBAUTHN_CABLEV2_ADD_PHONE); } std::u16string AuthenticatorQRSheetModel::GetStepDescription() const { - // TODO: i18n once final strings are ready. - return u"Scan this QR Code with your Android phone."; + return l10n_util::GetStringUTF16(IDS_BROWSER_SHARING_QR_CODE_DIALOG_TOOLTIP); }
diff --git a/chrome/browser/ui/webui/chromeos/bluetooth_pairing_dialog.cc b/chrome/browser/ui/webui/chromeos/bluetooth_pairing_dialog.cc index 8ce1ebe..d89ef02 100644 --- a/chrome/browser/ui/webui/chromeos/bluetooth_pairing_dialog.cc +++ b/chrome/browser/ui/webui/chromeos/bluetooth_pairing_dialog.cc
@@ -33,7 +33,7 @@ namespace { constexpr int kBluetoothPairingDialogHeight = 375; -constexpr int kBluetoothPairingDialogHeightWithFlag = 408; +constexpr int kBluetoothPairingDialogHeightWithFlag = 424; void AddBluetoothStrings(content::WebUIDataSource* html_source) { struct {
diff --git a/chrome/browser/ui/webui/chromeos/login/app_downloading_screen_handler.cc b/chrome/browser/ui/webui/chromeos/login/app_downloading_screen_handler.cc index 5e80581..116a53e 100644 --- a/chrome/browser/ui/webui/chromeos/login/app_downloading_screen_handler.cc +++ b/chrome/browser/ui/webui/chromeos/login/app_downloading_screen_handler.cc
@@ -37,7 +37,10 @@ set_user_acted_method_path("login.AppDownloadingScreen.userActed"); } -AppDownloadingScreenHandler::~AppDownloadingScreenHandler() {} +AppDownloadingScreenHandler::~AppDownloadingScreenHandler() { + if (screen_) + screen_->OnViewDestroyed(this); +} void AppDownloadingScreenHandler::DeclareLocalizedValues( ::login::LocalizedValuesBuilder* builder) {
diff --git a/chrome/browser/ui/webui/chromeos/parent_access/parent_access_ui_handler_impl.cc b/chrome/browser/ui/webui/chromeos/parent_access/parent_access_ui_handler_impl.cc index 9ef662b4a..1d6001c 100644 --- a/chrome/browser/ui/webui/chromeos/parent_access/parent_access_ui_handler_impl.cc +++ b/chrome/browser/ui/webui/chromeos/parent_access/parent_access_ui_handler_impl.cc
@@ -35,7 +35,6 @@ signin::ScopeSet scopes; scopes.insert(GaiaConstants::kParentApprovalOAuth2Scope); scopes.insert(GaiaConstants::kProgrammaticChallengeOAuth2Scope); - scopes.insert(GaiaConstants::kKidManagementOAuth2Scope); if (oauth2_access_token_fetcher_) { // Only one GetOAuthToken call can happen at a time.
diff --git a/chrome/browser/ui/webui/history/browsing_history_handler.cc b/chrome/browser/ui/webui/history/browsing_history_handler.cc index 5436f1e..867d4fb9 100644 --- a/chrome/browser/ui/webui/history/browsing_history_handler.cc +++ b/chrome/browser/ui/webui/history/browsing_history_handler.cc
@@ -37,7 +37,7 @@ #include "components/favicon/core/fallback_url_util.h" #include "components/favicon/core/large_icon_service.h" #include "components/favicon_base/favicon_url_parser.h" -#include "components/history_clusters/core/memories_features.h" +#include "components/history_clusters/core/features.h" #include "components/keyed_service/core/service_access_type.h" #include "components/prefs/pref_service.h" #include "components/query_parser/snippet.h"
diff --git a/chrome/browser/ui/webui/history/history_ui.cc b/chrome/browser/ui/webui/history/history_ui.cc index d808487..caa6e79 100644 --- a/chrome/browser/ui/webui/history/history_ui.cc +++ b/chrome/browser/ui/webui/history/history_ui.cc
@@ -35,8 +35,8 @@ #include "chrome/grit/locale_settings.h" #include "components/favicon_base/favicon_url_parser.h" #include "components/grit/components_scaled_resources.h" +#include "components/history_clusters/core/features.h" #include "components/history_clusters/core/history_clusters_prefs.h" -#include "components/history_clusters/core/memories_features.h" #include "components/prefs/pref_service.h" #include "components/signin/public/base/signin_pref_names.h" #include "components/signin/public/identity_manager/identity_manager.h"
diff --git a/chrome/browser/ui/webui/history_clusters/history_clusters_handler.cc b/chrome/browser/ui/webui/history_clusters/history_clusters_handler.cc index be1ca95..b94e0ee 100644 --- a/chrome/browser/ui/webui/history_clusters/history_clusters_handler.cc +++ b/chrome/browser/ui/webui/history_clusters/history_clusters_handler.cc
@@ -20,8 +20,8 @@ #include "chrome/browser/search_engines/template_url_service_factory.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_finder.h" +#include "components/history_clusters/core/features.h" #include "components/history_clusters/core/history_clusters_prefs.h" -#include "components/history_clusters/core/memories_features.h" #include "components/prefs/pref_service.h" #include "components/search_engines/template_url.h" #include "components/search_engines/template_url_service.h"
diff --git a/chrome/browser/ui/webui/history_clusters/history_clusters_handler_browsertest.cc b/chrome/browser/ui/webui/history_clusters/history_clusters_handler_browsertest.cc index 2cfcaca..d665d80 100644 --- a/chrome/browser/ui/webui/history_clusters/history_clusters_handler_browsertest.cc +++ b/chrome/browser/ui/webui/history_clusters/history_clusters_handler_browsertest.cc
@@ -13,7 +13,7 @@ #include "chrome/common/webui_url_constants.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" -#include "components/history_clusters/core/memories_features.h" +#include "components/history_clusters/core/features.h" #include "content/public/test/browser_test.h" #include "content/public/test/browser_test_utils.h"
diff --git a/chrome/browser/ui/webui/settings/privacy_review_handler_unittest.cc b/chrome/browser/ui/webui/settings/privacy_review_handler_unittest.cc index 5cfb73a..bf3e199 100644 --- a/chrome/browser/ui/webui/settings/privacy_review_handler_unittest.cc +++ b/chrome/browser/ui/webui/settings/privacy_review_handler_unittest.cc
@@ -64,10 +64,9 @@ PrivacyReviewHandler* handler() { return handler_.get(); } TestingProfile* profile() { return &profile_; } - protected: + private: content::BrowserTaskEnvironment browser_task_environment_; content::RenderViewHostTestEnabler render_view_host_test_enabler_; - base::test::ScopedFeatureList feature_list_; TestingProfile profile_; std::unique_ptr<content::WebContents> web_contents_ = content::WebContentsTester::CreateTestWebContents(profile(), nullptr); @@ -75,27 +74,15 @@ std::unique_ptr<PrivacyReviewHandler> handler_; }; -class PrivacyReviewHandlerDisabledTest : public PrivacyReviewHandlerTest { - public: - PrivacyReviewHandlerDisabledTest() { - feature_list_.InitAndDisableFeature(features::kPrivacyReview); - } -}; - -class PrivacyReviewHandlerEnabledTest : public PrivacyReviewHandlerTest { - public: - PrivacyReviewHandlerEnabledTest() { - feature_list_.InitAndEnableFeature(features::kPrivacyReview); - } -}; - -TEST_F(PrivacyReviewHandlerDisabledTest, IsPrivacyReviewAvailable) { +TEST_F(PrivacyReviewHandlerTest, IsPrivacyReviewAvailable) { // Privacy review is not available when the experimental flag is disabled. + base::test::ScopedFeatureList feature_list; + feature_list.InitAndDisableFeature(features::kPrivacyReview); ValidateIsPrivacyReviewAvailable(false); -} -TEST_F(PrivacyReviewHandlerEnabledTest, IsPrivacyReviewAvailable) { - // Privacy review is available when the experimental flag is enabled. + // Once the flag is enabled, privacy review is available. + feature_list.Reset(); + feature_list.InitAndEnableFeature(features::kPrivacyReview); ValidateIsPrivacyReviewAvailable(true); // If the browser is managed, then privacy review is not available.
diff --git a/chrome/browser/ui/webui/settings/settings_security_key_handler.cc b/chrome/browser/ui/webui/settings/settings_security_key_handler.cc index 4c813f51..7efb7f2 100644 --- a/chrome/browser/ui/webui/settings/settings_security_key_handler.cc +++ b/chrome/browser/ui/webui/settings/settings_security_key_handler.cc
@@ -492,8 +492,7 @@ for (const auto& response : *responses) { for (const auto& credential : response.credentials) { base::DictionaryValue credential_value; - std::string credential_id = - base::HexEncode(credential.credential_id.id()); + std::string credential_id = base::HexEncode(credential.credential_id.id); if (credential_id.empty()) { NOTREACHED(); continue;
diff --git a/chrome/browser/ui/webui/settings/settings_ui.cc b/chrome/browser/ui/webui/settings/settings_ui.cc index 3febf74..66f32a2 100644 --- a/chrome/browser/ui/webui/settings/settings_ui.cc +++ b/chrome/browser/ui/webui/settings/settings_ui.cc
@@ -263,14 +263,6 @@ std::make_unique<IncompatibleApplicationsHandler>()); #endif // OS_WIN && BUILDFLAG(GOOGLE_CHROME_BRANDING) - // TODO(crbug.com/1271661): Update the UI and stop passing this boolean. - bool enable_landing_page_redesign = true; - html_source->AddString( - "enableLandingPageRedesignAttribute", - enable_landing_page_redesign ? "enable-landing-page-redesign" : ""); - html_source->AddBoolean("enableLandingPageRedesign", - enable_landing_page_redesign); - html_source->AddString( "enableBrandingUpdateAttribute", base::FeatureList::IsEnabled(features::kWebUIBrandingUpdate)
diff --git a/chrome/browser/web_applications/isolated_app_browsertest.cc b/chrome/browser/web_applications/isolated_app_browsertest.cc index a66da45f..ca2823a0 100644 --- a/chrome/browser/web_applications/isolated_app_browsertest.cc +++ b/chrome/browser/web_applications/isolated_app_browsertest.cc
@@ -9,6 +9,8 @@ #include "chrome/browser/web_applications/test/web_app_test_utils.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/test/browser_test.h" +#include "content/public/test/browser_test_utils.h" +#include "net/test/embedded_test_server/embedded_test_server.h" #include "third_party/blink/public/common/features.h" namespace web_app { @@ -17,6 +19,7 @@ const char kAppHost[] = "app.com"; const char kApp2Host[] = "app2.com"; +const char kNonAppHost[] = "nonapp.com"; } // namespace @@ -75,4 +78,107 @@ app2_frame->GetStoragePartition()); } +class IsolatedAppBrowserCookieTest : public IsolatedAppBrowserTest { + public: + using CookieHeaders = std::vector<std::string>; + + void SetUpOnMainThread() override { + https_server()->RegisterRequestMonitor(base::BindRepeating( + &IsolatedAppBrowserCookieTest::MonitorRequest, base::Unretained(this))); + + IsolatedAppBrowserTest::SetUpOnMainThread(); + } + + protected: + // Returns the "Cookie" headers that were received for the given URL. + const CookieHeaders& GetCookieHeadersForUrl(const GURL& url) { + return cookie_map_[url.spec()]; + } + + void CreateIframe(content::RenderFrameHost* parent_frame, + const std::string& iframe_id, + const GURL& url) { + EXPECT_EQ(true, content::EvalJs(parent_frame, + content::JsReplace(R"( + new Promise(resolve => { + let f = document.createElement('iframe'); + f.id = $1; + f.src = $2; + f.addEventListener('load', () => resolve(true)); + document.body.appendChild(f); + }); + )", + iframe_id, url))); + } + + content::RenderFrameHost* NavigateToURLInNewTab(const GURL& url) { + auto new_contents = content::WebContents::Create( + content::WebContents::CreateParams(browser()->profile())); + browser()->tab_strip_model()->AppendWebContents(std::move(new_contents), + /*foreground=*/true); + return ui_test_utils::NavigateToURL(browser(), url); + } + + private: + void MonitorRequest(const net::test_server::HttpRequest& request) { + // Replace the host in |request.GetURL()| with the value from the Host + // header, as GetURL()'s host will be 127.0.0.1. + std::string host = GURL("https://" + GetHeader(request, "Host")).host(); + GURL::Replacements replace_host; + replace_host.SetHostStr(host); + GURL url = request.GetURL().ReplaceComponents(replace_host); + cookie_map_[url.spec()].push_back(GetHeader(request, "cookie")); + } + + std::string GetHeader(const net::test_server::HttpRequest& request, + std::string header_name) { + auto header = request.headers.find(header_name); + return header != request.headers.end() ? header->second : ""; + } + + // Maps GURLs to a vector of cookie strings. The nth item in the vector will + // contain the contents of the "Cookies" header for the nth request to the + // given GURL. + std::unordered_map<std::string, CookieHeaders> cookie_map_; +}; + +IN_PROC_BROWSER_TEST_F(IsolatedAppBrowserCookieTest, Cookies) { + InstallIsolatedApp(kAppHost); + + // Load a page that sets a cookie, then create a cross-origin iframe that + // loads the same page. + GURL app_url = + https_server()->GetURL(kAppHost, "/banners/isolated/cookie.html"); + auto* app_window = NavigateInNewWindowAndAwaitInstallabilityCheck(app_url); + auto* app_frame = GetMainFrame(app_window); + GURL non_app_url = + https_server()->GetURL(kNonAppHost, "/banners/isolated/cookie.html"); + CreateIframe(app_frame, "child", non_app_url); + + const auto& app_cookies = GetCookieHeadersForUrl(app_url); + EXPECT_EQ(1u, app_cookies.size()); + EXPECT_TRUE(app_cookies[0].empty()); + const auto& non_app_cookies = GetCookieHeadersForUrl(non_app_url); + EXPECT_EQ(1u, non_app_cookies.size()); + EXPECT_TRUE(non_app_cookies[0].empty()); + + // Load the pages again. Both frames should send the cookie in their requests. + auto* app_window2 = NavigateInNewWindowAndAwaitInstallabilityCheck(app_url); + auto* app_frame2 = GetMainFrame(app_window2); + CreateIframe(app_frame2, "child", non_app_url); + + EXPECT_EQ(2u, app_cookies.size()); + EXPECT_EQ("foo=bar", app_cookies[1]); + EXPECT_EQ(2u, non_app_cookies.size()); + EXPECT_EQ("foo=bar", non_app_cookies[1]); + + // Load the cross-origin's iframe as a top-level page. Because this page was + // previously loaded in an isolated app, it shouldn't have cookies set when + // loaded in a main frame here. + ASSERT_TRUE(NavigateToURLInNewTab(non_app_url)); + + EXPECT_EQ(3u, non_app_cookies.size()); + EXPECT_TRUE(non_app_cookies[2].empty()); +} + } // namespace web_app
diff --git a/chrome/browser/webauthn/authenticator_request_dialog_model.cc b/chrome/browser/webauthn/authenticator_request_dialog_model.cc index 60c4c6ab..4427cf4 100644 --- a/chrome/browser/webauthn/authenticator_request_dialog_model.cc +++ b/chrome/browser/webauthn/authenticator_request_dialog_model.cc
@@ -728,7 +728,7 @@ } } -void AuthenticatorRequestDialogModel::StartGuidedFlowForOtherPhone( +void AuthenticatorRequestDialogModel::StartGuidedFlowForAddPhone( size_t mechanism_index) { current_mechanism_ = mechanism_index; EnsureBleAdapterIsPoweredAndContinueWithStep(Step::kCableV2QRCode); @@ -848,7 +848,7 @@ }; const auto kCable = AuthenticatorTransport::kCloudAssistedBluetoothLowEnergy; - bool include_other_phone_mechanism = false; + bool include_add_phone_option = false; if (cable_ui_type_) { switch (*cable_ui_type_) { @@ -856,7 +856,7 @@ if (base::FeatureList::IsEnabled(device::kWebAuthPhoneSupport) && base::Contains(transport_availability_.available_transports, kCable)) { - include_other_phone_mechanism = true; + include_add_phone_option = true; } break; @@ -886,6 +886,17 @@ } } + if (include_add_phone_option) { + const std::u16string label = + l10n_util::GetStringUTF16(IDS_WEBAUTHN_CABLEV2_ADD_PHONE); + mechanisms_.emplace_back( + Mechanism::AddPhone(), label, label, &kQrcodeGeneratorIcon, + base::BindRepeating( + &AuthenticatorRequestDialogModel::StartGuidedFlowForAddPhone, + base::Unretained(this), mechanisms_.size()), + /*is_priority=*/false); + } + for (const auto transport : transports_to_list_if_active) { if (!base::Contains(transport_availability_.available_transports, transport)) { @@ -933,19 +944,6 @@ mechanisms_.size()), /*priority=*/false); } - - if (include_other_phone_mechanism) { - // TODO(agl): i18n once final strings are ready. - const std::u16string label = - paired_phones_.empty() ? u"Your phone" : u"Another phone"; - - mechanisms_.emplace_back( - Mechanism::OtherPhone(), label, label, GetTransportIcon(kCable), - base::BindRepeating( - &AuthenticatorRequestDialogModel::StartGuidedFlowForOtherPhone, - base::Unretained(this), mechanisms_.size()), - /*is_priority=*/false); - } } // At most one mechanism has priority.
diff --git a/chrome/browser/webauthn/authenticator_request_dialog_model.h b/chrome/browser/webauthn/authenticator_request_dialog_model.h index d494f5e..a9e10138 100644 --- a/chrome/browser/webauthn/authenticator_request_dialog_model.h +++ b/chrome/browser/webauthn/authenticator_request_dialog_model.h
@@ -158,9 +158,9 @@ using WindowsAPI = base::StrongAlias<class WindowsAPITag, bool /* unused, but cannot be void */>; using Phone = base::StrongAlias<class PhoneTag, std::string>; - using OtherPhone = base::StrongAlias<class OtherPhoneTag, - bool /* unused, but cannot be void */>; - using Type = absl::variant<Transport, WindowsAPI, Phone, OtherPhone>; + using AddPhone = base::StrongAlias<class AddPhoneTag, + bool /* unused, but cannot be void */>; + using Type = absl::variant<Transport, WindowsAPI, Phone, AddPhone>; Mechanism(Type type, std::u16string name, @@ -577,7 +577,7 @@ size_t mechanism_index); // Starts the flow for adding an unlisted phone by showing a QR code. - void StartGuidedFlowForOtherPhone(size_t mechanism_index); + void StartGuidedFlowForAddPhone(size_t mechanism_index); // Displays a resident-key warning if needed and then calls // |HideDialogAndDispatchToNativeWindowsApi|.
diff --git a/chrome/build/linux.pgo.txt b/chrome/build/linux.pgo.txt index 848043b..fc5f827 100644 --- a/chrome/build/linux.pgo.txt +++ b/chrome/build/linux.pgo.txt
@@ -1 +1 @@ -chrome-linux-main-1638878402-257c3d035086dd3184da72d5e94956c6ae0542a0.profdata +chrome-linux-main-1638900013-db184c25401df262649790cdae5da13614a59acd.profdata
diff --git a/chrome/build/mac.pgo.txt b/chrome/build/mac.pgo.txt index 50aebbb..a80e016a 100644 --- a/chrome/build/mac.pgo.txt +++ b/chrome/build/mac.pgo.txt
@@ -1 +1 @@ -chrome-mac-main-1638878402-dd7da4b8a6d403311de80201ef628ea2af4f9c10.profdata +chrome-mac-main-1638900013-010ce28736fd8ab0074480388494541e79eec8bb.profdata
diff --git a/chrome/build/win32.pgo.txt b/chrome/build/win32.pgo.txt index b8a6a45..23c0269 100644 --- a/chrome/build/win32.pgo.txt +++ b/chrome/build/win32.pgo.txt
@@ -1 +1 @@ -chrome-win32-main-1638878402-e319e7696f32fb798b4dafc535f5819f66681318.profdata +chrome-win32-main-1638900013-7b4fa9227e1500597c04f339b6c0f220bba38bfc.profdata
diff --git a/chrome/build/win64.pgo.txt b/chrome/build/win64.pgo.txt index a1cac20..63cbb2e 100644 --- a/chrome/build/win64.pgo.txt +++ b/chrome/build/win64.pgo.txt
@@ -1 +1 @@ -chrome-win64-main-1638845609-0991408c5eca403a0ac4a7e202b5601f453bd29b.profdata +chrome-win64-main-1638900013-d1c807884ad964426f81cb800819d31ca57389a5.profdata
diff --git a/chrome/renderer/DEPS b/chrome/renderer/DEPS index 3229da0..2cc4b43 100644 --- a/chrome/renderer/DEPS +++ b/chrome/renderer/DEPS
@@ -28,7 +28,7 @@ "+components/feed/feed_feature_list.h", "+components/grit", "+components/guest_view/renderer", - "+components/history_clusters/core/memories_features.h", + "+components/history_clusters/core/features.h", "+components/metrics/child_call_stack_profile_collector.h", "+components/nacl/common", "+components/nacl/renderer",
diff --git a/chrome/renderer/chrome_content_renderer_client.cc b/chrome/renderer/chrome_content_renderer_client.cc index 2bc6361..b8cd3aa29 100644 --- a/chrome/renderer/chrome_content_renderer_client.cc +++ b/chrome/renderer/chrome_content_renderer_client.cc
@@ -87,7 +87,7 @@ #include "components/error_page/common/localized_error.h" #include "components/feed/buildflags.h" #include "components/grit/components_scaled_resources.h" -#include "components/history_clusters/core/memories_features.h" +#include "components/history_clusters/core/features.h" #include "components/network_hints/renderer/web_prescient_networking_impl.h" #include "components/no_state_prefetch/common/prerender_url_loader_throttle.h" #include "components/no_state_prefetch/renderer/no_state_prefetch_client.h"
diff --git a/chrome/services/printing/print_backend_service_impl.cc b/chrome/services/printing/print_backend_service_impl.cc index 854e7e3..7ab2b7a 100644 --- a/chrome/services/printing/print_backend_service_impl.cc +++ b/chrome/services/printing/print_backend_service_impl.cc
@@ -368,16 +368,6 @@ return; } - // Save all the document settings for use through the print job, until the - // time that this document can complete printing. Track the order of - // received documents with position in `documents_`. - auto document = base::MakeRefCounted<PrintedDocument>( - std::make_unique<PrintSettings>(settings), document_name, - document_cookie); - documents_.push_back( - std::make_unique<PrintBackendServiceImpl::DocumentContainer>( - document, target_type, std::move(callback))); - #if defined(OS_CHROMEOS) && defined(USE_CUPS) CupsConnectionPool* connection_pool = CupsConnectionPool::GetInstance(); if (connection_pool) { @@ -394,6 +384,16 @@ } #endif + // Save all the document settings for use through the print job, until the + // time that this document can complete printing. Track the order of + // received documents with position in `documents_`. + auto document = base::MakeRefCounted<PrintedDocument>( + std::make_unique<PrintSettings>(settings), document_name, + document_cookie); + documents_.push_back( + std::make_unique<PrintBackendServiceImpl::DocumentContainer>( + document, target_type, std::move(callback))); + // Safe to use `base::Unretained(this)` because `this` outlives the callback. // The entire service process goes away when `this` lifetime expires. DocumentContainer& document_container = *documents_.back();
diff --git a/chrome/test/data/banners/isolated/cookie.html b/chrome/test/data/banners/isolated/cookie.html new file mode 100644 index 0000000..54bcc5a --- /dev/null +++ b/chrome/test/data/banners/isolated/cookie.html
@@ -0,0 +1 @@ +Page whose response sets a cookie and COOP/COEP/CORP headers.
diff --git a/chrome/test/data/banners/isolated/cookie.html.mock-http-headers b/chrome/test/data/banners/isolated/cookie.html.mock-http-headers new file mode 100644 index 0000000..b3b4871 --- /dev/null +++ b/chrome/test/data/banners/isolated/cookie.html.mock-http-headers
@@ -0,0 +1,6 @@ +HTTP/1.1 200 OK +Content-Type: text/html +Cross-Origin-Opener-Policy: same-origin +Cross-Origin-Embedder-Policy: require-corp +Cross-Origin-Resource-Policy: cross-origin +Set-Cookie: foo=bar; SameSite=None; Secure
diff --git a/chrome/test/data/webui/chromeos/shimless_rma/fake_shimless_rma_service_test.js b/chrome/test/data/webui/chromeos/shimless_rma/fake_shimless_rma_service_test.js index ba20cfa3..94b0342 100644 --- a/chrome/test/data/webui/chromeos/shimless_rma/fake_shimless_rma_service_test.js +++ b/chrome/test/data/webui/chromeos/shimless_rma/fake_shimless_rma_service_test.js
@@ -4,7 +4,7 @@ import {fakeCalibrationComponents} from 'chrome://shimless-rma/fake_data.js'; import {FakeShimlessRmaService} from 'chrome://shimless-rma/fake_shimless_rma_service.js'; -import {CalibrationComponentStatus, CalibrationObserverRemote, CalibrationOverallStatus, CalibrationSetupInstruction, CalibrationStatus, ComponentRepairStatus, ComponentType, ErrorObserverRemote, FinalizationObserverRemote, FinalizationStatus, HardwareVerificationStatusObserverRemote, HardwareWriteProtectionStateObserverRemote, OsUpdateObserverRemote, OsUpdateOperation, PowerCableStateObserverRemote, ProvisioningObserverRemote, ProvisioningStatus, RmadErrorCode, State, WriteProtectDisableCompleteAction} from 'chrome://shimless-rma/shimless_rma_types.js'; +import {CalibrationComponentStatus, CalibrationObserverRemote, CalibrationOverallStatus, CalibrationSetupInstruction, CalibrationStatus, ComponentRepairStatus, ComponentType, ErrorObserverRemote, FinalizationObserverRemote, FinalizationStatus, HardwareVerificationStatusObserverRemote, HardwareWriteProtectionStateObserverRemote, OsUpdateObserverRemote, OsUpdateOperation, PowerCableStateObserverRemote, ProvisioningObserverRemote, ProvisioningStatus, RmadErrorCode, State, UpdateRoFirmwareObserverRemote, UpdateRoFirmwareStatus, WriteProtectDisableCompleteAction} from 'chrome://shimless-rma/shimless_rma_types.js'; import {assertDeepEquals, assertEquals, assertFalse, assertTrue} from '../../chai_assert.js'; @@ -849,6 +849,24 @@ OsUpdateOperation.kDownloading, 0.75, 0); }); + test('ObserveRoFirmwareUpdate', () => { + /** @type {!UpdateRoFirmwareObserverRemote} */ + const roFirmwareUpdateObserver = + /** @type {!UpdateRoFirmwareObserverRemote} */ ({ + /** + * Implements + * UpdateRoFirmwareObserver.onUpdateRoFirmwareStatusChanged() + * @param {!UpdateRoFirmwareStatus} status + */ + onUpdateRoFirmwareStatusChanged(status) { + assertEquals(UpdateRoFirmwareStatus.kDownloading, status); + } + }); + service.observeRoFirmwareUpdateProgress(roFirmwareUpdateObserver); + return service.triggerUpdateRoFirmwareObserver( + UpdateRoFirmwareStatus.kDownloading, 0); + }); + test('ObserveCalibrationUpdated', () => { /** @type {!CalibrationObserverRemote} */ const calibrationObserver = /** @type {!CalibrationObserverRemote} */ ({
diff --git a/chrome/test/data/webui/chromeos/shimless_rma/shimless_rma_app_test.js b/chrome/test/data/webui/chromeos/shimless_rma/shimless_rma_app_test.js index 4f413a4..69ec7b00 100644 --- a/chrome/test/data/webui/chromeos/shimless_rma/shimless_rma_app_test.js +++ b/chrome/test/data/webui/chromeos/shimless_rma/shimless_rma_app_test.js
@@ -248,4 +248,27 @@ 'Error: kReimagingUsbInvalidImage(23)', suppressedErrorMessage(component)); }); + + test('BusyStateButtonSpinners', async () => { + await initializeShimlessRMAApp(fakeStates, fakeChromeVersion[0]); + + const initialPage = + component.shadowRoot.querySelector('onboarding-landing-page'); + assertTrue(!!initialPage); + + const resolver = new PromiseResolver(); + initialPage.onNextButtonClick = () => resolver.promise; + + const nextButtonSpinner = + component.shadowRoot.querySelector('#nextButtonSpinner'); + assertTrue(nextButtonSpinner.hidden); + + await clickNext(); + assertFalse(nextButtonSpinner.hidden); + + resolver.resolve({state: State.kUpdateOs, error: RmadErrorCode.kOk}); + await flushTasks(); + + assertTrue(nextButtonSpinner.hidden); + }); }
diff --git a/chrome/test/data/webui/new_tab_page/realbox/realbox_test.js b/chrome/test/data/webui/new_tab_page/realbox/realbox_test.js index 12424389..58992a9 100644 --- a/chrome/test/data/webui/new_tab_page/realbox/realbox_test.js +++ b/chrome/test/data/webui/new_tab_page/realbox/realbox_test.js
@@ -319,17 +319,12 @@ assertStyle(realbox, '--search-box-placeholder', 'rgba(0, 0, 3, 1)'); assertStyle(realbox, '--search-box-results-bg', 'rgba(0, 0, 4, 1)'); assertStyle(realbox, '--search-box-text', 'rgba(0, 0, 13, 1)'); - assertStyle(realbox, '--search-box-icon', 'rgba(0, 0, 1, 1)'); - assertStyle(matches, '--search-box-icon', 'rgba(0, 0, 1, 1)'); + assertStyle(matches, '--search-box-icon-selected', 'rgba(0, 0, 2, 1)'); assertStyle(matches, '--search-box-results-bg-hovered', 'rgba(0, 0, 5, 1)'); - assertStyle( - matches, '--search-box-results-bg-selected', 'rgba(0, 0, 6, 1)'); assertStyle(matches, '--search-box-results-bg', 'rgba(0, 0, 4, 1)'); assertStyle( matches, '--search-box-results-dim-selected', 'rgba(0, 0, 8, 1)'); assertStyle(matches, '--search-box-results-dim', 'rgba(0, 0, 7, 1)'); - assertStyle( - matches, '--search-box-results-text-selected', 'rgba(0, 0, 10, 1)'); assertStyle(matches, '--search-box-results-text', 'rgba(0, 0, 9, 1)'); assertStyle( matches, '--search-box-results-url-selected', 'rgba(0, 0, 12, 1)'); @@ -1787,6 +1782,65 @@ assertEquals(matchEls[0], realbox.$.matches.shadowRoot.activeElement); }); + test('focus indicator', async () => { + realbox.$.input.focus(); + realbox.$.input.value = 'clear browsing history'; + realbox.$.input.dispatchEvent(new InputEvent('input')); + + const matches = [createSearchMatch({ + action: { + a11yLabel: mojoString16(''), + hint: mojoString16('Clear Browsing History'), + suggestionContents: mojoString16(''), + iconUrl: 'chrome://theme/current-channel-logo' + }, + fillIntoEdit: mojoString16('clear browsing history'), + supportsDeletion: true + })]; + testProxy.callbackRouterRemote.autocompleteResultChanged({ + input: mojoString16(realbox.$.input.value.trimLeft()), + matches, + suggestionGroupsMap: {}, + }); + await testProxy.callbackRouterRemote.$.flushForTesting(); + + assertTrue(areMatchesShowing()); + let matchEls = + realbox.$.matches.shadowRoot.querySelectorAll('ntp-realbox-match'); + + let focusIndicator = matchEls[0].$['focus-indicator']; + + // Select the first match + let arrowDownEvent = new KeyboardEvent('keydown', { + bubbles: true, + cancelable: true, + composed: true, // So it propagates across shadow DOM boundary. + key: 'ArrowDown', + }); + realbox.$.input.dispatchEvent(arrowDownEvent); + assertTrue(arrowDownEvent.defaultPrevented); + + assertTrue(matchEls[0].classList.contains(CLASSES.SELECTED)); + assertEquals('clear browsing history', realbox.$.input.value); + assertEquals(window.getComputedStyle(focusIndicator).display, 'block'); + + // Give focus to the action button + let action = $$(matchEls[0], '#action'); + action.focus(); + + assertTrue(matchEls[0].classList.contains(CLASSES.SELECTED)); + assertEquals(action, matchEls[0].shadowRoot.activeElement); + assertEquals(window.getComputedStyle(focusIndicator).display, 'none'); + + // Give focus to remove button + let removeButton = matchEls[0].$.remove; + removeButton.focus(); + + assertTrue(matchEls[0].classList.contains(CLASSES.SELECTED)); + assertEquals(removeButton, matchEls[0].shadowRoot.activeElement); + assertEquals(window.getComputedStyle(focusIndicator).display, 'none'); + }); + //============================================================================ // Test Metrics //============================================================================
diff --git a/chrome/test/data/webui/settings/advanced_page_test.js b/chrome/test/data/webui/settings/advanced_page_test.js index 4dfa6fe..ae2b4a3 100644 --- a/chrome/test/data/webui/settings/advanced_page_test.js +++ b/chrome/test/data/webui/settings/advanced_page_test.js
@@ -38,11 +38,10 @@ }); /** - * Verifies the section has a visible #main element and that any possible - * sub-pages are hidden. + * Verifies that a section is rendered but hidden, including all its subpages. * @param {!Node} section The DOM node for the section. */ - function verifySubpagesHidden(section) { + function verifySectionWithSubpagesHidden(section) { // Check if there are sub-pages to verify. const pages = section.firstElementChild.shadowRoot.querySelector( 'settings-animated-pages'); @@ -58,16 +57,17 @@ return element.tagName !== 'TEMPLATE'; }); - // The section's main child should be stamped and visible. + // The section's main child should be hidden since only the section + // corresponding to the current route should be visible. const main = stampedChildren.filter(function(element) { return element.getAttribute('route-path') === 'default'; }); const sectionName = /** @type {{section: string}} */ (section).section; assertEquals( main.length, 1, 'default card not found for section ' + sectionName); - assertGT(main[0].offsetHeight, 0); + assertEquals(main[0].offsetHeight, 0); - // Any other stamped subpages should not be visible. + // Any other stamped subpages should also be hidden. const subpages = stampedChildren.filter(function(element) { return element.getAttribute('route-path') !== 'default'; }); @@ -89,7 +89,7 @@ const section = getSection( /** @type {!SettingsBasicPageElement} */ (basicPage), sections[i]); assertTrue(!!section); - verifySubpagesHidden(/** @type {!Node} */ (section)); + verifySectionWithSubpagesHidden(/** @type {!Node} */ (section)); } }); });
diff --git a/chrome/test/data/webui/settings/basic_page_test.js b/chrome/test/data/webui/settings/basic_page_test.js index 94086562..0e19d90 100644 --- a/chrome/test/data/webui/settings/basic_page_test.js +++ b/chrome/test/data/webui/settings/basic_page_test.js
@@ -15,14 +15,27 @@ import {eventToPromise, flushTasks, isVisible} from 'chrome://webui-test/test_util.js'; // clang-format on -// Register mocha tests. -suite('SettingsBasicPage', function() { +suite('SettingsBasicPage', () => { let page = null; - setup(function() { + setup(async function() { PolymerTest.clearBody(); page = document.createElement('settings-basic-page'); document.body.appendChild(page); + page.scroller = document.body; + + // Need to wait for the 'show-container' event to fire after every + // transition, to ensure no logic related to previous transitions is still + // running when later transitions are tested. + const whenDone = eventToPromise('show-container', page); + + // Ensure that all settings-section instances are rendered. + flush(); + await page.$$('#advancedPageTemplate').get(); + const sections = page.shadowRoot.querySelectorAll('settings-section'); + assertTrue(sections.length > 1); + + await whenDone; }); test('load page', function() { @@ -56,41 +69,6 @@ const sectionElement = page.$$('settings-section-safety-check'); assertFalse(!!sectionElement); }); -}); - -suite('SettingsBasicPageRedesign', () => { - let page = null; - - suiteSetup(function() { - assertTrue(loadTimeData.getBoolean('enableLandingPageRedesign')); - const attribute = - loadTimeData.getString('enableLandingPageRedesignAttribute'); - assertEquals('enable-landing-page-redesign', attribute); - - // Do this manually as it is normally part of settings.html, which is not - // part of this test. - document.documentElement.toggleAttribute(attribute, true); - }); - - setup(async function() { - PolymerTest.clearBody(); - page = document.createElement('settings-basic-page'); - document.body.appendChild(page); - page.scroller = document.body; - - // Need to wait for the 'show-container' event to fire after every - // transition, to ensure no logic related to previous transitions is still - // running when later transitions are tested. - const whenDone = eventToPromise('show-container', page); - - // Ensure that all settings-section instances are rendered. - flush(); - await page.$$('#advancedPageTemplate').get(); - const sections = page.shadowRoot.querySelectorAll('settings-section'); - assertTrue(sections.length > 1); - - await whenDone; - }); /** @param {string} section */ function assertActiveSection(section) {
diff --git a/chrome/test/data/webui/settings/cr_settings_browsertest.js b/chrome/test/data/webui/settings/cr_settings_browsertest.js index 3fd5ea56c..36597583 100644 --- a/chrome/test/data/webui/settings/cr_settings_browsertest.js +++ b/chrome/test/data/webui/settings/cr_settings_browsertest.js
@@ -82,17 +82,6 @@ runMochaSuite('SettingsBasicPage'); }); -var CrSettingsBasicPageRedesignTest = class extends CrSettingsBrowserTest { - /** @override */ - get browsePreload() { - return 'chrome://settings/test_loader.html?module=settings/basic_page_test.js&host=webui-test'; - } -}; - -TEST_F('CrSettingsBasicPageRedesignTest', 'All', function() { - runMochaSuite('SettingsBasicPageRedesign'); -}); - GEN('#if !BUILDFLAG(IS_CHROMEOS_ASH)'); var CrSettingsLanguagesPageTest = class extends CrSettingsBrowserTest { /** @override */
diff --git a/chrome/test/data/webui/settings/settings_menu_test.ts b/chrome/test/data/webui/settings/settings_menu_test.ts index 824a2502..6779142 100644 --- a/chrome/test/data/webui/settings/settings_menu_test.ts +++ b/chrome/test/data/webui/settings/settings_menu_test.ts
@@ -5,7 +5,6 @@ /** @fileoverview Runs tests for the settings menu. */ // clang-format off -import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {pageVisibility, Router, routes, SettingsMenuElement} from 'chrome://settings/settings.js'; import {assertEquals, assertFalse, assertNotEquals, assertTrue} from 'chrome://webui-test/chai_assert.js'; @@ -151,13 +150,6 @@ settingsMenu.shadowRoot!.querySelector<HTMLElement>( '#reset')!.hidden); - if (!loadTimeData.getBoolean('enableLandingPageRedesign')) { - assertEquals( - expectedHidden, - settingsMenu.shadowRoot!.querySelector<HTMLElement>( - '#safetyCheck')!.hidden); - } - // <if expr="not chromeos and not lacros"> assertEquals( expectedHidden,
diff --git a/chromecast/browser/accessibility/touch_exploration_controller.cc b/chromecast/browser/accessibility/touch_exploration_controller.cc index b36da86c..00bf1b3 100644 --- a/chromecast/browser/accessibility/touch_exploration_controller.cc +++ b/chromecast/browser/accessibility/touch_exploration_controller.cc
@@ -317,7 +317,6 @@ if (type == ui::ET_TOUCH_RELEASED || type == ui::ET_TOUCH_CANCELLED) { if (current_touch_ids_.size() == 0 && event.pointer_details().id == initial_press_->pointer_details().id) { - MaybeSendSimulatedTapInLiftActivationBounds(event, continuation); SET_STATE(SINGLE_TAP_RELEASED); } else if (current_touch_ids_.size() == 0) { SET_STATE(NO_FINGERS_DOWN);
diff --git a/chromecast/browser/accessibility/touch_exploration_controller_unittest.cc b/chromecast/browser/accessibility/touch_exploration_controller_unittest.cc index 24e98fc..df1e080c 100644 --- a/chromecast/browser/accessibility/touch_exploration_controller_unittest.cc +++ b/chromecast/browser/accessibility/touch_exploration_controller_unittest.cc
@@ -1890,22 +1890,10 @@ generator_->PressTouchId(1); generator_->ReleaseTouchId(1); const EventList& captured_events = GetCapturedEvents(); - EXPECT_EQ(2U, captured_events.size()); - EXPECT_EQ(ui::ET_TOUCH_PRESSED, captured_events[0]->type()); - EXPECT_EQ(ui::ET_TOUCH_RELEASED, captured_events[1]->type()); - ASSERT_EQ(1U, accessibility_sound_player_.NumTouchTypeSounds()); - accessibility_sound_player_.ResetCountersToZero(); + // There should be no events since single tap should not take effect in lift + // activation area. + EXPECT_EQ(0U, captured_events.size()); ClearCapturedEvents(); - - gfx::Point out_tap_location(tap_location.x(), lift_activation.bottom() + 20); - SetTouchAccessibilityAnchorPoint(out_tap_location); - generator_->set_current_screen_location(out_tap_location); - generator_->PressTouchId(1); - generator_->ReleaseTouchId(1); - - const EventList& out_captured_events = GetCapturedEvents(); - ASSERT_TRUE(out_captured_events.empty()); - ASSERT_EQ(0U, accessibility_sound_player_.NumTouchTypeSounds()); } TEST_F(TouchExplorationTest, TouchExploreLiftInLiftActivationArea) {
diff --git a/chromecast/browser/extensions/api/accessibility_private/accessibility_extension_api.cc b/chromecast/browser/extensions/api/accessibility_private/accessibility_extension_api.cc index 611c39a..67c616b 100644 --- a/chromecast/browser/extensions/api/accessibility_private/accessibility_extension_api.cc +++ b/chromecast/browser/extensions/api/accessibility_private/accessibility_extension_api.cc
@@ -137,51 +137,48 @@ ExtensionFunction::ResponseAction AccessibilityPrivateSendSyntheticMouseEventFunction::Run() { + // Translate the mouse event to touch event so that touch exploration + // controller can handle them. std::unique_ptr<accessibility_private::SendSyntheticMouseEvent::Params> params = accessibility_private::SendSyntheticMouseEvent::Params::Create( args()); EXTENSION_FUNCTION_VALIDATE(params); accessibility_private::SyntheticMouseEvent* mouse_data = ¶ms->mouse_event; - if (mouse_data->type == - accessibility_private::SYNTHETIC_MOUSE_EVENT_TYPE_RELEASE && - mouse_data->mouse_button == - accessibility_private::SYNTHETIC_MOUSE_EVENT_BUTTON_LEFT) { - // ui::ET_TOUCH_PRESSED and ui::ET_TOUCH_RELEASED is sent for synthetic - // mouse event left button click. - ui::PointerDetails pointer_details; - pointer_details.pointer_type = ui::EventPointerType::kTouch; - - gfx::Point location(mouse_data->x, mouse_data->y); - - auto* host = chromecast::shell::CastBrowserProcess::GetInstance() - ->accessibility_manager() - ->window_tree_host(); - DCHECK(host); - - std::unique_ptr<ui::TouchEvent> touch_press = - std::make_unique<ui::TouchEvent>(ui::ET_TOUCH_PRESSED, gfx::Point(), - ui::EventTimeForNow(), - pointer_details); - touch_press->set_location(location); - touch_press->set_root_location(location); - touch_press->UpdateForRootTransform( - host->GetRootTransform(), - host->GetRootTransformForLocalEventCoordinates()); - host->DeliverEventToSink(touch_press.get()); - - std::unique_ptr<ui::TouchEvent> touch_release = - std::make_unique<ui::TouchEvent>(ui::ET_TOUCH_RELEASED, gfx::Point(), - ui::EventTimeForNow(), - pointer_details); - touch_release->set_location(location); - touch_release->set_root_location(location); - touch_release->UpdateForRootTransform( - host->GetRootTransform(), - host->GetRootTransformForLocalEventCoordinates()); - host->DeliverEventToSink(touch_release.get()); + ui::EventType type = ui::ET_UNKNOWN; + switch (mouse_data->type) { + case accessibility_private::SYNTHETIC_MOUSE_EVENT_TYPE_PRESS: + type = ui::ET_TOUCH_PRESSED; + break; + case accessibility_private::SYNTHETIC_MOUSE_EVENT_TYPE_RELEASE: + type = ui::ET_TOUCH_RELEASED; + break; + default: + // skip other gestures. + return RespondNow(NoArguments()); } + // Locations are assumed to be in screen coordinates. + gfx::Point location_in_screen(mouse_data->x, mouse_data->y); + auto* host = chromecast::shell::CastBrowserProcess::GetInstance() + ->accessibility_manager() + ->window_tree_host(); + DCHECK(host); + + ui::PointerDetails pointer_details; + pointer_details.pointer_type = ui::EventPointerType::kTouch; + gfx::Point location(mouse_data->x, mouse_data->y); + + std::unique_ptr<ui::TouchEvent> touch_event = + std::make_unique<ui::TouchEvent>(type, gfx::Point(), + ui::EventTimeForNow(), pointer_details); + touch_event->set_location(location); + touch_event->set_root_location(location); + touch_event->UpdateForRootTransform( + host->GetRootTransform(), + host->GetRootTransformForLocalEventCoordinates()); + // Still go through the event rewriters. + host->SendEventToSink(touch_event.get()); return RespondNow(NoArguments()); }
diff --git a/chromecast/cast_core/streaming_receiver_session_client.h b/chromecast/cast_core/streaming_receiver_session_client.h index 8c7b129b..f615129 100644 --- a/chromecast/cast_core/streaming_receiver_session_client.h +++ b/chromecast/cast_core/streaming_receiver_session_client.h
@@ -183,7 +183,7 @@ // The AssociatedRemote that must be provided when starting the // |receiver_session_|. - mojo::AssociatedRemote<::mojom::CastStreamingReceiver> + mojo::AssociatedRemote<cast_streaming::mojom::CastStreamingReceiver> cast_streaming_receiver_; // Responsible for managing the streaming session.
diff --git a/chromecast/cast_core/streaming_receiver_session_client_unittest.cc b/chromecast/cast_core/streaming_receiver_session_client_unittest.cc index 091284f..d1f69f0e 100644 --- a/chromecast/cast_core/streaming_receiver_session_client_unittest.cc +++ b/chromecast/cast_core/streaming_receiver_session_client_unittest.cc
@@ -9,6 +9,7 @@ #include "chromecast/shared/platform_info_serializer.h" #include "components/cast_streaming/browser/public/receiver_session.h" #include "components/cast_streaming/public/mojom/cast_streaming_session.mojom.h" +#include "components/cast_streaming/public/mojom/renderer_controller.mojom.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -29,7 +30,8 @@ ~MockReceiverSession() override = default; MOCK_METHOD1(SetCastStreamingReceiver, - void(mojo::AssociatedRemote<::mojom::CastStreamingReceiver>)); + void(mojo::AssociatedRemote< + cast_streaming::mojom::CastStreamingReceiver>)); }; class MockStreamingReceiverSessionHandler
diff --git a/chromeos/components/sync_wifi/network_test_helper.cc b/chromeos/components/sync_wifi/network_test_helper.cc index 39b119ed..9abb178 100644 --- a/chromeos/components/sync_wifi/network_test_helper.cc +++ b/chromeos/components/sync_wifi/network_test_helper.cc
@@ -9,9 +9,7 @@ #include "base/strings/stringprintf.h" #include "chromeos/components/sync_wifi/network_type_conversions.h" #include "chromeos/login/login_state/login_state.h" -#include "chromeos/network/cellular_esim_profile_handler_impl.h" #include "chromeos/network/cellular_metrics_logger.h" -#include "chromeos/network/network_handler.h" #include "chromeos/network/network_handler_test_helper.h" #include "chromeos/network/network_metadata_store.h" #include "chromeos/services/network_config/in_process_instance.h" @@ -31,12 +29,6 @@ LoginState::Initialize(); PrefProxyConfigTrackerImpl::RegisterProfilePrefs(user_prefs_.registry()); PrefProxyConfigTrackerImpl::RegisterPrefs(local_state_.registry()); - ::onc::RegisterProfilePrefs(user_prefs_.registry()); - ::onc::RegisterPrefs(local_state_.registry()); - CellularESimProfileHandlerImpl::RegisterLocalStatePrefs( - local_state_.registry()); - NetworkMetadataStore::RegisterPrefs(user_prefs_.registry()); - NetworkMetadataStore::RegisterPrefs(local_state_.registry()); network_profile_handler_ = NetworkProfileHandler::InitializeForTesting(); network_configuration_handler_ = @@ -68,6 +60,10 @@ LoginUser(primary_user_); Initialize(managed_network_configuration_handler_.get()); + + network_handler_test_helper_ = std::make_unique<NetworkHandlerTestHelper>(); + network_handler_test_helper_->RegisterPrefs(user_prefs_.registry(), + local_state_.registry()); } NetworkTestHelper::~NetworkTestHelper() { @@ -77,8 +73,7 @@ } void NetworkTestHelper::SetUp() { - network_handler_test_helper_ = std::make_unique<NetworkHandlerTestHelper>(); - NetworkHandler::Get()->InitializePrefServices(&user_prefs_, &local_state_); + network_handler_test_helper_->InitializePrefs(&user_prefs_, &local_state_); network_state_helper_.ResetDevicesAndServices(); network_state_helper_.profile_test()->AddProfile( /*profile_path=*/network_state_helper_.UserHash(),
diff --git a/chromeos/network/BUILD.gn b/chromeos/network/BUILD.gn index 4e14fef..c7650ce 100644 --- a/chromeos/network/BUILD.gn +++ b/chromeos/network/BUILD.gn
@@ -222,6 +222,7 @@ "//chromeos/dbus/hermes:hermes_clients", "//chromeos/services/network_config/public/cpp", "//chromeos/services/network_config/public/mojom", + "//components/onc", "//components/sync_preferences:test_support", "//dbus", "//net:test_support",
diff --git a/chromeos/network/metrics/network_metrics_helper_unittest.cc b/chromeos/network/metrics/network_metrics_helper_unittest.cc index 0ef7435..0c1a27a 100644 --- a/chromeos/network/metrics/network_metrics_helper_unittest.cc +++ b/chromeos/network/metrics/network_metrics_helper_unittest.cc
@@ -10,7 +10,6 @@ #include "base/test/metrics/histogram_tester.h" #include "base/test/task_environment.h" #include "chromeos/dbus/shill/shill_service_client.h" -#include "chromeos/network/cellular_esim_profile_handler_impl.h" #include "chromeos/network/network_handler_test_helper.h" #include "components/prefs/testing_pref_service.h" #include "testing/gtest/include/gtest/gtest.h" @@ -61,10 +60,11 @@ shill_service_client_->ClearServices(); base::RunLoop().RunUntilIdle(); - CellularESimProfileHandlerImpl::RegisterLocalStatePrefs( - local_state_.registry()); - chromeos::NetworkHandler::Get()->InitializePrefServices(&profile_prefs_, - &local_state_); + network_handler_test_helper_->RegisterPrefs(profile_prefs_.registry(), + local_state_.registry()); + + network_handler_test_helper_->InitializePrefs(&profile_prefs_, + &local_state_); } void TearDown() override {
diff --git a/chromeos/network/network_handler_test_helper.cc b/chromeos/network/network_handler_test_helper.cc index 7748ffa0..27d3790 100644 --- a/chromeos/network/network_handler_test_helper.cc +++ b/chromeos/network/network_handler_test_helper.cc
@@ -4,8 +4,11 @@ #include "chromeos/network/network_handler_test_helper.h" +#include "chromeos/network/cellular_esim_profile_handler_impl.h" #include "chromeos/network/network_handler.h" +#include "chromeos/network/network_metadata_store.h" #include "chromeos/network/network_test_helper_base.h" +#include "components/onc/onc_pref_names.h" namespace chromeos { @@ -21,4 +24,22 @@ NetworkHandler::Shutdown(); } +void NetworkHandlerTestHelper::RegisterPrefs( + PrefRegistrySimple* user_registry, + PrefRegistrySimple* device_registry) { + DCHECK(device_registry); + ::onc::RegisterPrefs(device_registry); + NetworkMetadataStore::RegisterPrefs(device_registry); + CellularESimProfileHandlerImpl::RegisterLocalStatePrefs(device_registry); + if (user_registry) { + NetworkMetadataStore::RegisterPrefs(user_registry); + ::onc::RegisterProfilePrefs(user_registry); + } +} + +void NetworkHandlerTestHelper::InitializePrefs(PrefService* user_prefs, + PrefService* device_prefs) { + NetworkHandler::Get()->InitializePrefServices(user_prefs, device_prefs); +} + } // namespace chromeos
diff --git a/chromeos/network/network_handler_test_helper.h b/chromeos/network/network_handler_test_helper.h index 8e14606..0b1e744 100644 --- a/chromeos/network/network_handler_test_helper.h +++ b/chromeos/network/network_handler_test_helper.h
@@ -7,6 +7,9 @@ #include "chromeos/network/network_test_helper_base.h" +class PrefRegistrySimple; +class PrefService; + namespace chromeos { // Helper class for tests that uses network handler classes. This class @@ -22,6 +25,13 @@ explicit NetworkHandlerTestHelper(); ~NetworkHandlerTestHelper(); + // Registers any prefs required by NetworkHandler. + void RegisterPrefs(PrefRegistrySimple* user_registry, + PrefRegistrySimple* device_registry); + + // Calls NetworkHandler::InitializePrefServices. + void InitializePrefs(PrefService* user_prefs, PrefService* device_prefs); + private: bool network_handler_initialized_ = false; };
diff --git a/chromeos/services/network_config/cros_network_config_unittest.cc b/chromeos/services/network_config/cros_network_config_unittest.cc index 15aecde..7309e036d 100644 --- a/chromeos/services/network_config/cros_network_config_unittest.cc +++ b/chromeos/services/network_config/cros_network_config_unittest.cc
@@ -15,7 +15,6 @@ #include "base/test/task_environment.h" #include "chromeos/dbus/shill/fake_shill_device_client.h" #include "chromeos/login/login_state/login_state.h" -#include "chromeos/network/cellular_esim_profile_handler_impl.h" #include "chromeos/network/cellular_inhibitor.h" #include "chromeos/network/cellular_metrics_logger.h" #include "chromeos/network/fake_stub_cellular_networks_provider.h" @@ -34,7 +33,6 @@ #include "chromeos/network/prohibited_technologies_handler.h" #include "chromeos/network/proxy/ui_proxy_config_service.h" #include "chromeos/network/system_token_cert_db_storage.h" -#include "chromeos/network/test_cellular_esim_profile_handler.h" #include "chromeos/services/network_config/public/cpp/cros_network_config_test_observer.h" #include "chromeos/services/network_config/public/mojom/cros_network_config.mojom-shared.h" #include "components/onc/onc_constants.h" @@ -117,15 +115,11 @@ helper_->AddDefaultProfiles(); helper_->ResetDevicesAndServices(); + helper_->RegisterPrefs(user_prefs_.registry(), local_state_.registry()); PrefProxyConfigTrackerImpl::RegisterProfilePrefs(user_prefs_.registry()); PrefProxyConfigTrackerImpl::RegisterPrefs(local_state_.registry()); - ::onc::RegisterProfilePrefs(user_prefs_.registry()); - ::onc::RegisterPrefs(local_state_.registry()); - NetworkMetadataStore::RegisterPrefs(user_prefs_.registry()); - NetworkMetadataStore::RegisterPrefs(local_state_.registry()); - CellularESimProfileHandlerImpl::RegisterLocalStatePrefs( - local_state_.registry()); - NetworkHandler::Get()->InitializePrefServices(&user_prefs_, &local_state_); + + helper_->InitializePrefs(&user_prefs_, &local_state_); NetworkHandler* network_handler = NetworkHandler::Get(); cros_network_config_ = std::make_unique<CrosNetworkConfig>(
diff --git a/components/android_autofill/browser/autofill_provider.cc b/components/android_autofill/browser/autofill_provider.cc index 91e386f..8a0483d5 100644 --- a/components/android_autofill/browser/autofill_provider.cc +++ b/components/android_autofill/browser/autofill_provider.cc
@@ -25,7 +25,7 @@ } AutofillProvider::AutofillProvider(content::WebContents* web_contents) - : web_contents_(web_contents) { + : content::WebContentsUserData<AutofillProvider>(*web_contents) { web_contents->SetUserData(UserDataKey(), base::WrapUnique(this)); }
diff --git a/components/android_autofill/browser/autofill_provider.h b/components/android_autofill/browser/autofill_provider.h index 8c44d36..174e109 100644 --- a/components/android_autofill/browser/autofill_provider.h +++ b/components/android_autofill/browser/autofill_provider.h
@@ -107,11 +107,9 @@ AutofillProvider() = default; #endif // UNIT_TEST - content::WebContents* web_contents() { return web_contents_; } + content::WebContents* web_contents() { return &GetWebContents(); } private: - raw_ptr<content::WebContents> web_contents_; - WEB_CONTENTS_USER_DATA_KEY_DECL(); };
diff --git a/components/autofill/core/browser/payments/autofill_save_card_infobar_delegate_mobile.h b/components/autofill/core/browser/payments/autofill_save_card_infobar_delegate_mobile.h index 19e50eb..d9af11f 100644 --- a/components/autofill/core/browser/payments/autofill_save_card_infobar_delegate_mobile.h +++ b/components/autofill/core/browser/payments/autofill_save_card_infobar_delegate_mobile.h
@@ -30,9 +30,8 @@ // cloud, as opposed to saving locally. Only one of // |upload_save_card_prompt_callback| and |local_save_card_prompt_callback| // will be executed. - // If |upload| is true, |displayed_target_account| must either be the account - // where the card will be saved, or empty if no target account should be - // shown. + // If |upload| is true, |displayed_target_account| should be the account to + // which the card will be saved. If |upload| is false, it must be empty. // TODO(crbug.com/1206190): Split into 2 static constructors (local/cloud), // each with the minimum set of required parameters. Also consider merging // the 2 callbacks into one.
diff --git a/components/autofill/core/browser/payments/credit_card_fido_authenticator_unittest.cc b/components/autofill/core/browser/payments/credit_card_fido_authenticator_unittest.cc index 5f950ad7..845bd8f 100644 --- a/components/autofill/core/browser/payments/credit_card_fido_authenticator_unittest.cc +++ b/components/autofill/core/browser/payments/credit_card_fido_authenticator_unittest.cc
@@ -353,7 +353,7 @@ EXPECT_EQ(kTestChallenge, BytesToBase64(request_options_ptr->challenge)); EXPECT_EQ(kTestRelyingPartyId, request_options_ptr->relying_party_id); EXPECT_EQ(kTestCredentialId, - BytesToBase64(request_options_ptr->allow_credentials.front().id())); + BytesToBase64(request_options_ptr->allow_credentials.front().id)); } TEST_F(CreditCardFIDOAuthenticatorTest, ParseAssertionResponse) { @@ -383,12 +383,12 @@ EXPECT_EQ(kTestRelyingPartyId, creation_options_ptr->relying_party.id); // Ensure only platform authenticators are allowed. - EXPECT_EQ(AuthenticatorAttachment::kPlatform, - creation_options_ptr->authenticator_selection - ->authenticator_attachment()); + EXPECT_EQ( + AuthenticatorAttachment::kPlatform, + creation_options_ptr->authenticator_selection->authenticator_attachment); EXPECT_EQ(UserVerificationRequirement::kRequired, creation_options_ptr->authenticator_selection - ->user_verification_requirement()); + ->user_verification_requirement); } TEST_F(CreditCardFIDOAuthenticatorTest, ParseAttestationResponse) {
diff --git a/components/autofill/core/browser/payments/test_credit_card_fido_authenticator.cc b/components/autofill/core/browser/payments/test_credit_card_fido_authenticator.cc index bb22f95..896a9cd 100644 --- a/components/autofill/core/browser/payments/test_credit_card_fido_authenticator.cc +++ b/components/autofill/core/browser/payments/test_credit_card_fido_authenticator.cc
@@ -83,7 +83,7 @@ std::vector<uint8_t> TestCreditCardFIDOAuthenticator::GetCredentialId() { DCHECK(!request_options_->allow_credentials.empty()); - return request_options_->allow_credentials.front().id(); + return request_options_->allow_credentials.front().id; } std::vector<uint8_t> TestCreditCardFIDOAuthenticator::GetChallenge() {
diff --git a/components/autofill/core/common/autofill_features.cc b/components/autofill/core/common/autofill_features.cc index 0b6d675..52855e32 100644 --- a/components/autofill/core/common/autofill_features.cc +++ b/components/autofill/core/common/autofill_features.cc
@@ -149,21 +149,6 @@ "AutofillEnableImportWhenMultiplePhoneNumbers", base::FEATURE_DISABLED_BY_DEFAULT}; -// When enabled and user has single account, a footer indicating user's e-mail -// address and profile picture will appear at the bottom of InfoBars which has -// corresponding account indication footer flags on. -const base::Feature - kAutofillEnableInfoBarAccountIndicationFooterForSingleAccountUsers{ - "AutofillEnableInfoBarAccountIndicationFooterForSingleAccountUsers", - base::FEATURE_ENABLED_BY_DEFAULT}; - -// When enabled and user is syncing, a footer indicating user's e-mail address -// and profile picture will appear at the bottom of InfoBars which has -// corresponding account indication footer flags on. -const base::Feature kAutofillEnableInfoBarAccountIndicationFooterForSyncUsers{ - "AutofillEnableInfoBarAccountIndicationFooterForSyncUsers", - base::FEATURE_ENABLED_BY_DEFAULT}; - // When enabled, the precedence is given to the field label over the name when // they match different types. Applied only for parsing of address forms in // Turkish.
diff --git a/components/autofill/core/common/autofill_features.h b/components/autofill/core/common/autofill_features.h index 321c3d1..35a90752 100644 --- a/components/autofill/core/common/autofill_features.h +++ b/components/autofill/core/common/autofill_features.h
@@ -62,12 +62,6 @@ extern const base::Feature kAutofillEnableImportWhenMultiplePhoneNumbers; COMPONENT_EXPORT(AUTOFILL) extern const base::Feature - kAutofillEnableInfoBarAccountIndicationFooterForSingleAccountUsers; -COMPONENT_EXPORT(AUTOFILL) -extern const base::Feature - kAutofillEnableInfoBarAccountIndicationFooterForSyncUsers; -COMPONENT_EXPORT(AUTOFILL) -extern const base::Feature kAutofillEnablePasswordInfoBarAccountIndicationFooter; COMPONENT_EXPORT(AUTOFILL) extern const base::Feature kAutofillEnableSupportForApartmentNumbers;
diff --git a/components/autofill/core/common/autofill_payments_features.cc b/components/autofill/core/common/autofill_payments_features.cc index e17f6790..593d56c 100644 --- a/components/autofill/core/common/autofill_payments_features.cc +++ b/components/autofill/core/common/autofill_payments_features.cc
@@ -87,12 +87,6 @@ const base::Feature kAutofillEnableOffersInDownstream{ "kAutofillEnableOffersInDownstream", base::FEATURE_ENABLED_BY_DEFAULT}; -// When enabled and user is signed in, a footer indicating user's e-mail address -// and profile picture will appear at the bottom of SaveCardInfoBar. -const base::Feature kAutofillEnableSaveCardInfoBarAccountIndicationFooter{ - "AutofillEnableSaveCardInfoBarAccountIndicationFooter", - base::FEATURE_ENABLED_BY_DEFAULT}; - // When enabled, if the user interacts with the manual fallback bottom sheet // on Android, it'll remain sticky until the user dismisses it. const base::Feature kAutofillEnableStickyManualFallbackForCards{
diff --git a/components/autofill/core/common/autofill_payments_features.h b/components/autofill/core/common/autofill_payments_features.h index 637fb04..4f46970 100644 --- a/components/autofill/core/common/autofill_payments_features.h +++ b/components/autofill/core/common/autofill_payments_features.h
@@ -26,8 +26,6 @@ extern const base::Feature kAutofillEnableOfferNotificationForPromoCodes; extern const base::Feature kAutofillEnableOffersInClankKeyboardAccessory; extern const base::Feature kAutofillEnableOffersInDownstream; -extern const base::Feature - kAutofillEnableSaveCardInfoBarAccountIndicationFooter; extern const base::Feature kAutofillEnableStickyManualFallbackForCards; extern const base::Feature kAutofillEnableToolbarStatusChip; extern const base::Feature kAutofillEnableVirtualCard;
diff --git a/components/cast_streaming/public/mojom/cast_streaming_session.mojom b/components/cast_streaming/public/mojom/cast_streaming_session.mojom index d94b83c..dba0009 100644 --- a/components/cast_streaming/public/mojom/cast_streaming_session.mojom +++ b/components/cast_streaming/public/mojom/cast_streaming_session.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 mojom; +module cast_streaming.mojom; import "media/mojo/mojom/media_types.mojom";
diff --git a/components/download/content/internal/download_driver_impl.cc b/components/download/content/internal/download_driver_impl.cc index feb0f7f..5c45c67e 100644 --- a/components/download/content/internal/download_driver_impl.cc +++ b/components/download/content/internal/download_driver_impl.cc
@@ -20,8 +20,11 @@ #include "components/download/public/common/download_interrupt_reasons.h" #include "components/download/public/common/download_url_parameters.h" #include "components/download/public/common/simple_download_manager_coordinator.h" +#include "net/http/http_byte_range.h" #include "net/http/http_response_headers.h" #include "net/http/http_status_code.h" +#include "net/http/http_util.h" +#include "third_party/abseil-cpp/absl/types/optional.h" namespace download { @@ -71,6 +74,24 @@ base::UmaHistogramSparse("Download.Service.Driver.InterruptReason", reason); } +absl::optional<net::HttpByteRange> ParseRangeHeader( + const net::HttpRequestHeaders& request_headers) { + std::vector<net::HttpByteRange> byte_ranges; + std::string range_header; + bool success = + request_headers.GetHeader(net::HttpRequestHeaders::kRange, &range_header); + if (!success) + return absl::nullopt; + + success = net::HttpUtil::ParseRangeHeader(range_header, &byte_ranges); + + // Multiple ranges are not supported. + if (!success || byte_ranges.empty() || byte_ranges.size() > 1) + return absl::nullopt; + + return byte_ranges.front(); +} + } // namespace // static @@ -171,8 +192,38 @@ // collision and return an error to fail the download cleanly. for (net::HttpRequestHeaders::Iterator it(request_params.request_headers); it.GetNext();) { + // Range and If-Range are managed by download core instead. + if (it.name() == net::HttpRequestHeaders::kRange || + it.name() == net::HttpRequestHeaders::kIfRange) { + continue; + } + download_url_params->add_request_header(it.name(), it.value()); } + + if (base::FeatureList::IsEnabled(features::kDownloadRange) && + request_params.request_headers.HasHeader( + net::HttpRequestHeaders::kRange)) { + absl::optional<net::HttpByteRange> byte_range = + ParseRangeHeader(request_params.request_headers); + if (byte_range.has_value()) { + download_url_params->set_use_if_range(false); + if (byte_range->IsSuffixByteRange()) { + download_url_params->set_range_request_offset( + kInvalidRange, byte_range->suffix_length()); + } else { + download_url_params->set_range_request_offset( + byte_range->first_byte_position(), + byte_range->last_byte_position()); + } + } else { + // TODO(xingliu): Do input validation in ControllerImpl::StartDownload, so + // we don't need to return here. + LOG(ERROR) << "Failed to parse Range request header."; + return; + } + } + download_url_params->set_guid(guid); download_url_params->set_transient(true); download_url_params->set_method(request_params.method); @@ -194,6 +245,7 @@ download_url_params->set_isolation_info( request_params.isolation_info.value()); } + download_manager_coordinator_->DownloadUrl(std::move(download_url_params)); }
diff --git a/components/download/content/internal/download_driver_impl_unittest.cc b/components/download/content/internal/download_driver_impl_unittest.cc index 5036fe82c..07fc4b6f 100644 --- a/components/download/content/internal/download_driver_impl_unittest.cc +++ b/components/download/content/internal/download_driver_impl_unittest.cc
@@ -9,14 +9,17 @@ #include "base/callback_helpers.h" #include "base/guid.h" +#include "base/test/scoped_feature_list.h" #include "base/test/test_simple_task_runner.h" #include "base/threading/thread_task_runner_handle.h" #include "components/download/content/public/all_download_item_notifier.h" #include "components/download/internal/background_service/test/mock_download_driver_client.h" +#include "components/download/public/common/download_features.h" #include "components/download/public/common/mock_simple_download_manager.h" #include "content/public/test/fake_download_item.h" #include "net/http/http_response_headers.h" #include "net/http/http_util.h" +#include "net/traffic_annotation/network_traffic_annotation_test_helper.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -34,6 +37,7 @@ } const char kFakeGuid[] = "fake_guid"; +const char kFakeURL[] = "https://www.example.com/kale"; // Matcher to compare driver entries. Not all the memeber fields are compared. // Currently no comparison in non test code, so no operator== override for @@ -67,15 +71,15 @@ .WillRepeatedly(Return(true)); driver_ = std::make_unique<DownloadDriverImpl>(&coordinator_); coordinator_.SetSimpleDownloadManager(&mock_manager_, true); + ON_CALL(mock_manager_, CanDownload(_)).WillByDefault(Return(true)); } - // TODO(xingliu): implements test download manager for embedders to test. + protected: SimpleDownloadManagerCoordinator coordinator_; NiceMock<MockSimpleDownloadManager> mock_manager_; MockDriverClient mock_client_; std::unique_ptr<DownloadDriverImpl> driver_; - - protected: + base::test::ScopedFeatureList scoped_feature_list_; scoped_refptr<base::TestSimpleTaskRunner> task_runner_; base::ThreadTaskRunnerHandle handle_; }; @@ -237,4 +241,51 @@ EXPECT_EQ(headers, entry.response_headers); } +bool HasHeader(const DownloadUrlParameters::RequestHeadersType& headers, + const std::string& header) { + for (const auto& pair : headers) { + if (pair.first == header) + return true; + } + return false; +} + +// Range header set in RequestParams will be set correctly in +// DownloadUrlParameters when calling |DownloadDriver::Start|. +TEST_F(DownloadDriverImplTest, Start_WithRangeHeader) { + scoped_feature_list_.InitAndEnableFeature(download::features::kDownloadRange); + RequestParams request_params; + request_params.url = GURL(kFakeURL); + request_params.request_headers.AddHeaderFromString("Range: bytes=5-10"); + EXPECT_CALL(mock_manager_, DownloadUrlMock(_)).RetiresOnSaturation(); + driver_->Start(request_params, kFakeGuid, base::FilePath(), nullptr, + TRAFFIC_ANNOTATION_FOR_TESTS); + const auto* download_url_parameters = + mock_manager_.GetDownloadUrlParameters(); + DCHECK(download_url_parameters); + EXPECT_FALSE(download_url_parameters->use_if_range()); + auto range_request_offset = download_url_parameters->range_request_offset(); + EXPECT_EQ(5, range_request_offset.first); + EXPECT_EQ(10, range_request_offset.second); + EXPECT_FALSE(HasHeader(download_url_parameters->request_headers(), + net::HttpRequestHeaders::kRange)); + EXPECT_FALSE(HasHeader(download_url_parameters->request_headers(), + net::HttpRequestHeaders::kIfRange)); + + request_params.request_headers.AddHeaderFromString("Range: bytes=-10"); + EXPECT_CALL(mock_manager_, DownloadUrlMock(_)).RetiresOnSaturation(); + driver_->Start(request_params, kFakeGuid, base::FilePath(), nullptr, + TRAFFIC_ANNOTATION_FOR_TESTS); + download_url_parameters = mock_manager_.GetDownloadUrlParameters(); + DCHECK(download_url_parameters); + EXPECT_FALSE(download_url_parameters->use_if_range()); + range_request_offset = download_url_parameters->range_request_offset(); + EXPECT_EQ(kInvalidRange, range_request_offset.first); + EXPECT_EQ(10, range_request_offset.second); + EXPECT_FALSE(HasHeader(download_url_parameters->request_headers(), + net::HttpRequestHeaders::kRange)); + EXPECT_FALSE(HasHeader(download_url_parameters->request_headers(), + net::HttpRequestHeaders::kIfRange)); +} + } // namespace download
diff --git a/components/download/public/common/download_url_parameters.h b/components/download/public/common/download_url_parameters.h index ebd719f..ba0a03c 100644 --- a/components/download/public/common/download_url_parameters.h +++ b/components/download/public/common/download_url_parameters.h
@@ -178,6 +178,7 @@ // Sets the range request header offset. Can use -1 for open ended request. // e.g, "bytes:100-". + // TODO(xingliu): Use net::HttpByteRange instead of two integer. void set_range_request_offset(int64_t from, int64_t to) { save_info_.range_request_from = from; save_info_.range_request_to = to;
diff --git a/components/download/public/common/mock_simple_download_manager.cc b/components/download/public/common/mock_simple_download_manager.cc index 0189b58..c396dc0 100644 --- a/components/download/public/common/mock_simple_download_manager.cc +++ b/components/download/public/common/mock_simple_download_manager.cc
@@ -19,4 +19,17 @@ observer.OnDownloadCreated(item); } +const DownloadUrlParameters* +MockSimpleDownloadManager::GetDownloadUrlParameters() { + DCHECK(params_.get()); + return params_.get(); +} + +void MockSimpleDownloadManager::DownloadUrl( + std::unique_ptr<DownloadUrlParameters> params) { + DCHECK(params.get()); + DownloadUrlMock(params.get()); + params_ = std::move(params); +} + } // namespace download
diff --git a/components/download/public/common/mock_simple_download_manager.h b/components/download/public/common/mock_simple_download_manager.h index 9a878f7c..7789f2b6 100644 --- a/components/download/public/common/mock_simple_download_manager.h +++ b/components/download/public/common/mock_simple_download_manager.h
@@ -26,9 +26,11 @@ // Notifies observers that downloads is initialized. void NotifyOnDownloadInitialized(); - void DownloadUrl(std::unique_ptr<DownloadUrlParameters> params) override { - DownloadUrlMock(params.get()); - } + // Get the DownloadUrlParameters passed to |DownloadUrl|. + const DownloadUrlParameters* GetDownloadUrlParameters(); + + // SimpleDownloadManager implementation. + void DownloadUrl(std::unique_ptr<DownloadUrlParameters> params) override; MOCK_METHOD1(CanDownload, bool(DownloadUrlParameters*)); MOCK_METHOD1(DownloadUrlMock, void(DownloadUrlParameters*)); @@ -37,6 +39,7 @@ private: base::ObserverList<Observer>::Unchecked observers_; + std::unique_ptr<DownloadUrlParameters> params_; }; } // namespace download
diff --git a/components/enterprise/common/proto/connectors.proto b/components/enterprise/common/proto/connectors.proto index b8d625ee..cb22a2e 100644 --- a/components/enterprise/common/proto/connectors.proto +++ b/components/enterprise/common/proto/connectors.proto
@@ -22,6 +22,7 @@ FILE_DOWNLOADED = 1; FILE_ATTACHED = 2; BULK_DATA_ENTRY = 3; + PRINT = 4; } message ContentMetaData {
diff --git a/components/heap_profiling/in_process/heap_profiler_controller.cc b/components/heap_profiling/in_process/heap_profiler_controller.cc index be654e6..dd1d2f5 100644 --- a/components/heap_profiling/in_process/heap_profiler_controller.cc +++ b/components/heap_profiling/in_process/heap_profiler_controller.cc
@@ -97,6 +97,8 @@ } void HeapProfilerController::Start() { + base::UmaHistogramBoolean("HeapProfiling.InProcess.Enabled", + profiling_enabled_); if (!profiling_enabled_) return; int sampling_rate = kSamplingRate.Get();
diff --git a/components/heap_profiling/in_process/heap_profiler_controller_unittest.cc b/components/heap_profiling/in_process/heap_profiler_controller_unittest.cc index c9fdc8db..b2ddc04 100644 --- a/components/heap_profiling/in_process/heap_profiler_controller_unittest.cc +++ b/components/heap_profiling/in_process/heap_profiler_controller_unittest.cc
@@ -15,6 +15,7 @@ #include "base/sampling_heap_profiler/sampling_heap_profiler.h" #include "base/strings/string_number_conversions.h" #include "base/test/bind.h" +#include "base/test/metrics/histogram_tester.h" #include "base/test/scoped_feature_list.h" #include "base/test/task_environment.h" #include "base/time/time.h" @@ -81,9 +82,14 @@ HeapProfilerController& controller() { return *controller_; } + const base::HistogramTester& histogram_tester() const { + return histogram_tester_; + } + private: std::unique_ptr<HeapProfilerController> controller_; base::test::ScopedFeatureList feature_list_; + base::HistogramTester histogram_tester_; }; // A callback that fails the test if any samples are received. @@ -191,6 +197,8 @@ version_info::Channel::STABLE, base::BindRepeating(&ExpectNoSamples), HeapProfilerReportingConfig{.enabled = false}); tester.controller().Start(); + tester.histogram_tester().ExpectUniqueSample( + "HeapProfiling.InProcess.Enabled", false, 1); AddOneSampleAndWait(); } @@ -206,6 +214,8 @@ base::BindRepeating(&ExpectNoSamples), feature_config); tester.controller().Start(); + tester.histogram_tester().ExpectUniqueSample( + "HeapProfiling.InProcess.Enabled", false, 1); AddOneSampleAndWait(); } @@ -219,6 +229,8 @@ version_info::Channel::CANARY, base::BindLambdaForTesting(watch_for_sample), feature_config); tester.controller().Start(); + tester.histogram_tester().ExpectUniqueSample( + "HeapProfiling.InProcess.Enabled", true, 1); AddOneSampleAndWait(); EXPECT_TRUE(got_sample); } @@ -240,6 +252,8 @@ version_info::Channel::STABLE, base::BindLambdaForTesting(watch_for_sample), feature_config); tester.controller().Start(); + tester.histogram_tester().ExpectUniqueSample( + "HeapProfiling.InProcess.Enabled", true, 1); AddOneSampleAndWait(); EXPECT_TRUE(got_sample); } @@ -250,6 +264,8 @@ base::BindRepeating(&ExpectNoSamples), feature_config); tester.controller().Start(); + tester.histogram_tester().ExpectUniqueSample( + "HeapProfiling.InProcess.Enabled", false, 1); AddOneSampleAndWait(); } }
diff --git a/components/history_clusters/core/BUILD.gn b/components/history_clusters/core/BUILD.gn index a3807df..7437a17 100644 --- a/components/history_clusters/core/BUILD.gn +++ b/components/history_clusters/core/BUILD.gn
@@ -20,6 +20,8 @@ static_library("core") { sources = [ "clustering_backend.h", + "features.cc", + "features.h", "history_clusters_db_tasks.cc", "history_clusters_db_tasks.h", "history_clusters_prefs.cc", @@ -28,8 +30,6 @@ "history_clusters_service.h", "history_clusters_types.cc", "history_clusters_types.h", - "memories_features.cc", - "memories_features.h", ] if (build_with_on_device_clustering_backend) { sources += [ @@ -82,6 +82,7 @@ source_set("unit_tests") { testonly = true sources = [ + "features_unittest.cc", "history_clusters_db_tasks_unittest.cc", "history_clusters_service_unittest.cc", ]
diff --git a/components/history_clusters/core/memories_features.cc b/components/history_clusters/core/features.cc similarity index 67% rename from components/history_clusters/core/memories_features.cc rename to components/history_clusters/core/features.cc index 22810409..1d706b8 100644 --- a/components/history_clusters/core/memories_features.cc +++ b/components/history_clusters/core/features.cc
@@ -2,10 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "components/history_clusters/core/memories_features.h" +#include "components/history_clusters/core/features.h" +#include "base/containers/contains.h" +#include "base/feature_list.h" #include "base/metrics/field_trial_params.h" +#include "base/strings/string_piece_forward.h" +#include "base/strings/string_split.h" #include "build/build_config.h" +#include "ui/base/l10n/l10n_util.h" namespace history_clusters { @@ -20,6 +25,27 @@ } // namespace +bool IsJourneysEnabled(const std::string& locale) { + if (!base::FeatureList::IsEnabled(kJourneys)) + return false; + + // Allow comma and colon as delimiters to the language list. + auto allowlist = + base::SplitString(kLocaleOrLanguageAllowlist.Get(), + ",:", base::WhitespaceHandling::TRIM_WHITESPACE, + base::SplitResult::SPLIT_WANT_NONEMPTY); + if (allowlist.empty()) + return true; + + // Allow any exact locale matches, and also allow any users where the primary + // language subtag, e.g. "en" from "en-US" to match any element of the list. + return base::Contains(allowlist, locale) || + base::Contains(allowlist, l10n_util::GetLanguage(locale)); +} + +const base::FeatureParam<std::string> kLocaleOrLanguageAllowlist{ + &kJourneys, "JourneysLocaleOrLanguageAllowlist", ""}; + const base::FeatureParam<int> kMaxVisitsToCluster{ &kJourneys, "JourneysMaxVisitsToCluster", 1000};
diff --git a/components/history_clusters/core/memories_features.h b/components/history_clusters/core/features.h similarity index 76% rename from components/history_clusters/core/memories_features.h rename to components/history_clusters/core/features.h index 9c2f7e0..b133290 100644 --- a/components/history_clusters/core/memories_features.h +++ b/components/history_clusters/core/features.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef COMPONENTS_HISTORY_CLUSTERS_CORE_MEMORIES_FEATURES_H_ -#define COMPONENTS_HISTORY_CLUSTERS_CORE_MEMORIES_FEATURES_H_ +#ifndef COMPONENTS_HISTORY_CLUSTERS_CORE_FEATURES_H_ +#define COMPONENTS_HISTORY_CLUSTERS_CORE_FEATURES_H_ #include "base/feature_list.h" #include "base/metrics/field_trial_params.h" @@ -13,6 +13,19 @@ // Params & helpers functions +// Returns true if Journeys in the Chrome History WebUI is enabled. +bool IsJourneysEnabled(const std::string& application_locale); + +// A comma (or colon) separated list of allowed locales and languages for which +// Journeys is enabled. If this string is empty, any application locale or +// language is allowed. If this string is non-empty, then the either the user's +// system locale or primary language subtag must match one of the elements for +// Journeys to be enabled. +// +// For example, "en,zh-TW" would mark English language users from any country, +// and Chinese language users from Taiwan as on the allowlist. +extern const base::FeatureParam<std::string> kLocaleOrLanguageAllowlist; + // The max number of visits to use for each clustering iteration. This limits // the number of visits sent to the clustering backend per batch. extern const base::FeatureParam<int> kMaxVisitsToCluster; @@ -52,7 +65,8 @@ // Features -// Enables Journeys in the Chrome History WebUI. +// Enables Journeys in the Chrome History WebUI. This flag shouldn't be checked +// directly. Instead use `IsJourneysEnabled()` for the system language filter. extern const base::Feature kJourneys; // Enables the Journeys Omnibox Action chip. `kJourneys` must also be enabled @@ -72,10 +86,10 @@ // enabled for all users shortly. This just provides a killswitch. // This flag is to enable us to turn on persisting context annotations WITHOUT -// exposing the Memories UI in general. If EITHER this flag or `kMemories` is +// exposing the Memories UI in general. If EITHER this flag or `kJourneys` is // enabled, users will have context annotations persisted into their History DB. extern const base::Feature kPersistContextAnnotationsInHistoryDb; } // namespace history_clusters -#endif // COMPONENTS_HISTORY_CLUSTERS_CORE_MEMORIES_FEATURES_H_ +#endif // COMPONENTS_HISTORY_CLUSTERS_CORE_FEATURES_H_
diff --git a/components/history_clusters/core/features_unittest.cc b/components/history_clusters/core/features_unittest.cc new file mode 100644 index 0000000..054807a --- /dev/null +++ b/components/history_clusters/core/features_unittest.cc
@@ -0,0 +1,53 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/history_clusters/core/features.h" + +#include "base/test/scoped_feature_list.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace history_clusters { + +TEST(HistoryClustersFeaturesTest, PlainEnabled) { + EXPECT_FALSE(IsJourneysEnabled("")); + EXPECT_FALSE(IsJourneysEnabled("en")); + EXPECT_FALSE(IsJourneysEnabled("fr")); + EXPECT_FALSE(IsJourneysEnabled("zh-TW")); + EXPECT_FALSE(IsJourneysEnabled(" random junk ")); + + base::test::ScopedFeatureList features; + features.InitWithFeatures({kJourneys, kOmniboxAction}, {}); + + EXPECT_TRUE(IsJourneysEnabled("")); + EXPECT_TRUE(IsJourneysEnabled("en")); + EXPECT_TRUE(IsJourneysEnabled("fr")); + EXPECT_TRUE(IsJourneysEnabled("zh-TW")); + EXPECT_TRUE(IsJourneysEnabled(" random junk ")); +} + +TEST(HistoryClustersFeaturesTest, LocaleOrLanguageAllowlist) { + base::test::ScopedFeatureList features; + features.InitWithFeaturesAndParameters( + {{ + kJourneys, + // Test that we're tolerant of spaces, colons, whole locales, as well + // as primary language subcodes. + {{"JourneysLocaleOrLanguageAllowlist", "en, fr:de:zh-TW"}}, + }, + {kOmniboxAction, {}}}, + {}); + + EXPECT_FALSE(IsJourneysEnabled("")); + EXPECT_TRUE(IsJourneysEnabled("en")); + EXPECT_TRUE(IsJourneysEnabled("en-US")); + EXPECT_TRUE(IsJourneysEnabled("fr")); + EXPECT_FALSE(IsJourneysEnabled(" random junk ")); + EXPECT_TRUE(IsJourneysEnabled("de")); + EXPECT_FALSE(IsJourneysEnabled("el")); + EXPECT_TRUE(IsJourneysEnabled("zh-TW")); + EXPECT_FALSE(IsJourneysEnabled("zh")); + EXPECT_FALSE(IsJourneysEnabled("zh-CN")); +} + +} // namespace history_clusters
diff --git a/components/history_clusters/core/history_clusters_db_tasks.cc b/components/history_clusters/core/history_clusters_db_tasks.cc index f44cd9ae..2ad7e344 100644 --- a/components/history_clusters/core/history_clusters_db_tasks.cc +++ b/components/history_clusters/core/history_clusters_db_tasks.cc
@@ -12,7 +12,7 @@ #include "components/history/core/browser/history_backend.h" #include "components/history/core/browser/history_database.h" #include "components/history/core/browser/history_types.h" -#include "components/history_clusters/core/memories_features.h" +#include "components/history_clusters/core/features.h" namespace history_clusters {
diff --git a/components/history_clusters/core/history_clusters_service.cc b/components/history_clusters/core/history_clusters_service.cc index 7ec76be..e17c3b77 100644 --- a/components/history_clusters/core/history_clusters_service.cc +++ b/components/history_clusters/core/history_clusters_service.cc
@@ -31,10 +31,10 @@ #include "components/history/core/browser/history_database.h" #include "components/history/core/browser/history_db_task.h" #include "components/history/core/browser/history_types.h" +#include "components/history_clusters/core/features.h" #include "components/history_clusters/core/history_clusters_buildflags.h" #include "components/history_clusters/core/history_clusters_db_tasks.h" #include "components/history_clusters/core/history_clusters_types.h" -#include "components/history_clusters/core/memories_features.h" #include "components/optimization_guide/core/entity_metadata_provider.h" #include "components/search_engines/template_url_service.h" #include "components/site_engagement/core/site_engagement_score_provider.h"
diff --git a/components/history_clusters/core/history_clusters_service_unittest.cc b/components/history_clusters/core/history_clusters_service_unittest.cc index 4800dd4..33e1fd0 100644 --- a/components/history_clusters/core/history_clusters_service_unittest.cc +++ b/components/history_clusters/core/history_clusters_service_unittest.cc
@@ -25,9 +25,9 @@ #include "components/history/core/browser/url_row.h" #include "components/history/core/test/history_service_test_util.h" #include "components/history_clusters/core/clustering_backend.h" +#include "components/history_clusters/core/features.h" #include "components/history_clusters/core/history_clusters_service_test_api.h" #include "components/history_clusters/core/history_clusters_types.h" -#include "components/history_clusters/core/memories_features.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h"
diff --git a/components/metrics/metrics_pref_names.cc b/components/metrics/metrics_pref_names.cc index 1217130..3d1365a 100644 --- a/components/metrics/metrics_pref_names.cc +++ b/components/metrics/metrics_pref_names.cc
@@ -163,10 +163,6 @@ const char kStabilityGpuCrashCount[] = "user_experience_metrics.stability.gpu_crash_count"; -// Number of times the session end did not complete. -const char kStabilityIncompleteSessionEndCount[] = - "user_experience_metrics.stability.incomplete_session_end_count"; - // Number of times the application was launched since last report. const char kStabilityLaunchCount[] = "user_experience_metrics.stability.launch_count"; @@ -201,11 +197,6 @@ const char kStabilitySavedSystemProfileHash[] = "user_experience_metrics.stability.saved_system_profile_hash"; -// False if we received a session end and either we crashed during processing -// the session end or ran out of time and windows terminated us. -const char kStabilitySessionEndCompleted[] = - "user_experience_metrics.stability.session_end_completed"; - // Build time, in seconds since an epoch, which is used to assure that stability // metrics reported reflect stability of the same build. const char kStabilityStatsBuildTime[] =
diff --git a/components/metrics/metrics_pref_names.h b/components/metrics/metrics_pref_names.h index 0900c6c..ebac80b1 100644 --- a/components/metrics/metrics_pref_names.h +++ b/components/metrics/metrics_pref_names.h
@@ -52,7 +52,6 @@ extern const char kStabilityFileMetricsUnsentFilesCount[]; extern const char kStabilityGmsCoreVersion[]; extern const char kStabilityGpuCrashCount[]; -extern const char kStabilityIncompleteSessionEndCount[]; extern const char kStabilityLaunchCount[]; extern const char kStabilityPageLoadCount[]; extern const char kStabilityRendererCrashCount[]; @@ -61,7 +60,6 @@ extern const char kStabilityRendererLaunchCount[]; extern const char kStabilitySavedSystemProfile[]; extern const char kStabilitySavedSystemProfileHash[]; -extern const char kStabilitySessionEndCompleted[]; extern const char kStabilityStatsBuildTime[]; extern const char kStabilityStatsVersion[]; extern const char kStabilitySystemCrashCount[];
diff --git a/components/metrics/metrics_service.cc b/components/metrics/metrics_service.cc index fcda875a..3c617a5 100644 --- a/components/metrics/metrics_service.cc +++ b/components/metrics/metrics_service.cc
@@ -621,7 +621,6 @@ // Notify stability metrics providers about the launch. provider.LogLaunch(); - provider.CheckLastSessionEndCompleted(); // Call GetUptimes() for the first time, thus allowing all later calls // to record incremental uptimes accurately. @@ -1028,7 +1027,6 @@ void MetricsService::LogCleanShutdown(bool end_completed) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); state_manager_->LogHasSessionShutdownCleanly(true); - StabilityMetricsProvider(local_state_).MarkSessionEndCompleted(end_completed); } void MetricsService::UpdateLastLiveTimestampTask() {
diff --git a/components/metrics/stability_metrics_helper.h b/components/metrics/stability_metrics_helper.h index 682ccb41..5f09aa66 100644 --- a/components/metrics/stability_metrics_helper.h +++ b/components/metrics/stability_metrics_helper.h
@@ -27,7 +27,7 @@ kChildProcessCrash = 6, kLaunch = 15, kBrowserCrash = 16, - kIncompleteShutdown = 17, + // kIncompleteShutdown = 17, // Removed due to disuse and correctness issues. kRendererFailedLaunch = 24, kExtensionRendererFailedLaunch = 25, kRendererLaunch = 26,
diff --git a/components/metrics/stability_metrics_provider.cc b/components/metrics/stability_metrics_provider.cc index 5f1a0c0e8..d5157bf 100644 --- a/components/metrics/stability_metrics_provider.cc +++ b/components/metrics/stability_metrics_provider.cc
@@ -58,8 +58,6 @@ // static void StabilityMetricsProvider::RegisterPrefs(PrefRegistrySimple* registry) { registry->RegisterIntegerPref(prefs::kStabilityCrashCount, 0); - registry->RegisterIntegerPref(prefs::kStabilityIncompleteSessionEndCount, 0); - registry->RegisterBooleanPref(prefs::kStabilitySessionEndCompleted, true); registry->RegisterIntegerPref(prefs::kStabilityLaunchCount, 0); registry->RegisterIntegerPref(prefs::kStabilityFileMetricsUnsentFilesCount, 0); @@ -86,9 +84,7 @@ void StabilityMetricsProvider::ClearSavedStabilityMetrics() { local_state_->SetInteger(prefs::kStabilityCrashCount, 0); - local_state_->SetInteger(prefs::kStabilityIncompleteSessionEndCount, 0); local_state_->SetInteger(prefs::kStabilityLaunchCount, 0); - local_state_->SetBoolean(prefs::kStabilitySessionEndCompleted, true); // The 0 is a valid value for the below prefs, clears pref instead // of setting to default value. @@ -120,11 +116,6 @@ } #endif - if (GetAndClearPrefValue(prefs::kStabilityIncompleteSessionEndCount, - &pref_value)) - stability->set_incomplete_shutdown_count(pref_value); - - if (local_state_->HasPrefPath(prefs::kStabilityFileMetricsUnsentFilesCount)) { UMA_STABILITY_HISTOGRAM_COUNTS_100( "Stability.Internals.FileMetricsProvider.BrowserMetrics." @@ -152,21 +143,6 @@ #endif } - -void StabilityMetricsProvider::CheckLastSessionEndCompleted() { - if (!local_state_->GetBoolean(prefs::kStabilitySessionEndCompleted)) { - IncrementPrefValue(prefs::kStabilityIncompleteSessionEndCount); - StabilityMetricsHelper::RecordStabilityEvent( - StabilityEventType::kIncompleteShutdown); - // This is marked false when we get a WM_ENDSESSION. - MarkSessionEndCompleted(true); - } -} - -void StabilityMetricsProvider::MarkSessionEndCompleted(bool end_completed) { - local_state_->SetBoolean(prefs::kStabilitySessionEndCompleted, end_completed); -} - void StabilityMetricsProvider::LogCrash(base::Time last_live_timestamp) { #if defined(OS_ANDROID) // On Android, if there is an update for GMS Core when Chrome is running,
diff --git a/components/metrics/stability_metrics_provider.h b/components/metrics/stability_metrics_provider.h index b546cdb..abea6ac67 100644 --- a/components/metrics/stability_metrics_provider.h +++ b/components/metrics/stability_metrics_provider.h
@@ -29,9 +29,6 @@ static void RegisterPrefs(PrefRegistrySimple* registry); - void CheckLastSessionEndCompleted(); - void MarkSessionEndCompleted(bool end_completed); - void LogCrash(base::Time last_live_timestamp); void LogLaunch();
diff --git a/components/metrics/stability_metrics_provider_unittest.cc b/components/metrics/stability_metrics_provider_unittest.cc index 17d5912a..17be076 100644 --- a/components/metrics/stability_metrics_provider_unittest.cc +++ b/components/metrics/stability_metrics_provider_unittest.cc
@@ -40,14 +40,11 @@ // Initial log metrics: only expected if non-zero. EXPECT_FALSE(stability.has_launch_count()); EXPECT_FALSE(stability.has_crash_count()); - EXPECT_FALSE(stability.has_incomplete_shutdown_count()); histogram_tester.ExpectBucketCount("Stability.Counts2", StabilityEventType::kLaunch, 0); histogram_tester.ExpectBucketCount("Stability.Counts2", StabilityEventType::kBrowserCrash, 0); - histogram_tester.ExpectBucketCount( - "Stability.Counts2", StabilityEventType::kIncompleteShutdown, 0); } TEST_F(StabilityMetricsProviderTest, RecordStabilityMetrics) { @@ -56,8 +53,6 @@ StabilityMetricsProvider recorder(&prefs_); recorder.LogLaunch(); recorder.LogCrash(base::Time()); - recorder.MarkSessionEndCompleted(false); - recorder.CheckLastSessionEndCompleted(); } { @@ -70,14 +65,11 @@ // Initial log metrics: only expected if non-zero. EXPECT_EQ(1, stability.launch_count()); EXPECT_EQ(1, stability.crash_count()); - EXPECT_EQ(1, stability.incomplete_shutdown_count()); histogram_tester.ExpectBucketCount("Stability.Counts2", StabilityEventType::kLaunch, 1); histogram_tester.ExpectBucketCount("Stability.Counts2", StabilityEventType::kBrowserCrash, 1); - histogram_tester.ExpectBucketCount( - "Stability.Counts2", StabilityEventType::kIncompleteShutdown, 1); } }
diff --git a/components/omnibox/browser/actions/history_clusters_action.cc b/components/omnibox/browser/actions/history_clusters_action.cc index 88bb23d..6adfb257 100644 --- a/components/omnibox/browser/actions/history_clusters_action.cc +++ b/components/omnibox/browser/actions/history_clusters_action.cc
@@ -9,9 +9,9 @@ #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" +#include "components/history_clusters/core/features.h" #include "components/history_clusters/core/history_clusters_prefs.h" #include "components/history_clusters/core/history_clusters_service.h" -#include "components/history_clusters/core/memories_features.h" #include "components/omnibox/browser/actions/omnibox_action.h" #include "components/omnibox/browser/autocomplete_result.h" #include "components/prefs/pref_service.h"
diff --git a/components/onc/onc_pref_names.cc b/components/onc/onc_pref_names.cc index 79b6658d4..6bebc5b8 100644 --- a/components/onc/onc_pref_names.cc +++ b/components/onc/onc_pref_names.cc
@@ -30,7 +30,7 @@ registry->RegisterListPref(prefs::kDeviceOpenNetworkConfiguration); } -void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry) { +void RegisterProfilePrefs(PrefRegistrySimple* registry) { registry->RegisterListPref(prefs::kOpenNetworkConfiguration); }
diff --git a/components/onc/onc_pref_names.h b/components/onc/onc_pref_names.h index 50a1409..8e7f7c9d 100644 --- a/components/onc/onc_pref_names.h +++ b/components/onc/onc_pref_names.h
@@ -9,10 +9,6 @@ class PrefRegistrySimple; -namespace user_prefs { -class PrefRegistrySyncable; -} - namespace onc { namespace prefs { @@ -25,7 +21,7 @@ COMPONENT_EXPORT(ONC) void RegisterPrefs(PrefRegistrySimple* registry); COMPONENT_EXPORT(ONC) -void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry); +void RegisterProfilePrefs(PrefRegistrySimple* registry); } // namespace onc
diff --git a/components/optimization_guide/content/browser/page_content_annotations_model_manager.cc b/components/optimization_guide/content/browser/page_content_annotations_model_manager.cc index 20a661a..269fcc25 100644 --- a/components/optimization_guide/content/browser/page_content_annotations_model_manager.cc +++ b/components/optimization_guide/content/browser/page_content_annotations_model_manager.cc
@@ -475,6 +475,16 @@ out_content_annotations->categories = final_categories; } +absl::optional<ModelInfo> +PageContentAnnotationsModelManager::GetModelInfoForType( + AnnotationType type) const { + if (type == AnnotationType::kPageTopics && + on_demand_page_topics_model_executor_) { + return on_demand_page_topics_model_executor_->GetModelInfo(); + } + return absl::nullopt; +} + void PageContentAnnotationsModelManager::Annotate( BatchAnnotationCallback callback, const std::vector<std::string>& inputs,
diff --git a/components/optimization_guide/content/browser/page_content_annotations_model_manager.h b/components/optimization_guide/content/browser/page_content_annotations_model_manager.h index 33b6229..4c4b8d6 100644 --- a/components/optimization_guide/content/browser/page_content_annotations_model_manager.h +++ b/components/optimization_guide/content/browser/page_content_annotations_model_manager.h
@@ -9,6 +9,7 @@ #include "components/optimization_guide/content/browser/page_content_annotator.h" #include "components/optimization_guide/core/bert_model_handler.h" #include "components/optimization_guide/core/entity_metadata.h" +#include "components/optimization_guide/core/model_info.h" #include "components/optimization_guide/core/page_content_annotation_job.h" #include "components/optimization_guide/core/page_content_annotations_common.h" #include "components/optimization_guide/core/page_topics_model_executor.h" @@ -55,6 +56,11 @@ const std::vector<std::string>& inputs, AnnotationType annotation_type) override; + // Returns the model info associated with the given AnnotationType, if it is + // available and loaded. + // TODO(crbug/1249632): Add support for more than just page topics. + absl::optional<ModelInfo> GetModelInfoForType(AnnotationType type) const; + // Returns the version of the page topics model that is currently being used // to annotate page content. Will return |absl::nullopt| if no model is being // used to annotate page topics for received page content.
diff --git a/components/optimization_guide/content/browser/page_content_annotations_model_manager_unittest.cc b/components/optimization_guide/content/browser/page_content_annotations_model_manager_unittest.cc index 8e5eaa8..e1600d9 100644 --- a/components/optimization_guide/content/browser/page_content_annotations_model_manager_unittest.cc +++ b/components/optimization_guide/content/browser/page_content_annotations_model_manager_unittest.cc
@@ -156,16 +156,7 @@ RunUntilIdle(); } - void SetupPageTopicsV2ModelExecutor() { - model_manager()->SetUpPageTopicsV2Model(model_observer_tracker()); - // If the feature flag is disabled, the executor won't have been created so - // skip everything else. - if (!model_manager()->on_demand_page_topics_model_executor_) - return; - - proto::Any any_metadata; - any_metadata.set_type_url( - "type.googleapis.com/com.foo.PageTopicsModelMetadata"); + proto::PageTopicsModelMetadata MakeValidPageTopicsModelMetadata() const { proto::PageTopicsModelMetadata page_topics_model_metadata; page_topics_model_metadata.set_version(123); page_topics_model_metadata.add_supported_output( @@ -177,8 +168,21 @@ page_topics_model_metadata.mutable_output_postprocessing_params() ->mutable_category_params() ->set_min_category_weight(0); + return page_topics_model_metadata; + } - page_topics_model_metadata.SerializeToString(any_metadata.mutable_value()); + void SetupPageTopicsV2ModelExecutor() { + model_manager()->SetUpPageTopicsV2Model(model_observer_tracker()); + // If the feature flag is disabled, the executor won't have been created so + // skip everything else. + if (!model_manager()->on_demand_page_topics_model_executor_) + return; + + proto::Any any_metadata; + any_metadata.set_type_url( + "type.googleapis.com/com.foo.PageTopicsModelMetadata"); + MakeValidPageTopicsModelMetadata().SerializeToString( + any_metadata.mutable_value()); base::FilePath source_root_dir; base::PathService::Get(base::DIR_SOURCE_ROOT, &source_root_dir); @@ -744,12 +748,6 @@ } TEST_F(PageContentAnnotationsModelManagerTest, BatchAnnotate_CalledTwice) { - proto::Any any_metadata; - any_metadata.set_type_url( - "type.googleapis.com/com.foo.PageTopicsModelMetadata"); - proto::PageTopicsModelMetadata page_topics_model_metadata; - page_topics_model_metadata.set_version(123); - page_topics_model_metadata.SerializeToString(any_metadata.mutable_value()); SetupPageTopicsV2ModelExecutor(); base::HistogramTester histogram_tester; @@ -811,6 +809,31 @@ EXPECT_EQ(result2[0].visibility_score(), absl::nullopt); } +TEST_F(PageContentAnnotationsModelManagerTest, GetModelInfoForType) { + EXPECT_FALSE( + model_manager()->GetModelInfoForType(AnnotationType::kPageTopics)); + EXPECT_FALSE( + model_manager()->GetModelInfoForType(AnnotationType::kContentVisibility)); + + SetupPageTopicsV2ModelExecutor(); + + proto::Any any_metadata; + any_metadata.set_type_url( + "type.googleapis.com/com.foo.PageTopicsModelMetadata"); + proto::PageTopicsModelMetadata page_topics_model_metadata; + page_topics_model_metadata.set_version(123); + page_topics_model_metadata.mutable_output_postprocessing_params() + ->mutable_visibility_params() + ->set_category_name("DO NOT EVALUATE"); + page_topics_model_metadata.SerializeToString(any_metadata.mutable_value()); + SendPageVisibilityModelToExecutor(any_metadata); + + EXPECT_TRUE( + model_manager()->GetModelInfoForType(AnnotationType::kPageTopics)); + EXPECT_FALSE( + model_manager()->GetModelInfoForType(AnnotationType::kContentVisibility)); +} + class PageContentAnnotationsModelManagerEntitiesOnlyTest : public PageContentAnnotationsModelManagerTest { public:
diff --git a/components/optimization_guide/content/browser/page_content_annotations_service.cc b/components/optimization_guide/content/browser/page_content_annotations_service.cc index cfbd33a..167b127 100644 --- a/components/optimization_guide/content/browser/page_content_annotations_service.cc +++ b/components/optimization_guide/content/browser/page_content_annotations_service.cc
@@ -124,6 +124,16 @@ annotator_->Annotate(std::move(callback), inputs, annotation_type); } +absl::optional<ModelInfo> PageContentAnnotationsService::GetModelInfoForType( + AnnotationType type) const { +#if BUILDFLAG(BUILD_WITH_TFLITE_LIB) + DCHECK(model_manager_); + return model_manager_->GetModelInfoForType(type); +#else + return absl::nullopt; +#endif +} + void PageContentAnnotationsService::ExtractRelatedSearches( const HistoryVisit& visit, content::WebContents* web_contents) { @@ -233,15 +243,6 @@ did_store_content_annotations ? kSuccess : kSpecificVisitForUrlNotFound); } -absl::optional<int64_t> -PageContentAnnotationsService::GetPageTopicsModelVersion() const { -#if BUILDFLAG(BUILD_WITH_TFLITE_LIB) - return model_manager_->GetPageTopicsModelVersion(); -#else - return absl::nullopt; -#endif -} - void PageContentAnnotationsService::GetMetadataForEntityId( const std::string& entity_id, EntityMetadataRetrievedCallback callback) {
diff --git a/components/optimization_guide/content/browser/page_content_annotations_service.h b/components/optimization_guide/content/browser/page_content_annotations_service.h index cc22c4f..dc01fc9 100644 --- a/components/optimization_guide/content/browser/page_content_annotations_service.h +++ b/components/optimization_guide/content/browser/page_content_annotations_service.h
@@ -23,6 +23,7 @@ #include "components/keyed_service/core/keyed_service.h" #include "components/optimization_guide/content/browser/page_content_annotator.h" #include "components/optimization_guide/core/entity_metadata_provider.h" +#include "components/optimization_guide/core/model_info.h" #include "components/optimization_guide/core/page_content_annotations_common.h" #include "components/optimization_guide/machine_learning_tflite_buildflags.h" #include "url/gurl.h" @@ -79,10 +80,9 @@ // test_page_content_annotator.h for an implementation designed for testing. void OverridePageContentAnnotatorForTesting(PageContentAnnotator* annotator); - // Returns the version of the page topics model that is currently being used - // to annotate page content. Will return |absl::nullopt| if no model is being - // used to annotate page topics for received page content. - absl::optional<int64_t> GetPageTopicsModelVersion() const; + // Returns the model info for the given annotation type, if the model file is + // available. + absl::optional<ModelInfo> GetModelInfoForType(AnnotationType type) const; // EntityMetadataProvider: void GetMetadataForEntityId(
diff --git a/components/optimization_guide/core/hints_manager.cc b/components/optimization_guide/core/hints_manager.cc index 7d1138f..ae5e3358 100644 --- a/components/optimization_guide/core/hints_manager.cc +++ b/components/optimization_guide/core/hints_manager.cc
@@ -65,9 +65,9 @@ // Provides a random time delta in seconds between |kFetchRandomMinDelay| and // |kFetchRandomMaxDelay|. base::TimeDelta RandomFetchDelay() { - return base::Seconds(base::RandInt( - optimization_guide::features::ActiveTabsHintsFetchRandomMinDelaySecs(), - optimization_guide::features::ActiveTabsHintsFetchRandomMaxDelaySecs())); + return base::Seconds( + base::RandInt(features::ActiveTabsHintsFetchRandomMinDelaySecs(), + features::ActiveTabsHintsFetchRandomMaxDelaySecs())); } void MaybeRunUpdateClosure(base::OnceClosure update_closure) { @@ -78,39 +78,35 @@ // Returns whether the particular component version can be processed, and if it // can be, locks the semaphore (in the form of a pref) to signal that the // processing of this particular version has started. -bool CanProcessComponentVersion( - PrefService* pref_service, - const base::Version& version, - optimization_guide::ProcessHintsComponentResult* out_result) { +bool CanProcessComponentVersion(PrefService* pref_service, + const base::Version& version, + ProcessHintsComponentResult* out_result) { DCHECK(version.IsValid()); DCHECK(out_result); - const std::string previous_attempted_version_string = pref_service->GetString( - optimization_guide::prefs::kPendingHintsProcessingVersion); + const std::string previous_attempted_version_string = + pref_service->GetString(prefs::kPendingHintsProcessingVersion); if (!previous_attempted_version_string.empty()) { const base::Version previous_attempted_version = base::Version(previous_attempted_version_string); if (!previous_attempted_version.IsValid()) { DLOG(ERROR) << "Bad contents in hints processing pref"; // Clear pref for fresh start next time. - pref_service->ClearPref( - optimization_guide::prefs::kPendingHintsProcessingVersion); - *out_result = optimization_guide::ProcessHintsComponentResult:: - kFailedPreviouslyAttemptedVersionInvalid; + pref_service->ClearPref(prefs::kPendingHintsProcessingVersion); + *out_result = + ProcessHintsComponentResult::kFailedPreviouslyAttemptedVersionInvalid; return false; } if (previous_attempted_version.CompareTo(version) == 0) { - *out_result = optimization_guide::ProcessHintsComponentResult:: - kFailedFinishProcessing; + *out_result = ProcessHintsComponentResult::kFailedFinishProcessing; // Previously attempted same version without completion. return false; } } // Write config version to pref. - pref_service->SetString( - optimization_guide::prefs::kPendingHintsProcessingVersion, - version.GetString()); + pref_service->SetString(prefs::kPendingHintsProcessingVersion, + version.GetString()); return true; } @@ -119,11 +115,10 @@ // populated with the metadata provided by the hint, if applicable. If // |page_hint| is not provided or |optimization_type| is not allowlisted, this // will return false. -bool IsOptimizationTypeAllowed( - const google::protobuf::RepeatedPtrField< - optimization_guide::proto::Optimization>& optimizations, - optimization_guide::proto::OptimizationType optimization_type, - optimization_guide::OptimizationMetadata* optimization_metadata) { +bool IsOptimizationTypeAllowed(const google::protobuf::RepeatedPtrField< + proto::Optimization>& optimizations, + proto::OptimizationType optimization_type, + OptimizationMetadata* optimization_metadata) { for (const auto& optimization : optimizations) { if (optimization_type != optimization.optimization_type()) continue; @@ -132,22 +127,22 @@ // metadata if applicable and return. if (optimization_metadata) { switch (optimization.metadata_case()) { - case optimization_guide::proto::Optimization::kPerformanceHintsMetadata: + case proto::Optimization::kPerformanceHintsMetadata: optimization_metadata->set_performance_hints_metadata( optimization.performance_hints_metadata()); break; - case optimization_guide::proto::Optimization::kPublicImageMetadata: + case proto::Optimization::kPublicImageMetadata: optimization_metadata->set_public_image_metadata( optimization.public_image_metadata()); break; - case optimization_guide::proto::Optimization::kLoadingPredictorMetadata: + case proto::Optimization::kLoadingPredictorMetadata: optimization_metadata->set_loading_predictor_metadata( optimization.loading_predictor_metadata()); break; - case optimization_guide::proto::Optimization::kAnyMetadata: + case proto::Optimization::kAnyMetadata: optimization_metadata->set_any_metadata(optimization.any_metadata()); break; - case optimization_guide::proto::Optimization::METADATA_NOT_SET: + case proto::Optimization::METADATA_NOT_SET: // Some optimization types do not have metadata, make sure we do not // DCHECK. break; @@ -166,16 +161,14 @@ public: explicit ScopedHintsManagerRaceNavigationHintsFetchAttemptRecorder( OptimizationGuideNavigationData* navigation_data) - : race_attempt_status_( - optimization_guide::RaceNavigationFetchAttemptStatus::kUnknown), + : race_attempt_status_(RaceNavigationFetchAttemptStatus::kUnknown), navigation_data_(navigation_data) {} ~ScopedHintsManagerRaceNavigationHintsFetchAttemptRecorder() { - DCHECK_NE(race_attempt_status_, - optimization_guide::RaceNavigationFetchAttemptStatus::kUnknown); + DCHECK_NE(race_attempt_status_, RaceNavigationFetchAttemptStatus::kUnknown); DCHECK_NE( race_attempt_status_, - optimization_guide::RaceNavigationFetchAttemptStatus:: + RaceNavigationFetchAttemptStatus:: kDeprecatedRaceNavigationFetchNotAttemptedTooManyConcurrentFetches); base::UmaHistogramEnumeration( "OptimizationGuide.HintsManager.RaceNavigationFetchAttemptStatus", @@ -185,25 +178,24 @@ } void set_race_attempt_status( - optimization_guide::RaceNavigationFetchAttemptStatus - race_attempt_status) { + RaceNavigationFetchAttemptStatus race_attempt_status) { race_attempt_status_ = race_attempt_status; } private: - optimization_guide::RaceNavigationFetchAttemptStatus race_attempt_status_; + RaceNavigationFetchAttemptStatus race_attempt_status_; raw_ptr<OptimizationGuideNavigationData> navigation_data_; }; // Returns true if the optimization type should be ignored when is newly // registered as the optimization type is likely launched. bool ShouldIgnoreNewlyRegisteredOptimizationType( - optimization_guide::proto::OptimizationType optimization_type) { + proto::OptimizationType optimization_type) { switch (optimization_type) { - case optimization_guide::proto::NOSCRIPT: - case optimization_guide::proto::RESOURCE_LOADING: - case optimization_guide::proto::LITE_PAGE_REDIRECT: - case optimization_guide::proto::DEFER_ALL_SCRIPT: + case proto::NOSCRIPT: + case proto::RESOURCE_LOADING: + case proto::LITE_PAGE_REDIRECT: + case proto::DEFER_ALL_SCRIPT: return true; default: return false; @@ -212,22 +204,19 @@ class ScopedCanApplyOptimizationLogger { public: - ScopedCanApplyOptimizationLogger( - optimization_guide::proto::OptimizationType opt_type, - GURL url) - : decision_(optimization_guide::OptimizationGuideDecision::kUnknown), - type_decision_(optimization_guide::OptimizationTypeDecision::kUnknown), + ScopedCanApplyOptimizationLogger(proto::OptimizationType opt_type, GURL url) + : decision_(OptimizationGuideDecision::kUnknown), + type_decision_(OptimizationTypeDecision::kUnknown), opt_type_(opt_type), has_metadata_(false), url_(url) {} ~ScopedCanApplyOptimizationLogger() { - if (!optimization_guide::switches::IsDebugLogsEnabled()) + if (!switches::IsDebugLogsEnabled()) return; - DCHECK_NE(type_decision_, - optimization_guide::OptimizationTypeDecision::kUnknown); + DCHECK_NE(type_decision_, OptimizationTypeDecision::kUnknown); DVLOG(0) << "OptimizationGuide: CanApplyOptimization: " - << optimization_guide::GetStringNameForOptimizationType(opt_type_) + << GetStringNameForOptimizationType(opt_type_) << "\nqueried on: " << url_ << "\nDecision: " << GetStringForOptimizationGuideDecision(decision_) << "\nTypeDecision: " << static_cast<int>(type_decision_) @@ -236,8 +225,7 @@ void set_has_metadata() { has_metadata_ = true; } - void set_type_decision( - optimization_guide::OptimizationTypeDecision type_decision) { + void set_type_decision(OptimizationTypeDecision type_decision) { type_decision_ = type_decision; decision_ = HintsManager::GetOptimizationGuideDecisionFromOptimizationTypeDecision( @@ -245,22 +233,22 @@ } private: - optimization_guide::OptimizationGuideDecision decision_; - optimization_guide::OptimizationTypeDecision type_decision_; - optimization_guide::proto::OptimizationType opt_type_; + OptimizationGuideDecision decision_; + OptimizationTypeDecision type_decision_; + proto::OptimizationType opt_type_; bool has_metadata_; GURL url_; }; // Reads component file and parses it into a Configuration proto. Should not be // called on the UI thread. -std::unique_ptr<optimization_guide::proto::Configuration> ReadComponentFile( - const optimization_guide::HintsComponentInfo& info) { - optimization_guide::ProcessHintsComponentResult out_result; - std::unique_ptr<optimization_guide::proto::Configuration> config = - optimization_guide::ProcessHintsComponent(info, &out_result); +std::unique_ptr<proto::Configuration> ReadComponentFile( + const HintsComponentInfo& info) { + ProcessHintsComponentResult out_result; + std::unique_ptr<proto::Configuration> config = + ProcessHintsComponent(info, &out_result); if (!config) { - optimization_guide::RecordProcessHintsComponentResult(out_result); + RecordProcessHintsComponentResult(out_result); return nullptr; } @@ -275,28 +263,25 @@ bool is_off_the_record, const std::string& application_locale, PrefService* pref_service, - optimization_guide::OptimizationGuideStore* hint_store, - optimization_guide::TopHostProvider* top_host_provider, - optimization_guide::TabUrlProvider* tab_url_provider, + OptimizationGuideStore* hint_store, + TopHostProvider* top_host_provider, + TabUrlProvider* tab_url_provider, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, network::NetworkConnectionTracker* network_connection_tracker, - std::unique_ptr<optimization_guide::PushNotificationManager> - push_notification_manager) + std::unique_ptr<PushNotificationManager> push_notification_manager) : is_off_the_record_(is_off_the_record), application_locale_(application_locale), pref_service_(pref_service), - hint_cache_(std::make_unique<optimization_guide::HintCache>( - hint_store, - optimization_guide::features::MaxHostKeyedHintCacheSize())), + hint_cache_( + std::make_unique<HintCache>(hint_store, + features::MaxHostKeyedHintCacheSize())), page_navigation_hints_fetchers_( - optimization_guide::features::MaxConcurrentPageNavigationFetches()), - hints_fetcher_factory_( - std::make_unique<optimization_guide::HintsFetcherFactory>( - url_loader_factory, - optimization_guide::features:: - GetOptimizationGuideServiceGetHintsURL(), - pref_service, - network_connection_tracker)), + features::MaxConcurrentPageNavigationFetches()), + hints_fetcher_factory_(std::make_unique<HintsFetcherFactory>( + url_loader_factory, + features::GetOptimizationGuideServiceGetHintsURL(), + pref_service, + network_connection_tracker)), top_host_provider_(top_host_provider), tab_url_provider_(tab_url_provider), push_notification_manager_(std::move(push_notification_manager)), @@ -306,10 +291,10 @@ if (push_notification_manager_) push_notification_manager_->SetDelegate(this); - hint_cache_->Initialize(optimization_guide::switches:: - ShouldPurgeOptimizationGuideStoreOnStartup(), - base::BindOnce(&HintsManager::OnHintCacheInitialized, - weak_ptr_factory_.GetWeakPtr())); + hint_cache_->Initialize( + switches::ShouldPurgeOptimizationGuideStoreOnStartup(), + base::BindOnce(&HintsManager::OnHintCacheInitialized, + weak_ptr_factory_.GetWeakPtr())); } HintsManager::~HintsManager() { @@ -318,8 +303,7 @@ void HintsManager::Shutdown() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - optimization_guide::OptimizationHintsComponentUpdateListener::GetInstance() - ->RemoveObserver(this); + OptimizationHintsComponentUpdateListener::GetInstance()->RemoveObserver(this); base::UmaHistogramBoolean("OptimizationGuide.ProcessingComponentAtShutdown", is_processing_component_); @@ -328,58 +312,51 @@ // down, we should clear the pref since the function to clear the pref will // not run after shut down and we will think that we failed to process the // component due to a crash. - pref_service_->ClearPref( - optimization_guide::prefs::kPendingHintsProcessingVersion); + pref_service_->ClearPref(prefs::kPendingHintsProcessingVersion); } } // static -optimization_guide::OptimizationGuideDecision +OptimizationGuideDecision HintsManager::GetOptimizationGuideDecisionFromOptimizationTypeDecision( - optimization_guide::OptimizationTypeDecision optimization_type_decision) { + OptimizationTypeDecision optimization_type_decision) { switch (optimization_type_decision) { - case optimization_guide::OptimizationTypeDecision:: - kAllowedByOptimizationFilter: - case optimization_guide::OptimizationTypeDecision::kAllowedByHint: - return optimization_guide::OptimizationGuideDecision::kTrue; - case optimization_guide::OptimizationTypeDecision::kUnknown: - case optimization_guide::OptimizationTypeDecision:: - kHadOptimizationFilterButNotLoadedInTime: - case optimization_guide::OptimizationTypeDecision:: - kHadHintButNotLoadedInTime: - case optimization_guide::OptimizationTypeDecision:: - kHintFetchStartedButNotAvailableInTime: - case optimization_guide::OptimizationTypeDecision::kDeciderNotInitialized: - return optimization_guide::OptimizationGuideDecision::kUnknown; - case optimization_guide::OptimizationTypeDecision::kNotAllowedByHint: - case optimization_guide::OptimizationTypeDecision::kNoMatchingPageHint: - case optimization_guide::OptimizationTypeDecision::kNoHintAvailable: - case optimization_guide::OptimizationTypeDecision:: - kNotAllowedByOptimizationFilter: - return optimization_guide::OptimizationGuideDecision::kFalse; + case OptimizationTypeDecision::kAllowedByOptimizationFilter: + case OptimizationTypeDecision::kAllowedByHint: + return OptimizationGuideDecision::kTrue; + case OptimizationTypeDecision::kUnknown: + case OptimizationTypeDecision::kHadOptimizationFilterButNotLoadedInTime: + case OptimizationTypeDecision::kHadHintButNotLoadedInTime: + case OptimizationTypeDecision::kHintFetchStartedButNotAvailableInTime: + case OptimizationTypeDecision::kDeciderNotInitialized: + return OptimizationGuideDecision::kUnknown; + case OptimizationTypeDecision::kNotAllowedByHint: + case OptimizationTypeDecision::kNoMatchingPageHint: + case OptimizationTypeDecision::kNoHintAvailable: + case OptimizationTypeDecision::kNotAllowedByOptimizationFilter: + return OptimizationGuideDecision::kFalse; } } -void HintsManager::OnHintsComponentAvailable( - const optimization_guide::HintsComponentInfo& info) { +void HintsManager::OnHintsComponentAvailable(const HintsComponentInfo& info) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // Check for if hint component is disabled. This check is needed because the // optimization guide still registers with the service as an observer for // components as a signal during testing. - if (optimization_guide::switches::IsHintComponentProcessingDisabled()) { + if (switches::IsHintComponentProcessingDisabled()) { MaybeRunUpdateClosure(std::move(next_update_closure_)); return; } - optimization_guide::ProcessHintsComponentResult out_result; + ProcessHintsComponentResult out_result; if (!CanProcessComponentVersion(pref_service_, info.version, &out_result)) { - optimization_guide::RecordProcessHintsComponentResult(out_result); + RecordProcessHintsComponentResult(out_result); MaybeRunUpdateClosure(std::move(next_update_closure_)); return; } - std::unique_ptr<optimization_guide::StoreUpdateData> update_data = + std::unique_ptr<StoreUpdateData> update_data = is_off_the_record_ ? nullptr : hint_cache_->MaybeCreateUpdateDataForComponentHints(info.version); @@ -408,11 +385,9 @@ } void HintsManager::ProcessOptimizationFilters( - const google::protobuf::RepeatedPtrField< - optimization_guide::proto::OptimizationFilter>& + const google::protobuf::RepeatedPtrField<proto::OptimizationFilter>& allowlist_optimization_filters, - const google::protobuf::RepeatedPtrField< - optimization_guide::proto::OptimizationFilter>& + const google::protobuf::RepeatedPtrField<proto::OptimizationFilter>& blocklist_optimization_filters) { optimization_types_with_filter_.clear(); allowlist_optimization_filters_.clear(); @@ -424,12 +399,11 @@ } void HintsManager::ProcessOptimizationFilterSet( - const google::protobuf::RepeatedPtrField< - optimization_guide::proto::OptimizationFilter>& filters, + const google::protobuf::RepeatedPtrField<proto::OptimizationFilter>& + filters, bool is_allowlist) { for (const auto& filter : filters) { - if (filter.optimization_type() != - optimization_guide::proto::TYPE_UNSPECIFIED) { + if (filter.optimization_type() != proto::TYPE_UNSPECIFIED) { optimization_types_with_filter_.insert(filter.optimization_type()); } @@ -439,27 +413,25 @@ continue; } - optimization_guide::RecordOptimizationFilterStatus( + RecordOptimizationFilterStatus( filter.optimization_type(), - optimization_guide::OptimizationFilterStatus::kFoundServerFilterConfig); + OptimizationFilterStatus::kFoundServerFilterConfig); // Do not parse duplicate optimization filters. if (allowlist_optimization_filters_.find(filter.optimization_type()) != allowlist_optimization_filters_.end() || blocklist_optimization_filters_.find(filter.optimization_type()) != blocklist_optimization_filters_.end()) { - optimization_guide::RecordOptimizationFilterStatus( + RecordOptimizationFilterStatus( filter.optimization_type(), - optimization_guide::OptimizationFilterStatus:: - kFailedServerFilterDuplicateConfig); + OptimizationFilterStatus::kFailedServerFilterDuplicateConfig); continue; } // Parse optimization filter. - optimization_guide::OptimizationFilterStatus status; - std::unique_ptr<optimization_guide::OptimizationFilter> - optimization_filter = - optimization_guide::ProcessOptimizationFilter(filter, &status); + OptimizationFilterStatus status; + std::unique_ptr<OptimizationFilter> optimization_filter = + ProcessOptimizationFilter(filter, &status); if (optimization_filter) { if (is_allowlist) { allowlist_optimization_filters_.insert( @@ -469,8 +441,7 @@ {filter.optimization_type(), std::move(optimization_filter)}); } } - optimization_guide::RecordOptimizationFilterStatus( - filter.optimization_type(), status); + RecordOptimizationFilterStatus(filter.optimization_type(), status); } } @@ -484,10 +455,10 @@ // Check if there is a valid hint proto given on the command line first. We // don't normally expect one, but if one is provided then use that and do not // register as an observer as the opt_guide service. - std::unique_ptr<optimization_guide::proto::Configuration> manual_config = - optimization_guide::switches::ParseComponentConfigFromCommandLine(); + std::unique_ptr<proto::Configuration> manual_config = + switches::ParseComponentConfigFromCommandLine(); if (manual_config) { - std::unique_ptr<optimization_guide::StoreUpdateData> update_data = + std::unique_ptr<StoreUpdateData> update_data = is_off_the_record_ ? nullptr : hint_cache_->MaybeCreateUpdateDataForComponentHints( @@ -507,21 +478,19 @@ // Register as an observer regardless of hint proto override usage. This is // needed as a signal during testing. - optimization_guide::OptimizationHintsComponentUpdateListener::GetInstance() - ->AddObserver(this); + OptimizationHintsComponentUpdateListener::GetInstance()->AddObserver(this); } void HintsManager::UpdateComponentHints( base::OnceClosure update_closure, - std::unique_ptr<optimization_guide::StoreUpdateData> update_data, - std::unique_ptr<optimization_guide::proto::Configuration> config) { + std::unique_ptr<StoreUpdateData> update_data, + std::unique_ptr<proto::Configuration> config) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // If we get here, the component file has been processed correctly and did not // crash the device. is_processing_component_ = false; - pref_service_->ClearPref( - optimization_guide::prefs::kPendingHintsProcessingVersion); + pref_service_->ClearPref(prefs::kPendingHintsProcessingVersion); if (!config) { MaybeRunUpdateClosure(std::move(update_closure)); @@ -535,15 +504,12 @@ if (update_data && !is_off_the_record_) { bool did_process_hints = hint_cache_->ProcessAndCacheHints( config->mutable_hints(), update_data.get()); - optimization_guide::RecordProcessHintsComponentResult( - did_process_hints - ? optimization_guide::ProcessHintsComponentResult::kSuccess - : optimization_guide::ProcessHintsComponentResult:: - kProcessedNoHints); + RecordProcessHintsComponentResult( + did_process_hints ? ProcessHintsComponentResult::kSuccess + : ProcessHintsComponentResult::kProcessedNoHints); } else { - optimization_guide::RecordProcessHintsComponentResult( - optimization_guide::ProcessHintsComponentResult:: - kSkippedProcessingHints); + RecordProcessHintsComponentResult( + ProcessHintsComponentResult::kSkippedProcessingHints); } if (update_data) { @@ -564,9 +530,8 @@ // Record the result of updating the hints. This is used as a signal for the // hints being fully processed in testing. - LOCAL_HISTOGRAM_BOOLEAN( - optimization_guide::kComponentHintsUpdatedResultHistogramString, - hints_updated); + LOCAL_HISTOGRAM_BOOLEAN(kComponentHintsUpdatedResultHistogramString, + hints_updated); // Initiate the hints fetch scheduling if deferred startup handling is not // enabled. Otherwise OnDeferredStartup() will iniitate it. @@ -576,11 +541,10 @@ } void HintsManager::InitiateHintsFetchScheduling() { - if (optimization_guide::features:: - ShouldBatchUpdateHintsForActiveTabsAndTopHosts()) { + if (features::ShouldBatchUpdateHintsForActiveTabsAndTopHosts()) { SetLastHintsFetchAttemptTime(clock_->Now()); - if (optimization_guide::switches::ShouldOverrideFetchHintsTimer() || + if (switches::ShouldOverrideFetchHintsTimer() || features::ShouldDeferStartupActiveTabsHintsFetch()) { FetchHintsForActiveTabs(); } else if (!active_tabs_hints_fetch_timer_.IsRunning()) { @@ -600,8 +564,7 @@ } void HintsManager::SetHintsFetcherFactoryForTesting( - std::unique_ptr<optimization_guide::HintsFetcherFactory> - hints_fetcher_factory) { + std::unique_ptr<HintsFetcherFactory> hints_fetcher_factory) { hints_fetcher_factory_ = std::move(hints_fetcher_factory); } @@ -613,13 +576,13 @@ DCHECK(!active_tabs_hints_fetch_timer_.IsRunning()); const base::TimeDelta active_tabs_refresh_duration = - optimization_guide::features::GetActiveTabsFetchRefreshDuration(); + features::GetActiveTabsFetchRefreshDuration(); const base::TimeDelta time_since_last_fetch = clock_->Now() - GetLastHintsFetchAttemptTime(); if (time_since_last_fetch >= active_tabs_refresh_duration) { // Fetched hints in the store should be updated and an attempt has not // been made in last - // |optimization_guide::features::GetActiveTabsFetchRefreshDuration()|. + // |features::GetActiveTabsFetchRefreshDuration()|. SetLastHintsFetchAttemptTime(clock_->Now()); active_tabs_hints_fetch_timer_.Start( FROM_HERE, RandomFetchDelay(), this, @@ -640,11 +603,11 @@ return {}; std::vector<GURL> active_tab_urls = tab_url_provider_->GetUrlsOfActiveTabs( - optimization_guide::features::GetActiveTabsStalenessTolerance()); + features::GetActiveTabsStalenessTolerance()); std::set<GURL> urls_to_refresh; for (const auto& url : active_tab_urls) { - if (!optimization_guide::IsValidURLForURLKeyedHint(url)) + if (!IsValidURLForURLKeyedHint(url)) continue; if (!hint_cache_->HasURLKeyedEntryForURL(url)) @@ -656,12 +619,11 @@ void HintsManager::FetchHintsForActiveTabs() { active_tabs_hints_fetch_timer_.Stop(); active_tabs_hints_fetch_timer_.Start( - FROM_HERE, - optimization_guide::features::GetActiveTabsFetchRefreshDuration(), this, + FROM_HERE, features::GetActiveTabsFetchRefreshDuration(), this, &HintsManager::ScheduleActiveTabsHintsFetch); - if (!optimization_guide::IsUserPermittedToFetchFromRemoteOptimizationGuide( - is_off_the_record_, pref_service_)) { + if (!IsUserPermittedToFetchFromRemoteOptimizationGuide(is_off_the_record_, + pref_service_)) { return; } @@ -690,7 +652,7 @@ // Add hosts of active tabs to list of hosts to fetch for. Since we are mainly // fetching for updated information on tabs, add those to the front of the // list. - if (optimization_guide::switches::IsDebugLogsEnabled()) { + if (switches::IsDebugLogsEnabled()) { DVLOG(0) << "OptimizationGuide: ActiveTabsFetching starting fetch for: "; DVLOG(0) << "OptimizationGuide: Registered Optimization Types: "; for (const auto& optimization_type : registered_optimization_types_) { @@ -702,7 +664,7 @@ base::flat_set<std::string> top_hosts_set = base::flat_set<std::string>(top_hosts.begin(), top_hosts.end()); for (const auto& url : active_tab_urls_to_refresh) { - if (optimization_guide::switches::IsDebugLogsEnabled()) + if (switches::IsDebugLogsEnabled()) DVLOG(0) << "OptimizationGuide: URL: " << url; if (!url.has_host() || top_hosts_set.find(url.host()) == top_hosts_set.end()) { @@ -711,15 +673,14 @@ if (!hint_cache_->HasHint(url.host())) { top_hosts_set.insert(url.host()); top_hosts.insert(top_hosts.begin(), url.host()); - if (optimization_guide::switches::IsDebugLogsEnabled()) + if (switches::IsDebugLogsEnabled()) DVLOG(0) << "OptimizationGuide: Host: " << url.host(); } } batch_update_hints_fetcher_->FetchOptimizationGuideServiceHints( top_hosts, active_tab_urls_to_refresh, registered_optimization_types_, - optimization_guide::proto::CONTEXT_BATCH_UPDATE_ACTIVE_TABS, - application_locale_, + proto::CONTEXT_BATCH_UPDATE_ACTIVE_TABS, application_locale_, base::BindOnce(&HintsManager::OnHintsForActiveTabsFetched, weak_ptr_factory_.GetWeakPtr(), top_hosts_set, base::flat_set<GURL>(active_tab_urls_to_refresh.begin(), @@ -729,19 +690,18 @@ void HintsManager::OnHintsForActiveTabsFetched( const base::flat_set<std::string>& hosts_fetched, const base::flat_set<GURL>& urls_fetched, - absl::optional<std::unique_ptr<optimization_guide::proto::GetHintsResponse>> + absl::optional<std::unique_ptr<proto::GetHintsResponse>> get_hints_response) { if (!get_hints_response) return; hint_cache_->UpdateFetchedHints( std::move(*get_hints_response), - clock_->Now() + - optimization_guide::features::GetActiveTabsFetchRefreshDuration(), + clock_->Now() + features::GetActiveTabsFetchRefreshDuration(), hosts_fetched, urls_fetched, base::BindOnce(&HintsManager::OnFetchedActiveTabsHintsStored, weak_ptr_factory_.GetWeakPtr())); - if (optimization_guide::switches::IsDebugLogsEnabled()) + if (switches::IsDebugLogsEnabled()) DVLOG(0) << "OptimizationGuide: OnHintsForActiveTabsFetched complete"; } @@ -750,7 +710,7 @@ const absl::optional<GURL>& navigation_url, const base::flat_set<GURL>& page_navigation_urls_requested, const base::flat_set<std::string>& page_navigation_hosts_requested, - absl::optional<std::unique_ptr<optimization_guide::proto::GetHintsResponse>> + absl::optional<std::unique_ptr<proto::GetHintsResponse>> get_hints_response) { if (!get_hints_response.has_value() || !get_hints_response.value()) { if (navigation_url) { @@ -762,8 +722,7 @@ hint_cache_->UpdateFetchedHints( std::move(*get_hints_response), - clock_->Now() + - optimization_guide::features::GetActiveTabsFetchRefreshDuration(), + clock_->Now() + features::GetActiveTabsFetchRefreshDuration(), page_navigation_hosts_requested, page_navigation_urls_requested, base::BindOnce(&HintsManager::OnFetchedPageNavigationHintsStored, weak_ptr_factory_.GetWeakPtr(), navigation_data_weak_ptr, @@ -774,7 +733,7 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); LOCAL_HISTOGRAM_BOOLEAN("OptimizationGuide.FetchedHints.Stored", true); - if (!optimization_guide::features::ShouldPersistHintsToDisk()) { + if (!features::ShouldPersistHintsToDisk()) { // If we aren't persisting hints to disk, there's no point in purging // hints from disk or starting a new fetch since at this point we should // just be fetching everything on page navigation and only storing @@ -818,15 +777,14 @@ base::Time HintsManager::GetLastHintsFetchAttemptTime() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - return base::Time::FromDeltaSinceWindowsEpoch( - base::Microseconds(pref_service_->GetInt64( - optimization_guide::prefs::kHintsFetcherLastFetchAttempt))); + return base::Time::FromDeltaSinceWindowsEpoch(base::Microseconds( + pref_service_->GetInt64(prefs::kHintsFetcherLastFetchAttempt))); } void HintsManager::SetLastHintsFetchAttemptTime(base::Time last_attempt_time) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); pref_service_->SetInt64( - optimization_guide::prefs::kHintsFetcherLastFetchAttempt, + prefs::kHintsFetcherLastFetchAttempt, last_attempt_time.ToDeltaSinceWindowsEpoch().InMicroseconds()); } @@ -855,7 +813,7 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // Collect hosts, stripping duplicates, but preserving the ordering. - optimization_guide::InsertionOrderedSet<std::string> target_hosts; + InsertionOrderedSet<std::string> target_hosts; for (const auto& url : target_urls) { target_hosts.insert(url.host()); } @@ -880,14 +838,12 @@ target_urls, target_hosts.set())); } -void HintsManager::OnHintLoaded( - base::OnceClosure callback, - const optimization_guide::proto::Hint* loaded_hint) const { +void HintsManager::OnHintLoaded(base::OnceClosure callback, + const proto::Hint* loaded_hint) const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // Record the result of loading a hint. This is used as a signal for testing. - LOCAL_HISTOGRAM_BOOLEAN(optimization_guide::kLoadedHintLocalHistogramString, - loaded_hint); + LOCAL_HISTOGRAM_BOOLEAN(kLoadedHintLocalHistogramString, loaded_hint); // Run the callback now that the hint is loaded. This is used as a signal by // tests. @@ -895,16 +851,14 @@ } void HintsManager::RegisterOptimizationTypes( - const std::vector<optimization_guide::proto::OptimizationType>& - optimization_types) { + const std::vector<proto::OptimizationType>& optimization_types) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); bool should_load_new_optimization_filter = false; DictionaryPrefUpdate previously_registered_opt_types( - pref_service_, - optimization_guide::prefs::kPreviouslyRegisteredOptimizationTypes); + pref_service_, prefs::kPreviouslyRegisteredOptimizationTypes); for (const auto optimization_type : optimization_types) { - if (optimization_type == optimization_guide::proto::TYPE_UNSPECIFIED) + if (optimization_type == proto::TYPE_UNSPECIFIED) continue; if (registered_optimization_types_.find(optimization_type) != @@ -913,14 +867,13 @@ } registered_optimization_types_.insert(optimization_type); - if (optimization_guide::switches::IsDebugLogsEnabled()) { + if (switches::IsDebugLogsEnabled()) { DVLOG(0) << "OptimizationGuide: Registered new OptimizationType: " - << optimization_guide::proto::OptimizationType_Name( - optimization_type); + << proto::OptimizationType_Name(optimization_type); } absl::optional<double> value = previously_registered_opt_types->FindBoolKey( - optimization_guide::proto::OptimizationType_Name(optimization_type)); + proto::OptimizationType_Name(optimization_type)); if (!value) { if (!is_off_the_record_ && !ShouldIgnoreNewlyRegisteredOptimizationType(optimization_type) && @@ -929,8 +882,7 @@ should_clear_hints_for_new_type_ = true; } previously_registered_opt_types->SetBoolKey( - optimization_guide::proto::OptimizationType_Name(optimization_type), - true); + proto::OptimizationType_Name(optimization_type), true); } if (!should_load_new_optimization_filter) { @@ -949,9 +901,9 @@ } if (should_load_new_optimization_filter) { - if (optimization_guide::switches::IsHintComponentProcessingDisabled()) { - std::unique_ptr<optimization_guide::proto::Configuration> manual_config = - optimization_guide::switches::ParseComponentConfigFromCommandLine(); + if (switches::IsHintComponentProcessingDisabled()) { + std::unique_ptr<proto::Configuration> manual_config = + switches::ParseComponentConfigFromCommandLine(); if (manual_config->optimization_allowlists_size() > 0 || manual_config->optimization_blocklists_size() > 0) { ProcessOptimizationFilters(manual_config->optimization_allowlists(), @@ -967,14 +919,14 @@ } bool HintsManager::HasLoadedOptimizationAllowlist( - optimization_guide::proto::OptimizationType optimization_type) { + proto::OptimizationType optimization_type) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); return allowlist_optimization_filters_.find(optimization_type) != allowlist_optimization_filters_.end(); } bool HintsManager::HasLoadedOptimizationBlocklist( - optimization_guide::proto::OptimizationType optimization_type) { + proto::OptimizationType optimization_type) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); return blocklist_optimization_filters_.find(optimization_type) != blocklist_optimization_filters_.end(); @@ -982,24 +934,23 @@ void HintsManager::CanApplyOptimizationAsync( const GURL& navigation_url, - optimization_guide::proto::OptimizationType optimization_type, - optimization_guide::OptimizationGuideDecisionCallback callback) { + proto::OptimizationType optimization_type, + OptimizationGuideDecisionCallback callback) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - optimization_guide::OptimizationMetadata metadata; - optimization_guide::OptimizationTypeDecision type_decision = + OptimizationMetadata metadata; + OptimizationTypeDecision type_decision = CanApplyOptimization(navigation_url, optimization_type, &metadata); - optimization_guide::OptimizationGuideDecision decision = + OptimizationGuideDecision decision = GetOptimizationGuideDecisionFromOptimizationTypeDecision(type_decision); // It's possible that a hint that applies to |navigation_url| will come in // later, so only run the callback if we are sure we can apply the decision. - if (decision == optimization_guide::OptimizationGuideDecision::kTrue || + if (decision == OptimizationGuideDecision::kTrue || HasAllInformationForDecisionAvailable(navigation_url, optimization_type)) { base::UmaHistogramEnumeration( "OptimizationGuide.ApplyDecisionAsync." + - optimization_guide::GetStringNameForOptimizationType( - optimization_type), + GetStringNameForOptimizationType(optimization_type), type_decision); std::move(callback).Run(decision, metadata); return; @@ -1009,10 +960,10 @@ std::move(callback)); } -optimization_guide::OptimizationTypeDecision HintsManager::CanApplyOptimization( +OptimizationTypeDecision HintsManager::CanApplyOptimization( const GURL& navigation_url, - optimization_guide::proto::OptimizationType optimization_type, - optimization_guide::OptimizationMetadata* optimization_metadata) { + proto::OptimizationType optimization_type, + OptimizationMetadata* optimization_metadata) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); ScopedCanApplyOptimizationLogger scoped_logger(optimization_type, @@ -1029,17 +980,15 @@ // just return. if (registered_optimization_types_.find(optimization_type) == registered_optimization_types_.end()) { - scoped_logger.set_type_decision( - optimization_guide::OptimizationTypeDecision::kNoHintAvailable); - return optimization_guide::OptimizationTypeDecision::kNoHintAvailable; + scoped_logger.set_type_decision(OptimizationTypeDecision::kNoHintAvailable); + return OptimizationTypeDecision::kNoHintAvailable; } // If the URL doesn't have a host, we cannot query the hint for it, so just // return early. if (!navigation_url.has_host()) { - scoped_logger.set_type_decision( - optimization_guide::OptimizationTypeDecision::kNoHintAvailable); - return optimization_guide::OptimizationTypeDecision::kNoHintAvailable; + scoped_logger.set_type_decision(OptimizationTypeDecision::kNoHintAvailable); + return OptimizationTypeDecision::kNoHintAvailable; } const auto& host = navigation_url.host(); @@ -1053,10 +1002,8 @@ const auto type_decision = allowlist_optimization_filters_[optimization_type]->Matches( navigation_url) - ? optimization_guide::OptimizationTypeDecision:: - kAllowedByOptimizationFilter - : optimization_guide::OptimizationTypeDecision:: - kNotAllowedByOptimizationFilter; + ? OptimizationTypeDecision::kAllowedByOptimizationFilter + : OptimizationTypeDecision::kNotAllowedByOptimizationFilter; scoped_logger.set_type_decision(type_decision); return type_decision; } @@ -1068,10 +1015,8 @@ const auto type_decision = blocklist_optimization_filters_[optimization_type]->Matches( navigation_url) - ? optimization_guide::OptimizationTypeDecision:: - kNotAllowedByOptimizationFilter - : optimization_guide::OptimizationTypeDecision:: - kAllowedByOptimizationFilter; + ? OptimizationTypeDecision::kNotAllowedByOptimizationFilter + : OptimizationTypeDecision::kAllowedByOptimizationFilter; scoped_logger.set_type_decision(type_decision); return type_decision; } @@ -1081,14 +1026,12 @@ if (optimization_types_with_filter_.find(optimization_type) != optimization_types_with_filter_.end()) { scoped_logger.set_type_decision( - optimization_guide::OptimizationTypeDecision:: - kHadOptimizationFilterButNotLoadedInTime); - return optimization_guide::OptimizationTypeDecision:: - kHadOptimizationFilterButNotLoadedInTime; + OptimizationTypeDecision::kHadOptimizationFilterButNotLoadedInTime); + return OptimizationTypeDecision::kHadOptimizationFilterButNotLoadedInTime; } // First, check if the optimization type is allowlisted by a URL-keyed hint. - const optimization_guide::proto::Hint* url_keyed_hint = + const proto::Hint* url_keyed_hint = hint_cache_->GetURLKeyedHint(navigation_url); if (url_keyed_hint) { DCHECK_EQ(url_keyed_hint->page_hints_size(), 1); @@ -1097,73 +1040,63 @@ url_keyed_hint->page_hints(0).allowlisted_optimizations(), optimization_type, optimization_metadata)) { scoped_logger.set_type_decision( - optimization_guide::OptimizationTypeDecision::kAllowedByHint); + OptimizationTypeDecision::kAllowedByHint); if (optimization_metadata && !optimization_metadata->empty()) scoped_logger.set_has_metadata(); - return optimization_guide::OptimizationTypeDecision::kAllowedByHint; + return OptimizationTypeDecision::kAllowedByHint; } } } // Check if we have a hint already loaded for this navigation. - const optimization_guide::proto::Hint* loaded_hint = - hint_cache_->GetHostKeyedHintIfLoaded(host); + const proto::Hint* loaded_hint = hint_cache_->GetHostKeyedHintIfLoaded(host); if (!loaded_hint) { if (hint_cache_->HasHint(host)) { // If we do not have a hint already loaded and we do not have one in the // cache, we do not know what to do with the URL so just return. // Otherwise, we do have information, but we just do not know it yet. - if (optimization_guide::features::ShouldPersistHintsToDisk()) { + if (features::ShouldPersistHintsToDisk()) { scoped_logger.set_type_decision( - optimization_guide::OptimizationTypeDecision:: - kHadHintButNotLoadedInTime); - return optimization_guide::OptimizationTypeDecision:: - kHadHintButNotLoadedInTime; + OptimizationTypeDecision::kHadHintButNotLoadedInTime); + return OptimizationTypeDecision::kHadHintButNotLoadedInTime; } else { scoped_logger.set_type_decision( - optimization_guide::OptimizationTypeDecision::kNoHintAvailable); - return optimization_guide::OptimizationTypeDecision::kNoHintAvailable; + OptimizationTypeDecision::kNoHintAvailable); + return OptimizationTypeDecision::kNoHintAvailable; } } if (IsHintBeingFetchedForNavigation(navigation_url)) { scoped_logger.set_type_decision( - optimization_guide::OptimizationTypeDecision:: - kHintFetchStartedButNotAvailableInTime); - return optimization_guide::OptimizationTypeDecision:: - kHintFetchStartedButNotAvailableInTime; + OptimizationTypeDecision::kHintFetchStartedButNotAvailableInTime); + return OptimizationTypeDecision::kHintFetchStartedButNotAvailableInTime; } - scoped_logger.set_type_decision( - optimization_guide::OptimizationTypeDecision::kNoHintAvailable); - return optimization_guide::OptimizationTypeDecision::kNoHintAvailable; + scoped_logger.set_type_decision(OptimizationTypeDecision::kNoHintAvailable); + return OptimizationTypeDecision::kNoHintAvailable; } if (IsOptimizationTypeAllowed(loaded_hint->allowlisted_optimizations(), optimization_type, optimization_metadata)) { - scoped_logger.set_type_decision( - optimization_guide::OptimizationTypeDecision::kAllowedByHint); + scoped_logger.set_type_decision(OptimizationTypeDecision::kAllowedByHint); if (optimization_metadata && !optimization_metadata->empty()) scoped_logger.set_has_metadata(); - return optimization_guide::OptimizationTypeDecision::kAllowedByHint; + return OptimizationTypeDecision::kAllowedByHint; } - const optimization_guide::proto::PageHint* matched_page_hint = - loaded_hint - ? optimization_guide::FindPageHintForURL(navigation_url, loaded_hint) - : nullptr; + const proto::PageHint* matched_page_hint = + loaded_hint ? FindPageHintForURL(navigation_url, loaded_hint) : nullptr; if (!matched_page_hint) { scoped_logger.set_type_decision( - optimization_guide::OptimizationTypeDecision::kNotAllowedByHint); - return optimization_guide::OptimizationTypeDecision::kNotAllowedByHint; + OptimizationTypeDecision::kNotAllowedByHint); + return OptimizationTypeDecision::kNotAllowedByHint; } bool is_allowed = IsOptimizationTypeAllowed(matched_page_hint->allowlisted_optimizations(), optimization_type, optimization_metadata); - const auto type_decision = - is_allowed - ? optimization_guide::OptimizationTypeDecision::kAllowedByHint - : optimization_guide::OptimizationTypeDecision::kNotAllowedByHint; + const auto type_decision = is_allowed + ? OptimizationTypeDecision::kAllowedByHint + : OptimizationTypeDecision::kNotAllowedByHint; scoped_logger.set_type_decision(type_decision); if (optimization_metadata && !optimization_metadata->empty()) scoped_logger.set_has_metadata(); @@ -1194,19 +1127,18 @@ for (auto& opt_type_and_callbacks : registered_callbacks_.at(navigation_url)) { - optimization_guide::proto::OptimizationType opt_type = - opt_type_and_callbacks.first; + proto::OptimizationType opt_type = opt_type_and_callbacks.first; for (auto& callback : opt_type_and_callbacks.second) { - optimization_guide::OptimizationMetadata metadata; - optimization_guide::OptimizationTypeDecision type_decision = + OptimizationMetadata metadata; + OptimizationTypeDecision type_decision = CanApplyOptimization(navigation_url, opt_type, &metadata); - optimization_guide::OptimizationGuideDecision decision = + OptimizationGuideDecision decision = GetOptimizationGuideDecisionFromOptimizationTypeDecision( type_decision); base::UmaHistogramEnumeration( "OptimizationGuide.ApplyDecisionAsync." + - optimization_guide::GetStringNameForOptimizationType(opt_type), + GetStringNameForOptimizationType(opt_type), type_decision); std::move(callback).Run(decision, metadata); } @@ -1233,8 +1165,8 @@ if (!HasOptimizationTypeToFetchFor()) return false; - if (!optimization_guide::IsUserPermittedToFetchFromRemoteOptimizationGuide( - is_off_the_record_, pref_service_)) { + if (!IsUserPermittedToFetchFromRemoteOptimizationGuide(is_off_the_record_, + pref_service_)) { return false; } DCHECK(!is_off_the_record_); @@ -1249,8 +1181,7 @@ LoadHintForURL(navigation_data->navigation_url(), std::move(callback)); - if (optimization_guide::switches:: - DisableFetchingHintsAtNavigationStartForTesting()) { + if (switches::DisableFetchingHintsAtNavigationStartForTesting()) { return; } @@ -1275,7 +1206,7 @@ // the logic to decide if we also require fetching hints for the host. if (IsHintBeingFetchedForNavigation(url)) { race_navigation_recorder.set_race_attempt_status( - optimization_guide::RaceNavigationFetchAttemptStatus:: + RaceNavigationFetchAttemptStatus:: kRaceNavigationFetchAlreadyInProgress); // Just set the hints fetch start to the start of the navigation, so we can @@ -1289,21 +1220,18 @@ if (!hint_cache_->HasHint(url.host())) { hosts.push_back(url.host()); race_navigation_recorder.set_race_attempt_status( - optimization_guide::RaceNavigationFetchAttemptStatus:: - kRaceNavigationFetchHost); + RaceNavigationFetchAttemptStatus::kRaceNavigationFetchHost); } if (!hint_cache_->HasURLKeyedEntryForURL(url)) { urls.push_back(url); race_navigation_recorder.set_race_attempt_status( - optimization_guide::RaceNavigationFetchAttemptStatus:: - kRaceNavigationFetchURL); + RaceNavigationFetchAttemptStatus::kRaceNavigationFetchURL); } if (hosts.empty() && urls.empty()) { race_navigation_recorder.set_race_attempt_status( - optimization_guide::RaceNavigationFetchAttemptStatus:: - kRaceNavigationFetchNotAttempted); + RaceNavigationFetchAttemptStatus::kRaceNavigationFetchNotAttempted); return; } @@ -1317,7 +1245,7 @@ bool fetch_attempted = it->second->FetchOptimizationGuideServiceHints( hosts, urls, registered_optimization_types_, - optimization_guide::proto::CONTEXT_PAGE_NAVIGATION, application_locale_, + proto::CONTEXT_PAGE_NAVIGATION, application_locale_, base::BindOnce(&HintsManager::OnPageNavigationHintsFetched, weak_ptr_factory_.GetWeakPtr(), navigation_data->GetWeakPtr(), url, @@ -1328,8 +1256,7 @@ if (!hosts.empty() && !urls.empty()) { race_navigation_recorder.set_race_attempt_status( - optimization_guide::RaceNavigationFetchAttemptStatus:: - kRaceNavigationFetchHostAndURL); + RaceNavigationFetchAttemptStatus::kRaceNavigationFetchHostAndURL); DVLOG(0) << "OptimizationGuide: Fetch hints for Navigation: "; DVLOG(0) << "OptimizationGuide: Registered Optimization Types: "; for (const auto& optimization_type : registered_optimization_types_) { @@ -1351,8 +1278,7 @@ } } else { race_navigation_recorder.set_race_attempt_status( - optimization_guide::RaceNavigationFetchAttemptStatus:: - kRaceNavigationFetchNotAttempted); + RaceNavigationFetchAttemptStatus::kRaceNavigationFetchNotAttempted); } } @@ -1375,27 +1301,25 @@ InitiateHintsFetchScheduling(); } -optimization_guide::OptimizationGuideStore* HintsManager::hint_store() { +OptimizationGuideStore* HintsManager::hint_store() { return hint_cache_->hint_store(); } -optimization_guide::HintCache* HintsManager::hint_cache() { +HintCache* HintsManager::hint_cache() { return hint_cache_.get(); } -optimization_guide::PushNotificationManager* -HintsManager::push_notification_manager() { +PushNotificationManager* HintsManager::push_notification_manager() { return push_notification_manager_.get(); } -optimization_guide::HintsFetcherFactory* -HintsManager::GetHintsFetcherFactory() { +HintsFetcherFactory* HintsManager::GetHintsFetcherFactory() { return hints_fetcher_factory_.get(); } bool HintsManager::HasAllInformationForDecisionAvailable( const GURL& navigation_url, - optimization_guide::proto::OptimizationType optimization_type) { + proto::OptimizationType optimization_type) { if (HasLoadedOptimizationAllowlist(optimization_type) || HasLoadedOptimizationBlocklist(optimization_type)) { // If we have an optimization filter for the optimization type, it is @@ -1436,27 +1360,24 @@ void HintsManager::ClearFetchedHints() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); hint_cache_->ClearFetchedHints(); - optimization_guide::HintsFetcher::ClearHostsSuccessfullyFetched( - pref_service_); + HintsFetcher::ClearHostsSuccessfullyFetched(pref_service_); } void HintsManager::ClearHostKeyedHints() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); hint_cache_->ClearHostKeyedHints(); - optimization_guide::HintsFetcher::ClearHostsSuccessfullyFetched( - pref_service_); + HintsFetcher::ClearHostsSuccessfullyFetched(pref_service_); } void HintsManager::AddHintForTesting( const GURL& url, - optimization_guide::proto::OptimizationType optimization_type, - const absl::optional<optimization_guide::OptimizationMetadata>& metadata) { - std::unique_ptr<optimization_guide::proto::Hint> hint = - std::make_unique<optimization_guide::proto::Hint>(); + proto::OptimizationType optimization_type, + const absl::optional<OptimizationMetadata>& metadata) { + std::unique_ptr<proto::Hint> hint = std::make_unique<proto::Hint>(); hint->set_key(url.spec()); - optimization_guide::proto::PageHint* page_hint = hint->add_page_hints(); + proto::PageHint* page_hint = hint->add_page_hints(); page_hint->set_page_pattern("*"); - optimization_guide::proto::Optimization* optimization = + proto::Optimization* optimization = page_hint->add_allowlisted_optimizations(); optimization->set_optimization_type(optimization_type); if (!metadata) { @@ -1484,21 +1405,21 @@ void HintsManager::RemoveFetchedEntriesByHintKeys( base::OnceClosure on_success, - optimization_guide::proto::KeyRepresentation key_representation, + proto::KeyRepresentation key_representation, const base::flat_set<std::string>& hint_keys) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // Make sure the key representation is something that we expect. switch (key_representation) { - case optimization_guide::proto::KeyRepresentation::HOST: - case optimization_guide::proto::KeyRepresentation::FULL_URL: + case proto::KeyRepresentation::HOST: + case proto::KeyRepresentation::FULL_URL: break; default: NOTREACHED(); return; } - if (key_representation == optimization_guide::proto::FULL_URL) { + if (key_representation == proto::FULL_URL) { base::flat_set<GURL> urls_to_remove; base::flat_set<std::string> hosts_to_remove; // It is possible that the hints may have upgraded from being HOST keyed to @@ -1517,8 +1438,7 @@ // Also clear the HintFetcher's host pref. for (const std::string& host : hosts_to_remove) { - optimization_guide::HintsFetcher::ClearSingleFetchedHost(pref_service_, - host); + HintsFetcher::ClearSingleFetchedHost(pref_service_, host); } hint_cache_->RemoveHintsForURLs(urls_to_remove); @@ -1528,8 +1448,7 @@ // Also clear the HintFetcher's host pref. for (const std::string& host : hint_keys) { - optimization_guide::HintsFetcher::ClearSingleFetchedHost(pref_service_, - host); + HintsFetcher::ClearSingleFetchedHost(pref_service_, host); } hint_cache_->RemoveHintsForHosts(std::move(on_success), hint_keys);
diff --git a/components/optimization_guide/core/hints_manager.h b/components/optimization_guide/core/hints_manager.h index 39f54ebb..b6b6c300 100644 --- a/components/optimization_guide/core/hints_manager.h +++ b/components/optimization_guide/core/hints_manager.h
@@ -56,13 +56,12 @@ bool is_off_the_record, const std::string& application_locale, PrefService* pref_service, - optimization_guide::OptimizationGuideStore* hint_store, - optimization_guide::TopHostProvider* top_host_provider, - optimization_guide::TabUrlProvider* tab_url_provider, + OptimizationGuideStore* hint_store, + TopHostProvider* top_host_provider, + TabUrlProvider* tab_url_provider, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, network::NetworkConnectionTracker* network_connection_tracker, - std::unique_ptr<optimization_guide::PushNotificationManager> - push_notification_manager); + std::unique_ptr<PushNotificationManager> push_notification_manager); ~HintsManager() override; @@ -73,13 +72,12 @@ void Shutdown(); // Returns the OptimizationGuideDecision from |optimization_type_decision|. - static optimization_guide::OptimizationGuideDecision + static OptimizationGuideDecision GetOptimizationGuideDecisionFromOptimizationTypeDecision( - optimization_guide::OptimizationTypeDecision optimization_type_decision); + OptimizationTypeDecision optimization_type_decision); - // optimization_guide::OptimizationHintsComponentObserver implementation: - void OnHintsComponentAvailable( - const optimization_guide::HintsComponentInfo& info) override; + // OptimizationHintsComponentObserver implementation: + void OnHintsComponentAvailable(const HintsComponentInfo& info) override; // |next_update_closure| is called the next time OnHintsComponentAvailable() // is called and the corresponding hints have been updated. @@ -88,38 +86,37 @@ // Registers the optimization types that have the potential for hints to be // called by consumers of the Optimization Guide. void RegisterOptimizationTypes( - const std::vector<optimization_guide::proto::OptimizationType>& - optimization_types); + const std::vector<proto::OptimizationType>& optimization_types); // Returns the optimization types that are registered. - base::flat_set<optimization_guide::proto::OptimizationType> - registered_optimization_types() const { + base::flat_set<proto::OptimizationType> registered_optimization_types() + const { return registered_optimization_types_; } // Returns whether there is an optimization allowlist loaded for // |optimization_type|. bool HasLoadedOptimizationAllowlist( - optimization_guide::proto::OptimizationType optimization_type); + proto::OptimizationType optimization_type); // Returns whether there is an optimization blocklist loaded for // |optimization_type|. bool HasLoadedOptimizationBlocklist( - optimization_guide::proto::OptimizationType optimization_type); + proto::OptimizationType optimization_type); // Returns the OptimizationTypeDecision based on the given parameters. // |optimization_metadata| will be populated, if applicable. - optimization_guide::OptimizationTypeDecision CanApplyOptimization( + OptimizationTypeDecision CanApplyOptimization( const GURL& navigation_url, - optimization_guide::proto::OptimizationType optimization_type, - optimization_guide::OptimizationMetadata* optimization_metadata); + proto::OptimizationType optimization_type, + OptimizationMetadata* optimization_metadata); // Invokes |callback| with the decision for |navigation_url| and // |optimization_type|, when sufficient information has been collected by // |this| to make the decision. Virtual for testing. virtual void CanApplyOptimizationAsync( const GURL& navigation_url, - optimization_guide::proto::OptimizationType optimization_type, - optimization_guide::OptimizationGuideDecisionCallback callback); + proto::OptimizationType optimization_type, + OptimizationGuideDecisionCallback callback); // Clears all fetched hints from |hint_cache_|. void ClearFetchedHints(); @@ -129,14 +126,13 @@ void ClearHostKeyedHints(); // Returns the current batch update hints fetcher. - optimization_guide::HintsFetcher* batch_update_hints_fetcher() const { + HintsFetcher* batch_update_hints_fetcher() const { return batch_update_hints_fetcher_.get(); } // Overrides |hints_fetcher_factory| for testing. void SetHintsFetcherFactoryForTesting( - std::unique_ptr<optimization_guide::HintsFetcherFactory> - hints_fetcher_factory); + std::unique_ptr<HintsFetcherFactory> hints_fetcher_factory); // Overrides |clock_| for testing. void SetClockForTesting(const base::Clock* clock); @@ -162,10 +158,10 @@ void FetchHintsForURLs(std::vector<GURL> target_urls, proto::RequestContext request_context); - // optimization_guide::PushNotificationManager::Delegate: + // PushNotificationManager::Delegate: void RemoveFetchedEntriesByHintKeys( base::OnceClosure on_success, - optimization_guide::proto::KeyRepresentation key_representation, + proto::KeyRepresentation key_representation, const base::flat_set<std::string>& hint_keys) override; void PurgeFetchedEntries(base::OnceClosure on_success) override; @@ -174,50 +170,45 @@ bool IsAllowedToFetchNavigationHints(const GURL& url); // Returns the hint cache for |this|. - optimization_guide::HintCache* hint_cache(); + HintCache* hint_cache(); // Returns the persistent store for |this|. - optimization_guide::OptimizationGuideStore* hint_store(); + OptimizationGuideStore* hint_store(); // Returns the push notification manager for |this|. May be nullptr; - optimization_guide::PushNotificationManager* push_notification_manager(); + PushNotificationManager* push_notification_manager(); // Add hints to the cache with the provided metadata. For testing only. - void AddHintForTesting( - const GURL& url, - optimization_guide::proto::OptimizationType optimization_type, - const absl::optional<optimization_guide::OptimizationMetadata>& metadata); + void AddHintForTesting(const GURL& url, + proto::OptimizationType optimization_type, + const absl::optional<OptimizationMetadata>& metadata); private: friend class ::OptimizationGuideTestAppInterfaceWrapper; // Processes the optimization filters contained in the hints component. void ProcessOptimizationFilters( - const google::protobuf::RepeatedPtrField< - optimization_guide::proto::OptimizationFilter>& + const google::protobuf::RepeatedPtrField<proto::OptimizationFilter>& allowlist_optimization_filters, - const google::protobuf::RepeatedPtrField< - optimization_guide::proto::OptimizationFilter>& + const google::protobuf::RepeatedPtrField<proto::OptimizationFilter>& blocklist_optimization_filters); // Process a set of optimization filters. // // |is_allowlist| will be used to ensure that the filters are either uses as // allowlists or blocklists. - void ProcessOptimizationFilterSet( - const google::protobuf::RepeatedPtrField< - optimization_guide::proto::OptimizationFilter>& filters, - bool is_allowlist); + void ProcessOptimizationFilterSet(const google::protobuf::RepeatedPtrField< + proto::OptimizationFilter>& filters, + bool is_allowlist); // Callback run after the hint cache is fully initialized. At this point, // the HintsManager is ready to process hints. void OnHintCacheInitialized(); // Updates the cache with the latest hints sent by the Component Updater. - void UpdateComponentHints( - base::OnceClosure update_closure, - std::unique_ptr<optimization_guide::StoreUpdateData> update_data, - std::unique_ptr<optimization_guide::proto::Configuration> config); + void UpdateComponentHints(base::OnceClosure update_closure, + std::unique_ptr<StoreUpdateData> update_data, + std::unique_ptr<proto::Configuration> config); // Called when the hints have been fully updated with the latest hints from // the Component Updater. This is used as a signal during tests. @@ -246,8 +237,7 @@ void OnHintsForActiveTabsFetched( const base::flat_set<std::string>& hosts_fetched, const base::flat_set<GURL>& urls_fetched, - absl::optional< - std::unique_ptr<optimization_guide::proto::GetHintsResponse>> + absl::optional<std::unique_ptr<proto::GetHintsResponse>> get_hints_response); // Called when the hints for a navigation have been fetched from the remote @@ -262,8 +252,7 @@ const absl::optional<GURL>& navigation_url, const base::flat_set<GURL>& page_navigation_urls_requested, const base::flat_set<std::string>& page_navigation_hosts_requested, - absl::optional< - std::unique_ptr<optimization_guide::proto::GetHintsResponse>> + absl::optional<std::unique_ptr<proto::GetHintsResponse>> get_hints_response); // Called when the fetched hints have been stored in |hint_cache| and are @@ -294,7 +283,7 @@ // Called when the request to load a hint has completed. void OnHintLoaded(base::OnceClosure callback, - const optimization_guide::proto::Hint* loaded_hint) const; + const proto::Hint* loaded_hint) const; // Loads the hint if available for navigation to |url|. // |callback| is run when the request has finished regardless of whether there @@ -332,13 +321,13 @@ // |navigation_url| and |optimization type}. bool HasAllInformationForDecisionAvailable( const GURL& navigation_url, - optimization_guide::proto::OptimizationType optimization_type); + proto::OptimizationType optimization_type); - optimization_guide::HintsFetcherFactory* GetHintsFetcherFactory(); + HintsFetcherFactory* GetHintsFetcherFactory(); // The information of the latest component delivered by // |optimization_guide_service_|. - absl::optional<optimization_guide::HintsComponentInfo> hints_component_info_; + absl::optional<HintsComponentInfo> hints_component_info_; // Whether the component is currently being processed. bool is_processing_component_ = false; @@ -347,32 +336,26 @@ // manager. // // Should only be read and modified on the UI thread. - base::flat_set<optimization_guide::proto::OptimizationType> - registered_optimization_types_; + base::flat_set<proto::OptimizationType> registered_optimization_types_; // The set of optimization types that the component specified by // |component_info_| has optimization filters for. - base::flat_set<optimization_guide::proto::OptimizationType> - optimization_types_with_filter_; + base::flat_set<proto::OptimizationType> optimization_types_with_filter_; // A map from optimization type to the host filter that holds the allowlist // for that type. - base::flat_map<optimization_guide::proto::OptimizationType, - std::unique_ptr<optimization_guide::OptimizationFilter>> + base::flat_map<proto::OptimizationType, std::unique_ptr<OptimizationFilter>> allowlist_optimization_filters_; // A map from optimization type to the host filter that holds the blocklist // for that type. - base::flat_map<optimization_guide::proto::OptimizationType, - std::unique_ptr<optimization_guide::OptimizationFilter>> + base::flat_map<proto::OptimizationType, std::unique_ptr<OptimizationFilter>> blocklist_optimization_filters_; // A map from URL to a map of callbacks keyed by their optimization type. - base::flat_map< - GURL, - base::flat_map< - optimization_guide::proto::OptimizationType, - std::vector<optimization_guide::OptimizationGuideDecisionCallback>>> + base::flat_map<GURL, + base::flat_map<proto::OptimizationType, + std::vector<OptimizationGuideDecisionCallback>>> registered_callbacks_; // Whether |this| was created for an off the record profile. @@ -386,29 +369,28 @@ // The hint cache that holds both hints received from the component and // fetched from the remote Optimization Guide Service. - std::unique_ptr<optimization_guide::HintCache> hint_cache_; + std::unique_ptr<HintCache> hint_cache_; // The fetcher that handles making requests for hints for multiple hosts from // the remote Optimization Guide Service. - std::unique_ptr<optimization_guide::HintsFetcher> batch_update_hints_fetcher_; + std::unique_ptr<HintsFetcher> batch_update_hints_fetcher_; // A cache keyed by navigation URL to the fetcher making a request for a hint // for that URL and/or host to the remote Optimization Guide Service that // keeps track of when an entry has been placed in the cache. - base::LRUCache<GURL, std::unique_ptr<optimization_guide::HintsFetcher>> + base::LRUCache<GURL, std::unique_ptr<HintsFetcher>> page_navigation_hints_fetchers_; // The factory used to create hints fetchers. It is mostly used to create // new fetchers for use under the page navigation context, but will also be // used to create the initial fetcher for the batch update context. - std::unique_ptr<optimization_guide::HintsFetcherFactory> - hints_fetcher_factory_; + std::unique_ptr<HintsFetcherFactory> hints_fetcher_factory_; // The top host provider that can be queried. Not owned. - raw_ptr<optimization_guide::TopHostProvider> top_host_provider_ = nullptr; + raw_ptr<TopHostProvider> top_host_provider_ = nullptr; // The tab URL provider that can be queried. Not owned. - raw_ptr<optimization_guide::TabUrlProvider> tab_url_provider_ = nullptr; + raw_ptr<TabUrlProvider> tab_url_provider_ = nullptr; // The timer used to schedule fetching hints from the remote Optimization // Guide Service. @@ -416,8 +398,7 @@ // The class that handles push notification processing and informs |this| of // what to do through the implemented Delegate above. - std::unique_ptr<optimization_guide::PushNotificationManager> - push_notification_manager_; + std::unique_ptr<PushNotificationManager> push_notification_manager_; // The clock used to schedule fetching from the remote Optimization Guide // Service.
diff --git a/components/optimization_guide/core/hints_manager_unittest.cc b/components/optimization_guide/core/hints_manager_unittest.cc index 51a3106..d4f124c 100644 --- a/components/optimization_guide/core/hints_manager_unittest.cc +++ b/components/optimization_guide/core/hints_manager_unittest.cc
@@ -54,69 +54,63 @@ const int kDefaultHostBloomFilterNumHashFunctions = 7; const int kDefaultHostBloomFilterNumBits = 511; -void PopulateBloomFilterWithDefaultHost( - optimization_guide::BloomFilter* bloom_filter) { +void PopulateBloomFilterWithDefaultHost(BloomFilter* bloom_filter) { bloom_filter->Add("host.com"); } -void AddBloomFilterToConfig( - optimization_guide::proto::OptimizationType optimization_type, - const optimization_guide::BloomFilter& bloom_filter, - int num_hash_functions, - int num_bits, - bool is_allowlist, - optimization_guide::proto::Configuration* config) { +void AddBloomFilterToConfig(proto::OptimizationType optimization_type, + const BloomFilter& bloom_filter, + int num_hash_functions, + int num_bits, + bool is_allowlist, + proto::Configuration* config) { std::string bloom_filter_data( reinterpret_cast<const char*>(&bloom_filter.bytes()[0]), bloom_filter.bytes().size()); - optimization_guide::proto::OptimizationFilter* of_proto = + proto::OptimizationFilter* of_proto = is_allowlist ? config->add_optimization_allowlists() : config->add_optimization_blocklists(); of_proto->set_optimization_type(optimization_type); - std::unique_ptr<optimization_guide::proto::BloomFilter> bloom_filter_proto = - std::make_unique<optimization_guide::proto::BloomFilter>(); + std::unique_ptr<proto::BloomFilter> bloom_filter_proto = + std::make_unique<proto::BloomFilter>(); bloom_filter_proto->set_num_hash_functions(num_hash_functions); bloom_filter_proto->set_num_bits(num_bits); bloom_filter_proto->set_data(bloom_filter_data); of_proto->set_allocated_bloom_filter(bloom_filter_proto.release()); } -std::unique_ptr<optimization_guide::proto::GetHintsResponse> BuildHintsResponse( +std::unique_ptr<proto::GetHintsResponse> BuildHintsResponse( const std::vector<std::string>& hosts, const std::vector<std::string>& urls) { - std::unique_ptr<optimization_guide::proto::GetHintsResponse> - get_hints_response = - std::make_unique<optimization_guide::proto::GetHintsResponse>(); + std::unique_ptr<proto::GetHintsResponse> get_hints_response = + std::make_unique<proto::GetHintsResponse>(); for (const auto& host : hosts) { - optimization_guide::proto::Hint* hint = get_hints_response->add_hints(); - hint->set_key_representation(optimization_guide::proto::HOST); + proto::Hint* hint = get_hints_response->add_hints(); + hint->set_key_representation(proto::HOST); hint->set_key(host); - optimization_guide::proto::PageHint* page_hint = hint->add_page_hints(); + proto::PageHint* page_hint = hint->add_page_hints(); page_hint->set_page_pattern("page pattern"); - optimization_guide::proto::Optimization* opt = - page_hint->add_allowlisted_optimizations(); - opt->set_optimization_type(optimization_guide::proto::DEFER_ALL_SCRIPT); + proto::Optimization* opt = page_hint->add_allowlisted_optimizations(); + opt->set_optimization_type(proto::DEFER_ALL_SCRIPT); } for (const auto& url : urls) { - optimization_guide::proto::Hint* hint = get_hints_response->add_hints(); - hint->set_key_representation(optimization_guide::proto::FULL_URL); + proto::Hint* hint = get_hints_response->add_hints(); + hint->set_key_representation(proto::FULL_URL); hint->set_key(url); hint->mutable_max_cache_duration()->set_seconds(60 * 60); - optimization_guide::proto::PageHint* page_hint = hint->add_page_hints(); + proto::PageHint* page_hint = hint->add_page_hints(); page_hint->set_page_pattern(url); - optimization_guide::proto::Optimization* opt = - page_hint->add_allowlisted_optimizations(); - opt->set_optimization_type( - optimization_guide::proto::COMPRESS_PUBLIC_IMAGES); + proto::Optimization* opt = page_hint->add_allowlisted_optimizations(); + opt->set_optimization_type(proto::COMPRESS_PUBLIC_IMAGES); opt->mutable_public_image_metadata()->add_url("someurl"); } return get_hints_response; } void RunHintsFetchedCallbackWithResponse( - optimization_guide::HintsFetchedCallback hints_fetched_callback, - std::unique_ptr<optimization_guide::proto::GetHintsResponse> response) { + HintsFetchedCallback hints_fetched_callback, + std::unique_ptr<proto::GetHintsResponse> response) { std::move(hints_fetched_callback).Run(std::move(response)); } @@ -137,14 +131,14 @@ params["defer_startup_active_tabs_hints_fetch"] = is_enabled ? "true" : "false"; scoped_feature_list->InitAndEnableFeatureWithParameters( - optimization_guide::features::kOptimizationHints, params); + features::kOptimizationHints, params); return scoped_feature_list; } } // namespace // A mock class implementation of TopHostProvider. -class FakeTopHostProvider : public optimization_guide::TopHostProvider { +class FakeTopHostProvider : public TopHostProvider { public: explicit FakeTopHostProvider(const std::vector<std::string>& top_hosts) : top_hosts_(top_hosts) {} @@ -163,7 +157,7 @@ }; // A mock class implementation of TabUrlProvider. -class FakeTabUrlProvider : public optimization_guide::TabUrlProvider { +class FakeTabUrlProvider : public TabUrlProvider { public: const std::vector<GURL> GetUrlsOfActiveTabs( const base::TimeDelta& duration_since_last_shown) override { @@ -190,7 +184,7 @@ // A mock class implementation of HintsFetcher. It will iterate through the // provided fetch states each time it is called. If it reaches the end of the // loop, it will just continue using the last fetch state. -class TestHintsFetcher : public optimization_guide::HintsFetcher { +class TestHintsFetcher : public HintsFetcher { public: TestHintsFetcher( scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, @@ -209,12 +203,10 @@ bool FetchOptimizationGuideServiceHints( const std::vector<std::string>& hosts, const std::vector<GURL>& urls, - const base::flat_set<optimization_guide::proto::OptimizationType>& - optimization_types, - optimization_guide::proto::RequestContext request_context, + const base::flat_set<proto::OptimizationType>& optimization_types, + proto::RequestContext request_context, const std::string& locale, - optimization_guide::HintsFetchedCallback hints_fetched_callback) - override { + HintsFetchedCallback hints_fetched_callback) override { HintsFetcherEndState fetch_state = num_fetches_requested_ < static_cast<int>(fetch_states_.size()) ? fetch_states_[num_fetches_requested_] @@ -268,7 +260,7 @@ // A mock class of HintsFetcherFactory that returns instances of // TestHintsFetchers with the provided fetch state. -class TestHintsFetcherFactory : public optimization_guide::HintsFetcherFactory { +class TestHintsFetcherFactory : public HintsFetcherFactory { public: TestHintsFetcherFactory( scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, @@ -282,7 +274,7 @@ network_connection_tracker), fetch_states_(fetch_states) {} - std::unique_ptr<optimization_guide::HintsFetcher> BuildInstance() override { + std::unique_ptr<HintsFetcher> BuildInstance() override { return std::make_unique<TestHintsFetcher>( url_loader_factory_, optimization_guide_service_url_, pref_service_, network_connection_tracker_, fetch_states_); @@ -292,12 +284,11 @@ std::vector<HintsFetcherEndState> fetch_states_; }; -class HintsManagerTest - : public optimization_guide::ProtoDatabaseProviderTestBase { +class HintsManagerTest : public ProtoDatabaseProviderTestBase { public: HintsManagerTest() { scoped_feature_list_.InitAndEnableFeatureWithParameters( - optimization_guide::features::kOptimizationHints, + features::kOptimizationHints, GetOptimizationHintsDefaultFeatureParams()); } ~HintsManagerTest() override = default; @@ -306,23 +297,22 @@ HintsManagerTest& operator=(const HintsManagerTest&) = delete; void SetUp() override { - optimization_guide::ProtoDatabaseProviderTestBase::SetUp(); + ProtoDatabaseProviderTestBase::SetUp(); CreateHintsManager(/*top_host_provider=*/nullptr); } void TearDown() override { ResetHintsManager(); - optimization_guide::ProtoDatabaseProviderTestBase::TearDown(); + ProtoDatabaseProviderTestBase::TearDown(); } - void CreateHintsManager( - optimization_guide::TopHostProvider* top_host_provider) { + void CreateHintsManager(TopHostProvider* top_host_provider) { if (hints_manager_) ResetHintsManager(); pref_service_ = std::make_unique<sync_preferences::TestingPrefServiceSyncable>(); - optimization_guide::prefs::RegisterProfilePrefs(pref_service_->registry()); + prefs::RegisterProfilePrefs(pref_service_->registry()); pref_service_->registry()->RegisterBooleanPref( data_reduction_proxy::prefs::kDataSaverEnabled, false); unified_consent::UnifiedConsentService::RegisterPrefs( @@ -332,7 +322,7 @@ base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>( &test_url_loader_factory_); - hint_store_ = std::make_unique<optimization_guide::OptimizationGuideStore>( + hint_store_ = std::make_unique<OptimizationGuideStore>( db_provider_.get(), temp_dir(), task_environment_.GetMainThreadTaskRunner()); @@ -361,7 +351,7 @@ } void ProcessInvalidHintsComponentInfo(const std::string& version) { - optimization_guide::HintsComponentInfo info( + HintsComponentInfo info( base::Version(version), temp_dir().Append(FILE_PATH_LITERAL("notaconfigfile"))); @@ -372,7 +362,7 @@ } void ProcessHintsComponentInfoWithBadConfig(const std::string& version) { - optimization_guide::HintsComponentInfo info( + HintsComponentInfo info( base::Version(version), temp_dir().Append(FILE_PATH_LITERAL("badconfig.pb"))); ASSERT_EQ(7, base::WriteFile(info.path, "garbage", 7)); @@ -381,10 +371,10 @@ RunUntilIdle(); } - void ProcessHints(const optimization_guide::proto::Configuration& config, + void ProcessHints(const proto::Configuration& config, const std::string& version, bool should_wait = true) { - optimization_guide::HintsComponentInfo info( + HintsComponentInfo info( base::Version(version), temp_dir().Append(FILE_PATH_LITERAL("somefile.pb"))); ASSERT_NO_FATAL_FAILURE(WriteConfigToFile(config, info.path)); @@ -399,30 +389,28 @@ void InitializeWithDefaultConfig(const std::string& version, bool should_wait = true) { - optimization_guide::proto::Configuration config; - optimization_guide::proto::Hint* hint1 = config.add_hints(); + proto::Configuration config; + proto::Hint* hint1 = config.add_hints(); hint1->set_key("somedomain.org"); - hint1->set_key_representation(optimization_guide::proto::HOST); + hint1->set_key_representation(proto::HOST); hint1->set_version("someversion"); - optimization_guide::proto::PageHint* page_hint1 = hint1->add_page_hints(); + proto::PageHint* page_hint1 = hint1->add_page_hints(); page_hint1->set_page_pattern("/news/"); - optimization_guide::proto::Optimization* default_opt = + proto::Optimization* default_opt = page_hint1->add_allowlisted_optimizations(); - default_opt->set_optimization_type(optimization_guide::proto::NOSCRIPT); + default_opt->set_optimization_type(proto::NOSCRIPT); // Add another hint so somedomain.org hint is not in-memory initially. - optimization_guide::proto::Hint* hint2 = config.add_hints(); + proto::Hint* hint2 = config.add_hints(); hint2->set_key("somedomain2.org"); - hint2->set_key_representation(optimization_guide::proto::HOST); + hint2->set_key_representation(proto::HOST); hint2->set_version("someversion"); - optimization_guide::proto::Optimization* opt = - hint2->add_allowlisted_optimizations(); - opt->set_optimization_type(optimization_guide::proto::NOSCRIPT); + proto::Optimization* opt = hint2->add_allowlisted_optimizations(); + opt->set_optimization_type(proto::NOSCRIPT); ProcessHints(config, version, should_wait); } - std::unique_ptr<optimization_guide::HintsFetcherFactory> - BuildTestHintsFetcherFactory( + std::unique_ptr<HintsFetcherFactory> BuildTestHintsFetcherFactory( const std::vector<HintsFetcherEndState>& fetch_states) { return std::make_unique<TestHintsFetcherFactory>( url_loader_factory_, GURL("https://hintsserver.com"), pref_service(), @@ -438,8 +426,7 @@ // |optimization_types|. std::unique_ptr<OptimizationGuideNavigationData> CreateTestNavigationData( const GURL& url, - const std::vector<optimization_guide::proto::OptimizationType>& - optimization_types) { + const std::vector<proto::OptimizationType>& optimization_types) { auto navigation_data = std::make_unique<OptimizationGuideNavigationData>( /*navigation_id=*/1, /*navigation_start*/ base::TimeTicks::Now()); navigation_data->set_navigation_url(url); @@ -497,7 +484,7 @@ } private: - void WriteConfigToFile(const optimization_guide::proto::Configuration& config, + void WriteConfigToFile(const proto::Configuration& config, const base::FilePath& filePath) { std::string serialized_config; ASSERT_TRUE(config.SerializeToString(&serialized_config)); @@ -509,7 +496,7 @@ base::test::TaskEnvironment task_environment_{ base::test::TaskEnvironment::TimeSource::MOCK_TIME}; base::test::ScopedFeatureList scoped_feature_list_; - std::unique_ptr<optimization_guide::OptimizationGuideStore> hint_store_; + std::unique_ptr<OptimizationGuideStore> hint_store_; std::unique_ptr<FakeTabUrlProvider> tab_url_provider_; std::unique_ptr<HintsManager> hints_manager_; std::unique_ptr<sync_preferences::TestingPrefServiceSyncable> pref_service_; @@ -520,24 +507,24 @@ TEST_F(HintsManagerTest, ProcessHintsWithValidCommandLineOverride) { base::HistogramTester histogram_tester; - optimization_guide::proto::Configuration config; - optimization_guide::proto::Hint* hint = config.add_hints(); + proto::Configuration config; + proto::Hint* hint = config.add_hints(); hint->set_key("somedomain.org"); - hint->set_key_representation(optimization_guide::proto::HOST); - optimization_guide::proto::PageHint* page_hint = hint->add_page_hints(); + hint->set_key_representation(proto::HOST); + proto::PageHint* page_hint = hint->add_page_hints(); page_hint->set_page_pattern("noscript_default_2g"); - optimization_guide::proto::Optimization* optimization = + proto::Optimization* optimization = page_hint->add_allowlisted_optimizations(); - optimization->set_optimization_type(optimization_guide::proto::NOSCRIPT); - optimization_guide::BloomFilter bloom_filter( - kDefaultHostBloomFilterNumHashFunctions, kDefaultHostBloomFilterNumBits); + optimization->set_optimization_type(proto::NOSCRIPT); + BloomFilter bloom_filter(kDefaultHostBloomFilterNumHashFunctions, + kDefaultHostBloomFilterNumBits); PopulateBloomFilterWithDefaultHost(&bloom_filter); - AddBloomFilterToConfig(optimization_guide::proto::LITE_PAGE_REDIRECT, - bloom_filter, kDefaultHostBloomFilterNumHashFunctions, + AddBloomFilterToConfig(proto::LITE_PAGE_REDIRECT, bloom_filter, + kDefaultHostBloomFilterNumHashFunctions, kDefaultHostBloomFilterNumBits, /*is_allowlist=*/false, &config); - AddBloomFilterToConfig(optimization_guide::proto::PERFORMANCE_HINTS, - bloom_filter, kDefaultHostBloomFilterNumHashFunctions, + AddBloomFilterToConfig(proto::PERFORMANCE_HINTS, bloom_filter, + kDefaultHostBloomFilterNumHashFunctions, kDefaultHostBloomFilterNumBits, /*is_allowlist=*/true, &config); @@ -546,16 +533,14 @@ base::Base64Encode(encoded_config, &encoded_config); base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( - optimization_guide::switches::kHintsProtoOverride, encoded_config); + switches::kHintsProtoOverride, encoded_config); CreateHintsManager(/*top_host_provider=*/nullptr); - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::LITE_PAGE_REDIRECT}); + hints_manager()->RegisterOptimizationTypes({proto::LITE_PAGE_REDIRECT}); // The below histogram should not be recorded since hints weren't coming // directly from the component. - histogram_tester.ExpectUniqueSample( - "OptimizationGuide.ProcessHintsResult", - optimization_guide::ProcessHintsComponentResult::kSuccess, 1); + histogram_tester.ExpectUniqueSample("OptimizationGuide.ProcessHintsResult", + ProcessHintsComponentResult::kSuccess, 1); // However, we still expect the local histogram for the hints being updated to // be recorded. histogram_tester.ExpectUniqueSample( @@ -567,24 +552,23 @@ RunUntilIdle(); EXPECT_TRUE(hints_manager()->HasLoadedOptimizationBlocklist( - optimization_guide::proto::LITE_PAGE_REDIRECT)); + proto::LITE_PAGE_REDIRECT)); EXPECT_FALSE(hints_manager()->HasLoadedOptimizationAllowlist( - optimization_guide::proto::PERFORMANCE_HINTS)); + proto::PERFORMANCE_HINTS)); // Now register a new type with an allowlist that has not yet been loaded. - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::PERFORMANCE_HINTS}); + hints_manager()->RegisterOptimizationTypes({proto::PERFORMANCE_HINTS}); RunUntilIdle(); EXPECT_TRUE(hints_manager()->HasLoadedOptimizationAllowlist( - optimization_guide::proto::PERFORMANCE_HINTS)); + proto::PERFORMANCE_HINTS)); } TEST_F(HintsManagerTest, ProcessHintsWithInvalidCommandLineOverride) { base::HistogramTester histogram_tester; base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( - optimization_guide::switches::kHintsProtoOverride, "this-is-not-a-proto"); + switches::kHintsProtoOverride, "this-is-not-a-proto"); CreateHintsManager(/*top_host_provider=*/nullptr); // The below histogram should not be recorded since hints weren't coming @@ -597,15 +581,15 @@ TEST_F(HintsManagerTest, ProcessHintsWithCommandLineOverrideShouldNotBeOverriddenByNewComponent) { - optimization_guide::proto::Configuration config; - optimization_guide::proto::Hint* hint = config.add_hints(); + proto::Configuration config; + proto::Hint* hint = config.add_hints(); hint->set_key("somedomain.org"); - hint->set_key_representation(optimization_guide::proto::HOST); - optimization_guide::proto::PageHint* page_hint = hint->add_page_hints(); + hint->set_key_representation(proto::HOST); + proto::PageHint* page_hint = hint->add_page_hints(); page_hint->set_page_pattern("noscript_default_2g"); - optimization_guide::proto::Optimization* optimization = + proto::Optimization* optimization = page_hint->add_allowlisted_optimizations(); - optimization->set_optimization_type(optimization_guide::proto::NOSCRIPT); + optimization->set_optimization_type(proto::NOSCRIPT); std::string encoded_config; config.SerializeToString(&encoded_config); @@ -614,11 +598,11 @@ { base::HistogramTester histogram_tester; base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( - optimization_guide::switches::kHintsProtoOverride, encoded_config); + switches::kHintsProtoOverride, encoded_config); CreateHintsManager(/*top_host_provider=*/nullptr); - histogram_tester.ExpectUniqueSample( - "OptimizationGuide.ProcessHintsResult", - optimization_guide::ProcessHintsComponentResult::kSuccess, 1); + histogram_tester.ExpectUniqueSample("OptimizationGuide.ProcessHintsResult", + ProcessHintsComponentResult::kSuccess, + 1); histogram_tester.ExpectUniqueSample( "OptimizationGuide.UpdateComponentHints.Result", true, 1); } @@ -637,34 +621,33 @@ } TEST_F(HintsManagerTest, ParseTwoConfigVersions) { - optimization_guide::proto::Configuration config; - optimization_guide::proto::Hint* hint1 = config.add_hints(); + proto::Configuration config; + proto::Hint* hint1 = config.add_hints(); hint1->set_key("somedomain.org"); - hint1->set_key_representation(optimization_guide::proto::HOST); + hint1->set_key_representation(proto::HOST); hint1->set_version("someversion"); - optimization_guide::proto::PageHint* page_hint1 = hint1->add_page_hints(); + proto::PageHint* page_hint1 = hint1->add_page_hints(); page_hint1->set_page_pattern("/news/"); - optimization_guide::proto::Optimization* optimization1 = + proto::Optimization* optimization1 = page_hint1->add_allowlisted_optimizations(); - optimization1->set_optimization_type( - optimization_guide::proto::RESOURCE_LOADING); + optimization1->set_optimization_type(proto::RESOURCE_LOADING); // Test the first time parsing the config. { base::HistogramTester histogram_tester; InitializeWithDefaultConfig("1.0.0.0"); - histogram_tester.ExpectUniqueSample( - "OptimizationGuide.ProcessHintsResult", - optimization_guide::ProcessHintsComponentResult::kSuccess, 1); + histogram_tester.ExpectUniqueSample("OptimizationGuide.ProcessHintsResult", + ProcessHintsComponentResult::kSuccess, + 1); } // Test the second time parsing the config. This should also update the hints. { base::HistogramTester histogram_tester; InitializeWithDefaultConfig("2.0.0.0"); - histogram_tester.ExpectUniqueSample( - "OptimizationGuide.ProcessHintsResult", - optimization_guide::ProcessHintsComponentResult::kSuccess, 1); + histogram_tester.ExpectUniqueSample("OptimizationGuide.ProcessHintsResult", + ProcessHintsComponentResult::kSuccess, + 1); } } @@ -673,9 +656,9 @@ { base::HistogramTester histogram_tester; InitializeWithDefaultConfig("1.0.0.0"); - histogram_tester.ExpectUniqueSample( - "OptimizationGuide.ProcessHintsResult", - optimization_guide::ProcessHintsComponentResult::kSuccess, 1); + histogram_tester.ExpectUniqueSample("OptimizationGuide.ProcessHintsResult", + ProcessHintsComponentResult::kSuccess, + 1); } { @@ -685,9 +668,7 @@ // for the hints to not be updated. histogram_tester.ExpectUniqueSample( "OptimizationGuide.ProcessHintsResult", - optimization_guide::ProcessHintsComponentResult:: - kFailedInvalidConfiguration, - 1); + ProcessHintsComponentResult::kFailedInvalidConfiguration, 1); } } @@ -700,9 +681,7 @@ "OptimizationGuide.ProcessingComponentAtShutdown", true, 1); EXPECT_TRUE( - pref_service() - ->GetString(optimization_guide::prefs::kPendingHintsProcessingVersion) - .empty()); + pref_service()->GetString(prefs::kPendingHintsProcessingVersion).empty()); } TEST_F(HintsManagerTest, ParseOlderConfigVersions) { @@ -710,9 +689,9 @@ { base::HistogramTester histogram_tester; InitializeWithDefaultConfig("10.0.0.0"); - histogram_tester.ExpectUniqueSample( - "OptimizationGuide.ProcessHintsResult", - optimization_guide::ProcessHintsComponentResult::kSuccess, 1); + histogram_tester.ExpectUniqueSample("OptimizationGuide.ProcessHintsResult", + ProcessHintsComponentResult::kSuccess, + 1); } // Test the second time parsing the config. This will be treated by the cache @@ -724,9 +703,7 @@ // for the hints to not be updated. histogram_tester.ExpectUniqueSample( "OptimizationGuide.ProcessHintsResult", - optimization_guide::ProcessHintsComponentResult:: - kSkippedProcessingHints, - 1); + ProcessHintsComponentResult::kSkippedProcessingHints, 1); } } @@ -737,9 +714,9 @@ { base::HistogramTester histogram_tester; InitializeWithDefaultConfig(version); - histogram_tester.ExpectUniqueSample( - "OptimizationGuide.ProcessHintsResult", - optimization_guide::ProcessHintsComponentResult::kSuccess, 1); + histogram_tester.ExpectUniqueSample("OptimizationGuide.ProcessHintsResult", + ProcessHintsComponentResult::kSuccess, + 1); } // Test the second time parsing the config. This will be treated by the cache @@ -749,9 +726,7 @@ InitializeWithDefaultConfig(version); histogram_tester.ExpectUniqueSample( "OptimizationGuide.ProcessHintsResult", - optimization_guide::ProcessHintsComponentResult:: - kSkippedProcessingHints, - 1); + ProcessHintsComponentResult::kSkippedProcessingHints, 1); } } @@ -760,13 +735,12 @@ ProcessInvalidHintsComponentInfo("1.0.0.0"); histogram_tester.ExpectUniqueSample( "OptimizationGuide.ProcessHintsResult", - optimization_guide::ProcessHintsComponentResult::kFailedReadingFile, 1); + ProcessHintsComponentResult::kFailedReadingFile, 1); } TEST_F(HintsManagerTest, ProcessHintsWithExistingPref) { // Write hints processing pref for version 2.0.0. - pref_service()->SetString( - optimization_guide::prefs::kPendingHintsProcessingVersion, "2.0.0"); + pref_service()->SetString(prefs::kPendingHintsProcessingVersion, "2.0.0"); // Verify config not processed for same version (2.0.0) and pref not cleared. { @@ -774,36 +748,29 @@ InitializeWithDefaultConfig("2.0.0"); histogram_tester.ExpectUniqueSample( "OptimizationGuide.ProcessHintsResult", - optimization_guide::ProcessHintsComponentResult:: - kFailedFinishProcessing, - 1); - EXPECT_FALSE( - pref_service() - ->GetString( - optimization_guide::prefs::kPendingHintsProcessingVersion) - .empty()); + ProcessHintsComponentResult::kFailedFinishProcessing, 1); + EXPECT_FALSE(pref_service() + ->GetString(prefs::kPendingHintsProcessingVersion) + .empty()); } // Now verify config is processed for different version and pref cleared. { base::HistogramTester histogram_tester; InitializeWithDefaultConfig("3.0.0"); - EXPECT_TRUE( - pref_service() - ->GetString( - optimization_guide::prefs::kPendingHintsProcessingVersion) - .empty()); - histogram_tester.ExpectUniqueSample( - "OptimizationGuide.ProcessHintsResult", - optimization_guide::ProcessHintsComponentResult::kSuccess, 1); + EXPECT_TRUE(pref_service() + ->GetString(prefs::kPendingHintsProcessingVersion) + .empty()); + histogram_tester.ExpectUniqueSample("OptimizationGuide.ProcessHintsResult", + ProcessHintsComponentResult::kSuccess, + 1); } } TEST_F(HintsManagerTest, ProcessHintsWithExistingPrefDoesNotClearOrCountAsMidProcessing) { // Write hints processing pref for version 2.0.0. - pref_service()->SetString( - optimization_guide::prefs::kPendingHintsProcessingVersion, "2.0.0"); + pref_service()->SetString(prefs::kPendingHintsProcessingVersion, "2.0.0"); // Verify component for same version counts as "failed". base::HistogramTester histogram_tester; @@ -812,38 +779,31 @@ histogram_tester.ExpectUniqueSample( "OptimizationGuide.ProcessHintsResult", - optimization_guide::ProcessHintsComponentResult::kFailedFinishProcessing, - 1); + ProcessHintsComponentResult::kFailedFinishProcessing, 1); // Verify that pref still not cleared at shutdown and was not counted as // mid-processing. histogram_tester.ExpectUniqueSample( "OptimizationGuide.ProcessingComponentAtShutdown", false, 1); EXPECT_FALSE( - pref_service() - ->GetString(optimization_guide::prefs::kPendingHintsProcessingVersion) - .empty()); + pref_service()->GetString(prefs::kPendingHintsProcessingVersion).empty()); } TEST_F(HintsManagerTest, ProcessHintsWithInvalidPref) { // Create pref file with invalid version. - pref_service()->SetString( - optimization_guide::prefs::kPendingHintsProcessingVersion, "bad-2.0.0"); + pref_service()->SetString(prefs::kPendingHintsProcessingVersion, "bad-2.0.0"); // Verify config not processed for existing pref with bad value but // that the pref is cleared. { base::HistogramTester histogram_tester; InitializeWithDefaultConfig("2.0.0"); - EXPECT_TRUE( - pref_service() - ->GetString( - optimization_guide::prefs::kPendingHintsProcessingVersion) - .empty()); + EXPECT_TRUE(pref_service() + ->GetString(prefs::kPendingHintsProcessingVersion) + .empty()); histogram_tester.ExpectUniqueSample( "OptimizationGuide.ProcessHintsResult", - optimization_guide::ProcessHintsComponentResult:: - kFailedPreviouslyAttemptedVersionInvalid, + ProcessHintsComponentResult::kFailedPreviouslyAttemptedVersionInvalid, 1); } @@ -851,14 +811,12 @@ { base::HistogramTester histogram_tester; InitializeWithDefaultConfig("2.0.0"); - EXPECT_TRUE( - pref_service() - ->GetString( - optimization_guide::prefs::kPendingHintsProcessingVersion) - .empty()); - histogram_tester.ExpectUniqueSample( - "OptimizationGuide.ProcessHintsResult", - optimization_guide::ProcessHintsComponentResult::kSuccess, 1); + EXPECT_TRUE(pref_service() + ->GetString(prefs::kPendingHintsProcessingVersion) + .empty()); + histogram_tester.ExpectUniqueSample("OptimizationGuide.ProcessHintsResult", + ProcessHintsComponentResult::kSuccess, + 1); } } @@ -908,20 +866,20 @@ } TEST_F(HintsManagerTest, OptimizationFiltersAreOnlyLoadedIfTypeIsRegistered) { - optimization_guide::proto::Configuration config; - optimization_guide::BloomFilter bloom_filter( - kDefaultHostBloomFilterNumHashFunctions, kDefaultHostBloomFilterNumBits); + proto::Configuration config; + BloomFilter bloom_filter(kDefaultHostBloomFilterNumHashFunctions, + kDefaultHostBloomFilterNumBits); PopulateBloomFilterWithDefaultHost(&bloom_filter); - AddBloomFilterToConfig(optimization_guide::proto::LITE_PAGE_REDIRECT, - bloom_filter, kDefaultHostBloomFilterNumHashFunctions, - kDefaultHostBloomFilterNumBits, - /*is_allowlist=*/false, &config); - AddBloomFilterToConfig(optimization_guide::proto::NOSCRIPT, bloom_filter, + AddBloomFilterToConfig(proto::LITE_PAGE_REDIRECT, bloom_filter, kDefaultHostBloomFilterNumHashFunctions, kDefaultHostBloomFilterNumBits, /*is_allowlist=*/false, &config); - AddBloomFilterToConfig(optimization_guide::proto::DEFER_ALL_SCRIPT, - bloom_filter, kDefaultHostBloomFilterNumHashFunctions, + AddBloomFilterToConfig(proto::NOSCRIPT, bloom_filter, + kDefaultHostBloomFilterNumHashFunctions, + kDefaultHostBloomFilterNumBits, + /*is_allowlist=*/false, &config); + AddBloomFilterToConfig(proto::DEFER_ALL_SCRIPT, bloom_filter, + kDefaultHostBloomFilterNumHashFunctions, kDefaultHostBloomFilterNumBits, /*is_allowlist=*/true, &config); @@ -944,27 +902,25 @@ base::RunLoop run_loop; hints_manager()->ListenForNextUpdateForTesting(run_loop.QuitClosure()); - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::LITE_PAGE_REDIRECT}); + hints_manager()->RegisterOptimizationTypes({proto::LITE_PAGE_REDIRECT}); run_loop.Run(); histogram_tester.ExpectBucketCount( "OptimizationGuide.OptimizationFilterStatus.LitePageRedirect", - optimization_guide::OptimizationFilterStatus::kFoundServerFilterConfig, - 1); + OptimizationFilterStatus::kFoundServerFilterConfig, 1); histogram_tester.ExpectBucketCount( "OptimizationGuide.OptimizationFilterStatus.LitePageRedirect", - optimization_guide::OptimizationFilterStatus::kCreatedServerFilter, 1); + OptimizationFilterStatus::kCreatedServerFilter, 1); histogram_tester.ExpectTotalCount( "OptimizationGuide.OptimizationFilterStatus.NoScript", 0); histogram_tester.ExpectTotalCount( "OptimizationGuide.OptimizationFilterStatus.DeferAllScript", 0); EXPECT_TRUE(hints_manager()->HasLoadedOptimizationBlocklist( - optimization_guide::proto::LITE_PAGE_REDIRECT)); - EXPECT_FALSE(hints_manager()->HasLoadedOptimizationBlocklist( - optimization_guide::proto::NOSCRIPT)); + proto::LITE_PAGE_REDIRECT)); + EXPECT_FALSE( + hints_manager()->HasLoadedOptimizationBlocklist(proto::NOSCRIPT)); EXPECT_FALSE(hints_manager()->HasLoadedOptimizationAllowlist( - optimization_guide::proto::DEFER_ALL_SCRIPT)); + proto::DEFER_ALL_SCRIPT)); } // Re-registering the same optimization type does not re-load the filter. @@ -973,8 +929,7 @@ base::RunLoop run_loop; hints_manager()->ListenForNextUpdateForTesting(run_loop.QuitClosure()); - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::LITE_PAGE_REDIRECT}); + hints_manager()->RegisterOptimizationTypes({proto::LITE_PAGE_REDIRECT}); run_loop.Run(); histogram_tester.ExpectTotalCount( @@ -992,8 +947,7 @@ base::RunLoop run_loop; hints_manager()->ListenForNextUpdateForTesting(run_loop.QuitClosure()); - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::PERFORMANCE_HINTS}); + hints_manager()->RegisterOptimizationTypes({proto::PERFORMANCE_HINTS}); run_loop.Run(); histogram_tester.ExpectTotalCount( @@ -1012,160 +966,143 @@ base::RunLoop run_loop; hints_manager()->ListenForNextUpdateForTesting(run_loop.QuitClosure()); hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::NOSCRIPT, - optimization_guide::proto::DEFER_ALL_SCRIPT}); + {proto::NOSCRIPT, proto::DEFER_ALL_SCRIPT}); run_loop.Run(); histogram_tester.ExpectBucketCount( "OptimizationGuide.OptimizationFilterStatus.LitePageRedirect", - optimization_guide::OptimizationFilterStatus::kFoundServerFilterConfig, - 1); + OptimizationFilterStatus::kFoundServerFilterConfig, 1); histogram_tester.ExpectBucketCount( "OptimizationGuide.OptimizationFilterStatus.LitePageRedirect", - optimization_guide::OptimizationFilterStatus::kCreatedServerFilter, 1); + OptimizationFilterStatus::kCreatedServerFilter, 1); histogram_tester.ExpectBucketCount( "OptimizationGuide.OptimizationFilterStatus.NoScript", - optimization_guide::OptimizationFilterStatus::kFoundServerFilterConfig, - 1); + OptimizationFilterStatus::kFoundServerFilterConfig, 1); histogram_tester.ExpectBucketCount( "OptimizationGuide.OptimizationFilterStatus.NoScript", - optimization_guide::OptimizationFilterStatus::kCreatedServerFilter, 1); + OptimizationFilterStatus::kCreatedServerFilter, 1); histogram_tester.ExpectBucketCount( "OptimizationGuide.OptimizationFilterStatus.DeferAllScript", - optimization_guide::OptimizationFilterStatus::kFoundServerFilterConfig, - 1); + OptimizationFilterStatus::kFoundServerFilterConfig, 1); histogram_tester.ExpectBucketCount( "OptimizationGuide.OptimizationFilterStatus.DeferAllScript", - optimization_guide::OptimizationFilterStatus::kCreatedServerFilter, 1); + OptimizationFilterStatus::kCreatedServerFilter, 1); EXPECT_TRUE(hints_manager()->HasLoadedOptimizationBlocklist( - optimization_guide::proto::LITE_PAGE_REDIRECT)); - EXPECT_TRUE(hints_manager()->HasLoadedOptimizationBlocklist( - optimization_guide::proto::NOSCRIPT)); + proto::LITE_PAGE_REDIRECT)); + EXPECT_TRUE( + hints_manager()->HasLoadedOptimizationBlocklist(proto::NOSCRIPT)); EXPECT_TRUE(hints_manager()->HasLoadedOptimizationAllowlist( - optimization_guide::proto::DEFER_ALL_SCRIPT)); + proto::DEFER_ALL_SCRIPT)); } } TEST_F(HintsManagerTest, OptimizationFiltersOnlyLoadOncePerType) { - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::LITE_PAGE_REDIRECT}); + hints_manager()->RegisterOptimizationTypes({proto::LITE_PAGE_REDIRECT}); base::HistogramTester histogram_tester; - optimization_guide::proto::Configuration config; - optimization_guide::BloomFilter blocklist_bloom_filter( - kDefaultHostBloomFilterNumHashFunctions, kDefaultHostBloomFilterNumBits); + proto::Configuration config; + BloomFilter blocklist_bloom_filter(kDefaultHostBloomFilterNumHashFunctions, + kDefaultHostBloomFilterNumBits); PopulateBloomFilterWithDefaultHost(&blocklist_bloom_filter); - AddBloomFilterToConfig( - optimization_guide::proto::LITE_PAGE_REDIRECT, blocklist_bloom_filter, - kDefaultHostBloomFilterNumHashFunctions, kDefaultHostBloomFilterNumBits, - /*is_allowlist=*/false, &config); - AddBloomFilterToConfig( - optimization_guide::proto::LITE_PAGE_REDIRECT, blocklist_bloom_filter, - kDefaultHostBloomFilterNumHashFunctions, kDefaultHostBloomFilterNumBits, - /*is_allowlist=*/false, &config); + AddBloomFilterToConfig(proto::LITE_PAGE_REDIRECT, blocklist_bloom_filter, + kDefaultHostBloomFilterNumHashFunctions, + kDefaultHostBloomFilterNumBits, + /*is_allowlist=*/false, &config); + AddBloomFilterToConfig(proto::LITE_PAGE_REDIRECT, blocklist_bloom_filter, + kDefaultHostBloomFilterNumHashFunctions, + kDefaultHostBloomFilterNumBits, + /*is_allowlist=*/false, &config); // Make sure it will only load one of an allowlist or a blocklist. - AddBloomFilterToConfig( - optimization_guide::proto::LITE_PAGE_REDIRECT, blocklist_bloom_filter, - kDefaultHostBloomFilterNumHashFunctions, kDefaultHostBloomFilterNumBits, - /*is_allowlist=*/true, &config); + AddBloomFilterToConfig(proto::LITE_PAGE_REDIRECT, blocklist_bloom_filter, + kDefaultHostBloomFilterNumHashFunctions, + kDefaultHostBloomFilterNumBits, + /*is_allowlist=*/true, &config); ProcessHints(config, "1.0.0.0"); // We found 2 LPR blocklists: parsed one and duped the other. histogram_tester.ExpectBucketCount( "OptimizationGuide.OptimizationFilterStatus.LitePageRedirect", - optimization_guide::OptimizationFilterStatus::kFoundServerFilterConfig, - 3); + OptimizationFilterStatus::kFoundServerFilterConfig, 3); histogram_tester.ExpectBucketCount( "OptimizationGuide.OptimizationFilterStatus.LitePageRedirect", - optimization_guide::OptimizationFilterStatus::kCreatedServerFilter, 1); + OptimizationFilterStatus::kCreatedServerFilter, 1); histogram_tester.ExpectBucketCount( "OptimizationGuide.OptimizationFilterStatus.LitePageRedirect", - optimization_guide::OptimizationFilterStatus:: - kFailedServerFilterDuplicateConfig, - 2); + OptimizationFilterStatus::kFailedServerFilterDuplicateConfig, 2); } TEST_F(HintsManagerTest, InvalidOptimizationFilterNotLoaded) { - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::LITE_PAGE_REDIRECT}); + hints_manager()->RegisterOptimizationTypes({proto::LITE_PAGE_REDIRECT}); base::HistogramTester histogram_tester; - int too_many_bits = - optimization_guide::features::MaxServerBloomFilterByteSize() * 8 + 1; + int too_many_bits = features::MaxServerBloomFilterByteSize() * 8 + 1; - optimization_guide::proto::Configuration config; - optimization_guide::BloomFilter blocklist_bloom_filter( - kDefaultHostBloomFilterNumHashFunctions, too_many_bits); + proto::Configuration config; + BloomFilter blocklist_bloom_filter(kDefaultHostBloomFilterNumHashFunctions, + too_many_bits); PopulateBloomFilterWithDefaultHost(&blocklist_bloom_filter); - AddBloomFilterToConfig(optimization_guide::proto::LITE_PAGE_REDIRECT, - blocklist_bloom_filter, + AddBloomFilterToConfig(proto::LITE_PAGE_REDIRECT, blocklist_bloom_filter, kDefaultHostBloomFilterNumHashFunctions, too_many_bits, /*is_allowlist=*/false, &config); ProcessHints(config, "1.0.0.0"); histogram_tester.ExpectBucketCount( "OptimizationGuide.OptimizationFilterStatus.LitePageRedirect", - optimization_guide::OptimizationFilterStatus::kFoundServerFilterConfig, - 1); + OptimizationFilterStatus::kFoundServerFilterConfig, 1); histogram_tester.ExpectBucketCount( "OptimizationGuide.OptimizationFilterStatus.LitePageRedirect", - optimization_guide::OptimizationFilterStatus::kFailedServerFilterTooBig, - 1); + OptimizationFilterStatus::kFailedServerFilterTooBig, 1); EXPECT_FALSE(hints_manager()->HasLoadedOptimizationBlocklist( - optimization_guide::proto::LITE_PAGE_REDIRECT)); + proto::LITE_PAGE_REDIRECT)); } TEST_F(HintsManagerTest, CanApplyOptimizationUrlWithNoHost) { - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::LITE_PAGE_REDIRECT}); + hints_manager()->RegisterOptimizationTypes({proto::LITE_PAGE_REDIRECT}); - optimization_guide::proto::Configuration config; - optimization_guide::BloomFilter blocklist_bloom_filter( - kDefaultHostBloomFilterNumHashFunctions, kDefaultHostBloomFilterNumBits); + proto::Configuration config; + BloomFilter blocklist_bloom_filter(kDefaultHostBloomFilterNumHashFunctions, + kDefaultHostBloomFilterNumBits); PopulateBloomFilterWithDefaultHost(&blocklist_bloom_filter); - AddBloomFilterToConfig( - optimization_guide::proto::LITE_PAGE_REDIRECT, blocklist_bloom_filter, - kDefaultHostBloomFilterNumHashFunctions, kDefaultHostBloomFilterNumBits, - /*is_allowlist=*/false, &config); + AddBloomFilterToConfig(proto::LITE_PAGE_REDIRECT, blocklist_bloom_filter, + kDefaultHostBloomFilterNumHashFunctions, + kDefaultHostBloomFilterNumBits, + /*is_allowlist=*/false, &config); ProcessHints(config, "1.0.0.0"); - optimization_guide::OptimizationTypeDecision optimization_type_decision = - hints_manager()->CanApplyOptimization( - GURL("urlwithnohost"), optimization_guide::proto::LITE_PAGE_REDIRECT, - /*optimization_metadata=*/nullptr); + OptimizationTypeDecision optimization_type_decision = + hints_manager()->CanApplyOptimization(GURL("urlwithnohost"), + proto::LITE_PAGE_REDIRECT, + /*optimization_metadata=*/nullptr); // Make sure decisions are logged correctly. - EXPECT_EQ(optimization_guide::OptimizationTypeDecision::kNoHintAvailable, + EXPECT_EQ(OptimizationTypeDecision::kNoHintAvailable, optimization_type_decision); } TEST_F(HintsManagerTest, CanApplyOptimizationHasFilterForTypeButNotLoadedYet) { - optimization_guide::proto::Configuration config; - optimization_guide::BloomFilter blocklist_bloom_filter( - kDefaultHostBloomFilterNumHashFunctions, kDefaultHostBloomFilterNumBits); + proto::Configuration config; + BloomFilter blocklist_bloom_filter(kDefaultHostBloomFilterNumHashFunctions, + kDefaultHostBloomFilterNumBits); PopulateBloomFilterWithDefaultHost(&blocklist_bloom_filter); - AddBloomFilterToConfig( - optimization_guide::proto::LITE_PAGE_REDIRECT, blocklist_bloom_filter, - kDefaultHostBloomFilterNumHashFunctions, kDefaultHostBloomFilterNumBits, - /*is_allowlist=*/false, &config); + AddBloomFilterToConfig(proto::LITE_PAGE_REDIRECT, blocklist_bloom_filter, + kDefaultHostBloomFilterNumHashFunctions, + kDefaultHostBloomFilterNumBits, + /*is_allowlist=*/false, &config); ProcessHints(config, "1.0.0.0"); // Append the switch for processing hints to force the filter to not get // loaded. base::CommandLine::ForCurrentProcess()->AppendSwitch( - optimization_guide::switches::kHintsProtoOverride); + switches::kHintsProtoOverride); - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::LITE_PAGE_REDIRECT}); - optimization_guide::OptimizationTypeDecision optimization_type_decision = - hints_manager()->CanApplyOptimization( - GURL("https://whatever.com/123"), - optimization_guide::proto::LITE_PAGE_REDIRECT, - /*optimization_metadata=*/nullptr); + hints_manager()->RegisterOptimizationTypes({proto::LITE_PAGE_REDIRECT}); + OptimizationTypeDecision optimization_type_decision = + hints_manager()->CanApplyOptimization(GURL("https://whatever.com/123"), + proto::LITE_PAGE_REDIRECT, + /*optimization_metadata=*/nullptr); - EXPECT_EQ(optimization_guide::OptimizationTypeDecision:: - kHadOptimizationFilterButNotLoadedInTime, + EXPECT_EQ(OptimizationTypeDecision::kHadOptimizationFilterButNotLoadedInTime, optimization_type_decision); // Run until idle to ensure we don't crash because the test object has gone @@ -1175,288 +1112,262 @@ TEST_F(HintsManagerTest, CanApplyOptimizationHasLoadedFilterForTypeUrlInAllowlist) { - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::LITE_PAGE_REDIRECT}); + hints_manager()->RegisterOptimizationTypes({proto::LITE_PAGE_REDIRECT}); - optimization_guide::proto::Configuration config; - optimization_guide::BloomFilter allowlist_bloom_filter( - kDefaultHostBloomFilterNumHashFunctions, kDefaultHostBloomFilterNumBits); + proto::Configuration config; + BloomFilter allowlist_bloom_filter(kDefaultHostBloomFilterNumHashFunctions, + kDefaultHostBloomFilterNumBits); PopulateBloomFilterWithDefaultHost(&allowlist_bloom_filter); - AddBloomFilterToConfig( - optimization_guide::proto::LITE_PAGE_REDIRECT, allowlist_bloom_filter, - kDefaultHostBloomFilterNumHashFunctions, kDefaultHostBloomFilterNumBits, - /*is_allowlist=*/true, &config); + AddBloomFilterToConfig(proto::LITE_PAGE_REDIRECT, allowlist_bloom_filter, + kDefaultHostBloomFilterNumHashFunctions, + kDefaultHostBloomFilterNumBits, + /*is_allowlist=*/true, &config); ProcessHints(config, "1.0.0.0"); - optimization_guide::OptimizationTypeDecision optimization_type_decision = - hints_manager()->CanApplyOptimization( - GURL("https://m.host.com/123"), - optimization_guide::proto::LITE_PAGE_REDIRECT, - /*optimization_metadata=*/nullptr); + OptimizationTypeDecision optimization_type_decision = + hints_manager()->CanApplyOptimization(GURL("https://m.host.com/123"), + proto::LITE_PAGE_REDIRECT, + /*optimization_metadata=*/nullptr); - EXPECT_EQ(optimization_guide::OptimizationTypeDecision:: - kAllowedByOptimizationFilter, + EXPECT_EQ(OptimizationTypeDecision::kAllowedByOptimizationFilter, optimization_type_decision); } TEST_F(HintsManagerTest, CanApplyOptimizationHasLoadedFilterForTypeUrlInBlocklist) { - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::LITE_PAGE_REDIRECT}); + hints_manager()->RegisterOptimizationTypes({proto::LITE_PAGE_REDIRECT}); - optimization_guide::proto::Configuration config; - optimization_guide::BloomFilter blocklist_bloom_filter( - kDefaultHostBloomFilterNumHashFunctions, kDefaultHostBloomFilterNumBits); + proto::Configuration config; + BloomFilter blocklist_bloom_filter(kDefaultHostBloomFilterNumHashFunctions, + kDefaultHostBloomFilterNumBits); PopulateBloomFilterWithDefaultHost(&blocklist_bloom_filter); - AddBloomFilterToConfig( - optimization_guide::proto::LITE_PAGE_REDIRECT, blocklist_bloom_filter, - kDefaultHostBloomFilterNumHashFunctions, kDefaultHostBloomFilterNumBits, - /*is_allowlist=*/false, &config); + AddBloomFilterToConfig(proto::LITE_PAGE_REDIRECT, blocklist_bloom_filter, + kDefaultHostBloomFilterNumHashFunctions, + kDefaultHostBloomFilterNumBits, + /*is_allowlist=*/false, &config); ProcessHints(config, "1.0.0.0"); - optimization_guide::OptimizationTypeDecision optimization_type_decision = - hints_manager()->CanApplyOptimization( - GURL("https://m.host.com/123"), - optimization_guide::proto::LITE_PAGE_REDIRECT, - /*optimization_metadata=*/nullptr); + OptimizationTypeDecision optimization_type_decision = + hints_manager()->CanApplyOptimization(GURL("https://m.host.com/123"), + proto::LITE_PAGE_REDIRECT, + /*optimization_metadata=*/nullptr); - EXPECT_EQ(optimization_guide::OptimizationTypeDecision:: - kNotAllowedByOptimizationFilter, + EXPECT_EQ(OptimizationTypeDecision::kNotAllowedByOptimizationFilter, optimization_type_decision); } TEST_F(HintsManagerTest, CanApplyOptimizationHasLoadedFilterForTypeUrlNotInAllowlistFilter) { - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::LITE_PAGE_REDIRECT}); + hints_manager()->RegisterOptimizationTypes({proto::LITE_PAGE_REDIRECT}); - optimization_guide::proto::Configuration config; - optimization_guide::BloomFilter allowlist_bloom_filter( - kDefaultHostBloomFilterNumHashFunctions, kDefaultHostBloomFilterNumBits); + proto::Configuration config; + BloomFilter allowlist_bloom_filter(kDefaultHostBloomFilterNumHashFunctions, + kDefaultHostBloomFilterNumBits); PopulateBloomFilterWithDefaultHost(&allowlist_bloom_filter); - AddBloomFilterToConfig( - optimization_guide::proto::LITE_PAGE_REDIRECT, allowlist_bloom_filter, - kDefaultHostBloomFilterNumHashFunctions, kDefaultHostBloomFilterNumBits, - /*is_allowlist=*/true, &config); + AddBloomFilterToConfig(proto::LITE_PAGE_REDIRECT, allowlist_bloom_filter, + kDefaultHostBloomFilterNumHashFunctions, + kDefaultHostBloomFilterNumBits, + /*is_allowlist=*/true, &config); ProcessHints(config, "1.0.0.0"); - optimization_guide::OptimizationTypeDecision optimization_type_decision = - hints_manager()->CanApplyOptimization( - GURL("https://whatever.com/123"), - optimization_guide::proto::LITE_PAGE_REDIRECT, - /*optimization_metadata=*/nullptr); + OptimizationTypeDecision optimization_type_decision = + hints_manager()->CanApplyOptimization(GURL("https://whatever.com/123"), + proto::LITE_PAGE_REDIRECT, + /*optimization_metadata=*/nullptr); - EXPECT_EQ(optimization_guide::OptimizationTypeDecision:: - kNotAllowedByOptimizationFilter, + EXPECT_EQ(OptimizationTypeDecision::kNotAllowedByOptimizationFilter, optimization_type_decision); } TEST_F(HintsManagerTest, CanApplyOptimizationHasLoadedFilterForTypeUrlNotInBlocklistFilter) { - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::LITE_PAGE_REDIRECT}); + hints_manager()->RegisterOptimizationTypes({proto::LITE_PAGE_REDIRECT}); - optimization_guide::proto::Configuration config; - optimization_guide::BloomFilter blocklist_bloom_filter( - kDefaultHostBloomFilterNumHashFunctions, kDefaultHostBloomFilterNumBits); + proto::Configuration config; + BloomFilter blocklist_bloom_filter(kDefaultHostBloomFilterNumHashFunctions, + kDefaultHostBloomFilterNumBits); PopulateBloomFilterWithDefaultHost(&blocklist_bloom_filter); - AddBloomFilterToConfig( - optimization_guide::proto::LITE_PAGE_REDIRECT, blocklist_bloom_filter, - kDefaultHostBloomFilterNumHashFunctions, kDefaultHostBloomFilterNumBits, - /*is_allowlist=*/false, &config); + AddBloomFilterToConfig(proto::LITE_PAGE_REDIRECT, blocklist_bloom_filter, + kDefaultHostBloomFilterNumHashFunctions, + kDefaultHostBloomFilterNumBits, + /*is_allowlist=*/false, &config); ProcessHints(config, "1.0.0.0"); - optimization_guide::OptimizationTypeDecision optimization_type_decision = - hints_manager()->CanApplyOptimization( - GURL("https://whatever.com/123"), - optimization_guide::proto::LITE_PAGE_REDIRECT, - /*optimization_metadata=*/nullptr); + OptimizationTypeDecision optimization_type_decision = + hints_manager()->CanApplyOptimization(GURL("https://whatever.com/123"), + proto::LITE_PAGE_REDIRECT, + /*optimization_metadata=*/nullptr); - EXPECT_EQ(optimization_guide::OptimizationTypeDecision:: - kAllowedByOptimizationFilter, + EXPECT_EQ(OptimizationTypeDecision::kAllowedByOptimizationFilter, optimization_type_decision); } TEST_F(HintsManagerTest, CanApplyOptimizationOptimizationTypeAllowlistedAtTopLevel) { - optimization_guide::proto::Configuration config; - optimization_guide::proto::Hint* hint1 = config.add_hints(); + proto::Configuration config; + proto::Hint* hint1 = config.add_hints(); hint1->set_key("somedomain.org"); - hint1->set_key_representation(optimization_guide::proto::HOST); + hint1->set_key_representation(proto::HOST); hint1->set_version("someversion"); - optimization_guide::proto::Optimization* opt1 = - hint1->add_allowlisted_optimizations(); - opt1->set_optimization_type(optimization_guide::proto::RESOURCE_LOADING); + proto::Optimization* opt1 = hint1->add_allowlisted_optimizations(); + opt1->set_optimization_type(proto::RESOURCE_LOADING); ProcessHints(config, "1.0.0.0"); - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::RESOURCE_LOADING}); + hints_manager()->RegisterOptimizationTypes({proto::RESOURCE_LOADING}); - auto navigation_data = CreateTestNavigationData( - url_with_hints(), {optimization_guide::proto::RESOURCE_LOADING}); + auto navigation_data = + CreateTestNavigationData(url_with_hints(), {proto::RESOURCE_LOADING}); base::RunLoop run_loop; CallOnNavigationStartOrRedirect(navigation_data.get(), run_loop.QuitClosure()); run_loop.Run(); - optimization_guide::OptimizationMetadata optimization_metadata; - optimization_guide::OptimizationTypeDecision optimization_type_decision = - hints_manager()->CanApplyOptimization( - navigation_data->navigation_url(), - optimization_guide::proto::RESOURCE_LOADING, &optimization_metadata); - EXPECT_EQ(optimization_guide::OptimizationTypeDecision::kAllowedByHint, + OptimizationMetadata optimization_metadata; + OptimizationTypeDecision optimization_type_decision = + hints_manager()->CanApplyOptimization(navigation_data->navigation_url(), + proto::RESOURCE_LOADING, + &optimization_metadata); + EXPECT_EQ(OptimizationTypeDecision::kAllowedByHint, optimization_type_decision); } TEST_F(HintsManagerTest, CanApplyOptimizationHasPageHintButNoMatchingOptType) { InitializeWithDefaultConfig("1.0.0.0"); - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::DEFER_ALL_SCRIPT}); + hints_manager()->RegisterOptimizationTypes({proto::DEFER_ALL_SCRIPT}); - auto navigation_data = CreateTestNavigationData( - url_with_hints(), {optimization_guide::proto::DEFER_ALL_SCRIPT}); + auto navigation_data = + CreateTestNavigationData(url_with_hints(), {proto::DEFER_ALL_SCRIPT}); base::RunLoop run_loop; CallOnNavigationStartOrRedirect(navigation_data.get(), run_loop.QuitClosure()); run_loop.Run(); - optimization_guide::OptimizationTypeDecision optimization_type_decision = - hints_manager()->CanApplyOptimization( - navigation_data->navigation_url(), - optimization_guide::proto::DEFER_ALL_SCRIPT, - /*optimization_metadata=*/nullptr); + OptimizationTypeDecision optimization_type_decision = + hints_manager()->CanApplyOptimization(navigation_data->navigation_url(), + proto::DEFER_ALL_SCRIPT, + /*optimization_metadata=*/nullptr); - EXPECT_EQ(optimization_guide::OptimizationTypeDecision::kNotAllowedByHint, + EXPECT_EQ(OptimizationTypeDecision::kNotAllowedByHint, optimization_type_decision); } TEST_F(HintsManagerTest, CanApplyOptimizationAndPopulatesPerformanceHintsMetadata) { - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::PERFORMANCE_HINTS}); - optimization_guide::proto::Configuration config; - optimization_guide::proto::Hint* hint = config.add_hints(); + hints_manager()->RegisterOptimizationTypes({proto::PERFORMANCE_HINTS}); + proto::Configuration config; + proto::Hint* hint = config.add_hints(); hint->set_key("somedomain.org"); - hint->set_key_representation(optimization_guide::proto::HOST); + hint->set_key_representation(proto::HOST); hint->set_version("someversion"); - optimization_guide::proto::PageHint* page_hint = hint->add_page_hints(); + proto::PageHint* page_hint = hint->add_page_hints(); page_hint->set_page_pattern("/news/"); - optimization_guide::proto::Optimization* opt = - page_hint->add_allowlisted_optimizations(); - opt->set_optimization_type(optimization_guide::proto::PERFORMANCE_HINTS); - optimization_guide::proto::PerformanceHint* performance_hint = + proto::Optimization* opt = page_hint->add_allowlisted_optimizations(); + opt->set_optimization_type(proto::PERFORMANCE_HINTS); + proto::PerformanceHint* performance_hint = opt->mutable_performance_hints_metadata()->add_performance_hints(); performance_hint->set_wildcard_pattern("somedomain.org"); - performance_hint->set_performance_class( - optimization_guide::proto::PERFORMANCE_SLOW); + performance_hint->set_performance_class(proto::PERFORMANCE_SLOW); ProcessHints(config, "1.0.0.0"); base::RunLoop run_loop; - auto navigation_data = CreateTestNavigationData( - url_with_hints(), {optimization_guide::proto::PERFORMANCE_HINTS}); + auto navigation_data = + CreateTestNavigationData(url_with_hints(), {proto::PERFORMANCE_HINTS}); CallOnNavigationStartOrRedirect(navigation_data.get(), run_loop.QuitClosure()); run_loop.Run(); - optimization_guide::OptimizationMetadata optimization_metadata; - optimization_guide::OptimizationTypeDecision optimization_type_decision = - hints_manager()->CanApplyOptimization( - navigation_data->navigation_url(), - optimization_guide::proto::PERFORMANCE_HINTS, &optimization_metadata); + OptimizationMetadata optimization_metadata; + OptimizationTypeDecision optimization_type_decision = + hints_manager()->CanApplyOptimization(navigation_data->navigation_url(), + proto::PERFORMANCE_HINTS, + &optimization_metadata); // Make sure performance hints metadata is populated. EXPECT_TRUE(optimization_metadata.performance_hints_metadata().has_value()); - EXPECT_EQ(optimization_guide::OptimizationTypeDecision::kAllowedByHint, + EXPECT_EQ(OptimizationTypeDecision::kAllowedByHint, optimization_type_decision); } TEST_F(HintsManagerTest, CanApplyOptimizationAndPopulatesPublicImageMetadata) { - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::COMPRESS_PUBLIC_IMAGES}); - optimization_guide::proto::Configuration config; - optimization_guide::proto::Hint* hint = config.add_hints(); + hints_manager()->RegisterOptimizationTypes({proto::COMPRESS_PUBLIC_IMAGES}); + proto::Configuration config; + proto::Hint* hint = config.add_hints(); hint->set_key("somedomain.org"); - hint->set_key_representation(optimization_guide::proto::HOST); + hint->set_key_representation(proto::HOST); hint->set_version("someversion"); - optimization_guide::proto::PageHint* page_hint = hint->add_page_hints(); + proto::PageHint* page_hint = hint->add_page_hints(); page_hint->set_page_pattern("/news/"); - optimization_guide::proto::Optimization* opt = - page_hint->add_allowlisted_optimizations(); - opt->set_optimization_type(optimization_guide::proto::COMPRESS_PUBLIC_IMAGES); + proto::Optimization* opt = page_hint->add_allowlisted_optimizations(); + opt->set_optimization_type(proto::COMPRESS_PUBLIC_IMAGES); opt->mutable_public_image_metadata()->add_url("someimage"); ProcessHints(config, "1.0.0.0"); auto navigation_data = CreateTestNavigationData( - url_with_hints(), {optimization_guide::proto::COMPRESS_PUBLIC_IMAGES}); + url_with_hints(), {proto::COMPRESS_PUBLIC_IMAGES}); base::RunLoop run_loop; CallOnNavigationStartOrRedirect(navigation_data.get(), run_loop.QuitClosure()); run_loop.Run(); - optimization_guide::OptimizationMetadata optimization_metadata; - optimization_guide::OptimizationTypeDecision optimization_type_decision = - hints_manager()->CanApplyOptimization( - navigation_data->navigation_url(), - optimization_guide::proto::COMPRESS_PUBLIC_IMAGES, - &optimization_metadata); + OptimizationMetadata optimization_metadata; + OptimizationTypeDecision optimization_type_decision = + hints_manager()->CanApplyOptimization(navigation_data->navigation_url(), + proto::COMPRESS_PUBLIC_IMAGES, + &optimization_metadata); // Make sure public images metadata is populated. EXPECT_TRUE(optimization_metadata.public_image_metadata().has_value()); - EXPECT_EQ(optimization_guide::OptimizationTypeDecision::kAllowedByHint, + EXPECT_EQ(OptimizationTypeDecision::kAllowedByHint, optimization_type_decision); } TEST_F(HintsManagerTest, CanApplyOptimizationAndPopulatesLoadingPredictorMetadata) { - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::LOADING_PREDICTOR}); - optimization_guide::proto::Configuration config; - optimization_guide::proto::Hint* hint = config.add_hints(); + hints_manager()->RegisterOptimizationTypes({proto::LOADING_PREDICTOR}); + proto::Configuration config; + proto::Hint* hint = config.add_hints(); hint->set_key("somedomain.org"); - hint->set_key_representation(optimization_guide::proto::HOST); + hint->set_key_representation(proto::HOST); hint->set_version("someversion"); - optimization_guide::proto::PageHint* page_hint = hint->add_page_hints(); + proto::PageHint* page_hint = hint->add_page_hints(); page_hint->set_page_pattern("/news/"); - optimization_guide::proto::Optimization* opt = - page_hint->add_allowlisted_optimizations(); - opt->set_optimization_type(optimization_guide::proto::LOADING_PREDICTOR); + proto::Optimization* opt = page_hint->add_allowlisted_optimizations(); + opt->set_optimization_type(proto::LOADING_PREDICTOR); opt->mutable_loading_predictor_metadata()->add_subresources()->set_url( "https://resource.com/"); ProcessHints(config, "1.0.0.0"); - auto navigation_data = CreateTestNavigationData( - url_with_hints(), {optimization_guide::proto::LOADING_PREDICTOR}); + auto navigation_data = + CreateTestNavigationData(url_with_hints(), {proto::LOADING_PREDICTOR}); base::RunLoop run_loop; CallOnNavigationStartOrRedirect(navigation_data.get(), run_loop.QuitClosure()); run_loop.Run(); - optimization_guide::OptimizationMetadata optimization_metadata; - optimization_guide::OptimizationTypeDecision optimization_type_decision = - hints_manager()->CanApplyOptimization( - navigation_data->navigation_url(), - optimization_guide::proto::LOADING_PREDICTOR, &optimization_metadata); + OptimizationMetadata optimization_metadata; + OptimizationTypeDecision optimization_type_decision = + hints_manager()->CanApplyOptimization(navigation_data->navigation_url(), + proto::LOADING_PREDICTOR, + &optimization_metadata); // Make sure loading predictor metadata is populated. EXPECT_TRUE(optimization_metadata.loading_predictor_metadata().has_value()); - EXPECT_EQ(optimization_guide::OptimizationTypeDecision::kAllowedByHint, + EXPECT_EQ(OptimizationTypeDecision::kAllowedByHint, optimization_type_decision); } TEST_F(HintsManagerTest, CanApplyOptimizationAndPopulatesAnyMetadata) { - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::LOADING_PREDICTOR}); - optimization_guide::proto::Configuration config; - optimization_guide::proto::Hint* hint = config.add_hints(); + hints_manager()->RegisterOptimizationTypes({proto::LOADING_PREDICTOR}); + proto::Configuration config; + proto::Hint* hint = config.add_hints(); hint->set_key("somedomain.org"); - hint->set_key_representation(optimization_guide::proto::HOST); + hint->set_key_representation(proto::HOST); hint->set_version("someversion"); - optimization_guide::proto::PageHint* page_hint = hint->add_page_hints(); + proto::PageHint* page_hint = hint->add_page_hints(); page_hint->set_page_pattern("/news/"); - optimization_guide::proto::Optimization* opt = - page_hint->add_allowlisted_optimizations(); - opt->set_optimization_type(optimization_guide::proto::LOADING_PREDICTOR); - optimization_guide::proto::LoadingPredictorMetadata lp_metadata; + proto::Optimization* opt = page_hint->add_allowlisted_optimizations(); + opt->set_optimization_type(proto::LOADING_PREDICTOR); + proto::LoadingPredictorMetadata lp_metadata; lp_metadata.add_subresources()->set_url("https://resource.com/"); lp_metadata.SerializeToString(opt->mutable_any_metadata()->mutable_value()); opt->mutable_any_metadata()->set_type_url( @@ -1464,24 +1375,23 @@ ProcessHints(config, "1.0.0.0"); - auto navigation_data = CreateTestNavigationData( - url_with_hints(), {optimization_guide::proto::LOADING_PREDICTOR}); + auto navigation_data = + CreateTestNavigationData(url_with_hints(), {proto::LOADING_PREDICTOR}); base::RunLoop run_loop; CallOnNavigationStartOrRedirect(navigation_data.get(), run_loop.QuitClosure()); run_loop.Run(); - optimization_guide::OptimizationMetadata optimization_metadata; - optimization_guide::OptimizationTypeDecision optimization_type_decision = - hints_manager()->CanApplyOptimization( - navigation_data->navigation_url(), - optimization_guide::proto::LOADING_PREDICTOR, &optimization_metadata); + OptimizationMetadata optimization_metadata; + OptimizationTypeDecision optimization_type_decision = + hints_manager()->CanApplyOptimization(navigation_data->navigation_url(), + proto::LOADING_PREDICTOR, + &optimization_metadata); // Make sure loading predictor metadata is populated. EXPECT_TRUE( - optimization_metadata - .ParsedMetadata<optimization_guide::proto::LoadingPredictorMetadata>() + optimization_metadata.ParsedMetadata<proto::LoadingPredictorMetadata>() .has_value()); - EXPECT_EQ(optimization_guide::OptimizationTypeDecision::kAllowedByHint, + EXPECT_EQ(OptimizationTypeDecision::kAllowedByHint, optimization_type_decision); } @@ -1497,14 +1407,13 @@ run_loop.QuitClosure()); run_loop.Run(); - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::NOSCRIPT}); - optimization_guide::OptimizationTypeDecision optimization_type_decision = + hints_manager()->RegisterOptimizationTypes({proto::NOSCRIPT}); + OptimizationTypeDecision optimization_type_decision = hints_manager()->CanApplyOptimization(navigation_data->navigation_url(), - optimization_guide::proto::NOSCRIPT, + proto::NOSCRIPT, /*optimization_metadata=*/nullptr); - EXPECT_EQ(optimization_guide::OptimizationTypeDecision::kNotAllowedByHint, + EXPECT_EQ(OptimizationTypeDecision::kNotAllowedByHint, optimization_type_decision); } @@ -1513,71 +1422,64 @@ InitializeWithDefaultConfig("1.0.0.0"); auto navigation_data = CreateTestNavigationData( - GURL("https://nohint.com"), - {optimization_guide::proto::COMPRESS_PUBLIC_IMAGES}); + GURL("https://nohint.com"), {proto::COMPRESS_PUBLIC_IMAGES}); - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::NOSCRIPT}); - optimization_guide::OptimizationMetadata optimization_metadata; + hints_manager()->RegisterOptimizationTypes({proto::NOSCRIPT}); + OptimizationMetadata optimization_metadata; - optimization_guide::proto::PerformanceHintsMetadata hints_metadata; + proto::PerformanceHintsMetadata hints_metadata; auto* hint = hints_metadata.add_performance_hints(); hint->set_wildcard_pattern("test.com"); - hint->set_performance_class(optimization_guide::proto::PERFORMANCE_SLOW); - optimization_guide::OptimizationMetadata metadata; + hint->set_performance_class(proto::PERFORMANCE_SLOW); + OptimizationMetadata metadata; optimization_metadata.set_performance_hints_metadata(hints_metadata); - optimization_guide::OptimizationTypeDecision optimization_type_decision = + OptimizationTypeDecision optimization_type_decision = hints_manager()->CanApplyOptimization(navigation_data->navigation_url(), - optimization_guide::proto::NOSCRIPT, + proto::NOSCRIPT, &optimization_metadata); EXPECT_FALSE(optimization_metadata.performance_hints_metadata().has_value()); - EXPECT_EQ(optimization_guide::OptimizationTypeDecision::kNoHintAvailable, + EXPECT_EQ(OptimizationTypeDecision::kNoHintAvailable, optimization_type_decision); } TEST_F(HintsManagerTest, CanApplyOptimizationHasHintInCacheButNotLoaded) { InitializeWithDefaultConfig("1.0.0.0"); - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::NOSCRIPT}); - optimization_guide::OptimizationMetadata optimization_metadata; - optimization_guide::OptimizationTypeDecision optimization_type_decision = - hints_manager()->CanApplyOptimization(url_with_hints(), - optimization_guide::proto::NOSCRIPT, + hints_manager()->RegisterOptimizationTypes({proto::NOSCRIPT}); + OptimizationMetadata optimization_metadata; + OptimizationTypeDecision optimization_type_decision = + hints_manager()->CanApplyOptimization(url_with_hints(), proto::NOSCRIPT, &optimization_metadata); - EXPECT_EQ( - optimization_guide::OptimizationTypeDecision::kHadHintButNotLoadedInTime, - optimization_type_decision); + EXPECT_EQ(OptimizationTypeDecision::kHadHintButNotLoadedInTime, + optimization_type_decision); } TEST_F(HintsManagerTest, CanApplyOptimizationFilterTakesPrecedence) { auto navigation_data = CreateTestNavigationData( GURL("https://m.host.com/urlinfilterandhints"), {}); - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::LITE_PAGE_REDIRECT}); + hints_manager()->RegisterOptimizationTypes({proto::LITE_PAGE_REDIRECT}); - optimization_guide::proto::Configuration config; - optimization_guide::proto::Hint* hint1 = config.add_hints(); + proto::Configuration config; + proto::Hint* hint1 = config.add_hints(); hint1->set_key("host.com"); - hint1->set_key_representation(optimization_guide::proto::HOST); + hint1->set_key_representation(proto::HOST); hint1->set_version("someversion"); - optimization_guide::proto::PageHint* page_hint1 = hint1->add_page_hints(); + proto::PageHint* page_hint1 = hint1->add_page_hints(); page_hint1->set_page_pattern("https://m.host.com"); - optimization_guide::proto::Optimization* optimization1 = + proto::Optimization* optimization1 = page_hint1->add_allowlisted_optimizations(); - optimization1->set_optimization_type( - optimization_guide::proto::LITE_PAGE_REDIRECT); - optimization_guide::BloomFilter blocklist_bloom_filter( - kDefaultHostBloomFilterNumHashFunctions, kDefaultHostBloomFilterNumBits); + optimization1->set_optimization_type(proto::LITE_PAGE_REDIRECT); + BloomFilter blocklist_bloom_filter(kDefaultHostBloomFilterNumHashFunctions, + kDefaultHostBloomFilterNumBits); PopulateBloomFilterWithDefaultHost(&blocklist_bloom_filter); - AddBloomFilterToConfig( - optimization_guide::proto::LITE_PAGE_REDIRECT, blocklist_bloom_filter, - kDefaultHostBloomFilterNumHashFunctions, kDefaultHostBloomFilterNumBits, - /*is_allowlist=*/false, &config); + AddBloomFilterToConfig(proto::LITE_PAGE_REDIRECT, blocklist_bloom_filter, + kDefaultHostBloomFilterNumHashFunctions, + kDefaultHostBloomFilterNumBits, + /*is_allowlist=*/false, &config); ProcessHints(config, "1.0.0.0"); base::RunLoop run_loop; @@ -1585,45 +1487,41 @@ run_loop.QuitClosure()); run_loop.Run(); - optimization_guide::OptimizationTypeDecision optimization_type_decision = - hints_manager()->CanApplyOptimization( - navigation_data->navigation_url(), - optimization_guide::proto::LITE_PAGE_REDIRECT, - /*optimization_metadata=*/nullptr); + OptimizationTypeDecision optimization_type_decision = + hints_manager()->CanApplyOptimization(navigation_data->navigation_url(), + proto::LITE_PAGE_REDIRECT, + /*optimization_metadata=*/nullptr); // Make sure decision points logged correctly. - EXPECT_EQ(optimization_guide::OptimizationTypeDecision:: - kNotAllowedByOptimizationFilter, + EXPECT_EQ(OptimizationTypeDecision::kNotAllowedByOptimizationFilter, optimization_type_decision); } TEST_F(HintsManagerTest, CanApplyOptimizationFilterTakesPrecedenceMatchesFilter) { - auto navigation_data = CreateTestNavigationData( - GURL("https://notfiltered.com/whatever"), - {optimization_guide::proto::COMPRESS_PUBLIC_IMAGES}); + auto navigation_data = + CreateTestNavigationData(GURL("https://notfiltered.com/whatever"), + {proto::COMPRESS_PUBLIC_IMAGES}); - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::LITE_PAGE_REDIRECT}); + hints_manager()->RegisterOptimizationTypes({proto::LITE_PAGE_REDIRECT}); - optimization_guide::proto::Configuration config; - optimization_guide::proto::Hint* hint1 = config.add_hints(); + proto::Configuration config; + proto::Hint* hint1 = config.add_hints(); hint1->set_key("notfiltered.com"); - hint1->set_key_representation(optimization_guide::proto::HOST); + hint1->set_key_representation(proto::HOST); hint1->set_version("someversion"); - optimization_guide::proto::PageHint* page_hint1 = hint1->add_page_hints(); + proto::PageHint* page_hint1 = hint1->add_page_hints(); page_hint1->set_page_pattern("https://notfiltered.com"); - optimization_guide::proto::Optimization* optimization1 = + proto::Optimization* optimization1 = page_hint1->add_allowlisted_optimizations(); - optimization1->set_optimization_type( - optimization_guide::proto::LITE_PAGE_REDIRECT); - optimization_guide::BloomFilter blocklist_bloom_filter( - kDefaultHostBloomFilterNumHashFunctions, kDefaultHostBloomFilterNumBits); + optimization1->set_optimization_type(proto::LITE_PAGE_REDIRECT); + BloomFilter blocklist_bloom_filter(kDefaultHostBloomFilterNumHashFunctions, + kDefaultHostBloomFilterNumBits); PopulateBloomFilterWithDefaultHost(&blocklist_bloom_filter); - AddBloomFilterToConfig( - optimization_guide::proto::LITE_PAGE_REDIRECT, blocklist_bloom_filter, - kDefaultHostBloomFilterNumHashFunctions, kDefaultHostBloomFilterNumBits, - /*is_allowlist=*/false, &config); + AddBloomFilterToConfig(proto::LITE_PAGE_REDIRECT, blocklist_bloom_filter, + kDefaultHostBloomFilterNumHashFunctions, + kDefaultHostBloomFilterNumBits, + /*is_allowlist=*/false, &config); ProcessHints(config, "1.0.0.0"); base::RunLoop run_loop; @@ -1631,14 +1529,12 @@ run_loop.QuitClosure()); run_loop.Run(); - optimization_guide::OptimizationTypeDecision optimization_type_decision = - hints_manager()->CanApplyOptimization( - navigation_data->navigation_url(), - optimization_guide::proto::LITE_PAGE_REDIRECT, - /*optimization_metadata=*/nullptr); + OptimizationTypeDecision optimization_type_decision = + hints_manager()->CanApplyOptimization(navigation_data->navigation_url(), + proto::LITE_PAGE_REDIRECT, + /*optimization_metadata=*/nullptr); - EXPECT_EQ(optimization_guide::OptimizationTypeDecision:: - kAllowedByOptimizationFilter, + EXPECT_EQ(OptimizationTypeDecision::kAllowedByOptimizationFilter, optimization_type_decision); } @@ -1646,7 +1542,7 @@ public: HintsManagerFetchingDisabledTest() { scoped_list_.InitAndDisableFeature( - optimization_guide::features::kRemoteOptimizationGuideFetching); + features::kRemoteOptimizationGuideFetching); } private: @@ -1656,7 +1552,7 @@ TEST_F(HintsManagerFetchingDisabledTest, HintsFetchNotAllowedIfFeatureIsNotEnabled) { base::CommandLine::ForCurrentProcess()->AppendSwitch( - optimization_guide::switches::kDisableCheckingUserPermissionsForTesting); + switches::kDisableCheckingUserPermissionsForTesting); std::unique_ptr<FakeTopHostProvider> top_host_provider = std::make_unique<FakeTopHostProvider>( @@ -1676,25 +1572,22 @@ CanApplyOptimizationAsyncReturnsRightAwayIfNotAllowedToFetch) { base::HistogramTester histogram_tester; - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::COMPRESS_PUBLIC_IMAGES}); + hints_manager()->RegisterOptimizationTypes({proto::COMPRESS_PUBLIC_IMAGES}); InitializeWithDefaultConfig("1.0.0.0"); auto navigation_data = CreateTestNavigationData( - url_without_hints(), {optimization_guide::proto::COMPRESS_PUBLIC_IMAGES}); + url_without_hints(), {proto::COMPRESS_PUBLIC_IMAGES}); hints_manager()->CanApplyOptimizationAsync( - url_without_hints(), optimization_guide::proto::COMPRESS_PUBLIC_IMAGES, - base::BindOnce( - [](optimization_guide::OptimizationGuideDecision decision, - const optimization_guide::OptimizationMetadata& metadata) { - EXPECT_EQ(optimization_guide::OptimizationGuideDecision::kFalse, - decision); - })); + url_without_hints(), proto::COMPRESS_PUBLIC_IMAGES, + base::BindOnce([](OptimizationGuideDecision decision, + const OptimizationMetadata& metadata) { + EXPECT_EQ(OptimizationGuideDecision::kFalse, decision); + })); RunUntilIdle(); histogram_tester.ExpectUniqueSample( "OptimizationGuide.ApplyDecisionAsync.CompressPublicImages", - optimization_guide::OptimizationTypeDecision::kNoHintAvailable, 1); + OptimizationTypeDecision::kNoHintAvailable, 1); } TEST_F( @@ -1702,12 +1595,11 @@ CanApplyOptimizationAsyncReturnsRightAwayIfNotAllowedToFetchAndNotAllowlistedByAvailableHint) { base::HistogramTester histogram_tester; - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::COMPRESS_PUBLIC_IMAGES}); + hints_manager()->RegisterOptimizationTypes({proto::COMPRESS_PUBLIC_IMAGES}); InitializeWithDefaultConfig("1.0.0.0"); auto navigation_data = CreateTestNavigationData( - url_with_hints(), {optimization_guide::proto::COMPRESS_PUBLIC_IMAGES}); + url_with_hints(), {proto::COMPRESS_PUBLIC_IMAGES}); // Wait for hint to be loaded. base::RunLoop run_loop; CallOnNavigationStartOrRedirect(navigation_data.get(), @@ -1715,39 +1607,36 @@ run_loop.Run(); hints_manager()->CanApplyOptimizationAsync( - url_with_hints(), optimization_guide::proto::COMPRESS_PUBLIC_IMAGES, - base::BindOnce( - [](optimization_guide::OptimizationGuideDecision decision, - const optimization_guide::OptimizationMetadata& metadata) { - EXPECT_EQ(optimization_guide::OptimizationGuideDecision::kFalse, - decision); - })); + url_with_hints(), proto::COMPRESS_PUBLIC_IMAGES, + base::BindOnce([](OptimizationGuideDecision decision, + const OptimizationMetadata& metadata) { + EXPECT_EQ(OptimizationGuideDecision::kFalse, decision); + })); RunUntilIdle(); histogram_tester.ExpectUniqueSample( "OptimizationGuide.ApplyDecisionAsync.CompressPublicImages", - optimization_guide::OptimizationTypeDecision::kNotAllowedByHint, 1); + OptimizationTypeDecision::kNotAllowedByHint, 1); } TEST_F(HintsManagerTest, RemoveFetchedEntriesByHintKeys_Host) { int cache_duration_in_secs = 60; GURL url("https://host.com/r/cats"); - std::unique_ptr<optimization_guide::proto::GetHintsResponse> - get_hints_response = - std::make_unique<optimization_guide::proto::GetHintsResponse>(); + std::unique_ptr<proto::GetHintsResponse> get_hints_response = + std::make_unique<proto::GetHintsResponse>(); - optimization_guide::proto::Hint* hint = get_hints_response->add_hints(); + proto::Hint* hint = get_hints_response->add_hints(); hint->set_key(url.spec()); - hint->set_key_representation(optimization_guide::proto::FULL_URL); + hint->set_key_representation(proto::FULL_URL); hint->mutable_max_cache_duration()->set_seconds(cache_duration_in_secs); - optimization_guide::proto::PageHint* page_hint = hint->add_page_hints(); + proto::PageHint* page_hint = hint->add_page_hints(); page_hint->add_allowlisted_optimizations()->set_optimization_type( - optimization_guide::proto::PERFORMANCE_HINTS); + proto::PERFORMANCE_HINTS); page_hint->set_page_pattern("whatever/*"); hint = get_hints_response->add_hints(); - hint->set_key_representation(optimization_guide::proto::HOST); + hint->set_key_representation(proto::HOST); hint->set_key(url.host()); page_hint = hint->add_page_hints(); page_hint->set_page_pattern("anything/*"); @@ -1761,8 +1650,7 @@ run_loop = std::make_unique<base::RunLoop>(); hints_manager()->RemoveFetchedEntriesByHintKeys( - run_loop->QuitClosure(), - optimization_guide::proto::KeyRepresentation::HOST, {url.host()}); + run_loop->QuitClosure(), proto::KeyRepresentation::HOST, {url.host()}); run_loop->Run(); EXPECT_FALSE(hints_manager()->hint_cache()->HasHint(url.host())); @@ -1773,21 +1661,20 @@ int cache_duration_in_secs = 60; GURL url("https://host.com/r/cats"); - std::unique_ptr<optimization_guide::proto::GetHintsResponse> - get_hints_response = - std::make_unique<optimization_guide::proto::GetHintsResponse>(); + std::unique_ptr<proto::GetHintsResponse> get_hints_response = + std::make_unique<proto::GetHintsResponse>(); - optimization_guide::proto::Hint* hint = get_hints_response->add_hints(); + proto::Hint* hint = get_hints_response->add_hints(); hint->set_key(url.spec()); - hint->set_key_representation(optimization_guide::proto::FULL_URL); + hint->set_key_representation(proto::FULL_URL); hint->mutable_max_cache_duration()->set_seconds(cache_duration_in_secs); - optimization_guide::proto::PageHint* page_hint = hint->add_page_hints(); + proto::PageHint* page_hint = hint->add_page_hints(); page_hint->add_allowlisted_optimizations()->set_optimization_type( - optimization_guide::proto::PERFORMANCE_HINTS); + proto::PERFORMANCE_HINTS); page_hint->set_page_pattern("whatever/*"); hint = get_hints_response->add_hints(); - hint->set_key_representation(optimization_guide::proto::HOST); + hint->set_key_representation(proto::HOST); hint->set_key(url.host()); page_hint = hint->add_page_hints(); page_hint->set_page_pattern("anything/*"); @@ -1801,8 +1688,8 @@ run_loop = std::make_unique<base::RunLoop>(); hints_manager()->RemoveFetchedEntriesByHintKeys( - run_loop->QuitClosure(), - optimization_guide::proto::KeyRepresentation::FULL_URL, {url.spec()}); + run_loop->QuitClosure(), proto::KeyRepresentation::FULL_URL, + {url.spec()}); run_loop->Run(); // Both the host and url entries should have been removed to support upgrading @@ -1815,21 +1702,20 @@ int cache_duration_in_secs = 60; GURL url("https://host.com/r/cats"); - std::unique_ptr<optimization_guide::proto::GetHintsResponse> - get_hints_response = - std::make_unique<optimization_guide::proto::GetHintsResponse>(); + std::unique_ptr<proto::GetHintsResponse> get_hints_response = + std::make_unique<proto::GetHintsResponse>(); - optimization_guide::proto::Hint* hint = get_hints_response->add_hints(); + proto::Hint* hint = get_hints_response->add_hints(); hint->set_key(url.spec()); - hint->set_key_representation(optimization_guide::proto::FULL_URL); + hint->set_key_representation(proto::FULL_URL); hint->mutable_max_cache_duration()->set_seconds(cache_duration_in_secs); - optimization_guide::proto::PageHint* page_hint = hint->add_page_hints(); + proto::PageHint* page_hint = hint->add_page_hints(); page_hint->add_allowlisted_optimizations()->set_optimization_type( - optimization_guide::proto::PERFORMANCE_HINTS); + proto::PERFORMANCE_HINTS); page_hint->set_page_pattern("whatever/*"); hint = get_hints_response->add_hints(); - hint->set_key_representation(optimization_guide::proto::HOST); + hint->set_key_representation(proto::HOST); hint->set_key(url.host()); page_hint = hint->add_page_hints(); page_hint->set_page_pattern("anything/*"); @@ -1851,58 +1737,54 @@ TEST_F(HintsManagerTest, HintFetcherPrefUpdated_URL) { base::Time expiry = base::Time::Now() + base::Hours(1); - optimization_guide::HintsFetcher::AddFetchedHostForTesting( - pref_service(), "host-key.com", expiry); - optimization_guide::HintsFetcher::AddFetchedHostForTesting( - pref_service(), "url-key.com", expiry); + HintsFetcher::AddFetchedHostForTesting(pref_service(), "host-key.com", + expiry); + HintsFetcher::AddFetchedHostForTesting(pref_service(), "url-key.com", expiry); - ASSERT_TRUE(optimization_guide::HintsFetcher::WasHostCoveredByFetch( - pref_service(), "host-key.com")); - ASSERT_TRUE(optimization_guide::HintsFetcher::WasHostCoveredByFetch( - pref_service(), "url-key.com")); + ASSERT_TRUE( + HintsFetcher::WasHostCoveredByFetch(pref_service(), "host-key.com")); + ASSERT_TRUE( + HintsFetcher::WasHostCoveredByFetch(pref_service(), "url-key.com")); std::unique_ptr<base::RunLoop> run_loop = std::make_unique<base::RunLoop>(); hints_manager()->RemoveFetchedEntriesByHintKeys( - run_loop->QuitClosure(), - optimization_guide::proto::KeyRepresentation::FULL_URL, + run_loop->QuitClosure(), proto::KeyRepresentation::FULL_URL, { GURL("https://host-key.com/page").spec(), GURL("https://url-key.com/page").spec(), }); run_loop->Run(); - EXPECT_FALSE(optimization_guide::HintsFetcher::WasHostCoveredByFetch( - pref_service(), "host-key.com")); - EXPECT_FALSE(optimization_guide::HintsFetcher::WasHostCoveredByFetch( - pref_service(), "url-key.com")); + EXPECT_FALSE( + HintsFetcher::WasHostCoveredByFetch(pref_service(), "host-key.com")); + EXPECT_FALSE( + HintsFetcher::WasHostCoveredByFetch(pref_service(), "url-key.com")); } TEST_F(HintsManagerTest, HintFetcherPrefUpdated_Hosts) { base::Time expiry = base::Time::Now() + base::Hours(1); - optimization_guide::HintsFetcher::AddFetchedHostForTesting( - pref_service(), "host-key.com", expiry); - optimization_guide::HintsFetcher::AddFetchedHostForTesting( - pref_service(), "url-key.com", expiry); + HintsFetcher::AddFetchedHostForTesting(pref_service(), "host-key.com", + expiry); + HintsFetcher::AddFetchedHostForTesting(pref_service(), "url-key.com", expiry); - ASSERT_TRUE(optimization_guide::HintsFetcher::WasHostCoveredByFetch( - pref_service(), "host-key.com")); - ASSERT_TRUE(optimization_guide::HintsFetcher::WasHostCoveredByFetch( - pref_service(), "url-key.com")); + ASSERT_TRUE( + HintsFetcher::WasHostCoveredByFetch(pref_service(), "host-key.com")); + ASSERT_TRUE( + HintsFetcher::WasHostCoveredByFetch(pref_service(), "url-key.com")); std::unique_ptr<base::RunLoop> run_loop = std::make_unique<base::RunLoop>(); hints_manager()->RemoveFetchedEntriesByHintKeys( - run_loop->QuitClosure(), - optimization_guide::proto::KeyRepresentation::HOST, + run_loop->QuitClosure(), proto::KeyRepresentation::HOST, { "host-key.com", "url-key.com", }); run_loop->Run(); - EXPECT_FALSE(optimization_guide::HintsFetcher::WasHostCoveredByFetch( - pref_service(), "host-key.com")); - EXPECT_FALSE(optimization_guide::HintsFetcher::WasHostCoveredByFetch( - pref_service(), "url-key.com")); + EXPECT_FALSE( + HintsFetcher::WasHostCoveredByFetch(pref_service(), "host-key.com")); + EXPECT_FALSE( + HintsFetcher::WasHostCoveredByFetch(pref_service(), "url-key.com")); } class HintsManagerFetchingTest : public HintsManagerTest { @@ -1911,12 +1793,11 @@ scoped_list_.InitWithFeaturesAndParameters( { { - optimization_guide::features::kRemoteOptimizationGuideFetching, + features::kRemoteOptimizationGuideFetching, {{"max_concurrent_page_navigation_fetches", "2"}}, }, }, - {optimization_guide::features:: - kRemoteOptimizationGuideFetchingAnonymousDataConsent}); + {features::kRemoteOptimizationGuideFetchingAnonymousDataConsent}); } private: @@ -1928,10 +1809,9 @@ TEST_F(HintsManagerFetchingTest, HintsFetchNotAllowedIfFeatureIsEnabledButUserNotAllowed) { base::CommandLine::ForCurrentProcess()->RemoveSwitch( - optimization_guide::switches::kDisableCheckingUserPermissionsForTesting); + switches::kDisableCheckingUserPermissionsForTesting); CreateHintsManager(/*top_host_provider=*/nullptr); - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::DEFER_ALL_SCRIPT}); + hints_manager()->RegisterOptimizationTypes({proto::DEFER_ALL_SCRIPT}); hints_manager()->SetHintsFetcherFactoryForTesting( BuildTestHintsFetcherFactory( {HintsFetcherEndState::kFetchSuccessWithHostHints})); @@ -1950,7 +1830,7 @@ std::vector<std::string>({"example1.com", "example2.com"})); base::CommandLine::ForCurrentProcess()->AppendSwitch( - optimization_guide::switches::kDisableCheckingUserPermissionsForTesting); + switches::kDisableCheckingUserPermissionsForTesting); CreateHintsManager(top_host_provider.get()); hints_manager()->SetHintsFetcherFactoryForTesting( @@ -1967,26 +1847,25 @@ TEST_F(HintsManagerFetchingTest, OnlyFilterTypesRegisteredHintsFetchNotAttempted) { - optimization_guide::proto::Configuration config; - optimization_guide::BloomFilter allowlist_bloom_filter( - kDefaultHostBloomFilterNumHashFunctions, kDefaultHostBloomFilterNumBits); + proto::Configuration config; + BloomFilter allowlist_bloom_filter(kDefaultHostBloomFilterNumHashFunctions, + kDefaultHostBloomFilterNumBits); PopulateBloomFilterWithDefaultHost(&allowlist_bloom_filter); - AddBloomFilterToConfig( - optimization_guide::proto::LITE_PAGE_REDIRECT, allowlist_bloom_filter, - kDefaultHostBloomFilterNumHashFunctions, kDefaultHostBloomFilterNumBits, - /*is_allowlist=*/true, &config); + AddBloomFilterToConfig(proto::LITE_PAGE_REDIRECT, allowlist_bloom_filter, + kDefaultHostBloomFilterNumHashFunctions, + kDefaultHostBloomFilterNumBits, + /*is_allowlist=*/true, &config); std::unique_ptr<FakeTopHostProvider> top_host_provider = std::make_unique<FakeTopHostProvider>( std::vector<std::string>({"example1.com", "example2.com"})); base::CommandLine::ForCurrentProcess()->AppendSwitch( - optimization_guide::switches::kDisableCheckingUserPermissionsForTesting); + switches::kDisableCheckingUserPermissionsForTesting); CreateHintsManager(top_host_provider.get()); ProcessHints(config, "1.0.0.0"); - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::LITE_PAGE_REDIRECT}); + hints_manager()->RegisterOptimizationTypes({proto::LITE_PAGE_REDIRECT}); hints_manager()->SetHintsFetcherFactoryForTesting( BuildTestHintsFetcherFactory( {HintsFetcherEndState::kFetchSuccessWithHostHints})); @@ -2002,13 +1881,12 @@ auto scoped_feature_list = SetUpDeferStartupActiveTabsHintsFetch(false); base::HistogramTester histogram_tester; base::CommandLine::ForCurrentProcess()->AppendSwitch( - optimization_guide::switches::kDisableCheckingUserPermissionsForTesting); + switches::kDisableCheckingUserPermissionsForTesting); std::unique_ptr<FakeTopHostProvider> top_host_provider = std::make_unique<FakeTopHostProvider>(std::vector<std::string>({})); CreateHintsManager(top_host_provider.get()); - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::DEFER_ALL_SCRIPT}); + hints_manager()->RegisterOptimizationTypes({proto::DEFER_ALL_SCRIPT}); hints_manager()->SetHintsFetcherFactoryForTesting( BuildTestHintsFetcherFactory( {HintsFetcherEndState::kFetchSuccessWithHostHints})); @@ -2038,13 +1916,12 @@ auto scoped_feature_list = SetUpDeferStartupActiveTabsHintsFetch(false); base::HistogramTester histogram_tester; base::CommandLine::ForCurrentProcess()->AppendSwitch( - optimization_guide::switches::kDisableCheckingUserPermissionsForTesting); + switches::kDisableCheckingUserPermissionsForTesting); std::unique_ptr<FakeTopHostProvider> top_host_provider = std::make_unique<FakeTopHostProvider>(std::vector<std::string>({})); CreateHintsManager(top_host_provider.get()); - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::DEFER_ALL_SCRIPT}); + hints_manager()->RegisterOptimizationTypes({proto::DEFER_ALL_SCRIPT}); hints_manager()->SetHintsFetcherFactoryForTesting( BuildTestHintsFetcherFactory( {HintsFetcherEndState::kFetchSuccessWithHostHints})); @@ -2087,13 +1964,12 @@ auto scoped_feature_list = SetUpDeferStartupActiveTabsHintsFetch(false); base::HistogramTester histogram_tester; base::CommandLine::ForCurrentProcess()->AppendSwitch( - optimization_guide::switches::kDisableCheckingUserPermissionsForTesting); + switches::kDisableCheckingUserPermissionsForTesting); std::unique_ptr<FakeTopHostProvider> top_host_provider = std::make_unique<FakeTopHostProvider>(std::vector<std::string>({})); CreateHintsManager(top_host_provider.get()); - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::DEFER_ALL_SCRIPT}); + hints_manager()->RegisterOptimizationTypes({proto::DEFER_ALL_SCRIPT}); hints_manager()->SetHintsFetcherFactoryForTesting( BuildTestHintsFetcherFactory( {HintsFetcherEndState::kFetchSuccessWithHostHints})); @@ -2133,13 +2009,12 @@ base::HistogramTester histogram_tester; base::CommandLine::ForCurrentProcess()->AppendSwitch( - optimization_guide::switches::kDisableCheckingUserPermissionsForTesting); + switches::kDisableCheckingUserPermissionsForTesting); std::unique_ptr<FakeTopHostProvider> top_host_provider = std::make_unique<FakeTopHostProvider>(std::vector<std::string>({})); CreateHintsManager(top_host_provider.get()); - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::DEFER_ALL_SCRIPT}); + hints_manager()->RegisterOptimizationTypes({proto::DEFER_ALL_SCRIPT}); hints_manager()->SetHintsFetcherFactoryForTesting( BuildTestHintsFetcherFactory( {HintsFetcherEndState::kFetchSuccessWithHostHints})); @@ -2173,24 +2048,23 @@ TEST_F(HintsManagerFetchingTest, HintsFetched_RegisteredOptimizationTypes_AllWithOptFilter) { base::CommandLine::ForCurrentProcess()->AppendSwitch( - optimization_guide::switches::kDisableCheckingUserPermissionsForTesting); - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::LITE_PAGE_REDIRECT}); + switches::kDisableCheckingUserPermissionsForTesting); + hints_manager()->RegisterOptimizationTypes({proto::LITE_PAGE_REDIRECT}); - optimization_guide::proto::Configuration config; - optimization_guide::BloomFilter allowlist_bloom_filter( - kDefaultHostBloomFilterNumHashFunctions, kDefaultHostBloomFilterNumBits); + proto::Configuration config; + BloomFilter allowlist_bloom_filter(kDefaultHostBloomFilterNumHashFunctions, + kDefaultHostBloomFilterNumBits); PopulateBloomFilterWithDefaultHost(&allowlist_bloom_filter); - AddBloomFilterToConfig( - optimization_guide::proto::LITE_PAGE_REDIRECT, allowlist_bloom_filter, - kDefaultHostBloomFilterNumHashFunctions, kDefaultHostBloomFilterNumBits, - /*is_allowlist=*/true, &config); + AddBloomFilterToConfig(proto::LITE_PAGE_REDIRECT, allowlist_bloom_filter, + kDefaultHostBloomFilterNumHashFunctions, + kDefaultHostBloomFilterNumBits, + /*is_allowlist=*/true, &config); ProcessHints(config, "1.0.0.0"); // Set to online so fetch is activated. SetConnectionOnline(); - auto navigation_data = CreateTestNavigationData( - url_without_hints(), {optimization_guide::proto::LITE_PAGE_REDIRECT}); + auto navigation_data = CreateTestNavigationData(url_without_hints(), + {proto::LITE_PAGE_REDIRECT}); base::HistogramTester histogram_tester; CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing()); RunUntilIdle(); @@ -2205,15 +2079,14 @@ TEST_F(HintsManagerFetchingTest, HintsFetchedAtNavigationTime) { base::CommandLine::ForCurrentProcess()->AppendSwitch( - optimization_guide::switches::kDisableCheckingUserPermissionsForTesting); - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::DEFER_ALL_SCRIPT}); + switches::kDisableCheckingUserPermissionsForTesting); + hints_manager()->RegisterOptimizationTypes({proto::DEFER_ALL_SCRIPT}); InitializeWithDefaultConfig("1.0.0.0"); // Set to online so fetch is activated. SetConnectionOnline(); - auto navigation_data = CreateTestNavigationData( - url_without_hints(), {optimization_guide::proto::DEFER_ALL_SCRIPT}); + auto navigation_data = + CreateTestNavigationData(url_without_hints(), {proto::DEFER_ALL_SCRIPT}); base::HistogramTester histogram_tester; CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing()); RunUntilIdle(); @@ -2224,23 +2097,20 @@ "OptimizationGuide.HintsFetcher.GetHintsRequest.UrlCount", 1, 1); histogram_tester.ExpectUniqueSample( "OptimizationGuide.HintsManager.RaceNavigationFetchAttemptStatus", - optimization_guide::RaceNavigationFetchAttemptStatus:: - kRaceNavigationFetchHostAndURL, - 1); + RaceNavigationFetchAttemptStatus::kRaceNavigationFetchHostAndURL, 1); } TEST_F(HintsManagerFetchingTest, HintsFetchedAtNavigationTime_FetchNotAttempted) { base::CommandLine::ForCurrentProcess()->AppendSwitch( - optimization_guide::switches::kDisableCheckingUserPermissionsForTesting); - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::DEFER_ALL_SCRIPT}); + switches::kDisableCheckingUserPermissionsForTesting); + hints_manager()->RegisterOptimizationTypes({proto::DEFER_ALL_SCRIPT}); InitializeWithDefaultConfig("1.0.0.0"); // Set to online so fetch is activated. SetConnectionOnline(); - auto navigation_data = CreateTestNavigationData( - url_without_hints(), {optimization_guide::proto::DEFER_ALL_SCRIPT}); + auto navigation_data = + CreateTestNavigationData(url_without_hints(), {proto::DEFER_ALL_SCRIPT}); hints_manager()->SetHintsFetcherFactoryForTesting( BuildTestHintsFetcherFactory({HintsFetcherEndState::kFetchFailed})); base::HistogramTester histogram_tester; @@ -2253,17 +2123,14 @@ "OptimizationGuide.HintsFetcher.GetHintsRequest.UrlCount", 0); histogram_tester.ExpectUniqueSample( "OptimizationGuide.HintsManager.RaceNavigationFetchAttemptStatus", - optimization_guide::RaceNavigationFetchAttemptStatus:: - kRaceNavigationFetchNotAttempted, - 1); + RaceNavigationFetchAttemptStatus::kRaceNavigationFetchNotAttempted, 1); } TEST_F(HintsManagerFetchingTest, HintsFetchedAtNavigationTime_HasComponentHintButNotFetched) { base::CommandLine::ForCurrentProcess()->AppendSwitch( - optimization_guide::switches::kDisableCheckingUserPermissionsForTesting); - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::DEFER_ALL_SCRIPT}); + switches::kDisableCheckingUserPermissionsForTesting); + hints_manager()->RegisterOptimizationTypes({proto::DEFER_ALL_SCRIPT}); InitializeWithDefaultConfig("1.0.0.0"); hints_manager()->SetHintsFetcherFactoryForTesting( BuildTestHintsFetcherFactory( @@ -2271,8 +2138,8 @@ // Set to online so fetch is activated. SetConnectionOnline(); - auto navigation_data = CreateTestNavigationData( - url_with_hints(), {optimization_guide::proto::DEFER_ALL_SCRIPT}); + auto navigation_data = + CreateTestNavigationData(url_with_hints(), {proto::DEFER_ALL_SCRIPT}); base::HistogramTester histogram_tester; CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing()); RunUntilIdle(); @@ -2280,42 +2147,38 @@ "OptimizationGuide.HintsFetcher.GetHintsRequest.HostCount", 0); histogram_tester.ExpectUniqueSample( "OptimizationGuide.HintsManager.RaceNavigationFetchAttemptStatus", - optimization_guide::RaceNavigationFetchAttemptStatus:: - kRaceNavigationFetchURL, - 1); + RaceNavigationFetchAttemptStatus::kRaceNavigationFetchURL, 1); } TEST_F(HintsManagerFetchingTest, HintsFetchedAtNavigationTime_DoesNotRemoveManualOverride) { GURL example_url("http://www.example.com/hasoverride"); - optimization_guide::proto::Configuration config; - optimization_guide::proto::Hint* hint = config.add_hints(); + proto::Configuration config; + proto::Hint* hint = config.add_hints(); hint->set_key(example_url.spec()); - hint->set_key_representation(optimization_guide::proto::FULL_URL); - optimization_guide::proto::PageHint* page_hint = hint->add_page_hints(); + hint->set_key_representation(proto::FULL_URL); + proto::PageHint* page_hint = hint->add_page_hints(); page_hint->set_page_pattern("*"); - optimization_guide::proto::Optimization* opt = - page_hint->add_allowlisted_optimizations(); - opt->set_optimization_type(optimization_guide::proto::DEFER_ALL_SCRIPT); + proto::Optimization* opt = page_hint->add_allowlisted_optimizations(); + opt->set_optimization_type(proto::DEFER_ALL_SCRIPT); std::string encoded_config; config.SerializeToString(&encoded_config); base::Base64Encode(encoded_config, &encoded_config); base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( - optimization_guide::switches::kHintsProtoOverride, encoded_config); + switches::kHintsProtoOverride, encoded_config); // Re-create hints manager with override. CreateHintsManager(/*top_host_provider=*/nullptr); base::CommandLine::ForCurrentProcess()->AppendSwitch( - optimization_guide::switches::kDisableCheckingUserPermissionsForTesting); - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::DEFER_ALL_SCRIPT}); + switches::kDisableCheckingUserPermissionsForTesting); + hints_manager()->RegisterOptimizationTypes({proto::DEFER_ALL_SCRIPT}); // Set to online so fetch is activated. SetConnectionOnline(); - auto navigation_data = CreateTestNavigationData( - example_url, {optimization_guide::proto::DEFER_ALL_SCRIPT}); + auto navigation_data = + CreateTestNavigationData(example_url, {proto::DEFER_ALL_SCRIPT}); base::HistogramTester histogram_tester; CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing()); RunUntilIdle(); @@ -2325,25 +2188,21 @@ "OptimizationGuide.HintsFetcher.GetHintsRequest.UrlCount", 0, 1); histogram_tester.ExpectUniqueSample( "OptimizationGuide.HintsManager.RaceNavigationFetchAttemptStatus", - optimization_guide::RaceNavigationFetchAttemptStatus:: - kRaceNavigationFetchHost, - 1); + RaceNavigationFetchAttemptStatus::kRaceNavigationFetchHost, 1); - optimization_guide::OptimizationTypeDecision optimization_type_decision = - hints_manager()->CanApplyOptimization( - navigation_data->navigation_url(), - optimization_guide::proto::DEFER_ALL_SCRIPT, - /*optimization_metadata=*/nullptr); + OptimizationTypeDecision optimization_type_decision = + hints_manager()->CanApplyOptimization(navigation_data->navigation_url(), + proto::DEFER_ALL_SCRIPT, + /*optimization_metadata=*/nullptr); EXPECT_EQ(optimization_type_decision, - optimization_guide::OptimizationTypeDecision::kAllowedByHint); + OptimizationTypeDecision::kAllowedByHint); } TEST_F(HintsManagerFetchingTest, URLHintsNotFetchedAtNavigationTime) { base::CommandLine::ForCurrentProcess()->AppendSwitch( - optimization_guide::switches::kDisableCheckingUserPermissionsForTesting); - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::DEFER_ALL_SCRIPT}); + switches::kDisableCheckingUserPermissionsForTesting); + hints_manager()->RegisterOptimizationTypes({proto::DEFER_ALL_SCRIPT}); InitializeWithDefaultConfig("1.0.0.0"); hints_manager()->SetHintsFetcherFactoryForTesting( BuildTestHintsFetcherFactory( @@ -2354,8 +2213,8 @@ { base::HistogramTester histogram_tester; - auto navigation_data = CreateTestNavigationData( - url_with_hints(), {optimization_guide::proto::DEFER_ALL_SCRIPT}); + auto navigation_data = + CreateTestNavigationData(url_with_hints(), {proto::DEFER_ALL_SCRIPT}); CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing()); RunUntilIdle(); @@ -2366,14 +2225,11 @@ // Make sure navigation data is populated correctly. EXPECT_TRUE(navigation_data->hints_fetch_latency().has_value()); EXPECT_EQ(navigation_data->hints_fetch_attempt_status(), - optimization_guide::RaceNavigationFetchAttemptStatus:: - kRaceNavigationFetchURL); + RaceNavigationFetchAttemptStatus::kRaceNavigationFetchURL); histogram_tester.ExpectBucketCount( "OptimizationGuide.HintsManager.RaceNavigationFetchAttemptStatus", - optimization_guide::RaceNavigationFetchAttemptStatus:: - kRaceNavigationFetchURL, - 1); + RaceNavigationFetchAttemptStatus::kRaceNavigationFetchURL, 1); histogram_tester.ExpectUniqueSample( "OptimizationGuide.HintsManager." "PageNavigationHintsReturnedBeforeDataFlushed", @@ -2383,22 +2239,20 @@ { base::HistogramTester histogram_tester; - auto navigation_data = CreateTestNavigationData( - url_with_hints(), {optimization_guide::proto::DEFER_ALL_SCRIPT}); + auto navigation_data = + CreateTestNavigationData(url_with_hints(), {proto::DEFER_ALL_SCRIPT}); CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing()); RunUntilIdle(); histogram_tester.ExpectBucketCount( "OptimizationGuide.HintsManager.RaceNavigationFetchAttemptStatus", - optimization_guide::RaceNavigationFetchAttemptStatus:: - kRaceNavigationFetchNotAttempted, - 1); + RaceNavigationFetchAttemptStatus::kRaceNavigationFetchNotAttempted, 1); // Make sure navigation data is populated correctly. EXPECT_FALSE(navigation_data->hints_fetch_latency().has_value()); - EXPECT_EQ(navigation_data->hints_fetch_attempt_status(), - optimization_guide::RaceNavigationFetchAttemptStatus:: - kRaceNavigationFetchNotAttempted); + EXPECT_EQ( + navigation_data->hints_fetch_attempt_status(), + RaceNavigationFetchAttemptStatus::kRaceNavigationFetchNotAttempted); histogram_tester.ExpectTotalCount( "OptimizationGuide.HintsManager." "PageNavigationHintsReturnedBeforeDataFlushed", @@ -2408,9 +2262,8 @@ TEST_F(HintsManagerFetchingTest, URLWithNoHintsNotRefetchedAtNavigationTime) { base::CommandLine::ForCurrentProcess()->AppendSwitch( - optimization_guide::switches::kDisableCheckingUserPermissionsForTesting); - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::DEFER_ALL_SCRIPT}); + switches::kDisableCheckingUserPermissionsForTesting); + hints_manager()->RegisterOptimizationTypes({proto::DEFER_ALL_SCRIPT}); InitializeWithDefaultConfig("1.0.0.0"); hints_manager()->SetHintsFetcherFactoryForTesting( BuildTestHintsFetcherFactory( @@ -2421,8 +2274,8 @@ base::HistogramTester histogram_tester; { - auto navigation_data = CreateTestNavigationData( - url_without_hints(), {optimization_guide::proto::DEFER_ALL_SCRIPT}); + auto navigation_data = CreateTestNavigationData(url_without_hints(), + {proto::DEFER_ALL_SCRIPT}); CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing()); RunUntilIdle(); @@ -2432,67 +2285,57 @@ // Make sure navigation data is populated correctly. EXPECT_TRUE(navigation_data->hints_fetch_latency().has_value()); EXPECT_EQ(navigation_data->hints_fetch_attempt_status(), - optimization_guide::RaceNavigationFetchAttemptStatus:: - kRaceNavigationFetchHostAndURL); + RaceNavigationFetchAttemptStatus::kRaceNavigationFetchHostAndURL); histogram_tester.ExpectBucketCount( "OptimizationGuide.HintsManager.RaceNavigationFetchAttemptStatus", - optimization_guide::RaceNavigationFetchAttemptStatus:: - kRaceNavigationFetchHostAndURL, - 1); + RaceNavigationFetchAttemptStatus::kRaceNavigationFetchHostAndURL, 1); RunUntilIdle(); } { - auto navigation_data = CreateTestNavigationData( - url_without_hints(), {optimization_guide::proto::DEFER_ALL_SCRIPT}); + auto navigation_data = CreateTestNavigationData(url_without_hints(), + {proto::DEFER_ALL_SCRIPT}); base::RunLoop run_loop; - navigation_data = CreateTestNavigationData( - url_without_hints(), {optimization_guide::proto::DEFER_ALL_SCRIPT}); + navigation_data = CreateTestNavigationData(url_without_hints(), + {proto::DEFER_ALL_SCRIPT}); CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing()); RunUntilIdle(); histogram_tester.ExpectBucketCount( "OptimizationGuide.HintsManager.RaceNavigationFetchAttemptStatus", - optimization_guide::RaceNavigationFetchAttemptStatus:: - kRaceNavigationFetchHost, - 1); + RaceNavigationFetchAttemptStatus::kRaceNavigationFetchHost, 1); EXPECT_TRUE(navigation_data->hints_fetch_latency().has_value()); EXPECT_EQ(navigation_data->hints_fetch_attempt_status(), - optimization_guide::RaceNavigationFetchAttemptStatus:: - kRaceNavigationFetchHost); + RaceNavigationFetchAttemptStatus::kRaceNavigationFetchHost); } } TEST_F(HintsManagerFetchingTest, CanApplyOptimizationCalledMidFetch) { base::CommandLine::ForCurrentProcess()->AppendSwitch( - optimization_guide::switches::kDisableCheckingUserPermissionsForTesting); - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::DEFER_ALL_SCRIPT}); + switches::kDisableCheckingUserPermissionsForTesting); + hints_manager()->RegisterOptimizationTypes({proto::DEFER_ALL_SCRIPT}); InitializeWithDefaultConfig("1.0.0.0"); // Set to online so fetch is activated. SetConnectionOnline(); - auto navigation_data = CreateTestNavigationData( - url_without_hints(), {optimization_guide::proto::DEFER_ALL_SCRIPT}); + auto navigation_data = + CreateTestNavigationData(url_without_hints(), {proto::DEFER_ALL_SCRIPT}); CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing()); - optimization_guide::OptimizationTypeDecision optimization_type_decision = - hints_manager()->CanApplyOptimization( - navigation_data->navigation_url(), - optimization_guide::proto::DEFER_ALL_SCRIPT, - /*optimization_metadata=*/nullptr); + OptimizationTypeDecision optimization_type_decision = + hints_manager()->CanApplyOptimization(navigation_data->navigation_url(), + proto::DEFER_ALL_SCRIPT, + /*optimization_metadata=*/nullptr); EXPECT_EQ(optimization_type_decision, - optimization_guide::OptimizationTypeDecision:: - kHintFetchStartedButNotAvailableInTime); + OptimizationTypeDecision::kHintFetchStartedButNotAvailableInTime); } TEST_F(HintsManagerFetchingTest, CanApplyOptimizationCalledPostFetchButNoHintsCameBack) { base::CommandLine::ForCurrentProcess()->AppendSwitch( - optimization_guide::switches::kDisableCheckingUserPermissionsForTesting); - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::DEFER_ALL_SCRIPT}); + switches::kDisableCheckingUserPermissionsForTesting); + hints_manager()->RegisterOptimizationTypes({proto::DEFER_ALL_SCRIPT}); InitializeWithDefaultConfig("1.0.0.0"); hints_manager()->SetHintsFetcherFactoryForTesting( @@ -2501,27 +2344,25 @@ // Set to online so fetch is activated. SetConnectionOnline(); - auto navigation_data = CreateTestNavigationData( - url_without_hints(), {optimization_guide::proto::DEFER_ALL_SCRIPT}); + auto navigation_data = + CreateTestNavigationData(url_without_hints(), {proto::DEFER_ALL_SCRIPT}); CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing()); RunUntilIdle(); - optimization_guide::OptimizationTypeDecision optimization_type_decision = - hints_manager()->CanApplyOptimization( - navigation_data->navigation_url(), - optimization_guide::proto::DEFER_ALL_SCRIPT, - /*optimization_metadata=*/nullptr); + OptimizationTypeDecision optimization_type_decision = + hints_manager()->CanApplyOptimization(navigation_data->navigation_url(), + proto::DEFER_ALL_SCRIPT, + /*optimization_metadata=*/nullptr); EXPECT_EQ(optimization_type_decision, - optimization_guide::OptimizationTypeDecision::kNoHintAvailable); + OptimizationTypeDecision::kNoHintAvailable); } TEST_F(HintsManagerFetchingTest, CanApplyOptimizationCalledPostFetchButFetchFailed) { base::CommandLine::ForCurrentProcess()->AppendSwitch( - optimization_guide::switches::kDisableCheckingUserPermissionsForTesting); - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::DEFER_ALL_SCRIPT}); + switches::kDisableCheckingUserPermissionsForTesting); + hints_manager()->RegisterOptimizationTypes({proto::DEFER_ALL_SCRIPT}); InitializeWithDefaultConfig("1.0.0.0"); hints_manager()->SetHintsFetcherFactoryForTesting( @@ -2529,27 +2370,25 @@ // Set to online so fetch is activated. SetConnectionOnline(); - auto navigation_data = CreateTestNavigationData( - url_without_hints(), {optimization_guide::proto::DEFER_ALL_SCRIPT}); + auto navigation_data = + CreateTestNavigationData(url_without_hints(), {proto::DEFER_ALL_SCRIPT}); CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing()); RunUntilIdle(); - optimization_guide::OptimizationTypeDecision optimization_type_decision = - hints_manager()->CanApplyOptimization( - navigation_data->navigation_url(), - optimization_guide::proto::DEFER_ALL_SCRIPT, - /*optimization_metadata=*/nullptr); + OptimizationTypeDecision optimization_type_decision = + hints_manager()->CanApplyOptimization(navigation_data->navigation_url(), + proto::DEFER_ALL_SCRIPT, + /*optimization_metadata=*/nullptr); EXPECT_EQ(optimization_type_decision, - optimization_guide::OptimizationTypeDecision::kNoHintAvailable); + OptimizationTypeDecision::kNoHintAvailable); } TEST_F(HintsManagerFetchingTest, CanApplyOptimizationWithURLKeyedHintApplicableForOptimizationType) { base::CommandLine::ForCurrentProcess()->AppendSwitch( - optimization_guide::switches::kDisableCheckingUserPermissionsForTesting); - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::COMPRESS_PUBLIC_IMAGES}); + switches::kDisableCheckingUserPermissionsForTesting); + hints_manager()->RegisterOptimizationTypes({proto::COMPRESS_PUBLIC_IMAGES}); InitializeWithDefaultConfig("1.0.0"); hints_manager()->SetHintsFetcherFactoryForTesting( @@ -2558,22 +2397,21 @@ // Set to online so fetch is activated. SetConnectionOnline(); - auto navigation_data = CreateTestNavigationData( - url_with_url_keyed_hint(), {optimization_guide::proto::DEFER_ALL_SCRIPT}); + auto navigation_data = CreateTestNavigationData(url_with_url_keyed_hint(), + {proto::DEFER_ALL_SCRIPT}); // Make sure URL-keyed hint is fetched and processed. CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing()); RunUntilIdle(); - optimization_guide::OptimizationMetadata optimization_metadata; - optimization_guide::OptimizationTypeDecision optimization_type_decision = - hints_manager()->CanApplyOptimization( - navigation_data->navigation_url(), - optimization_guide::proto::COMPRESS_PUBLIC_IMAGES, - &optimization_metadata); + OptimizationMetadata optimization_metadata; + OptimizationTypeDecision optimization_type_decision = + hints_manager()->CanApplyOptimization(navigation_data->navigation_url(), + proto::COMPRESS_PUBLIC_IMAGES, + &optimization_metadata); // Make sure decisions are logged correctly and metadata is populated off // a URL-keyed hint. - EXPECT_EQ(optimization_guide::OptimizationTypeDecision::kAllowedByHint, + EXPECT_EQ(OptimizationTypeDecision::kAllowedByHint, optimization_type_decision); EXPECT_TRUE(optimization_metadata.public_image_metadata().has_value()); } @@ -2581,9 +2419,8 @@ TEST_F(HintsManagerFetchingTest, CanApplyOptimizationNotAllowedByURLButAllowedByHostKeyedHint) { base::CommandLine::ForCurrentProcess()->AppendSwitch( - optimization_guide::switches::kDisableCheckingUserPermissionsForTesting); - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::NOSCRIPT}); + switches::kDisableCheckingUserPermissionsForTesting); + hints_manager()->RegisterOptimizationTypes({proto::NOSCRIPT}); InitializeWithDefaultConfig("1.0.0.0"); @@ -2594,27 +2431,26 @@ hints_manager()->SetHintsFetcherFactoryForTesting( BuildTestHintsFetcherFactory( {HintsFetcherEndState::kFetchSuccessWithURLHints})); - auto navigation_data = CreateTestNavigationData( - url_with_url_keyed_hint(), {optimization_guide::proto::NOSCRIPT}); + auto navigation_data = + CreateTestNavigationData(url_with_url_keyed_hint(), {proto::NOSCRIPT}); CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing()); RunUntilIdle(); - optimization_guide::OptimizationMetadata optimization_metadata; - optimization_guide::OptimizationTypeDecision optimization_type_decision = + OptimizationMetadata optimization_metadata; + OptimizationTypeDecision optimization_type_decision = hints_manager()->CanApplyOptimization(navigation_data->navigation_url(), - optimization_guide::proto::NOSCRIPT, + proto::NOSCRIPT, &optimization_metadata); - EXPECT_EQ(optimization_guide::OptimizationTypeDecision::kAllowedByHint, + EXPECT_EQ(OptimizationTypeDecision::kAllowedByHint, optimization_type_decision); } TEST_F(HintsManagerFetchingTest, CanApplyOptimizationNotAllowedByURLOrHostKeyedHint) { base::CommandLine::ForCurrentProcess()->AppendSwitch( - optimization_guide::switches::kDisableCheckingUserPermissionsForTesting); - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::RESOURCE_LOADING}); + switches::kDisableCheckingUserPermissionsForTesting); + hints_manager()->RegisterOptimizationTypes({proto::RESOURCE_LOADING}); InitializeWithDefaultConfig("1.0.0.0"); @@ -2625,27 +2461,26 @@ hints_manager()->SetHintsFetcherFactoryForTesting( BuildTestHintsFetcherFactory( {HintsFetcherEndState::kFetchSuccessWithURLHints})); - auto navigation_data = CreateTestNavigationData( - url_with_url_keyed_hint(), {optimization_guide::proto::RESOURCE_LOADING}); + auto navigation_data = CreateTestNavigationData(url_with_url_keyed_hint(), + {proto::RESOURCE_LOADING}); CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing()); RunUntilIdle(); - optimization_guide::OptimizationMetadata optimization_metadata; - optimization_guide::OptimizationTypeDecision optimization_type_decision = - hints_manager()->CanApplyOptimization( - navigation_data->navigation_url(), - optimization_guide::proto::RESOURCE_LOADING, &optimization_metadata); + OptimizationMetadata optimization_metadata; + OptimizationTypeDecision optimization_type_decision = + hints_manager()->CanApplyOptimization(navigation_data->navigation_url(), + proto::RESOURCE_LOADING, + &optimization_metadata); - EXPECT_EQ(optimization_guide::OptimizationTypeDecision::kNotAllowedByHint, + EXPECT_EQ(OptimizationTypeDecision::kNotAllowedByHint, optimization_type_decision); } TEST_F(HintsManagerFetchingTest, CanApplyOptimizationNoURLKeyedHintOrHostKeyedHint) { base::CommandLine::ForCurrentProcess()->AppendSwitch( - optimization_guide::switches::kDisableCheckingUserPermissionsForTesting); - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::COMPRESS_PUBLIC_IMAGES}); + switches::kDisableCheckingUserPermissionsForTesting); + hints_manager()->RegisterOptimizationTypes({proto::COMPRESS_PUBLIC_IMAGES}); InitializeWithDefaultConfig("1.0.0.0"); @@ -2656,29 +2491,27 @@ BuildTestHintsFetcherFactory( {HintsFetcherEndState::kFetchSuccessWithNoHints})); auto navigation_data = CreateTestNavigationData( - url_without_hints(), {optimization_guide::proto::COMPRESS_PUBLIC_IMAGES}); + url_without_hints(), {proto::COMPRESS_PUBLIC_IMAGES}); // Attempt to fetch a hint but ensure nothing comes back. CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing()); RunUntilIdle(); - optimization_guide::OptimizationMetadata optimization_metadata; - optimization_guide::OptimizationTypeDecision optimization_type_decision = - hints_manager()->CanApplyOptimization( - navigation_data->navigation_url(), - optimization_guide::proto::COMPRESS_PUBLIC_IMAGES, - &optimization_metadata); + OptimizationMetadata optimization_metadata; + OptimizationTypeDecision optimization_type_decision = + hints_manager()->CanApplyOptimization(navigation_data->navigation_url(), + proto::COMPRESS_PUBLIC_IMAGES, + &optimization_metadata); - EXPECT_EQ(optimization_guide::OptimizationTypeDecision::kNoHintAvailable, + EXPECT_EQ(OptimizationTypeDecision::kNoHintAvailable, optimization_type_decision); } TEST_F(HintsManagerFetchingTest, CanApplyOptimizationCalledMidFetchForURLKeyedOptimization) { base::CommandLine::ForCurrentProcess()->AppendSwitch( - optimization_guide::switches::kDisableCheckingUserPermissionsForTesting); - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::COMPRESS_PUBLIC_IMAGES}); + switches::kDisableCheckingUserPermissionsForTesting); + hints_manager()->RegisterOptimizationTypes({proto::COMPRESS_PUBLIC_IMAGES}); InitializeWithDefaultConfig("1.0.0.0"); @@ -2688,29 +2521,26 @@ // Attempt to fetch a hint but call CanApplyOptimization right away to // simulate being mid-fetch. auto navigation_data = CreateTestNavigationData( - url_without_hints(), {optimization_guide::proto::COMPRESS_PUBLIC_IMAGES}); + url_without_hints(), {proto::COMPRESS_PUBLIC_IMAGES}); hints_manager()->SetHintsFetcherFactoryForTesting( BuildTestHintsFetcherFactory( {HintsFetcherEndState::kFetchSuccessWithHostHints})); CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing()); - optimization_guide::OptimizationMetadata optimization_metadata; - optimization_guide::OptimizationTypeDecision optimization_type_decision = - hints_manager()->CanApplyOptimization( - navigation_data->navigation_url(), - optimization_guide::proto::COMPRESS_PUBLIC_IMAGES, - &optimization_metadata); + OptimizationMetadata optimization_metadata; + OptimizationTypeDecision optimization_type_decision = + hints_manager()->CanApplyOptimization(navigation_data->navigation_url(), + proto::COMPRESS_PUBLIC_IMAGES, + &optimization_metadata); - EXPECT_EQ(optimization_guide::OptimizationTypeDecision:: - kHintFetchStartedButNotAvailableInTime, + EXPECT_EQ(OptimizationTypeDecision::kHintFetchStartedButNotAvailableInTime, optimization_type_decision); } TEST_F(HintsManagerFetchingTest, OnNavigationStartOrRedirectWontInitiateFetchIfAlreadyStartedForTheURL) { base::CommandLine::ForCurrentProcess()->AppendSwitch( - optimization_guide::switches::kDisableCheckingUserPermissionsForTesting); - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::RESOURCE_LOADING}); + switches::kDisableCheckingUserPermissionsForTesting); + hints_manager()->RegisterOptimizationTypes({proto::RESOURCE_LOADING}); InitializeWithDefaultConfig("1.0.0.0"); @@ -2719,8 +2549,8 @@ // Attempt to fetch a hint but initiate the next navigation right away to // simulate being mid-fetch. - auto navigation_data = CreateTestNavigationData( - url_without_hints(), {optimization_guide::proto::RESOURCE_LOADING}); + auto navigation_data = + CreateTestNavigationData(url_without_hints(), {proto::RESOURCE_LOADING}); { base::HistogramTester histogram_tester; hints_manager()->SetHintsFetcherFactoryForTesting( @@ -2729,9 +2559,7 @@ CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing()); histogram_tester.ExpectUniqueSample( "OptimizationGuide.HintsManager.RaceNavigationFetchAttemptStatus", - optimization_guide::RaceNavigationFetchAttemptStatus:: - kRaceNavigationFetchHostAndURL, - 1); + RaceNavigationFetchAttemptStatus::kRaceNavigationFetchHostAndURL, 1); histogram_tester.ExpectUniqueSample( "OptimizationGuide.HintsManager.ConcurrentPageNavigationFetches", 1, 1); } @@ -2744,8 +2572,7 @@ CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing()); histogram_tester.ExpectUniqueSample( "OptimizationGuide.HintsManager.RaceNavigationFetchAttemptStatus", - optimization_guide::RaceNavigationFetchAttemptStatus:: - kRaceNavigationFetchAlreadyInProgress, + RaceNavigationFetchAttemptStatus::kRaceNavigationFetchAlreadyInProgress, 1); // Should not be recorded since we are not attempting a new fetch. histogram_tester.ExpectTotalCount( @@ -2755,7 +2582,7 @@ navigation_data->set_hints_fetch_end(base::TimeTicks::Now()); EXPECT_TRUE(navigation_data->hints_fetch_latency().has_value()); EXPECT_EQ(navigation_data->hints_fetch_attempt_status(), - optimization_guide::RaceNavigationFetchAttemptStatus:: + RaceNavigationFetchAttemptStatus:: kRaceNavigationFetchAlreadyInProgress); } } @@ -2763,9 +2590,8 @@ TEST_F(HintsManagerFetchingTest, PageNavigationHintsFetcherGetsCleanedUpOnceHintsAreStored) { base::CommandLine::ForCurrentProcess()->AppendSwitch( - optimization_guide::switches::kDisableCheckingUserPermissionsForTesting); - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::RESOURCE_LOADING}); + switches::kDisableCheckingUserPermissionsForTesting); + hints_manager()->RegisterOptimizationTypes({proto::RESOURCE_LOADING}); InitializeWithDefaultConfig("1.0.0.0"); @@ -2777,16 +2603,14 @@ // Attempt to fetch a hint but initiate the next navigation right away to // simulate being mid-fetch. - auto navigation_data = CreateTestNavigationData( - url_without_hints(), {optimization_guide::proto::RESOURCE_LOADING}); + auto navigation_data = + CreateTestNavigationData(url_without_hints(), {proto::RESOURCE_LOADING}); { base::HistogramTester histogram_tester; CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing()); histogram_tester.ExpectUniqueSample( "OptimizationGuide.HintsManager.RaceNavigationFetchAttemptStatus", - optimization_guide::RaceNavigationFetchAttemptStatus:: - kRaceNavigationFetchHostAndURL, - 1); + RaceNavigationFetchAttemptStatus::kRaceNavigationFetchHostAndURL, 1); histogram_tester.ExpectUniqueSample( "OptimizationGuide.HintsManager.ConcurrentPageNavigationFetches", 1, 1); @@ -2799,9 +2623,7 @@ CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing()); histogram_tester.ExpectUniqueSample( "OptimizationGuide.HintsManager.RaceNavigationFetchAttemptStatus", - optimization_guide::RaceNavigationFetchAttemptStatus:: - kRaceNavigationFetchHost, - 1); + RaceNavigationFetchAttemptStatus::kRaceNavigationFetchHost, 1); histogram_tester.ExpectUniqueSample( "OptimizationGuide.HintsManager.ConcurrentPageNavigationFetches", 1, 1); } @@ -2810,9 +2632,8 @@ TEST_F(HintsManagerFetchingTest, PageNavigationHintsFetcherCanFetchMultipleThingsConcurrently) { base::CommandLine::ForCurrentProcess()->AppendSwitch( - optimization_guide::switches::kDisableCheckingUserPermissionsForTesting); - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::COMPRESS_PUBLIC_IMAGES}); + switches::kDisableCheckingUserPermissionsForTesting); + hints_manager()->RegisterOptimizationTypes({proto::COMPRESS_PUBLIC_IMAGES}); InitializeWithDefaultConfig("1.0.0.0"); @@ -2823,13 +2644,11 @@ {HintsFetcherEndState::kFetchSuccessWithURLHints})); auto navigation_data_with_hints = CreateTestNavigationData( - url_with_url_keyed_hint(), - {optimization_guide::proto::COMPRESS_PUBLIC_IMAGES}); + url_with_url_keyed_hint(), {proto::COMPRESS_PUBLIC_IMAGES}); auto navigation_data_without_hints = CreateTestNavigationData( - GURL("https://doesntmatter.com/"), - {optimization_guide::proto::COMPRESS_PUBLIC_IMAGES}); + GURL("https://doesntmatter.com/"), {proto::COMPRESS_PUBLIC_IMAGES}); auto navigation_data_without_hints2 = CreateTestNavigationData( - url_without_hints(), {optimization_guide::proto::COMPRESS_PUBLIC_IMAGES}); + url_without_hints(), {proto::COMPRESS_PUBLIC_IMAGES}); // Attempt to fetch a hint but initiate the next navigations right away to // simulate being mid-fetch. @@ -2855,9 +2674,8 @@ base::HistogramTester histogram_tester; base::CommandLine::ForCurrentProcess()->AppendSwitch( - optimization_guide::switches::kDisableCheckingUserPermissionsForTesting); - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::COMPRESS_PUBLIC_IMAGES}); + switches::kDisableCheckingUserPermissionsForTesting); + hints_manager()->RegisterOptimizationTypes({proto::COMPRESS_PUBLIC_IMAGES}); InitializeWithDefaultConfig("1.0.0.0"); // Set to online so fetch is activated. @@ -2867,24 +2685,20 @@ BuildTestHintsFetcherFactory( {HintsFetcherEndState::kFetchSuccessWithURLHints})); auto navigation_data = CreateTestNavigationData( - url_with_url_keyed_hint(), - {optimization_guide::proto::COMPRESS_PUBLIC_IMAGES}); + url_with_url_keyed_hint(), {proto::COMPRESS_PUBLIC_IMAGES}); CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing()); hints_manager()->CanApplyOptimizationAsync( - url_with_url_keyed_hint(), - optimization_guide::proto::COMPRESS_PUBLIC_IMAGES, - base::BindOnce( - [](optimization_guide::OptimizationGuideDecision decision, - const optimization_guide::OptimizationMetadata& metadata) { - EXPECT_EQ(optimization_guide::OptimizationGuideDecision::kTrue, - decision); - EXPECT_TRUE(metadata.public_image_metadata().has_value()); - })); + url_with_url_keyed_hint(), proto::COMPRESS_PUBLIC_IMAGES, + base::BindOnce([](OptimizationGuideDecision decision, + const OptimizationMetadata& metadata) { + EXPECT_EQ(OptimizationGuideDecision::kTrue, decision); + EXPECT_TRUE(metadata.public_image_metadata().has_value()); + })); RunUntilIdle(); histogram_tester.ExpectUniqueSample( "OptimizationGuide.ApplyDecisionAsync.CompressPublicImages", - optimization_guide::OptimizationTypeDecision::kAllowedByHint, 1); + OptimizationTypeDecision::kAllowedByHint, 1); } TEST_F(HintsManagerFetchingTest, @@ -2892,9 +2706,8 @@ base::HistogramTester histogram_tester; base::CommandLine::ForCurrentProcess()->AppendSwitch( - optimization_guide::switches::kDisableCheckingUserPermissionsForTesting); - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::COMPRESS_PUBLIC_IMAGES}); + switches::kDisableCheckingUserPermissionsForTesting); + hints_manager()->RegisterOptimizationTypes({proto::COMPRESS_PUBLIC_IMAGES}); InitializeWithDefaultConfig("1.0.0.0"); // Set to online so fetch is activated. @@ -2904,34 +2717,27 @@ BuildTestHintsFetcherFactory( {HintsFetcherEndState::kFetchSuccessWithURLHints})); auto navigation_data = CreateTestNavigationData( - url_with_url_keyed_hint(), - {optimization_guide::proto::COMPRESS_PUBLIC_IMAGES}); + url_with_url_keyed_hint(), {proto::COMPRESS_PUBLIC_IMAGES}); hints_manager()->CanApplyOptimizationAsync( - url_with_url_keyed_hint(), - optimization_guide::proto::COMPRESS_PUBLIC_IMAGES, - base::BindOnce( - [](optimization_guide::OptimizationGuideDecision decision, - const optimization_guide::OptimizationMetadata& metadata) { - EXPECT_EQ(optimization_guide::OptimizationGuideDecision::kTrue, - decision); - EXPECT_TRUE(metadata.public_image_metadata().has_value()); - })); + url_with_url_keyed_hint(), proto::COMPRESS_PUBLIC_IMAGES, + base::BindOnce([](OptimizationGuideDecision decision, + const OptimizationMetadata& metadata) { + EXPECT_EQ(OptimizationGuideDecision::kTrue, decision); + EXPECT_TRUE(metadata.public_image_metadata().has_value()); + })); hints_manager()->CanApplyOptimizationAsync( - url_with_url_keyed_hint(), - optimization_guide::proto::COMPRESS_PUBLIC_IMAGES, - base::BindOnce( - [](optimization_guide::OptimizationGuideDecision decision, - const optimization_guide::OptimizationMetadata& metadata) { - EXPECT_EQ(optimization_guide::OptimizationGuideDecision::kTrue, - decision); - EXPECT_TRUE(metadata.public_image_metadata().has_value()); - })); + url_with_url_keyed_hint(), proto::COMPRESS_PUBLIC_IMAGES, + base::BindOnce([](OptimizationGuideDecision decision, + const OptimizationMetadata& metadata) { + EXPECT_EQ(OptimizationGuideDecision::kTrue, decision); + EXPECT_TRUE(metadata.public_image_metadata().has_value()); + })); CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing()); RunUntilIdle(); histogram_tester.ExpectUniqueSample( "OptimizationGuide.ApplyDecisionAsync.CompressPublicImages", - optimization_guide::OptimizationTypeDecision::kAllowedByHint, 2); + OptimizationTypeDecision::kAllowedByHint, 2); } TEST_F( @@ -2940,9 +2746,8 @@ base::HistogramTester histogram_tester; base::CommandLine::ForCurrentProcess()->AppendSwitch( - optimization_guide::switches::kDisableCheckingUserPermissionsForTesting); - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::RESOURCE_LOADING}); + switches::kDisableCheckingUserPermissionsForTesting); + hints_manager()->RegisterOptimizationTypes({proto::RESOURCE_LOADING}); InitializeWithDefaultConfig("1.0.0.0"); // Set to online so fetch is activated. @@ -2951,22 +2756,20 @@ hints_manager()->SetHintsFetcherFactoryForTesting( BuildTestHintsFetcherFactory( {HintsFetcherEndState::kFetchSuccessWithURLHints})); - auto navigation_data = CreateTestNavigationData( - url_with_url_keyed_hint(), {optimization_guide::proto::RESOURCE_LOADING}); + auto navigation_data = CreateTestNavigationData(url_with_url_keyed_hint(), + {proto::RESOURCE_LOADING}); CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing()); hints_manager()->CanApplyOptimizationAsync( - url_with_url_keyed_hint(), optimization_guide::proto::RESOURCE_LOADING, - base::BindOnce( - [](optimization_guide::OptimizationGuideDecision decision, - const optimization_guide::OptimizationMetadata& metadata) { - EXPECT_EQ(optimization_guide::OptimizationGuideDecision::kFalse, - decision); - })); + url_with_url_keyed_hint(), proto::RESOURCE_LOADING, + base::BindOnce([](OptimizationGuideDecision decision, + const OptimizationMetadata& metadata) { + EXPECT_EQ(OptimizationGuideDecision::kFalse, decision); + })); RunUntilIdle(); histogram_tester.ExpectUniqueSample( "OptimizationGuide.ApplyDecisionAsync.ResourceLoading", - optimization_guide::OptimizationTypeDecision::kNotAllowedByHint, 1); + OptimizationTypeDecision::kNotAllowedByHint, 1); } TEST_F(HintsManagerFetchingTest, @@ -2974,9 +2777,8 @@ base::HistogramTester histogram_tester; base::CommandLine::ForCurrentProcess()->AppendSwitch( - optimization_guide::switches::kDisableCheckingUserPermissionsForTesting); - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::COMPRESS_PUBLIC_IMAGES}); + switches::kDisableCheckingUserPermissionsForTesting); + hints_manager()->RegisterOptimizationTypes({proto::COMPRESS_PUBLIC_IMAGES}); InitializeWithDefaultConfig("1.0.0.0"); @@ -2986,23 +2788,19 @@ hints_manager()->SetHintsFetcherFactoryForTesting( BuildTestHintsFetcherFactory({HintsFetcherEndState::kFetchFailed})); auto navigation_data = CreateTestNavigationData( - url_with_url_keyed_hint(), - {optimization_guide::proto::COMPRESS_PUBLIC_IMAGES}); + url_with_url_keyed_hint(), {proto::COMPRESS_PUBLIC_IMAGES}); hints_manager()->CanApplyOptimizationAsync( - url_with_url_keyed_hint(), - optimization_guide::proto::COMPRESS_PUBLIC_IMAGES, - base::BindOnce( - [](optimization_guide::OptimizationGuideDecision decision, - const optimization_guide::OptimizationMetadata& metadata) { - EXPECT_EQ(optimization_guide::OptimizationGuideDecision::kFalse, - decision); - })); + url_with_url_keyed_hint(), proto::COMPRESS_PUBLIC_IMAGES, + base::BindOnce([](OptimizationGuideDecision decision, + const OptimizationMetadata& metadata) { + EXPECT_EQ(OptimizationGuideDecision::kFalse, decision); + })); CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing()); RunUntilIdle(); histogram_tester.ExpectUniqueSample( "OptimizationGuide.ApplyDecisionAsync.CompressPublicImages", - optimization_guide::OptimizationTypeDecision::kNotAllowedByHint, 1); + OptimizationTypeDecision::kNotAllowedByHint, 1); } TEST_F(HintsManagerFetchingTest, @@ -3010,9 +2808,8 @@ base::HistogramTester histogram_tester; base::CommandLine::ForCurrentProcess()->AppendSwitch( - optimization_guide::switches::kDisableCheckingUserPermissionsForTesting); - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::COMPRESS_PUBLIC_IMAGES}); + switches::kDisableCheckingUserPermissionsForTesting); + hints_manager()->RegisterOptimizationTypes({proto::COMPRESS_PUBLIC_IMAGES}); InitializeWithDefaultConfig("1.0.0.0"); @@ -3023,26 +2820,22 @@ BuildTestHintsFetcherFactory( {HintsFetcherEndState::kFetchSuccessWithURLHints})); auto navigation_data = CreateTestNavigationData( - url_with_url_keyed_hint(), - {optimization_guide::proto::COMPRESS_PUBLIC_IMAGES}); + url_with_url_keyed_hint(), {proto::COMPRESS_PUBLIC_IMAGES}); CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing()); RunUntilIdle(); hints_manager()->CanApplyOptimizationAsync( - url_with_url_keyed_hint(), - optimization_guide::proto::COMPRESS_PUBLIC_IMAGES, - base::BindOnce( - [](optimization_guide::OptimizationGuideDecision decision, - const optimization_guide::OptimizationMetadata& metadata) { - EXPECT_EQ(optimization_guide::OptimizationGuideDecision::kTrue, - decision); - EXPECT_TRUE(metadata.public_image_metadata().has_value()); - })); + url_with_url_keyed_hint(), proto::COMPRESS_PUBLIC_IMAGES, + base::BindOnce([](OptimizationGuideDecision decision, + const OptimizationMetadata& metadata) { + EXPECT_EQ(OptimizationGuideDecision::kTrue, decision); + EXPECT_TRUE(metadata.public_image_metadata().has_value()); + })); RunUntilIdle(); histogram_tester.ExpectUniqueSample( "OptimizationGuide.ApplyDecisionAsync.CompressPublicImages", - optimization_guide::OptimizationTypeDecision::kAllowedByHint, 1); + OptimizationTypeDecision::kAllowedByHint, 1); } TEST_F(HintsManagerFetchingTest, @@ -3050,9 +2843,8 @@ base::HistogramTester histogram_tester; base::CommandLine::ForCurrentProcess()->AppendSwitch( - optimization_guide::switches::kDisableCheckingUserPermissionsForTesting); - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::PERFORMANCE_HINTS}); + switches::kDisableCheckingUserPermissionsForTesting); + hints_manager()->RegisterOptimizationTypes({proto::PERFORMANCE_HINTS}); InitializeWithDefaultConfig("1.0.0.0"); @@ -3062,25 +2854,22 @@ hints_manager()->SetHintsFetcherFactoryForTesting( BuildTestHintsFetcherFactory( {HintsFetcherEndState::kFetchSuccessWithURLHints})); - auto navigation_data = - CreateTestNavigationData(url_with_url_keyed_hint(), - {optimization_guide::proto::PERFORMANCE_HINTS}); + auto navigation_data = CreateTestNavigationData(url_with_url_keyed_hint(), + {proto::PERFORMANCE_HINTS}); CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing()); RunUntilIdle(); hints_manager()->CanApplyOptimizationAsync( - url_with_url_keyed_hint(), optimization_guide::proto::PERFORMANCE_HINTS, - base::BindOnce( - [](optimization_guide::OptimizationGuideDecision decision, - const optimization_guide::OptimizationMetadata& metadata) { - EXPECT_EQ(optimization_guide::OptimizationGuideDecision::kFalse, - decision); - })); + url_with_url_keyed_hint(), proto::PERFORMANCE_HINTS, + base::BindOnce([](OptimizationGuideDecision decision, + const OptimizationMetadata& metadata) { + EXPECT_EQ(OptimizationGuideDecision::kFalse, decision); + })); RunUntilIdle(); histogram_tester.ExpectUniqueSample( "OptimizationGuide.ApplyDecisionAsync.PerformanceHints", - optimization_guide::OptimizationTypeDecision::kNotAllowedByHint, 1); + OptimizationTypeDecision::kNotAllowedByHint, 1); } TEST_F(HintsManagerFetchingTest, @@ -3088,9 +2877,8 @@ base::HistogramTester histogram_tester; base::CommandLine::ForCurrentProcess()->AppendSwitch( - optimization_guide::switches::kDisableCheckingUserPermissionsForTesting); - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::PERFORMANCE_HINTS}); + switches::kDisableCheckingUserPermissionsForTesting); + hints_manager()->RegisterOptimizationTypes({proto::PERFORMANCE_HINTS}); InitializeWithDefaultConfig("1.0.0.0"); @@ -3100,22 +2888,20 @@ hints_manager()->SetHintsFetcherFactoryForTesting( BuildTestHintsFetcherFactory( {HintsFetcherEndState::kFetchSuccessWithNoHints})); - auto navigation_data = CreateTestNavigationData( - url_without_hints(), {optimization_guide::proto::PERFORMANCE_HINTS}); + auto navigation_data = + CreateTestNavigationData(url_without_hints(), {proto::PERFORMANCE_HINTS}); CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing()); hints_manager()->CanApplyOptimizationAsync( - url_without_hints(), optimization_guide::proto::PERFORMANCE_HINTS, - base::BindOnce( - [](optimization_guide::OptimizationGuideDecision decision, - const optimization_guide::OptimizationMetadata& metadata) { - EXPECT_EQ(optimization_guide::OptimizationGuideDecision::kFalse, - decision); - })); + url_without_hints(), proto::PERFORMANCE_HINTS, + base::BindOnce([](OptimizationGuideDecision decision, + const OptimizationMetadata& metadata) { + EXPECT_EQ(OptimizationGuideDecision::kFalse, decision); + })); RunUntilIdle(); histogram_tester.ExpectUniqueSample( "OptimizationGuide.ApplyDecisionAsync.PerformanceHints", - optimization_guide::OptimizationTypeDecision::kNoHintAvailable, 1); + OptimizationTypeDecision::kNoHintAvailable, 1); } TEST_F(HintsManagerFetchingTest, @@ -3123,9 +2909,8 @@ base::HistogramTester histogram_tester; base::CommandLine::ForCurrentProcess()->AppendSwitch( - optimization_guide::switches::kDisableCheckingUserPermissionsForTesting); - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::COMPRESS_PUBLIC_IMAGES}); + switches::kDisableCheckingUserPermissionsForTesting); + hints_manager()->RegisterOptimizationTypes({proto::COMPRESS_PUBLIC_IMAGES}); InitializeWithDefaultConfig("1.0.0.0"); @@ -3134,22 +2919,20 @@ GURL url_that_redirected("https://urlthatredirected.com"); auto navigation_data_redirect = CreateTestNavigationData( - url_that_redirected, {optimization_guide::proto::COMPRESS_PUBLIC_IMAGES}); + url_that_redirected, {proto::COMPRESS_PUBLIC_IMAGES}); hints_manager()->CanApplyOptimizationAsync( - url_that_redirected, optimization_guide::proto::COMPRESS_PUBLIC_IMAGES, - base::BindOnce( - [](optimization_guide::OptimizationGuideDecision decision, - const optimization_guide::OptimizationMetadata& metadata) { - EXPECT_EQ(optimization_guide::OptimizationGuideDecision::kFalse, - decision); - })); + url_that_redirected, proto::COMPRESS_PUBLIC_IMAGES, + base::BindOnce([](OptimizationGuideDecision decision, + const OptimizationMetadata& metadata) { + EXPECT_EQ(OptimizationGuideDecision::kFalse, decision); + })); hints_manager()->OnNavigationFinish( {url_that_redirected, GURL("https://otherurl.com/")}); RunUntilIdle(); histogram_tester.ExpectUniqueSample( "OptimizationGuide.ApplyDecisionAsync.CompressPublicImages", - optimization_guide::OptimizationTypeDecision::kNoHintAvailable, 1); + OptimizationTypeDecision::kNoHintAvailable, 1); } TEST_F(HintsManagerFetchingTest, @@ -3157,9 +2940,8 @@ base::HistogramTester histogram_tester; base::CommandLine::ForCurrentProcess()->AppendSwitch( - optimization_guide::switches::kDisableCheckingUserPermissionsForTesting); - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::COMPRESS_PUBLIC_IMAGES}); + switches::kDisableCheckingUserPermissionsForTesting); + hints_manager()->RegisterOptimizationTypes({proto::COMPRESS_PUBLIC_IMAGES}); InitializeWithDefaultConfig("1.0.0.0"); @@ -3170,100 +2952,82 @@ BuildTestHintsFetcherFactory( {HintsFetcherEndState::kFetchSuccessWithNoHints})); auto navigation_data = CreateTestNavigationData( - url_with_url_keyed_hint(), - {optimization_guide::proto::COMPRESS_PUBLIC_IMAGES}); + url_with_url_keyed_hint(), {proto::COMPRESS_PUBLIC_IMAGES}); CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing()); hints_manager()->CanApplyOptimizationAsync( - url_with_url_keyed_hint(), - optimization_guide::proto::COMPRESS_PUBLIC_IMAGES, - base::BindOnce( - [](optimization_guide::OptimizationGuideDecision decision, - const optimization_guide::OptimizationMetadata& metadata) { - EXPECT_EQ(optimization_guide::OptimizationGuideDecision::kFalse, - decision); - })); + url_with_url_keyed_hint(), proto::COMPRESS_PUBLIC_IMAGES, + base::BindOnce([](OptimizationGuideDecision decision, + const OptimizationMetadata& metadata) { + EXPECT_EQ(OptimizationGuideDecision::kFalse, decision); + })); hints_manager()->OnNavigationFinish({url_with_url_keyed_hint()}); RunUntilIdle(); histogram_tester.ExpectUniqueSample( "OptimizationGuide.ApplyDecisionAsync.CompressPublicImages", - optimization_guide::OptimizationTypeDecision::kNotAllowedByHint, 1); + OptimizationTypeDecision::kNotAllowedByHint, 1); } TEST_F(HintsManagerFetchingTest, CanApplyOptimizationAsyncWithDecisionFromAllowlistReturnsRightAway) { base::HistogramTester histogram_tester; - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::LITE_PAGE_REDIRECT}); + hints_manager()->RegisterOptimizationTypes({proto::LITE_PAGE_REDIRECT}); - optimization_guide::proto::Configuration config; - optimization_guide::BloomFilter allowlist_bloom_filter( - kDefaultHostBloomFilterNumHashFunctions, kDefaultHostBloomFilterNumBits); + proto::Configuration config; + BloomFilter allowlist_bloom_filter(kDefaultHostBloomFilterNumHashFunctions, + kDefaultHostBloomFilterNumBits); PopulateBloomFilterWithDefaultHost(&allowlist_bloom_filter); - AddBloomFilterToConfig( - optimization_guide::proto::LITE_PAGE_REDIRECT, allowlist_bloom_filter, - kDefaultHostBloomFilterNumHashFunctions, kDefaultHostBloomFilterNumBits, - /*is_allowlist=*/true, &config); + AddBloomFilterToConfig(proto::LITE_PAGE_REDIRECT, allowlist_bloom_filter, + kDefaultHostBloomFilterNumHashFunctions, + kDefaultHostBloomFilterNumBits, + /*is_allowlist=*/true, &config); ProcessHints(config, "1.0.0.0"); - auto navigation_data = - CreateTestNavigationData(GURL("https://notallowed.com/123"), - {optimization_guide::proto::LITE_PAGE_REDIRECT}); + auto navigation_data = CreateTestNavigationData( + GURL("https://notallowed.com/123"), {proto::LITE_PAGE_REDIRECT}); hints_manager()->CanApplyOptimizationAsync( - navigation_data->navigation_url(), - optimization_guide::proto::LITE_PAGE_REDIRECT, - base::BindOnce( - [](optimization_guide::OptimizationGuideDecision decision, - const optimization_guide::OptimizationMetadata& metadata) { - EXPECT_EQ(optimization_guide::OptimizationGuideDecision::kFalse, - decision); - })); + navigation_data->navigation_url(), proto::LITE_PAGE_REDIRECT, + base::BindOnce([](OptimizationGuideDecision decision, + const OptimizationMetadata& metadata) { + EXPECT_EQ(OptimizationGuideDecision::kFalse, decision); + })); RunUntilIdle(); histogram_tester.ExpectUniqueSample( "OptimizationGuide.ApplyDecisionAsync.LitePageRedirect", - optimization_guide::OptimizationTypeDecision:: - kNotAllowedByOptimizationFilter, - 1); + OptimizationTypeDecision::kNotAllowedByOptimizationFilter, 1); } TEST_F(HintsManagerFetchingTest, CanApplyOptimizationAsyncWithDecisionFromBlocklistReturnsRightAway) { base::HistogramTester histogram_tester; - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::LITE_PAGE_REDIRECT}); + hints_manager()->RegisterOptimizationTypes({proto::LITE_PAGE_REDIRECT}); - optimization_guide::proto::Configuration config; - optimization_guide::BloomFilter blocklist_bloom_filter( - kDefaultHostBloomFilterNumHashFunctions, kDefaultHostBloomFilterNumBits); + proto::Configuration config; + BloomFilter blocklist_bloom_filter(kDefaultHostBloomFilterNumHashFunctions, + kDefaultHostBloomFilterNumBits); PopulateBloomFilterWithDefaultHost(&blocklist_bloom_filter); - AddBloomFilterToConfig( - optimization_guide::proto::LITE_PAGE_REDIRECT, blocklist_bloom_filter, - kDefaultHostBloomFilterNumHashFunctions, kDefaultHostBloomFilterNumBits, - /*is_allowlist=*/false, &config); + AddBloomFilterToConfig(proto::LITE_PAGE_REDIRECT, blocklist_bloom_filter, + kDefaultHostBloomFilterNumHashFunctions, + kDefaultHostBloomFilterNumBits, + /*is_allowlist=*/false, &config); ProcessHints(config, "1.0.0.0"); - auto navigation_data = - CreateTestNavigationData(GURL("https://m.host.com/123"), - {optimization_guide::proto::LITE_PAGE_REDIRECT}); + auto navigation_data = CreateTestNavigationData( + GURL("https://m.host.com/123"), {proto::LITE_PAGE_REDIRECT}); hints_manager()->CanApplyOptimizationAsync( - navigation_data->navigation_url(), - optimization_guide::proto::LITE_PAGE_REDIRECT, - base::BindOnce( - [](optimization_guide::OptimizationGuideDecision decision, - const optimization_guide::OptimizationMetadata& metadata) { - EXPECT_EQ(optimization_guide::OptimizationGuideDecision::kFalse, - decision); - })); + navigation_data->navigation_url(), proto::LITE_PAGE_REDIRECT, + base::BindOnce([](OptimizationGuideDecision decision, + const OptimizationMetadata& metadata) { + EXPECT_EQ(OptimizationGuideDecision::kFalse, decision); + })); RunUntilIdle(); histogram_tester.ExpectUniqueSample( "OptimizationGuide.ApplyDecisionAsync.LitePageRedirect", - optimization_guide::OptimizationTypeDecision:: - kNotAllowedByOptimizationFilter, - 1); + OptimizationTypeDecision::kNotAllowedByOptimizationFilter, 1); } TEST_F(HintsManagerFetchingTest, @@ -3271,9 +3035,8 @@ base::HistogramTester histogram_tester; base::CommandLine::ForCurrentProcess()->AppendSwitch( - optimization_guide::switches::kDisableCheckingUserPermissionsForTesting); - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::COMPRESS_PUBLIC_IMAGES}); + switches::kDisableCheckingUserPermissionsForTesting); + hints_manager()->RegisterOptimizationTypes({proto::COMPRESS_PUBLIC_IMAGES}); InitializeWithDefaultConfig("1.0.0.0"); @@ -3283,34 +3046,29 @@ hints_manager()->SetHintsFetcherFactoryForTesting( BuildTestHintsFetcherFactory( {HintsFetcherEndState::kFetchSuccessWithURLHints})); - auto navigation_data = - CreateTestNavigationData(url_with_url_keyed_hint(), - {optimization_guide::proto::LITE_PAGE_REDIRECT}); + auto navigation_data = CreateTestNavigationData(url_with_url_keyed_hint(), + {proto::LITE_PAGE_REDIRECT}); CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing()); hints_manager()->CanApplyOptimizationAsync( - url_with_url_keyed_hint(), - optimization_guide::proto::COMPRESS_PUBLIC_IMAGES, - base::BindOnce( - [](optimization_guide::OptimizationGuideDecision decision, - const optimization_guide::OptimizationMetadata& metadata) { - EXPECT_EQ(optimization_guide::OptimizationGuideDecision::kTrue, - decision); - EXPECT_TRUE(metadata.public_image_metadata().has_value()); - })); + url_with_url_keyed_hint(), proto::COMPRESS_PUBLIC_IMAGES, + base::BindOnce([](OptimizationGuideDecision decision, + const OptimizationMetadata& metadata) { + EXPECT_EQ(OptimizationGuideDecision::kTrue, decision); + EXPECT_TRUE(metadata.public_image_metadata().has_value()); + })); hints_manager()->OnNavigationFinish({url_with_url_keyed_hint()}); RunUntilIdle(); histogram_tester.ExpectUniqueSample( "OptimizationGuide.ApplyDecisionAsync.CompressPublicImages", - optimization_guide::OptimizationTypeDecision::kAllowedByHint, 1); + OptimizationTypeDecision::kAllowedByHint, 1); } TEST_F(HintsManagerFetchingTest, OnNavigationFinishDoesNotCrashWithoutAnyCallbacksRegistered) { base::CommandLine::ForCurrentProcess()->AppendSwitch( - optimization_guide::switches::kDisableCheckingUserPermissionsForTesting); - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::COMPRESS_PUBLIC_IMAGES}); + switches::kDisableCheckingUserPermissionsForTesting); + hints_manager()->RegisterOptimizationTypes({proto::COMPRESS_PUBLIC_IMAGES}); InitializeWithDefaultConfig("1.0.0.0"); @@ -3321,9 +3079,8 @@ TEST_F(HintsManagerFetchingTest, NewOptTypeRegisteredClearsHintCache) { base::CommandLine::ForCurrentProcess()->AppendSwitch( - optimization_guide::switches::kDisableCheckingUserPermissionsForTesting); - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::DEFER_ALL_SCRIPT}); + switches::kDisableCheckingUserPermissionsForTesting); + hints_manager()->RegisterOptimizationTypes({proto::DEFER_ALL_SCRIPT}); InitializeWithDefaultConfig("1.0.0.0"); @@ -3335,26 +3092,25 @@ hints_manager()->SetHintsFetcherFactoryForTesting( BuildTestHintsFetcherFactory( {HintsFetcherEndState::kFetchSuccessWithHostHints})); - auto navigation_data = CreateTestNavigationData( - url, {optimization_guide::proto::DEFER_ALL_SCRIPT}); + auto navigation_data = + CreateTestNavigationData(url, {proto::DEFER_ALL_SCRIPT}); // Attempt to fetch a hint but ensure nothing comes back. CallOnNavigationStartOrRedirect(navigation_data.get(), base::DoNothing()); RunUntilIdle(); - optimization_guide::OptimizationMetadata optimization_metadata; - optimization_guide::OptimizationTypeDecision optimization_type_decision = - hints_manager()->CanApplyOptimization( - navigation_data->navigation_url(), - optimization_guide::proto::DEFER_ALL_SCRIPT, &optimization_metadata); + OptimizationMetadata optimization_metadata; + OptimizationTypeDecision optimization_type_decision = + hints_manager()->CanApplyOptimization(navigation_data->navigation_url(), + proto::DEFER_ALL_SCRIPT, + &optimization_metadata); - EXPECT_EQ(optimization_guide::OptimizationTypeDecision::kNotAllowedByHint, + EXPECT_EQ(OptimizationTypeDecision::kNotAllowedByHint, optimization_type_decision); // Register a new type that is unlaunched - this should clear the Fetched // hints. - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::COMPRESS_PUBLIC_IMAGES}); + hints_manager()->RegisterOptimizationTypes({proto::COMPRESS_PUBLIC_IMAGES}); RunUntilIdle(); @@ -3366,31 +3122,28 @@ base::HistogramTester histogram_tester; - navigation_data = CreateTestNavigationData( - url, {optimization_guide::proto::DEFER_ALL_SCRIPT}); + navigation_data = CreateTestNavigationData(url, {proto::DEFER_ALL_SCRIPT}); CallOnNavigationStartOrRedirect(navigation_data.get(), run_loop.QuitClosure()); run_loop.Run(); optimization_type_decision = hints_manager()->CanApplyOptimization( - navigation_data->navigation_url(), - optimization_guide::proto::DEFER_ALL_SCRIPT, &optimization_metadata); + navigation_data->navigation_url(), proto::DEFER_ALL_SCRIPT, + &optimization_metadata); // The previously fetched hints for the host should not be available after // registering a new optimization type. histogram_tester.ExpectUniqueSample( "OptimizationGuide.HintsManager.RaceNavigationFetchAttemptStatus", - optimization_guide::RaceNavigationFetchAttemptStatus:: - kRaceNavigationFetchHost, - 1); + RaceNavigationFetchAttemptStatus::kRaceNavigationFetchHost, 1); } class HintsManagerFetchingNoBatchUpdateTest : public HintsManagerTest { public: HintsManagerFetchingNoBatchUpdateTest() { scoped_list_.InitAndEnableFeatureWithParameters( - optimization_guide::features::kRemoteOptimizationGuideFetching, + features::kRemoteOptimizationGuideFetching, {{"batch_update_hints_for_top_hosts", "false"}}); } @@ -3401,15 +3154,14 @@ TEST_F(HintsManagerFetchingNoBatchUpdateTest, BatchUpdateHintsFetchNotScheduledIfNotAllowed) { base::CommandLine::ForCurrentProcess()->AppendSwitch( - optimization_guide::switches::kDisableCheckingUserPermissionsForTesting); + switches::kDisableCheckingUserPermissionsForTesting); std::unique_ptr<FakeTopHostProvider> top_host_provider = std::make_unique<FakeTopHostProvider>( std::vector<std::string>({"example1.com", "example2.com"})); // Force hints fetch scheduling. CreateHintsManager(top_host_provider.get()); - hints_manager()->RegisterOptimizationTypes( - {optimization_guide::proto::DEFER_ALL_SCRIPT}); + hints_manager()->RegisterOptimizationTypes({proto::DEFER_ALL_SCRIPT}); hints_manager()->SetHintsFetcherFactoryForTesting( BuildTestHintsFetcherFactory( {HintsFetcherEndState::kFetchSuccessWithHostHints}));
diff --git a/components/optimization_guide/core/model_handler.h b/components/optimization_guide/core/model_handler.h index a4c6492..878ca9ce 100644 --- a/components/optimization_guide/core/model_handler.h +++ b/components/optimization_guide/core/model_handler.h
@@ -18,6 +18,7 @@ #include "components/optimization_guide/core/optimization_guide_model_provider.h" #include "components/optimization_guide/core/optimization_guide_util.h" #include "components/optimization_guide/core/optimization_target_model_observer.h" +#include "components/optimization_guide/proto/models.pb.h" #include "third_party/abseil-cpp/absl/types/optional.h" namespace optimization_guide { @@ -113,7 +114,7 @@ if (optimization_target_ != optimization_target) return; - supported_features_for_loaded_model_ = model_info.GetModelMetadata(); + model_info_ = model_info; model_available_ = true; background_task_runner_->PostTask( @@ -130,17 +131,22 @@ return model_available_; } - // Validates that |supported_features_for_loaded_model_| is of the same type - // and is parseable as |T|. Will return metadata if all checks pass. + absl::optional<ModelInfo> GetModelInfo() const { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + return model_info_; + } + + // Validates that the model info's metadata is of the same type and is + // parseable as |T|. Will return metadata if all checks pass. template < class T, class = typename std::enable_if< std::is_convertible<T*, google::protobuf::MessageLite*>{}>::type> absl::optional<T> ParsedSupportedFeaturesForLoadedModel() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (!supported_features_for_loaded_model_) + if (!model_info_ || !model_info_->GetModelMetadata()) return absl::nullopt; - return ParsedAnyMetadata<T>(*supported_features_for_loaded_model_); + return ParsedAnyMetadata<T>(*model_info_->GetModelMetadata()); } private: @@ -185,8 +191,7 @@ scoped_refptr<base::SequencedTaskRunner> background_task_runner_; // Set in |OnModelUpdated|. - absl::optional<proto::Any> supported_features_for_loaded_model_ - GUARDED_BY_CONTEXT(sequence_checker_); + absl::optional<ModelInfo> model_info_ GUARDED_BY_CONTEXT(sequence_checker_); // Set in |OnModelUpdated|. bool model_available_ GUARDED_BY_CONTEXT(sequence_checker_) = false;
diff --git a/components/optimization_guide/core/model_handler_unittest.cc b/components/optimization_guide/core/model_handler_unittest.cc index db4aece..6def3dc 100644 --- a/components/optimization_guide/core/model_handler_unittest.cc +++ b/components/optimization_guide/core/model_handler_unittest.cc
@@ -142,6 +142,7 @@ proto::OptimizationTarget::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD, /*model_metadata=*/absl::nullopt); EXPECT_TRUE(model_handler()->ModelAvailable()); + EXPECT_TRUE(model_handler()->GetModelInfo()); EXPECT_FALSE(model_handler() ->ParsedSupportedFeaturesForLoadedModel<proto::Duration>() @@ -165,6 +166,7 @@ model_handler()->ParsedSupportedFeaturesForLoadedModel<proto::Duration>(); ASSERT_TRUE(supported_features_for_loaded_model.has_value()); EXPECT_EQ(123, supported_features_for_loaded_model->seconds()); + EXPECT_TRUE(model_handler()->GetModelInfo()); } TEST_F(ModelHandlerTest, Execute) {
diff --git a/components/payments/core/strings_util.cc b/components/payments/core/strings_util.cc index ba496d5..e6d9389 100644 --- a/components/payments/core/strings_util.cc +++ b/components/payments/core/strings_util.cc
@@ -33,24 +33,6 @@ base::size(kLabelFields), locale); } -std::u16string GetBillingAddressLabelFromAutofillProfile( - const autofill::AutofillProfile& profile, - const std::string& locale) { - // Name, company, phone number, and country are not included in the billing - // address label. - static constexpr autofill::ServerFieldType kLabelFields[] = { - autofill::ADDRESS_HOME_STREET_ADDRESS, - autofill::ADDRESS_HOME_DEPENDENT_LOCALITY, - autofill::ADDRESS_HOME_CITY, - autofill::ADDRESS_HOME_STATE, - autofill::ADDRESS_HOME_ZIP, - autofill::ADDRESS_HOME_SORTING_CODE, - }; - - return profile.ConstructInferredLabel(kLabelFields, base::size(kLabelFields), - base::size(kLabelFields), locale); -} - std::u16string GetShippingAddressSelectorInfoMessage( PaymentShippingType shipping_type) { switch (shipping_type) { @@ -84,58 +66,6 @@ } } -#if defined(OS_IOS) -std::u16string GetChooseShippingAddressButtonLabel( - PaymentShippingType shipping_type) { - switch (shipping_type) { - case PaymentShippingType::DELIVERY: - return l10n_util::GetStringUTF16( - IDS_PAYMENTS_CHOOSE_DELIVERY_ADDRESS_LABEL); - case PaymentShippingType::PICKUP: - return l10n_util::GetStringUTF16( - IDS_PAYMENTS_CHOOSE_PICKUP_ADDRESS_LABEL); - case PaymentShippingType::SHIPPING: - return l10n_util::GetStringUTF16( - IDS_PAYMENTS_CHOOSE_SHIPPING_ADDRESS_LABEL); - default: - NOTREACHED(); - return std::u16string(); - } -} - -std::u16string GetAddShippingAddressButtonLabel( - PaymentShippingType shipping_type) { - switch (shipping_type) { - case PaymentShippingType::DELIVERY: - return l10n_util::GetStringUTF16(IDS_PAYMENTS_ADD_DELIVERY_ADDRESS_LABEL); - case PaymentShippingType::PICKUP: - return l10n_util::GetStringUTF16(IDS_PAYMENTS_ADD_PICKUP_ADDRESS_LABEL); - case PaymentShippingType::SHIPPING: - return l10n_util::GetStringUTF16(IDS_PAYMENTS_ADD_SHIPPING_ADDRESS_LABEL); - default: - NOTREACHED(); - return std::u16string(); - } -} - -std::u16string GetChooseShippingOptionButtonLabel( - PaymentShippingType shipping_type) { - switch (shipping_type) { - case PaymentShippingType::DELIVERY: - return l10n_util::GetStringUTF16( - IDS_PAYMENTS_CHOOSE_DELIVERY_OPTION_LABEL); - case PaymentShippingType::PICKUP: - return l10n_util::GetStringUTF16(IDS_PAYMENTS_CHOOSE_PICKUP_OPTION_LABEL); - case PaymentShippingType::SHIPPING: - return l10n_util::GetStringUTF16( - IDS_PAYMENTS_CHOOSE_SHIPPING_OPTION_LABEL); - default: - NOTREACHED(); - return std::u16string(); - } -} -#endif // defined(OS_IOS) - std::u16string GetShippingOptionSectionString( PaymentShippingType shipping_type) { switch (shipping_type) {
diff --git a/components/payments/core/strings_util.h b/components/payments/core/strings_util.h index ea2fe243..eb524860 100644 --- a/components/payments/core/strings_util.h +++ b/components/payments/core/strings_util.h
@@ -23,11 +23,6 @@ const autofill::AutofillProfile& profile, const std::string& locale); -// Helper function to create a billing address label from an autofill profile. -std::u16string GetBillingAddressLabelFromAutofillProfile( - const autofill::AutofillProfile& profile, - const std::string& locale); - // Gets the informational message to be displayed in the shipping address // selector view when there are no valid shipping options. std::u16string GetShippingAddressSelectorInfoMessage( @@ -38,23 +33,6 @@ std::u16string GetShippingAddressSectionString( PaymentShippingType shipping_type); -#if defined(OS_IOS) -// Gets the appropriate display string for the Choose Shipping Address string -// for the given PaymentShippingType. -std::u16string GetChooseShippingAddressButtonLabel( - PaymentShippingType shipping_type); - -// Gets the appropriate display string for the Add Shipping Address string -// for the given PaymentShippingType. -std::u16string GetAddShippingAddressButtonLabel( - PaymentShippingType shipping_type); - -// Gets the appropriate display string for the Choose Shipping Option string for -// the given PaymentShippingType. -std::u16string GetChooseShippingOptionButtonLabel( - PaymentShippingType shipping_type); -#endif // defined(OS_IOS) - // Gets the appropriate display string for the Shipping Option string for the // given PaymentShippingType. std::u16string GetShippingOptionSectionString(
diff --git a/components/policy/core/browser/signin/user_cloud_signin_restriction_policy_fetcher.cc b/components/policy/core/browser/signin/user_cloud_signin_restriction_policy_fetcher.cc index df33bb2..06de577 100644 --- a/components/policy/core/browser/signin/user_cloud_signin_restriction_policy_fetcher.cc +++ b/components/policy/core/browser/signin/user_cloud_signin_restriction_policy_fetcher.cc
@@ -28,7 +28,7 @@ const char kAuthorizationHeaderFormat[] = "Bearer %s"; const char kProtobufferContentType[] = "application/x-protobuf"; const char kSecureConnectApiGetManagedAccountsSigninRestrictionsUrl[] = - "https://secureconnect-pa.googleapis.com/" + "https://secureconnect-pa.clients6.google.com/" "v1:getManagedAccountsSigninRestriction"; std::unique_ptr<network::SimpleURLLoader> CreateUrlLoader(
diff --git a/components/policy/core/browser/signin/user_cloud_signin_restriction_policy_fetcher_unittest.cc b/components/policy/core/browser/signin/user_cloud_signin_restriction_policy_fetcher_unittest.cc index 718e91ea..eb68e81 100644 --- a/components/policy/core/browser/signin/user_cloud_signin_restriction_policy_fetcher_unittest.cc +++ b/components/policy/core/browser/signin/user_cloud_signin_restriction_policy_fetcher_unittest.cc
@@ -22,9 +22,8 @@ namespace { const char kSecureConnectApiGetManagedAccountsSigninRestrictionsUrl[] = - "https://secureconnect-pa.googleapis.com/" + "https://secureconnect-pa.clients6.google.com/" "v1:getManagedAccountsSigninRestriction"; - } namespace policy {
diff --git a/components/policy/core/common/BUILD.gn b/components/policy/core/common/BUILD.gn index bcef9fa..1b97421 100644 --- a/components/policy/core/common/BUILD.gn +++ b/components/policy/core/common/BUILD.gn
@@ -436,10 +436,8 @@ "cloud/affiliation_unittest.cc", "cloud/cloud_policy_client_unittest.cc", "cloud/cloud_policy_core_unittest.cc", - "cloud/cloud_policy_manager_unittest.cc", "cloud/cloud_policy_refresh_scheduler_unittest.cc", "cloud/cloud_policy_service_unittest.cc", - "cloud/cloud_policy_validator_unittest.cc", "cloud/device_management_service_unittest.cc", "cloud/user_info_fetcher_unittest.cc", "command_line_policy_provider_unittest.cc", @@ -459,6 +457,15 @@ "schema_unittest.cc", "values_util_unittest.cc", ] + + # TODO(crbug.com/1270429): Enable these tests on Fuchsia if appropriate. + if (!is_fuchsia) { + sources += [ + "cloud/cloud_policy_manager_unittest.cc", + "cloud/cloud_policy_validator_unittest.cc", + ] + } + if (is_win || is_linux || is_chromeos) { sources += [ "preg_parser_unittest.cc", @@ -473,19 +480,16 @@ } else { sources += [ "cloud/machine_level_user_cloud_policy_manager_unittest.cc", - "cloud/machine_level_user_cloud_policy_store_unittest.cc", "cloud/user_cloud_policy_manager_unittest.cc", - "cloud/user_cloud_policy_store_unittest.cc", ] - } - if (is_fuchsia) { - sources -= [ - "cloud/cloud_policy_manager_unittest.cc", - "cloud/cloud_policy_validator_unittest.cc", - "cloud/machine_level_user_cloud_policy_store_unittest.cc", - "cloud/user_cloud_policy_store_unittest.cc", - ] + # TODO(crbug.com/1270429): Enable these tests on Fuchsia if appropriate. + if (!is_fuchsia) { + sources += [ + "cloud/machine_level_user_cloud_policy_store_unittest.cc", + "cloud/user_cloud_policy_store_unittest.cc", + ] + } } if (is_win || is_mac) {
diff --git a/components/safe_browsing/content/browser/web_ui/safe_browsing_ui.cc b/components/safe_browsing/content/browser/web_ui/safe_browsing_ui.cc index 3381067..ad32a53 100644 --- a/components/safe_browsing/content/browser/web_ui/safe_browsing_ui.cc +++ b/components/safe_browsing/content/browser/web_ui/safe_browsing_ui.cc
@@ -1814,6 +1814,9 @@ case enterprise_connectors::BULK_DATA_ENTRY: request_dict.SetStringKey("analysis_connector", "BULK_DATA_ENTRY"); break; + case enterprise_connectors::PRINT: + request_dict.SetStringKey("analysis_connector", "PRINT"); + break; } if (request.has_request_data()) {
diff --git a/components/safe_browsing/content/renderer/phishing_classifier/flatbuffer_scorer.cc b/components/safe_browsing/content/renderer/phishing_classifier/flatbuffer_scorer.cc index b8feb2a5..9e68b4c 100644 --- a/components/safe_browsing/content/renderer/phishing_classifier/flatbuffer_scorer.cc +++ b/components/safe_browsing/content/renderer/phishing_classifier/flatbuffer_scorer.cc
@@ -196,9 +196,7 @@ base::BindOnce(&ApplyVisualTfLiteModelHelper, bitmap, flatbuffer_model_->tflite_metadata()->input_width(), flatbuffer_model_->tflite_metadata()->input_height(), - std::string(reinterpret_cast<const char*>( - visual_tflite_model_.data()), - visual_tflite_model_.length())), + GetWeakPtr()), std::move(callback)); base::UmaHistogramTimes( "SBClientPhishing.TfLiteModelLoadTime.FlatbufferScorer",
diff --git a/components/safe_browsing/content/renderer/phishing_classifier/protobuf_scorer.cc b/components/safe_browsing/content/renderer/phishing_classifier/protobuf_scorer.cc index 3a93e73..371ee73 100644 --- a/components/safe_browsing/content/renderer/phishing_classifier/protobuf_scorer.cc +++ b/components/safe_browsing/content/renderer/phishing_classifier/protobuf_scorer.cc
@@ -161,10 +161,7 @@ {base::TaskPriority::BEST_EFFORT, base::WithBaseSyncPrimitives()}, base::BindOnce(&ApplyVisualTfLiteModelHelper, bitmap, model_.tflite_metadata().input_width(), - model_.tflite_metadata().input_height(), - std::string(reinterpret_cast<const char*>( - visual_tflite_model_.data()), - visual_tflite_model_.length())), + model_.tflite_metadata().input_height(), GetWeakPtr()), std::move(callback)); base::UmaHistogramTimes( "SBClientPhishing.TfLiteModelLoadTime.ProtobufScorer",
diff --git a/components/safe_browsing/content/renderer/phishing_classifier/scorer.cc b/components/safe_browsing/content/renderer/phishing_classifier/scorer.cc index f133431..b1134224 100644 --- a/components/safe_browsing/content/renderer/phishing_classifier/scorer.cc +++ b/components/safe_browsing/content/renderer/phishing_classifier/scorer.cc
@@ -113,10 +113,16 @@ const SkBitmap& bitmap, int input_width, int input_height, - const std::string& model_data) { + base::WeakPtr<Scorer> scorer) { + if (!scorer) + return std::vector<double>(); + TRACE_EVENT0("safe_browsing", "ApplyVisualTfLiteModel"); + std::string model_data = std::string( + reinterpret_cast<const char*>(scorer->visual_tflite_model().data()), + scorer->visual_tflite_model().length()); std::unique_ptr<tflite::task::vision::ImageClassifier> classifier = - CreateClassifier(model_data); + CreateClassifier(std::move(model_data)); if (!classifier) return std::vector<double>(); @@ -161,4 +167,8 @@ Scorer::Scorer() = default; Scorer::~Scorer() = default; +base::WeakPtr<Scorer> Scorer::GetWeakPtr() const { + return weak_ptr_factory_.GetWeakPtr(); +} + } // namespace safe_browsing
diff --git a/components/safe_browsing/content/renderer/phishing_classifier/scorer.h b/components/safe_browsing/content/renderer/phishing_classifier/scorer.h index 9713478..abeb7b210 100644 --- a/components/safe_browsing/content/renderer/phishing_classifier/scorer.h +++ b/components/safe_browsing/content/renderer/phishing_classifier/scorer.h
@@ -84,6 +84,11 @@ virtual void ApplyVisualTfLiteModel( const SkBitmap& bitmap, base::OnceCallback<void(std::vector<double>)> callback) const = 0; + + const base::MemoryMappedFile& visual_tflite_model() const { + return visual_tflite_model_; + } + #endif // Returns the version number of the loaded client model. @@ -128,6 +133,8 @@ Scorer(const Scorer&) = delete; Scorer& operator=(const Scorer&) = delete; + base::WeakPtr<Scorer> GetWeakPtr() const; + protected: // Helper function which converts log odds to a probability in the range // [0.0,1.0]. @@ -138,7 +145,7 @@ const SkBitmap& bitmap, int input_width, int input_height, - const std::string& model_data); + base::WeakPtr<Scorer> scorer); base::MemoryMappedFile visual_tflite_model_; base::WeakPtrFactory<Scorer> weak_ptr_factory_{this};
diff --git a/components/safe_browsing/content/resources/download_file_types.asciipb b/components/safe_browsing/content/resources/download_file_types.asciipb index 104dced..f9315442 100644 --- a/components/safe_browsing/content/resources/download_file_types.asciipb +++ b/components/safe_browsing/content/resources/download_file_types.asciipb
@@ -8,7 +8,7 @@ ## ## Top level settings ## -version_id: 45 +version_id: 47 sampled_ping_probability: 0.01 max_archived_binaries_to_report: 10 default_file_type { @@ -744,7 +744,7 @@ uma_value: 12 ping_setting: FULL_PING platform_settings { - danger_level: DANGEROUS + danger_level: ALLOW_ON_USER_GESTURE auto_open_hint: DISALLOW_AUTO_OPEN } platform_settings { @@ -758,7 +758,7 @@ uma_value: 128 ping_setting: FULL_PING platform_settings { - danger_level: DANGEROUS + danger_level: ALLOW_ON_USER_GESTURE auto_open_hint: DISALLOW_AUTO_OPEN } platform_settings {
diff --git a/components/safe_browsing/content/resources/download_file_types_experiment.asciipb b/components/safe_browsing/content/resources/download_file_types_experiment.asciipb index f041d38..0630edb2 100644 --- a/components/safe_browsing/content/resources/download_file_types_experiment.asciipb +++ b/components/safe_browsing/content/resources/download_file_types_experiment.asciipb
@@ -12,7 +12,7 @@ ## version id is larger than the version id in download_file_types.asciipb. If ## there isn't an ongoing experiment, this version id is equal to the version id ## in download_file_types.asciipb. -version_id: 46 +version_id: 47 sampled_ping_probability: 0.01 max_archived_binaries_to_report: 10 default_file_type {
diff --git a/components/safe_browsing/core/common/features.cc b/components/safe_browsing/core/common/features.cc index b990623..2b93f33 100644 --- a/components/safe_browsing/core/common/features.cc +++ b/components/safe_browsing/core/common/features.cc
@@ -63,7 +63,7 @@ "ConnectorsScanningReportOnlyUI", base::FEATURE_DISABLED_BY_DEFAULT}; const base::Feature kFileTypePoliciesTag{"FileTypePoliciesTag", - base::FEATURE_DISABLED_BY_DEFAULT}; + base::FEATURE_ENABLED_BY_DEFAULT}; const base::Feature kDelayedWarnings{"SafeBrowsingDelayedWarnings", base::FEATURE_DISABLED_BY_DEFAULT}; @@ -247,12 +247,13 @@ } std::string GetFileTypePoliciesTag() { - if (base::FeatureList::IsEnabled(kFileTypePoliciesTag)) { - return variations::GetVariationParamValueByFeature( - kFileTypePoliciesTag, kFileTypePoliciesTagParamName); + if (!base::FeatureList::IsEnabled(kFileTypePoliciesTag)) { + return "default"; } + std::string tag_value = variations::GetVariationParamValueByFeature( + kFileTypePoliciesTag, kFileTypePoliciesTagParamName); - return "default"; + return tag_value.empty() ? "default" : tag_value; } } // namespace safe_browsing
diff --git a/components/safe_browsing/core/common/features_unittest.cc b/components/safe_browsing/core/common/features_unittest.cc index 8efbd32..1aa5ae3b 100644 --- a/components/safe_browsing/core/common/features_unittest.cc +++ b/components/safe_browsing/core/common/features_unittest.cc
@@ -105,4 +105,10 @@ EXPECT_EQ(GetFileTypePoliciesTag(), "45"); } +TEST(SafeBrowsingFeatures, FileTypePoliciesTagNoParam) { + base::test::ScopedFeatureList feature_list; + feature_list.InitAndEnableFeature(kFileTypePoliciesTag); + EXPECT_EQ(GetFileTypePoliciesTag(), "default"); +} + } // namespace safe_browsing
diff --git a/components/ui_devtools/BUILD.gn b/components/ui_devtools/BUILD.gn index 56b308d..0d42a82c 100644 --- a/components/ui_devtools/BUILD.gn +++ b/components/ui_devtools/BUILD.gn
@@ -90,6 +90,7 @@ defines = [ "UI_DEVTOOLS_IMPLEMENTATION" ] deps = [ + ":features", ":protocol_generated_sources", "//base", "//mojo/public/cpp/bindings", @@ -109,6 +110,19 @@ ] } +component("features") { + output_name = "ui_devtools_features" + + defines = [ "IS_UI_DEVTOOLS_FEATURES_IMPL" ] + + sources = [ + "ui_devtools_features.cc", + "ui_devtools_features.h", + ] + + deps = [ "//base" ] +} + static_library("test_support") { testonly = true sources = [
diff --git a/components/ui_devtools/dom_agent.cc b/components/ui_devtools/dom_agent.cc index 7c5f211..92153b89 100644 --- a/components/ui_devtools/dom_agent.cc +++ b/components/ui_devtools/dom_agent.cc
@@ -14,6 +14,7 @@ #include "base/strings/string_util.h" #include "components/ui_devtools/devtools_server.h" #include "components/ui_devtools/root_element.h" +#include "components/ui_devtools/ui_devtools_features.h" #include "components/ui_devtools/ui_element.h" #include "ui/base/interaction/element_identifier.h" @@ -409,6 +410,9 @@ protocol::Response DOMAgent::dispatchMouseEvent( int node_id, std::unique_ptr<protocol::DOM::MouseEvent> event) { + if (!base::FeatureList::IsEnabled( + ui_devtools::kUIDebugToolsEnableSyntheticEvents)) + return Response::ServerError("Dispatch mouse events is not enabled."); if (node_id_to_ui_element_.count(node_id) == 0) return Response::ServerError("Element not found on node id"); if (!node_id_to_ui_element_[node_id]->DispatchMouseEvent(event.get())) @@ -419,6 +423,9 @@ protocol::Response DOMAgent::dispatchKeyEvent( int node_id, std::unique_ptr<protocol::DOM::KeyEvent> event) { + if (!base::FeatureList::IsEnabled( + ui_devtools::kUIDebugToolsEnableSyntheticEvents)) + return Response::ServerError("Dispatch key events is not enabled."); if (node_id_to_ui_element_.count(node_id) == 0) return Response::ServerError("Element not found on node id"); if (!node_id_to_ui_element_[node_id]->DispatchKeyEvent(event.get()))
diff --git a/components/ui_devtools/ui_devtools_features.cc b/components/ui_devtools/ui_devtools_features.cc new file mode 100644 index 0000000..4f89e0a --- /dev/null +++ b/components/ui_devtools/ui_devtools_features.cc
@@ -0,0 +1,13 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/ui_devtools/ui_devtools_features.h" + +namespace ui_devtools { + +const base::Feature kUIDebugToolsEnableSyntheticEvents{ + "ui-debug-tools-enable-synthetic-events", + base::FEATURE_DISABLED_BY_DEFAULT}; + +} // namespace ui_devtools
diff --git a/components/ui_devtools/ui_devtools_features.h b/components/ui_devtools/ui_devtools_features.h new file mode 100644 index 0000000..b85541c --- /dev/null +++ b/components/ui_devtools/ui_devtools_features.h
@@ -0,0 +1,20 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_UI_DEVTOOLS_UI_DEVTOOLS_FEATURES_H_ +#define COMPONENTS_UI_DEVTOOLS_UI_DEVTOOLS_FEATURES_H_ + +#include "base/component_export.h" +#include "base/feature_list.h" + +namespace ui_devtools { + +// Enables UI debugging tools to send synthetic events. +// This is used by the telemetry benchmarking tools only. +COMPONENT_EXPORT(UI_DEVTOOLS_FEATURES) +extern const base::Feature kUIDebugToolsEnableSyntheticEvents; + +} // namespace ui_devtools + +#endif // COMPONENTS_UI_DEVTOOLS_UI_DEVTOOLS_FEATURES_H_
diff --git a/components/update_client/protocol_definition.h b/components/update_client/protocol_definition.h index 89aee18c..5aff3ba 100644 --- a/components/update_client/protocol_definition.h +++ b/components/update_client/protocol_definition.h
@@ -30,6 +30,13 @@ struct HW { uint32_t physmemory = 0; // Physical memory rounded down to the closest GB. + bool sse = false; + bool sse2 = false; + bool sse3 = false; + bool sse41 = false; + bool sse42 = false; + bool ssse3 = false; + bool avx = false; }; struct OS {
diff --git a/components/update_client/protocol_serializer.cc b/components/update_client/protocol_serializer.cc index 9c5619c..3489725 100644 --- a/components/update_client/protocol_serializer.cc +++ b/components/update_client/protocol_serializer.cc
@@ -10,6 +10,7 @@ #include "base/check.h" #include "base/containers/flat_map.h" +#include "base/cpu.h" #include "base/guid.h" #include "base/strings/strcat.h" #include "base/strings/string_number_conversions.h" @@ -142,7 +143,15 @@ } // HW platform information. + base::CPU cpu; request.hw.physmemory = GetPhysicalMemoryGB(); + request.hw.sse = cpu.has_sse(); + request.hw.sse2 = cpu.has_sse2(); + request.hw.sse3 = cpu.has_sse3(); + request.hw.ssse3 = cpu.has_ssse3(); + request.hw.sse41 = cpu.has_sse41(); + request.hw.sse42 = cpu.has_sse42(); + request.hw.avx = cpu.has_avx(); // OS version and platform information. request.os.platform = os_long_name;
diff --git a/components/update_client/protocol_serializer_json.cc b/components/update_client/protocol_serializer_json.cc index 938b9b08..12c3310 100644 --- a/components/update_client/protocol_serializer_json.cc +++ b/components/update_client/protocol_serializer_json.cc
@@ -58,6 +58,13 @@ // HW platform information. auto* hw_node = request_node->SetKey("hw", Value(Value::Type::DICTIONARY)); hw_node->SetKey("physmemory", Value(static_cast<int>(request.hw.physmemory))); + hw_node->SetKey("sse", Value(request.hw.sse)); + hw_node->SetKey("sse2", Value(request.hw.sse2)); + hw_node->SetKey("sse3", Value(request.hw.sse3)); + hw_node->SetKey("sse41", Value(request.hw.sse41)); + hw_node->SetKey("sse42", Value(request.hw.sse42)); + hw_node->SetKey("ssse3", Value(request.hw.ssse3)); + hw_node->SetKey("avx", Value(request.hw.avx)); // OS version and platform information. auto* os_node = request_node->SetKey("os", Value(Value::Type::DICTIONARY));
diff --git a/components/update_client/protocol_serializer_json_unittest.cc b/components/update_client/protocol_serializer_json_unittest.cc index e3f009c..7f7e2c3 100644 --- a/components/update_client/protocol_serializer_json_unittest.cc +++ b/components/update_client/protocol_serializer_json_unittest.cc
@@ -71,7 +71,10 @@ R"("release_channel":"test",)" R"("updatecheck":{"rollback_allowed":true,"targetversionprefix":"33.12",)" R"("updatedisabled":true},"version":"1.0"}],"arch":"\w+","dedup":"cr",)" - R"("dlpref":"cacheable","extra":"params","hw":{"physmemory":\d+},)" + R"("dlpref":"cacheable","extra":"params","hw":{"avx":(true|false),)" + R"("physmemory":\d+,"sse":(true|false),"sse2":(true|false),)" + R"("sse3":(true|false),"sse41":(true|false),"sse42":(true|false),)" + R"("ssse3":(true|false)},)" R"("ismachine":false,"lang":"lang","nacl_arch":"[-\w]+",)" R"("os":{"arch":"[_,-.\w]+","platform":"OS",)" R"(("sp":"[\s\w]+",)?"version":"[+-.\w]+"},"prodchannel":"channel",)" @@ -118,7 +121,11 @@ R"({"request":{"@os":"\w+","@updater":"prod_id",)" R"("acceptformat":"crx3","arch":"\w+","dedup":"cr",)" R"("dlpref":"cacheable","domainjoined":true,"extra":"params",)" - R"("hw":{"physmemory":\d+},"ismachine":true,"lang":"lang",)" + R"("hw":{"avx":(true|false),)" + R"("physmemory":\d+,"sse":(true|false),"sse2":(true|false),)" + R"("sse3":(true|false),"sse41":(true|false),"sse42":(true|false),)" + R"("ssse3":(true|false)},)" + R"("ismachine":true,"lang":"lang",)" R"("nacl_arch":"[-\w]+",)" R"("os":{"arch":"[,-.\w]+","platform":"OS",("sp":"[\s\w]+",)?)" R"("version":"[+-.\w]+"},"prodchannel":"channel","prodversion":"1.0",)"
diff --git a/components/viz/common/resources/transferable_resource.h b/components/viz/common/resources/transferable_resource.h index 284b9b9f..8f91691 100644 --- a/components/viz/common/resources/transferable_resource.h +++ b/components/viz/common/resources/transferable_resource.h
@@ -123,6 +123,9 @@ // drawing a quad in the compositor. However, for now, we use this flag to // refuse to promote so that the compositor will draw the quad. bool is_backed_by_surface_texture = false; +#endif + +#if defined(OS_ANDROID) || defined(OS_WIN) // Indicates that this resource would like a promotion hint. bool wants_promotion_hint = false; #endif @@ -139,6 +142,8 @@ #if defined(OS_ANDROID) is_backed_by_surface_texture == o.is_backed_by_surface_texture && wants_promotion_hint == o.wants_promotion_hint && +#elif defined(OS_WIN) + wants_promotion_hint == o.wants_promotion_hint && #endif read_lock_fences_enabled == o.read_lock_fences_enabled; }
diff --git a/components/viz/service/BUILD.gn b/components/viz/service/BUILD.gn index cca3986..e1a3b3bd 100644 --- a/components/viz/service/BUILD.gn +++ b/components/viz/service/BUILD.gn
@@ -173,6 +173,7 @@ "frame_sinks/video_capture/shared_memory_video_frame_pool.h", "frame_sinks/video_capture/video_capture_overlay.cc", "frame_sinks/video_capture/video_capture_overlay.h", + "frame_sinks/video_capture/video_frame_pool.cc", "frame_sinks/video_capture/video_frame_pool.h", "frame_sinks/video_detector.cc", "frame_sinks/video_detector.h",
diff --git a/components/viz/service/display/display_resource_provider.cc b/components/viz/service/display/display_resource_provider.cc index ce13a874..bddf5020 100644 --- a/components/viz/service/display/display_resource_provider.cc +++ b/components/viz/service/display/display_resource_provider.cc
@@ -119,7 +119,9 @@ ChildResource* resource = GetResource(id); return resource->transferable.is_backed_by_surface_texture; } +#endif +#if defined(OS_ANDROID) || defined(OS_WIN) bool DisplayResourceProvider::DoesResourceWantPromotionHint(ResourceId id) { ChildResource* resource = TryGetResource(id); // TODO(ericrk): We should never fail TryGetResource, but we appear to
diff --git a/components/viz/service/display/display_resource_provider.h b/components/viz/service/display/display_resource_provider.h index 6b438c9..f69e597b 100644 --- a/components/viz/service/display/display_resource_provider.h +++ b/components/viz/service/display/display_resource_provider.h
@@ -75,7 +75,9 @@ // Indicates if this resource is backed by an Android SurfaceTexture, and thus // can't really be promoted to an overlay. bool IsBackedBySurfaceTexture(ResourceId id); +#endif +#if defined(OS_ANDROID) || defined(OS_WIN) // Indicates if this resource wants to receive promotion hints. bool DoesResourceWantPromotionHint(ResourceId id); #endif
diff --git a/components/viz/service/display/draw_polygon.cc b/components/viz/service/display/draw_polygon.cc index 9bacd7a..ae10dda 100644 --- a/components/viz/service/display/draw_polygon.cc +++ b/components/viz/service/display/draw_polygon.cc
@@ -5,6 +5,7 @@ #include "components/viz/service/display/draw_polygon.h" #include <stddef.h> +#include <cmath> #include <utility> #include <vector> @@ -268,18 +269,28 @@ // Compute the intersection points. N.B.: If the "pre" vertex is on // the thick plane, then the intersection will be at the same point, because // we set vertex_distance to 0 in this case. + // + // Consistently use the vertex distances rather than taking dot + // products with the normal, because there may be some amount of + // accumulated floating point error in the coplanarity of the points. + // The vertex distances are what we used to separate front from back, + // so using them guarantees a nonzero denominator. PointInterpolate( polygon->points_[pre_front_begin], polygon->points_[front_begin], - -vertex_distance[pre_front_begin] / - gfx::DotProduct(normal_, polygon->points_[front_begin] - - polygon->points_[pre_front_begin]), + vertex_distance[pre_front_begin] / + (vertex_distance[pre_front_begin] - vertex_distance[front_begin]), &pre_pos_intersection); + DCHECK(std::isfinite(pre_pos_intersection.x())); + DCHECK(std::isfinite(pre_pos_intersection.y())); + DCHECK(std::isfinite(pre_pos_intersection.z())); PointInterpolate( polygon->points_[pre_back_begin], polygon->points_[back_begin], - -vertex_distance[pre_back_begin] / - gfx::DotProduct(normal_, polygon->points_[back_begin] - - polygon->points_[pre_back_begin]), + vertex_distance[pre_back_begin] / + (vertex_distance[pre_back_begin] - vertex_distance[back_begin]), &pre_neg_intersection); + DCHECK(std::isfinite(pre_neg_intersection.x())); + DCHECK(std::isfinite(pre_neg_intersection.y())); + DCHECK(std::isfinite(pre_neg_intersection.z())); // Build the front and back polygons. std::vector<gfx::Point3F> out_points;
diff --git a/components/viz/service/display/draw_polygon_unittest.cc b/components/viz/service/display/draw_polygon_unittest.cc index c07ba25..b658aa2 100644 --- a/components/viz/service/display/draw_polygon_unittest.cc +++ b/components/viz/service/display/draw_polygon_unittest.cc
@@ -5,6 +5,7 @@ #include <stddef.h> #include <algorithm> +#include <cmath> #include <limits> #include <utility> #include <vector> @@ -601,6 +602,95 @@ } } +// This test was derived from crbug.com/1264787. +TEST(DrawPolygonSplitTest, SplitNoNaNs) { + std::vector<gfx::Point3F> vertices_a; + vertices_a.emplace_back(-438777.031f, -999211.938f, 782768.312f); + vertices_a.emplace_back(733.815186f, 168.424362f, -133.606277f); + vertices_a.emplace_back(829.194641f, 173.089539f, -80.6844864f); + vertices_a.emplace_back(-237207.141f, -999021.0f, 904761.812f); + std::vector<gfx::Point3F> vertices_b; + vertices_b.emplace_back(1068.28625f, 184.783997f, 51.9764748f); + vertices_b.emplace_back(733.815247f, 168.424393f, -133.606277f); + vertices_b.emplace_back(567.472534f, 456.538422f, -133.606277f); + vertices_b.emplace_back(817.688904f, 618.831238f, 51.9764748f); + + CREATE_NEW_DRAW_POLYGON_PTR(splitting_polygon, vertices_a, + gfx::Vector3dF(0, 0, 0), 0); + CREATE_NEW_DRAW_POLYGON_PTR(split_polygon, vertices_b, + gfx::Vector3dF(0, 0, 0), 1); + + splitting_polygon->RecomputeNormalForTesting(); + split_polygon->RecomputeNormalForTesting(); + + std::unique_ptr<DrawPolygon> front_polygon; + std::unique_ptr<DrawPolygon> back_polygon; + bool is_coplanar; + + splitting_polygon->SplitPolygon(std::move(split_polygon), &front_polygon, + &back_polygon, &is_coplanar); + + EXPECT_FALSE(is_coplanar); + EXPECT_TRUE(front_polygon != nullptr); + EXPECT_TRUE(back_polygon != nullptr); + + for (auto point : front_polygon->points()) { + EXPECT_TRUE(std::isfinite(point.x())); + EXPECT_TRUE(std::isfinite(point.y())); + EXPECT_TRUE(std::isfinite(point.z())); + } + + for (auto point : back_polygon->points()) { + EXPECT_TRUE(std::isfinite(point.x())); + EXPECT_TRUE(std::isfinite(point.y())); + EXPECT_TRUE(std::isfinite(point.z())); + } +} + +// This test was derived from crbug.com/1264787. +TEST(DrawPolygonSplitTest, SplitNoInfs) { + // clang-format off + gfx::RectF rect_a(0, 0, 1140, 418); + gfx::Transform transform_a( + 1.39069271, -0.131110176, 0.5, -503.545319, + 1.00984585, -0.273445308, -0.866025388, -828.169128, + -0.722961724, 0.690888107, 4.23046966e-17, 570.098511, + 0.00144592347, -0.0013817763, -8.46093968e-20, -0.140197217); + gfx::RectF rect_b(430, 0, 560, 454); + gfx::Transform transform_b( + 0.131110176, -0.5, 1.39069271, 952.04541, + 0.273445308, 0.866025388, 1.00984585, 52.3442955, + -0.690888107, 0, -0.722961724, 429.901398, + 0.0013817763, 0, 0.00144592347, 0.140197009); + // clang-format on + + CREATE_NEW_DRAW_POLYGON_PTR(splitting_polygon, rect_a, transform_a, 0); + CREATE_NEW_DRAW_POLYGON_PTR(split_polygon, rect_b, transform_b, 1); + + std::unique_ptr<DrawPolygon> front_polygon; + std::unique_ptr<DrawPolygon> back_polygon; + bool is_coplanar; + + splitting_polygon->SplitPolygon(std::move(split_polygon), &front_polygon, + &back_polygon, &is_coplanar); + + EXPECT_FALSE(is_coplanar); + EXPECT_TRUE(front_polygon != nullptr); + EXPECT_TRUE(back_polygon != nullptr); + + for (auto point : front_polygon->points()) { + EXPECT_TRUE(std::isfinite(point.x())); + EXPECT_TRUE(std::isfinite(point.y())); + EXPECT_TRUE(std::isfinite(point.z())); + } + + for (auto point : back_polygon->points()) { + EXPECT_TRUE(std::isfinite(point.x())); + EXPECT_TRUE(std::isfinite(point.y())); + EXPECT_TRUE(std::isfinite(point.z())); + } +} + TEST(DrawPolygonTransformTest, TransformNormal) { std::vector<gfx::Point3F> vertices_a; vertices_a.emplace_back(1.0f, 0.0f, 1.0f);
diff --git a/components/viz/service/display/surface_aggregator.cc b/components/viz/service/display/surface_aggregator.cc index c3941f791..8443a09 100644 --- a/components/viz/service/display/surface_aggregator.cc +++ b/components/viz/service/display/surface_aggregator.cc
@@ -400,10 +400,6 @@ damage_rect_in_root_target_space.Intersect(root_clip_rect); } - // TODO(crbug.com/1257765): CHECK is temporary and is for validating whether - // the change in HandleSurfaceQuad() works or not. https://crrev.com/c/3220115 - // Remove this CHECK before next branch M98 on 12/9/2021. - CHECK(damage_rect_in_root_target_space.size().GetCheckedArea().IsValid()); surface_damage_rect_list_->push_back(damage_rect_in_root_target_space); }
diff --git a/components/viz/service/frame_sinks/video_capture/frame_sink_video_capturer_impl.cc b/components/viz/service/frame_sinks/video_capture/frame_sink_video_capturer_impl.cc index 34a26323..00f63e4 100644 --- a/components/viz/service/frame_sinks/video_capture/frame_sink_video_capturer_impl.cc +++ b/components/viz/service/frame_sinks/video_capture/frame_sink_video_capturer_impl.cc
@@ -24,6 +24,7 @@ #include "components/viz/common/frame_sinks/copy_output_util.h" #include "components/viz/common/surfaces/local_surface_id.h" #include "components/viz/service/frame_sinks/video_capture/frame_sink_video_capturer_manager.h" +#include "components/viz/service/frame_sinks/video_capture/shared_memory_video_frame_pool.h" #include "media/base/limits.h" #include "media/base/video_util.h" #include "media/capture/mojom/video_capture_buffer.mojom.h" @@ -58,9 +59,14 @@ // static constexpr media::VideoPixelFormat FrameSinkVideoCapturerImpl::kDefaultPixelFormat; - // static constexpr gfx::ColorSpace FrameSinkVideoCapturerImpl::kDefaultColorSpace; +// static +constexpr int FrameSinkVideoCapturerImpl::kDesignLimitMaxFrames; +// static +constexpr int FrameSinkVideoCapturerImpl::kFramePoolCapacity; +// static +constexpr float FrameSinkVideoCapturerImpl::kTargetPipelineUtilization; FrameSinkVideoCapturerImpl::FrameSinkVideoCapturerImpl( FrameSinkVideoCapturerManager* frame_sink_manager, @@ -71,7 +77,8 @@ copy_request_source_(base::UnguessableToken::Create()), clock_(base::DefaultTickClock::GetInstance()), oracle_(std::move(oracle)), - frame_pool_(kFramePoolCapacity), + frame_pool_( + std::make_unique<SharedMemoryVideoFramePool>(kFramePoolCapacity)), feedback_weak_factory_(oracle_.get()), log_to_webrtc_(log_to_webrtc) { DCHECK(frame_sink_manager_); @@ -573,7 +580,7 @@ TRACE_EVENT_SCOPE_THREAD); frame = ResurrectFrame(); } else { - frame = frame_pool_.ReserveVideoFrame(pixel_format_, capture_size); + frame = frame_pool_->ReserveVideoFrame(pixel_format_, capture_size); } // Compute the current in-flight utilization and attenuate it: The utilization @@ -991,7 +998,7 @@ // Clone a handle to the shared memory backing the populated video frame, to // send to the consumer. - auto handle = frame_pool_.CloneHandleForDelivery(*frame); + auto handle = frame_pool_->CloneHandleForDelivery(*frame); DCHECK(handle); DCHECK(handle->is_read_only_shmem_region());
diff --git a/components/viz/service/frame_sinks/video_capture/frame_sink_video_capturer_impl.h b/components/viz/service/frame_sinks/video_capture/frame_sink_video_capturer_impl.h index 1f0f932..d330e0a6 100644 --- a/components/viz/service/frame_sinks/video_capture/frame_sink_video_capturer_impl.h +++ b/components/viz/service/frame_sinks/video_capture/frame_sink_video_capturer_impl.h
@@ -25,9 +25,8 @@ #include "components/viz/common/surfaces/video_capture_target.h" #include "components/viz/service/frame_sinks/video_capture/capturable_frame_sink.h" #include "components/viz/service/frame_sinks/video_capture/in_flight_frame_delivery.h" -#include "components/viz/service/frame_sinks/video_capture/shared_memory_video_frame_pool.h" #include "components/viz/service/frame_sinks/video_capture/video_capture_overlay.h" -#include "components/viz/service/viz_service_export.h" +#include "components/viz/service/frame_sinks/video_capture/video_frame_pool.h" #include "media/base/video_frame.h" #include "media/capture/content/video_capture_oracle.h" #include "mojo/public/cpp/bindings/pending_receiver.h" @@ -380,7 +379,7 @@ // Provides a pool of VideoFrames that can be efficiently delivered across // processes. The size of this pool is used to limit the maximum number of // frames in-flight at any one time. - SharedMemoryVideoFramePool frame_pool_; + std::unique_ptr<VideoFramePool> frame_pool_; // Increased every time the source content changes or a forced refresh is // requested.
diff --git a/components/viz/service/frame_sinks/video_capture/shared_memory_video_frame_pool.cc b/components/viz/service/frame_sinks/video_capture/shared_memory_video_frame_pool.cc index 7ed15859..a8dde4b6 100644 --- a/components/viz/service/frame_sinks/video_capture/shared_memory_video_frame_pool.cc +++ b/components/viz/service/frame_sinks/video_capture/shared_memory_video_frame_pool.cc
@@ -63,7 +63,7 @@ // There are no available buffers. If the pool is at max capacity, punt. // Otherwise, allocate a new buffer, wrap it in a VideoFrame and return it. - if (utilized_buffers_.size() >= capacity_) { + if (utilized_buffers_.size() >= capacity()) { return nullptr; } PooledBuffer additional = @@ -87,10 +87,10 @@ it->second.Duplicate()); } -float SharedMemoryVideoFramePool::GetUtilization() const { +size_t SharedMemoryVideoFramePool::GetNumberOfReservedFrames() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - return static_cast<float>(utilized_buffers_.size()) / capacity_; + return utilized_buffers_.size(); } scoped_refptr<VideoFrame> SharedMemoryVideoFramePool::WrapBuffer( @@ -142,7 +142,7 @@ PooledBuffer{std::move(it->second), std::move(mapping)}); DCHECK(available_buffers_.back().IsValid()); utilized_buffers_.erase(it); - DCHECK_LE(available_buffers_.size() + utilized_buffers_.size(), capacity_); + DCHECK_LE(available_buffers_.size() + utilized_buffers_.size(), capacity()); } bool SharedMemoryVideoFramePool::CanLogSharedMemoryFailure() {
diff --git a/components/viz/service/frame_sinks/video_capture/shared_memory_video_frame_pool.h b/components/viz/service/frame_sinks/video_capture/shared_memory_video_frame_pool.h index 9bb9d2e..ffeb3b9 100644 --- a/components/viz/service/frame_sinks/video_capture/shared_memory_video_frame_pool.h +++ b/components/viz/service/frame_sinks/video_capture/shared_memory_video_frame_pool.h
@@ -47,7 +47,7 @@ media::mojom::VideoBufferHandlePtr CloneHandleForDelivery( const media::VideoFrame& frame) override; - float GetUtilization() const override; + size_t GetNumberOfReservedFrames() const override; private: using PooledBuffer = base::MappedReadOnlyRegion;
diff --git a/components/viz/service/frame_sinks/video_capture/shared_memory_video_frame_pool_unittest.cc b/components/viz/service/frame_sinks/video_capture/shared_memory_video_frame_pool_unittest.cc index 3fdb080..fa11951 100644 --- a/components/viz/service/frame_sinks/video_capture/shared_memory_video_frame_pool_unittest.cc +++ b/components/viz/service/frame_sinks/video_capture/shared_memory_video_frame_pool_unittest.cc
@@ -4,6 +4,8 @@ #include "components/viz/service/frame_sinks/video_capture/shared_memory_video_frame_pool.h" +#include <memory> + #include "media/base/video_frame.h" #include "media/base/video_util.h" #include "testing/gtest/include/gtest/gtest.h" @@ -127,12 +129,14 @@ TEST(SharedMemoryVideoFramePoolTest, ReportsCorrectUtilization) { SharedMemoryVideoFramePool pool(2); + ASSERT_EQ(0u, pool.GetNumberOfReservedFrames()); ASSERT_EQ(0.0f, pool.GetUtilization()); // Reserve the frame and expect 1/2 the pool to be utilized. scoped_refptr<media::VideoFrame> frame = pool.ReserveVideoFrame(kFormat, kSize); ASSERT_TRUE(frame); + ASSERT_EQ(1u, pool.GetNumberOfReservedFrames()); ASSERT_EQ(0.5f, pool.GetUtilization()); // Signal that the frame will be delivered. This should not change the @@ -141,14 +145,81 @@ auto handle = pool.CloneHandleForDelivery(*frame); ExpectValidHandleForDelivery(handle->get_read_only_shmem_region()); } + ASSERT_EQ(1u, pool.GetNumberOfReservedFrames()); ASSERT_EQ(0.5f, pool.GetUtilization()); // Finally, release the frame to indicate it has been delivered and is no // longer in-use by downstream consumers. This should cause the utilization // to go back down to zero. frame = nullptr; + ASSERT_EQ(0u, pool.GetNumberOfReservedFrames()); ASSERT_EQ(0.0f, pool.GetUtilization()); } +// Returns true iff each plane of the given |frame| is filled with +// |values[plane]|. +bool PlanesAreFilledWithValues(const VideoFrame& frame, const uint8_t* values) { + static_assert(VideoFrame::kUPlane == (VideoFrame::kYPlane + 1) && + VideoFrame::kVPlane == (VideoFrame::kUPlane + 1), + "enum values changed, will break code below"); + for (int plane = VideoFrame::kYPlane; plane <= VideoFrame::kVPlane; ++plane) { + const uint8_t expected_value = values[plane - VideoFrame::kYPlane]; + for (int y = 0; y < frame.rows(plane); ++y) { + const uint8_t* row = frame.visible_data(plane) + y * frame.stride(plane); + for (int x = 0; x < frame.row_bytes(plane); ++x) { + EXPECT_EQ(expected_value, row[x]) + << "at row " << y << " in plane " << plane; + if (expected_value != row[x]) + return false; + } + } + } + return true; +} + +TEST(SharedMemoryVideoFramePoolTest, FramesReturnedWhenPoolIsGone) { + constexpr gfx::ColorSpace kArbitraryColorSpace1 = + gfx::ColorSpace::CreateREC709(); + constexpr gfx::ColorSpace kArbitraryColorSpace2 = + gfx::ColorSpace::CreateSRGB(); + + // Create a pool dynamically, we will release it and verify that frames are + // still usable. + auto pool = std::make_unique<SharedMemoryVideoFramePool>(1); + + // Reserve a frame, populate it: + scoped_refptr<media::VideoFrame> frame = + pool->ReserveVideoFrame(kFormat, kSize); + ASSERT_TRUE(frame); + + constexpr uint8_t kValues1[3] = {0x11, 0x22, 0x33}; + media::FillYUV(frame.get(), kValues1[0], kValues1[1], kValues1[2]); + frame->set_color_space(kArbitraryColorSpace1); + + // Release pool, the VideoFrame should still be alive. + pool = nullptr; + + // Check that we can read the frame: + ASSERT_TRUE(frame); + ASSERT_EQ(kFormat, frame->format()); + ASSERT_EQ(kSize, frame->coded_size()); + ASSERT_EQ(kSize, frame->visible_rect().size()); + ASSERT_EQ(kSize, frame->natural_size()); + ASSERT_EQ(kArbitraryColorSpace1, frame->ColorSpace()); + ASSERT_TRUE(PlanesAreFilledWithValues(*frame, kValues1)); + + // Check that we can write to the frame: + constexpr uint8_t kValues2[3] = {0x44, 0x55, 0x66}; + media::FillYUV(frame.get(), kValues2[0], kValues2[1], kValues2[2]); + frame->set_color_space(kArbitraryColorSpace2); + + // Read again, this time expect new values: + ASSERT_EQ(kArbitraryColorSpace2, frame->ColorSpace()); + ASSERT_TRUE(PlanesAreFilledWithValues(*frame, kValues2)); + + // Release the frame to force the dtor to run now: + frame = nullptr; +} + } // namespace } // namespace viz
diff --git a/components/viz/service/frame_sinks/video_capture/video_frame_pool.cc b/components/viz/service/frame_sinks/video_capture/video_frame_pool.cc new file mode 100644 index 0000000..5b63bcb --- /dev/null +++ b/components/viz/service/frame_sinks/video_capture/video_frame_pool.cc
@@ -0,0 +1,24 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include <algorithm> +#include <memory> + +#include "components/viz/service/frame_sinks/video_capture/shared_memory_video_frame_pool.h" +#include "components/viz/service/frame_sinks/video_capture/video_frame_pool.h" + +namespace viz { + +VideoFramePool::VideoFramePool(int capacity) + : capacity_(std::max(0, capacity)) { + DCHECK_GT(capacity_, 0u); +} + +VideoFramePool::~VideoFramePool() = default; + +float VideoFramePool::GetUtilization() const { + return static_cast<float>(GetNumberOfReservedFrames()) / capacity_; +} + +} // namespace viz
diff --git a/components/viz/service/frame_sinks/video_capture/video_frame_pool.h b/components/viz/service/frame_sinks/video_capture/video_frame_pool.h index 1fd997ca..a15a470 100644 --- a/components/viz/service/frame_sinks/video_capture/video_frame_pool.h +++ b/components/viz/service/frame_sinks/video_capture/video_frame_pool.h
@@ -27,7 +27,7 @@ VideoFramePool& operator=(const VideoFramePool&) = delete; VideoFramePool& operator=(VideoFramePool&&) = delete; - virtual ~VideoFramePool() = default; + virtual ~VideoFramePool(); // Reserves a buffer from the pool and creates a VideoFrame backed by it. // When the ref-count of the returned VideoFrame goes to zero, the @@ -47,15 +47,20 @@ // Returns the current pool utilization, based on the number of VideoFrames // being held by the client. - virtual float GetUtilization() const = 0; + float GetUtilization() const; + + // Returns the number of frames that are currently reserved (and thus still + // owned by the caller of |ReserveVideoFrame()|). + virtual size_t GetNumberOfReservedFrames() const = 0; + + size_t capacity() const { return capacity_; } protected: // |capacity| is the maximum number of pooled VideoFrames; but they can be of // any byte size. - explicit VideoFramePool(int capacity) : capacity_(capacity) { - DCHECK_GT(capacity_, 0u); - } + explicit VideoFramePool(int capacity); + private: // The maximum number of buffers. However, the buffers themselves can be of // any byte size. const size_t capacity_;
diff --git a/content/browser/BUILD.gn b/content/browser/BUILD.gn index 2c15b74..fa31673 100644 --- a/content/browser/BUILD.gn +++ b/content/browser/BUILD.gn
@@ -2493,13 +2493,16 @@ "media/capture/desktop_capturer_lacros.cc", "media/capture/desktop_capturer_lacros.h", ] - deps += [ - "//chromeos/crosapi/mojom", - "//chromeos/lacros", - ] } } + if (is_chromeos_lacros) { + deps += [ + "//chromeos/crosapi/mojom", + "//chromeos/lacros", + ] + } + if (is_win) { sources += [ "font_access/font_enumeration_cache_win.cc",
diff --git a/content/browser/accessibility/dump_accessibility_node_browsertest.cc b/content/browser/accessibility/dump_accessibility_node_browsertest.cc index 433c8fd..e7da6b6 100644 --- a/content/browser/accessibility/dump_accessibility_node_browsertest.cc +++ b/content/browser/accessibility/dump_accessibility_node_browsertest.cc
@@ -941,6 +941,18 @@ } IN_PROC_BROWSER_TEST_P(DumpAccessibilityAccNameTest, + NameTextLabelledbyHiddenDifferentVisibilityTypes) { + RunAccNameTest(FILE_PATH_LITERAL( + "name-text-labelledby-hidden-different-visibility-types.html")); +} + +IN_PROC_BROWSER_TEST_P(DumpAccessibilityAccNameTest, + NameTextLabelledbyHiddenMultipleLevels) { + RunAccNameTest( + FILE_PATH_LITERAL("name-text-labelledby-hidden-multiple-levels.html")); +} + +IN_PROC_BROWSER_TEST_P(DumpAccessibilityAccNameTest, NameTextLabelledbyHiddenWithHiddenChild) { RunAccNameTest( FILE_PATH_LITERAL("name-text-labelledby-hidden-with-hidden-child.html")); @@ -966,6 +978,11 @@ RunAccNameTest(FILE_PATH_LITERAL("name-text-label-with-input.html")); } +IN_PROC_BROWSER_TEST_P(DumpAccessibilityAccNameTest, + NameTextLabelWithReadonlyInput) { + RunAccNameTest(FILE_PATH_LITERAL("name-text-label-with-readonly-input.html")); +} + IN_PROC_BROWSER_TEST_P(DumpAccessibilityAccNameTest, NameTextSelectInLabel) { RunAccNameTest(FILE_PATH_LITERAL("name-text-select-in-label.html")); }
diff --git a/content/browser/android/overscroll_controller_android_unittest.cc b/content/browser/android/overscroll_controller_android_unittest.cc index c7fde9c..5edcaefa 100644 --- a/content/browser/android/overscroll_controller_android_unittest.cc +++ b/content/browser/android/overscroll_controller_android_unittest.cc
@@ -48,6 +48,10 @@ void OnUpdateRefreshRate(float refresh_rate) override {} void OnUpdateSupportedRefreshRates( const std::vector<float>& supported_refresh_rates) override {} + std::unique_ptr<ui::CompositorLock> GetCompositorLock( + base::TimeDelta timeout) override { + return nullptr; + } }; class MockGlowClient : public OverscrollGlowClient {
diff --git a/content/browser/bad_message.h b/content/browser/bad_message.h index 35e5348..fca5ef2 100644 --- a/content/browser/bad_message.h +++ b/content/browser/bad_message.h
@@ -281,6 +281,7 @@ RFH_CREATE_CHILD_FRAME_SANDBOX_FLAGS = 254, RFPH_FOCUSED_FENCED_FRAME = 255, WCI_REQUEST_LOCK_MOUSE_FENCED_FRAME = 256, + RFH_FENCED_FRAME_MOJO_WHEN_DISABLED = 257, // Please add new elements here. The naming convention is abbreviated class // name (e.g. RenderFrameHost becomes RFH) plus a unique description of the
diff --git a/content/browser/blob_storage/blob_registry_wrapper.cc b/content/browser/blob_storage/blob_registry_wrapper.cc index 2d460c74..abd1e81 100644 --- a/content/browser/blob_storage/blob_registry_wrapper.cc +++ b/content/browser/blob_storage/blob_registry_wrapper.cc
@@ -30,9 +30,10 @@ bool CanReadFileSystemFile(const storage::FileSystemURL& url) override { return security_policy_handle_.CanReadFileSystemFile(url); } - bool CanCommitURL(const GURL& url) override { - return security_policy_handle_.CanCommitURL(url); + bool CanAccessDataForOrigin(const url::Origin& origin) override { + return security_policy_handle_.CanAccessDataForOrigin(origin); } + private: ChildProcessSecurityPolicyImpl::Handle security_policy_handle_; };
diff --git a/content/browser/devtools/protocol/target_handler.cc b/content/browser/devtools/protocol/target_handler.cc index 95023d3..66400f9 100644 --- a/content/browser/devtools/protocol/target_handler.cc +++ b/content/browser/devtools/protocol/target_handler.cc
@@ -1286,8 +1286,10 @@ return; if (auto_attached_sessions_.count(agent_host)) { - auto_attached_sessions_[agent_host]->SetWorkerThrottle( - std::move(throttle_handle)); + if (auto_attached_sessions_[agent_host]->IsWaitingForDebuggerOnStart()) { + auto_attached_sessions_[agent_host]->SetWorkerThrottle( + std::move(throttle_handle)); + } } }
diff --git a/content/browser/direct_sockets/direct_sockets_service_impl.cc b/content/browser/direct_sockets/direct_sockets_service_impl.cc index 267a2bf..c241bae 100644 --- a/content/browser/direct_sockets/direct_sockets_service_impl.cc +++ b/content/browser/direct_sockets/direct_sockets_service_impl.cc
@@ -33,6 +33,9 @@ #include "base/enterprise_util.h" #elif BUILDFLAG(IS_CHROMEOS_ASH) #include "chromeos/tpm/install_attributes.h" +#elif BUILDFLAG(IS_CHROMEOS_LACROS) +#include "chromeos/crosapi/mojom/crosapi.mojom.h" // nogncheck +#include "chromeos/lacros/lacros_service.h" // nogncheck #endif namespace content { @@ -147,6 +150,9 @@ #elif BUILDFLAG(IS_CHROMEOS_ASH) return chromeos::InstallAttributes::IsInitialized() && chromeos::InstallAttributes::Get()->IsEnterpriseManaged(); +#elif BUILDFLAG(IS_CHROMEOS_LACROS) + auto* lacros_service = chromeos::LacrosService::Get(); + return lacros_service->init_params()->is_device_enterprised_managed; #else return false; #endif
diff --git a/content/browser/renderer_host/compositor_impl_android.cc b/content/browser/renderer_host/compositor_impl_android.cc index da09b5c..13e92e6 100644 --- a/content/browser/renderer_host/compositor_impl_android.cc +++ b/content/browser/renderer_host/compositor_impl_android.cc
@@ -292,7 +292,8 @@ client_(client), needs_animate_(false), pending_frames_(0U), - layer_tree_frame_sink_request_pending_(false) { + layer_tree_frame_sink_request_pending_(false), + lock_manager_(base::ThreadTaskRunnerHandle::Get()) { DCHECK(client); SetRootWindow(root_window); @@ -675,6 +676,14 @@ return gpu_capabilities_.texture_format_etc1_npot; } +std::unique_ptr<ui::CompositorLock> CompositorImpl::GetCompositorLock( + base::TimeDelta timeout) { + if (!host_) + return nullptr; + return lock_manager_.GetCompositorLock(/*client=*/nullptr, timeout, + host_->DeferMainFrameUpdate()); +} + void CompositorImpl::DidSubmitCompositorFrame() { TRACE_EVENT0("compositor", "CompositorImpl::DidSubmitCompositorFrame"); pending_frames_++;
diff --git a/content/browser/renderer_host/compositor_impl_android.h b/content/browser/renderer_host/compositor_impl_android.h index d5d3f26..c7f34ab 100644 --- a/content/browser/renderer_host/compositor_impl_android.h +++ b/content/browser/renderer_host/compositor_impl_android.h
@@ -171,6 +171,8 @@ void OnUpdateRefreshRate(float refresh_rate) override; void OnUpdateSupportedRefreshRates( const std::vector<float>& supported_refresh_rates) override; + std::unique_ptr<ui::CompositorLock> GetCompositorLock( + base::TimeDelta timeout) override; // viz::HostFrameSinkClient implementation. void OnFirstSurfaceActivation(const viz::SurfaceInfo& surface_info) override; @@ -286,6 +288,8 @@ // factor accordingly. display::ScopedDisplayObserver display_observer_{this}; + ui::CompositorLockManager lock_manager_; + base::WeakPtrFactory<CompositorImpl> weak_factory_{this}; };
diff --git a/content/browser/renderer_host/navigation_request.cc b/content/browser/renderer_host/navigation_request.cc index 85f281d..5d347b9 100644 --- a/content/browser/renderer_host/navigation_request.cc +++ b/content/browser/renderer_host/navigation_request.cc
@@ -150,9 +150,15 @@ #include "third_party/blink/public/mojom/service_worker/service_worker_provider.mojom.h" #include "third_party/blink/public/mojom/web_feature/web_feature.mojom.h" #include "third_party/blink/public/platform/resource_request_blocked_reason.h" +#include "ui/compositor/compositor_lock.h" #include "url/origin.h" #include "url/url_constants.h" +#if defined(OS_ANDROID) +#include "ui/android/window_android.h" +#include "ui/android/window_android_compositor.h" +#endif + namespace content { namespace { @@ -1607,6 +1613,31 @@ } begin_params_->headers = headers.ToString(); + +#if defined(OS_ANDROID) + static constexpr base::Feature kOptimizeEarlyNavigation{ + "OptimizeEarlyNavigation", base::FEATURE_DISABLED_BY_DEFAULT}; + static constexpr base::FeatureParam<base::TimeDelta> kCompositorLockTimeout{ + &kOptimizeEarlyNavigation, "compositor_lock_timeout", + base::Milliseconds(150)}; + + RenderWidgetHostImpl* host = RenderWidgetHostImpl::From( + frame_tree_node_->current_frame_host()->GetRenderWidgetHost()); + if (base::FeatureList::IsEnabled(kOptimizeEarlyNavigation) && + NeedsUrlLoader() && frame_tree_node_->IsMainFrame() && host && + !host->is_hidden() && host->GetView() && + host->GetView()->GetNativeView() && + host->GetView()->GetNativeView()->GetWindowAndroid()) { + // If the compositor changes, we will just let the lock timeout instead of + // trying to deal with it explicitly. + ui::WindowAndroidCompositor* compositor = + host->GetView()->GetNativeView()->GetWindowAndroid()->GetCompositor(); + if (compositor) { + compositor_lock_ = + compositor->GetCompositorLock(kCompositorLockTimeout.Get()); + } + } +#endif } NavigationRequest::~NavigationRequest() { @@ -3861,6 +3892,9 @@ network::mojom::WebSandboxFlags sandbox_flags = commit_params_->frame_policy.sandbox_flags; + // Reset the compositor lock before starting the loader. + compositor_lock_.reset(); + loader_ = NavigationURLLoader::Create( browser_context, partition, std::make_unique<NavigationRequestInfo>( @@ -3884,6 +3918,7 @@ NetworkServiceDevToolsObserver::MakeSelfOwned(frame_tree_node_), std::move(cached_response_head), std::move(interceptor)); DCHECK(!render_frame_host_); + loader_->Start(); // DO NOT ADD CODE after this. The previous call to // NavigationURLLoader::Start() could cause the destruction of the
diff --git a/content/browser/renderer_host/navigation_request.h b/content/browser/renderer_host/navigation_request.h index 2d5525d..e64960d5 100644 --- a/content/browser/renderer_host/navigation_request.h +++ b/content/browser/renderer_host/navigation_request.h
@@ -83,6 +83,10 @@ struct URLLoaderCompletionStatus; } // namespace network +namespace ui { +class CompositorLock; +} // namespace ui + namespace content { class CrossOriginEmbedderPolicyReporter; @@ -1937,6 +1941,10 @@ // PrerenderTriggerType is kEmbedder. Only used for metrics. std::string prerender_embedder_histogram_suffix_; + // Prevents the compositor from requesting main frame updates early in + // navigation. + std::unique_ptr<ui::CompositorLock> compositor_lock_; + base::WeakPtrFactory<NavigationRequest> weak_factory_{this}; };
diff --git a/content/browser/renderer_host/render_frame_host_impl.cc b/content/browser/renderer_host/render_frame_host_impl.cc index 1e7bcbb5..34241f2 100644 --- a/content/browser/renderer_host/render_frame_host_impl.cc +++ b/content/browser/renderer_host/render_frame_host_impl.cc
@@ -6888,6 +6888,12 @@ mojo::PendingAssociatedReceiver<blink::mojom::FencedFrameOwnerHost> pending_receiver, CreateFencedFrameCallback callback) { + if (!blink::features::IsFencedFramesEnabled() || + !blink::features::IsFencedFramesMPArchBased()) { + bad_message::ReceivedBadMessage( + GetProcess(), bad_message::RFH_FENCED_FRAME_MOJO_WHEN_DISABLED); + return; + } fenced_frames_.push_back( std::make_unique<FencedFrame>(weak_ptr_factory_.GetSafeRef())); FencedFrame* fenced_frame = fenced_frames_.back().get();
diff --git a/content/browser/renderer_host/render_widget_host_view_android.cc b/content/browser/renderer_host/render_widget_host_view_android.cc index a61504d6..091f350 100644 --- a/content/browser/renderer_host/render_widget_host_view_android.cc +++ b/content/browser/renderer_host/render_widget_host_view_android.cc
@@ -1157,6 +1157,9 @@ for (auto& observer : destruction_observers_) observer.RenderWidgetHostViewDestroyed(this); destruction_observers_.Clear(); + // Call this before the derived class is destroyed so that virtual function + // calls back into `this` still work. + NotifyObserversAboutShutdown(); RenderWidgetHostViewBase::Destroy(); delete this; }
diff --git a/content/browser/renderer_host/render_widget_host_view_aura.cc b/content/browser/renderer_host/render_widget_host_view_aura.cc index 1c1dab5..9bbfba2 100644 --- a/content/browser/renderer_host/render_widget_host_view_aura.cc +++ b/content/browser/renderer_host/render_widget_host_view_aura.cc
@@ -817,6 +817,10 @@ // destructor is invoked directly from here. So all destruction/cleanup code // should happen there, not here. in_shutdown_ = true; + // Call this here in case any observers need access to `this` before we + // destruct the derived class. + NotifyObserversAboutShutdown(); + if (window_) delete window_; else
diff --git a/content/browser/security_exploit_browsertest.cc b/content/browser/security_exploit_browsertest.cc index b01bc217..afdc02f 100644 --- a/content/browser/security_exploit_browsertest.cc +++ b/content/browser/security_exploit_browsertest.cc
@@ -1854,4 +1854,28 @@ Optional(HasSubstr("Trust Token params in fenced frame nav"))); } +// Ensure that we kill the renderer process if we try to create a +// fenced-frame when the blink::features::kFencedFrames feature is not enabled. +IN_PROC_BROWSER_TEST_F(SecurityExploitBrowserTest, + CreateFencedFrameWhenFeatureDisabled) { + GURL foo("http://foo.com/simple_page.html"); + EXPECT_TRUE(NavigateToURL(shell(), foo)); + EXPECT_EQ(u"OK", shell()->web_contents()->GetTitle()); + EXPECT_FALSE(blink::features::IsFencedFramesEnabled()); + + RenderFrameHostImpl* compromised_rfh = static_cast<RenderFrameHostImpl*>( + shell()->web_contents()->GetMainFrame()); + + mojo::PendingAssociatedRemote<blink::mojom::FencedFrameOwnerHost> remote; + mojo::PendingAssociatedReceiver<blink::mojom::FencedFrameOwnerHost> receiver; + receiver = remote.InitWithNewEndpointAndPassReceiver(); + + RenderProcessHostBadIpcMessageWaiter kill_waiter( + compromised_rfh->GetProcess()); + static_cast<mojom::FrameHost*>(compromised_rfh) + ->CreateFencedFrame(std::move(receiver), base::NullCallback()); + EXPECT_EQ(bad_message::RFH_FENCED_FRAME_MOJO_WHEN_DISABLED, + kill_waiter.Wait()); +} + } // namespace content
diff --git a/content/browser/webauth/authenticator_common.cc b/content/browser/webauth/authenticator_common.cc index b7052d3..a728c9b 100644 --- a/content/browser/webauth/authenticator_common.cc +++ b/content/browser/webauth/authenticator_common.cc
@@ -775,7 +775,7 @@ // UV_REQUIRED only makes sense if UV is required overall. (options->protection_policy == blink::mojom::ProtectionPolicy::UV_REQUIRED && - authenticator_selection_criteria.user_verification_requirement() != + authenticator_selection_criteria.user_verification_requirement != device::UserVerificationRequirement::kRequired)) { CompleteMakeCredentialRequest( blink::mojom::AuthenticatorStatus::PROTECTION_POLICY_INCONSISTENT); @@ -1767,7 +1767,7 @@ auto common_info = blink::mojom::CommonCredentialInfo::New(); common_info->client_data_json.assign(client_data_json_.begin(), client_data_json_.end()); - common_info->raw_id = response_data.credential->id(); + common_info->raw_id = response_data.credential->id; common_info->id = Base64UrlEncode(common_info->raw_id); response->info = std::move(common_info); response->info->authenticator_data =
diff --git a/content/browser/webauth/authenticator_impl_unittest.cc b/content/browser/webauth/authenticator_impl_unittest.cc index 6b01d86..485344f1 100644 --- a/content/browser/webauth/authenticator_impl_unittest.cc +++ b/content/browser/webauth/authenticator_impl_unittest.cc
@@ -860,8 +860,8 @@ PublicKeyCredentialCreationOptionsPtr options = GetTestPublicKeyCredentialCreationOptions(); - options->authenticator_selection->SetUserVerificationRequirementForTesting( - device::UserVerificationRequirement::kRequired); + options->authenticator_selection->user_verification_requirement = + device::UserVerificationRequirement::kRequired; EXPECT_EQ( AuthenticatorMakeCredentialAndWaitForTimeout(std::move(options)).status, @@ -873,8 +873,8 @@ PublicKeyCredentialCreationOptionsPtr options = GetTestPublicKeyCredentialCreationOptions(); - options->authenticator_selection->SetResidentKeyForTesting( - device::ResidentKeyRequirement::kRequired); + options->authenticator_selection->resident_key = + device::ResidentKeyRequirement::kRequired; EXPECT_EQ(AuthenticatorMakeCredential(std::move(options)).status, AuthenticatorStatus::RESIDENT_CREDENTIALS_UNSUPPORTED); @@ -887,8 +887,8 @@ PublicKeyCredentialCreationOptionsPtr options = GetTestPublicKeyCredentialCreationOptions(); - options->authenticator_selection->SetAuthenticatorAttachmentForTesting( - device::AuthenticatorAttachment::kPlatform); + options->authenticator_selection->authenticator_attachment = + device::AuthenticatorAttachment::kPlatform; EXPECT_EQ( AuthenticatorMakeCredentialAndWaitForTimeout(std::move(options)).status, @@ -1044,7 +1044,7 @@ // Inject a registration for the URL (which is a U2F AppID). ASSERT_TRUE(virtual_device_factory_->mutable_state()->InjectRegistration( - options->allow_credentials[0].id(), kTestOrigin1)); + options->allow_credentials[0].id, kTestOrigin1)); options->appid = kTestOrigin1; @@ -1063,7 +1063,7 @@ // Inject a registration for the URL (which is a U2F AppID). ASSERT_TRUE(virtual_device_factory_->mutable_state()->InjectRegistration( - options->allow_credentials[0].id(), kTestOrigin1)); + options->allow_credentials[0].id, kTestOrigin1)); options->appid = kTestOrigin1; @@ -1133,7 +1133,7 @@ PublicKeyCredentialRequestOptionsPtr options = GetTestPublicKeyCredentialRequestOptions(); ASSERT_TRUE(virtual_device_factory_->mutable_state()->InjectRegistration( - options->allow_credentials[0].id(), kTestOrigin1)); + options->allow_credentials[0].id, kTestOrigin1)); options->appid = kTestOrigin1; EXPECT_EQ(AuthenticatorGetAssertion(std::move(options)).status, @@ -1150,7 +1150,7 @@ PublicKeyCredentialRequestOptionsPtr options = GetTestPublicKeyCredentialRequestOptions(); ASSERT_TRUE(virtual_device_factory_->mutable_state()->InjectRegistration( - options->allow_credentials[0].id(), kTestOrigin1)); + options->allow_credentials[0].id, kTestOrigin1)); options->appid = kTestOrigin1; EXPECT_EQ( @@ -1172,7 +1172,7 @@ PublicKeyCredentialRequestOptionsPtr options = GetTestPublicKeyCredentialRequestOptions(); ASSERT_TRUE(virtual_device_factory_->mutable_state()->InjectRegistration( - options->allow_credentials[0].id(), kTestOrigin1)); + options->allow_credentials[0].id, kTestOrigin1)); options->appid = kTestOrigin1; EXPECT_EQ(AuthenticatorGetAssertion(std::move(options)).status, @@ -1223,7 +1223,7 @@ PublicKeyCredentialRequestOptionsPtr options = GetTestPublicKeyCredentialRequestOptions(); ASSERT_TRUE(virtual_device_factory_->mutable_state()->InjectRegistration( - options->allow_credentials[0].id(), kTestRelyingPartyId)); + options->allow_credentials[0].id, kTestRelyingPartyId)); GetAssertionResult result = AuthenticatorGetAssertion(std::move(options)); ASSERT_EQ(result.status, AuthenticatorStatus::SUCCESS); @@ -1237,7 +1237,7 @@ PublicKeyCredentialRequestOptionsPtr options = GetTestPublicKeyCredentialRequestOptions(); ASSERT_TRUE(virtual_device_factory_->mutable_state()->InjectRegistration( - options->allow_credentials[0].id(), kTestRelyingPartyId)); + options->allow_credentials[0].id, kTestRelyingPartyId)); // This AppID won't be used because the RP ID will be tried (successfully) // first. @@ -1256,7 +1256,7 @@ GetTestPublicKeyCredentialRequestOptions(); // Inject a registration for the URL (which is a U2F AppID). ASSERT_TRUE(virtual_device_factory_->mutable_state()->InjectRegistration( - options->allow_credentials[0].id(), kTestOrigin1)); + options->allow_credentials[0].id, kTestOrigin1)); options->appid = kTestOrigin1; @@ -1281,7 +1281,7 @@ PublicKeyCredentialRequestOptionsPtr options = GetTestPublicKeyCredentialRequestOptions(); ASSERT_TRUE(virtual_device_factory_->mutable_state()->InjectRegistration( - options->allow_credentials[0].id(), kTestOrigin1)); + options->allow_credentials[0].id, kTestOrigin1)); options->appid = kTestOrigin1; @@ -1316,7 +1316,7 @@ if (credential_already_exists) { ASSERT_TRUE( virtual_device_factory_->mutable_state()->InjectRegistration( - options->exclude_credentials[0].id(), kTestOrigin1)); + options->exclude_credentials[0].id, kTestOrigin1)); } MakeCredentialResult result = @@ -1357,7 +1357,7 @@ options->exclude_credentials = GetTestCredentials(); for (const auto& cred : options->exclude_credentials) { - ASSERT_GT(cred.id().size(), config.max_credential_id_length); + ASSERT_GT(cred.id.size(), config.max_credential_id_length); } EXPECT_EQ(AuthenticatorMakeCredential(std::move(options)).status, @@ -1392,15 +1392,15 @@ PublicKeyCredentialRequestOptionsPtr options = GetTestPublicKeyCredentialRequestOptions(); device::PublicKeyCredentialDescriptor credential; - credential.SetCredentialTypeForTesting(device::CredentialType::kPublicKey); - credential.GetIdForTesting().resize(size); - credential.GetTransportsForTesting().emplace( + credential.credential_type = device::CredentialType::kPublicKey; + credential.id.resize(size); + credential.transports.emplace( device::FidoTransportProtocol::kUsbHumanInterfaceDevice); const bool should_be_valid = size < 256; if (should_be_valid) { ASSERT_TRUE(virtual_device_factory_->mutable_state()->InjectRegistration( - credential.id(), kTestRelyingPartyId)); + credential.id, kTestRelyingPartyId)); } options->allow_credentials.emplace_back(credential); @@ -1435,14 +1435,14 @@ virtual_device_factory_->SetTransport( device::FidoTransportProtocol::kCloudAssistedBluetoothLowEnergy); for (auto& cred : options->allow_credentials) { - cred.GetTransportsForTesting().clear(); - cred.GetTransportsForTesting().emplace( + cred.transports.clear(); + cred.transports.emplace( device::FidoTransportProtocol::kCloudAssistedBluetoothLowEnergy); } } ASSERT_TRUE(virtual_device_factory_->mutable_state()->InjectRegistration( - options->allow_credentials[0].id(), kTestRelyingPartyId)); + options->allow_credentials[0].id, kTestRelyingPartyId)); // If a caBLE device is not simulated then silent requests should be used. // The virtual device will return an error because @@ -1461,7 +1461,7 @@ // Inject credential ID to the virtual device so that successful sign in is // possible. ASSERT_TRUE(virtual_device_factory_->mutable_state()->InjectRegistration( - options->allow_credentials[0].id(), kTestRelyingPartyId)); + options->allow_credentials[0].id, kTestRelyingPartyId)); EXPECT_EQ(AuthenticatorGetAssertion(std::move(options)).status, AuthenticatorStatus::SUCCESS); @@ -1485,7 +1485,7 @@ // Exclude the one already registered credential. options->exclude_credentials = GetTestCredentials(); ASSERT_TRUE(virtual_device_factory_->mutable_state()->InjectRegistration( - options->exclude_credentials[0].id(), kTestRelyingPartyId)); + options->exclude_credentials[0].id, kTestRelyingPartyId)); EXPECT_EQ(AuthenticatorMakeCredential(std::move(options)).status, AuthenticatorStatus::CREDENTIAL_EXCLUDED); @@ -1630,7 +1630,7 @@ PublicKeyCredentialRequestOptionsPtr options = GetTestPublicKeyCredentialRequestOptions(); ASSERT_TRUE(virtual_device_factory_->mutable_state()->InjectRegistration( - options->allow_credentials[0].id(), kTestRelyingPartyId)); + options->allow_credentials[0].id, kTestRelyingPartyId)); NavigateAndCommit(GURL(kTestOrigin1)); @@ -2979,7 +2979,7 @@ GetTestPublicKeyCredentialRequestOptions(); if (!credential_added) { ASSERT_TRUE(virtual_device_factory_->mutable_state()->InjectRegistration( - options->allow_credentials[0].id(), kTestRelyingPartyId)); + options->allow_credentials[0].id, kTestRelyingPartyId)); credential_added = true; } @@ -3097,13 +3097,13 @@ { device::PublicKeyCredentialDescriptor credential; - credential.SetCredentialTypeForTesting(device::CredentialType::kPublicKey); - credential.GetIdForTesting().resize(16); - credential.GetTransportsForTesting() = { + credential.credential_type = device::CredentialType::kPublicKey; + credential.id.resize(16); + credential.transports = { device::FidoTransportProtocol::kUsbHumanInterfaceDevice}; ASSERT_TRUE(virtual_device_factory_->mutable_state()->InjectRegistration( - credential.id(), kTestRelyingPartyId)); + credential.id, kTestRelyingPartyId)); PublicKeyCredentialRequestOptionsPtr options = GetTestPublicKeyCredentialRequestOptions(); options->allow_credentials.emplace_back(credential); @@ -3374,7 +3374,7 @@ GetTestPublicKeyCredentialCreationOptions(); options->exclude_credentials = GetTestCredentials(); ASSERT_TRUE(virtual_device_factory_->mutable_state()->InjectRegistration( - options->exclude_credentials[0].id(), kTestRelyingPartyId)); + options->exclude_credentials[0].id, kTestRelyingPartyId)); TestMakeCredentialCallback callback_receiver; authenticator->MakeCredential(std::move(options), @@ -3507,7 +3507,7 @@ options->exclude_credentials = GetTestCredentials(/*num_credentials=*/10); if (has_excluded_credential) { ASSERT_TRUE(virtual_device_factory_->mutable_state()->InjectRegistration( - options->exclude_credentials.back().id(), kTestRelyingPartyId)); + options->exclude_credentials.back().id, kTestRelyingPartyId)); } EXPECT_EQ(AuthenticatorMakeCredential(std::move(options)).status, @@ -3536,7 +3536,7 @@ options->allow_credentials = GetTestCredentials(/*num_credentials=*/10); if (has_allowed_credential) { ASSERT_TRUE(virtual_device_factory_->mutable_state()->InjectRegistration( - options->allow_credentials.back().id(), kTestRelyingPartyId)); + options->allow_credentials.back().id, kTestRelyingPartyId)); } EXPECT_EQ(AuthenticatorGetAssertion(std::move(options)).status, @@ -3565,7 +3565,7 @@ auto test_credentials = GetTestCredentials(/*num_credentials=*/1); ASSERT_TRUE(virtual_device_factory_->mutable_state()->InjectRegistration( - test_credentials.front().id(), kTestRelyingPartyId)); + test_credentials.front().id, kTestRelyingPartyId)); PublicKeyCredentialRequestOptionsPtr options = GetTestPublicKeyCredentialRequestOptions(); @@ -3597,7 +3597,7 @@ /*num_credentials=*/kBatchSize + (allow_list_fits_single_batch ? 0 : 1)); ASSERT_TRUE(virtual_device_factory_->mutable_state()->InjectRegistration( - test_credentials.back().id(), kTestRelyingPartyId)); + test_credentials.back().id, kTestRelyingPartyId)); PublicKeyCredentialRequestOptionsPtr options = GetTestPublicKeyCredentialRequestOptions(); @@ -3654,7 +3654,7 @@ auto test_credentials = GetTestCredentials(num_credentials); for (const auto& cred : test_credentials) { ASSERT_TRUE(virtual_device_factory_->mutable_state()->InjectRegistration( - cred.id(), kTestRelyingPartyId)); + cred.id, kTestRelyingPartyId)); } PublicKeyCredentialRequestOptionsPtr options = @@ -3744,7 +3744,7 @@ {device::FidoTransportProtocol::kBluetoothLowEnergy}); ASSERT_TRUE(virtual_device_factory_->mutable_state()->InjectRegistration( - cred_b.id(), kTestRelyingPartyId)); + cred_b.id, kTestRelyingPartyId)); PublicKeyCredentialRequestOptionsPtr options = GetTestPublicKeyCredentialRequestOptions(); @@ -3843,7 +3843,7 @@ kPublicKeyCredentialDescriptorListMaxSize + 1); ASSERT_TRUE(virtual_device_factory_->mutable_state()->InjectRegistration( - test_credentials.at(0).id(), kTestRelyingPartyId)); + test_credentials.at(0).id, kTestRelyingPartyId)); PublicKeyCredentialRequestOptionsPtr options = GetTestPublicKeyCredentialRequestOptions(); @@ -3902,7 +3902,7 @@ PublicKeyCredentialRequestOptionsPtr assertion_options = GetTestPublicKeyCredentialRequestOptions(); ASSERT_TRUE(virtual_device_factory_->mutable_state()->InjectRegistration( - assertion_options->allow_credentials.back().id(), kTestRelyingPartyId)); + assertion_options->allow_credentials.back().id, kTestRelyingPartyId)); EXPECT_EQ(AuthenticatorGetAssertion(std::move(assertion_options)).status, AuthenticatorStatus::NOT_ALLOWED_ERROR); } @@ -3921,7 +3921,7 @@ PublicKeyCredentialRequestOptionsPtr assertion_options = GetTestPublicKeyCredentialRequestOptions(); ASSERT_TRUE(virtual_device_factory_->mutable_state()->InjectRegistration( - assertion_options->allow_credentials.back().id(), kTestRelyingPartyId)); + assertion_options->allow_credentials.back().id, kTestRelyingPartyId)); EXPECT_EQ(AuthenticatorGetAssertion(std::move(assertion_options)).status, AuthenticatorStatus::SUCCESS); } @@ -3954,7 +3954,7 @@ std::vector<uint8_t>(kTestCredentialIdLength + 1, 1)}); if (authenticator_has_excluded_credential) { ASSERT_TRUE(virtual_device_factory_->mutable_state()->InjectRegistration( - test_credentials.back().id(), kTestRelyingPartyId)); + test_credentials.back().id, kTestRelyingPartyId)); } PublicKeyCredentialCreationOptionsPtr options = @@ -4217,7 +4217,7 @@ PublicKeyCredentialRequestOptionsPtr options = GetTestPublicKeyCredentialRequestOptions(); ASSERT_TRUE(virtual_device_factory_->mutable_state()->InjectRegistration( - options->allow_credentials[0].id(), kTestOrigin1)); + options->allow_credentials[0].id, kTestOrigin1)); options->appid = kTestOrigin1; EXPECT_EQ( @@ -4436,7 +4436,7 @@ PublicKeyCredentialRequestOptionsPtr dummy_options = GetTestPublicKeyCredentialRequestOptions(); ASSERT_TRUE(device_1.state->InjectRegistration( - dummy_options->allow_credentials[0].id(), kTestRelyingPartyId)); + dummy_options->allow_credentials[0].id, kTestRelyingPartyId)); discovery->AddDevice(std::move(device_1)); // Make a device that does not support PUATs but can still handle the @@ -4572,8 +4572,7 @@ CHECK(exclude_credentials); options->appid_exclude = kTestOrigin1; } - options->authenticator_selection->SetUserVerificationRequirementForTesting( - uv); + options->authenticator_selection->user_verification_requirement = uv; return options; } @@ -5167,13 +5166,12 @@ } PublicKeyCredentialCreationOptionsPtr request = make_credential_options(); - request->authenticator_selection - ->SetUserVerificationRequirementForTesting( - request_uv ? device::UserVerificationRequirement::kPreferred - : device::UserVerificationRequirement::kDiscouraged); - request->authenticator_selection->SetResidentKeyForTesting( + request->authenticator_selection->user_verification_requirement = + request_uv ? device::UserVerificationRequirement::kPreferred + : device::UserVerificationRequirement::kDiscouraged; + request->authenticator_selection->resident_key = discoverable ? device::ResidentKeyRequirement::kPreferred - : device::ResidentKeyRequirement::kDiscouraged); + : device::ResidentKeyRequirement::kDiscouraged; MakeCredentialResult result = AuthenticatorMakeCredential(std::move(request)); @@ -5243,7 +5241,7 @@ PublicKeyCredentialRequestOptionsPtr dummy_options = get_credential_options(); ASSERT_TRUE(virtual_device_factory_->mutable_state()->InjectRegistration( - dummy_options->allow_credentials[0].id(), kTestRelyingPartyId)); + dummy_options->allow_credentials[0].id, kTestRelyingPartyId)); for (bool pin_uv_auth_token : {false, true}) { for (bool ui_support : {false, true}) { @@ -5321,7 +5319,7 @@ PublicKeyCredentialRequestOptionsPtr options = get_credential_options(); ASSERT_TRUE(virtual_device_factory_->mutable_state()->InjectRegistration( - options->allow_credentials[0].id(), kTestRelyingPartyId)); + options->allow_credentials[0].id, kTestRelyingPartyId)); test_client_.expected = {{PINReason::kChallenge, u"wrong", 8}, {PINReason::kChallenge, u"wrong", 7, @@ -5343,7 +5341,7 @@ PublicKeyCredentialRequestOptionsPtr options = get_credential_options(); ASSERT_TRUE(virtual_device_factory_->mutable_state()->InjectRegistration( - options->allow_credentials[0].id(), kTestRelyingPartyId)); + options->allow_credentials[0].id, kTestRelyingPartyId)); test_client_.expected = {{PINReason::kChallenge, u"wrong", 1}}; EXPECT_EQ(AuthenticatorGetAssertion(std::move(options)).status, @@ -5364,7 +5362,7 @@ }); PublicKeyCredentialRequestOptionsPtr options = get_credential_options(); ASSERT_TRUE(virtual_device_factory_->mutable_state()->InjectRegistration( - options->allow_credentials[0].id(), kTestRelyingPartyId)); + options->allow_credentials[0].id, kTestRelyingPartyId)); test_client_.expected = { {PINReason::kChallenge, kTestPIN16, device::kMaxPinRetries}}; EXPECT_EQ(AuthenticatorGetAssertion(std::move(options)).status, @@ -5394,7 +5392,7 @@ }); PublicKeyCredentialRequestOptionsPtr options = get_credential_options(); ASSERT_TRUE(device_2.state->InjectRegistration( - options->allow_credentials[0].id(), kTestRelyingPartyId)); + options->allow_credentials[0].id, kTestRelyingPartyId)); discovery->AddDevice(std::move(device_2)); AuthenticatorEnvironmentImpl::GetInstance() @@ -5419,7 +5417,7 @@ PublicKeyCredentialRequestOptionsPtr options = get_credential_options(device::UserVerificationRequirement::kDiscouraged); ASSERT_TRUE(virtual_device_factory_->mutable_state()->InjectRegistration( - options->allow_credentials[0].id(), kTestRelyingPartyId)); + options->allow_credentials[0].id, kTestRelyingPartyId)); test_client_.expected = { {PINReason::kChallenge, kTestPIN16, device::kMaxPinRetries}}; @@ -5435,7 +5433,7 @@ PublicKeyCredentialRequestOptionsPtr options = get_credential_options(device::UserVerificationRequirement::kDiscouraged); ASSERT_TRUE(virtual_device_factory_->mutable_state()->InjectRegistration( - options->allow_credentials[0].id(), kTestRelyingPartyId)); + options->allow_credentials[0].id, kTestRelyingPartyId)); for (bool internal_uv : {true, false}) { SCOPED_TRACE(::testing::Message() << "internal_uv=" << internal_uv); @@ -5506,8 +5504,8 @@ PublicKeyCredentialCreationOptionsPtr options = GetTestPublicKeyCredentialCreationOptions(); // Set uv=discouraged so that U2F fallback is possible. - options->authenticator_selection->SetUserVerificationRequirementForTesting( - device::UserVerificationRequirement::kDiscouraged); + options->authenticator_selection->user_verification_requirement = + device::UserVerificationRequirement::kDiscouraged; options->public_key_parameters = GetTestPublicKeyCredentialParameters(static_cast<int32_t>( device::CoseAlgorithmIdentifier::kInvalidForTesting)); @@ -5538,8 +5536,8 @@ PublicKeyCredentialCreationOptionsPtr options = GetTestPublicKeyCredentialCreationOptions(); // Set uv=discouraged so that U2F fallback is possible. - options->authenticator_selection->SetUserVerificationRequirementForTesting( - device::UserVerificationRequirement::kDiscouraged); + options->authenticator_selection->user_verification_requirement = + device::UserVerificationRequirement::kDiscouraged; if (i == 0) { // Sanity check: request should fallback to U2F. (If it doesn't fallback @@ -5600,7 +5598,7 @@ kTestRelyingPartyId); cred_protect_credential.protection = device::CredProtect::kUVRequired; ASSERT_TRUE(virtual_device_factory_->mutable_state()->InjectRegistration( - test_credentials.back().id(), std::move(cred_protect_credential))); + test_credentials.back().id, std::move(cred_protect_credential))); // The request should fail because the exclude list matches. PublicKeyCredentialCreationOptionsPtr options = @@ -5868,13 +5866,12 @@ virtual_device_factory_->mutable_state()->fingerprints_enrolled = true; PublicKeyCredentialCreationOptionsPtr request = make_credential_options(); - request->authenticator_selection - ->SetUserVerificationRequirementForTesting( - request_uv ? device::UserVerificationRequirement::kPreferred - : device::UserVerificationRequirement::kDiscouraged); - request->authenticator_selection->SetResidentKeyForTesting( + request->authenticator_selection->user_verification_requirement = + request_uv ? device::UserVerificationRequirement::kPreferred + : device::UserVerificationRequirement::kDiscouraged; + request->authenticator_selection->resident_key = discoverable ? device::ResidentKeyRequirement::kPreferred - : device::ResidentKeyRequirement::kDiscouraged); + : device::ResidentKeyRequirement::kDiscouraged; MakeCredentialResult result = AuthenticatorMakeCredential(std::move(request)); @@ -5891,8 +5888,7 @@ TEST_F(InternalUVAuthenticatorImplTest, GetAssertion) { ASSERT_TRUE(virtual_device_factory_->mutable_state()->InjectRegistration( - get_credential_options()->allow_credentials[0].id(), - kTestRelyingPartyId)); + get_credential_options()->allow_credentials[0].id, kTestRelyingPartyId)); for (const auto test_case : GetTestCases()) { ConfigureDevice(test_case); @@ -5934,8 +5930,7 @@ virtual_device_factory_->SetCtap2Config(config); ASSERT_TRUE(virtual_device_factory_->mutable_state()->InjectRegistration( - get_credential_options()->allow_credentials[0].id(), - kTestRelyingPartyId)); + get_credential_options()->allow_credentials[0].id, kTestRelyingPartyId)); GetAssertionResult result = AuthenticatorGetAssertion( get_credential_options(device::UserVerificationRequirement::kRequired)); @@ -5949,8 +5944,7 @@ TEST_F(InternalUVAuthenticatorImplTest, GetAssertionCryptotoken) { NavigateAndCommit(GURL(kCryptotokenOrigin)); ASSERT_TRUE(virtual_device_factory_->mutable_state()->InjectRegistration( - get_credential_options()->allow_credentials[0].id(), - kTestRelyingPartyId)); + get_credential_options()->allow_credentials[0].id, kTestRelyingPartyId)); for (const auto fingerprints_enrolled : {false, true}) { SCOPED_TRACE(::testing::Message() @@ -5983,8 +5977,7 @@ TEST_F(UVTokenAuthenticatorImplTest, GetAssertionUVToken) { ASSERT_TRUE(virtual_device_factory_->mutable_state()->InjectRegistration( - get_credential_options()->allow_credentials[0].id(), - kTestRelyingPartyId)); + get_credential_options()->allow_credentials[0].id, kTestRelyingPartyId)); for (const auto fingerprints_enrolled : {false, true}) { SCOPED_TRACE(::testing::Message() @@ -6033,8 +6026,7 @@ virtual_device_factory_->SetCtap2Config(config); virtual_device_factory_->mutable_state()->fingerprints_enrolled = true; ASSERT_TRUE(virtual_device_factory_->mutable_state()->InjectRegistration( - get_credential_options()->allow_credentials[0].id(), - kTestRelyingPartyId)); + get_credential_options()->allow_credentials[0].id, kTestRelyingPartyId)); int expected_retries = 5; virtual_device_factory_->mutable_state()->uv_retries = expected_retries; @@ -6063,8 +6055,7 @@ virtual_device_factory_->mutable_state()->fingerprints_enrolled = true; virtual_device_factory_->mutable_state()->pin = kTestPIN; ASSERT_TRUE(virtual_device_factory_->mutable_state()->InjectRegistration( - get_credential_options()->allow_credentials[0].id(), - kTestRelyingPartyId)); + get_credential_options()->allow_credentials[0].id, kTestRelyingPartyId)); int taps = 0; virtual_device_factory_->mutable_state()->uv_retries = 5; @@ -6098,8 +6089,7 @@ virtual_device_factory_->mutable_state()->fingerprints_enrolled = true; virtual_device_factory_->mutable_state()->pin = kTestPIN; ASSERT_TRUE(virtual_device_factory_->mutable_state()->InjectRegistration( - get_credential_options()->allow_credentials[0].id(), - kTestRelyingPartyId)); + get_credential_options()->allow_credentials[0].id, kTestRelyingPartyId)); EXPECT_EQ(AuthenticatorGetAssertion(get_credential_options()).status, AuthenticatorStatus::SUCCESS); @@ -6152,8 +6142,7 @@ virtual_device_factory_->SetCtap2Config(config); virtual_device_factory_->mutable_state()->fingerprints_enrolled = true; ASSERT_TRUE(virtual_device_factory_->mutable_state()->InjectRegistration( - get_credential_options()->allow_credentials[0].id(), - kTestRelyingPartyId)); + get_credential_options()->allow_credentials[0].id, kTestRelyingPartyId)); int expected_retries = 5; virtual_device_factory_->mutable_state()->uv_retries = expected_retries; @@ -6182,8 +6171,7 @@ virtual_device_factory_->mutable_state()->fingerprints_enrolled = true; virtual_device_factory_->mutable_state()->pin = kTestPIN; ASSERT_TRUE(virtual_device_factory_->mutable_state()->InjectRegistration( - get_credential_options()->allow_credentials[0].id(), - kTestRelyingPartyId)); + get_credential_options()->allow_credentials[0].id, kTestRelyingPartyId)); int taps = 0; virtual_device_factory_->mutable_state()->uv_retries = 5; @@ -6217,8 +6205,7 @@ virtual_device_factory_->mutable_state()->fingerprints_enrolled = true; virtual_device_factory_->mutable_state()->pin = kTestPIN; ASSERT_TRUE(virtual_device_factory_->mutable_state()->InjectRegistration( - get_credential_options()->allow_credentials[0].id(), - kTestRelyingPartyId)); + get_credential_options()->allow_credentials[0].id, kTestRelyingPartyId)); EXPECT_EQ(AuthenticatorMakeCredential(make_credential_options()).status, AuthenticatorStatus::SUCCESS); @@ -6500,7 +6487,7 @@ device::ResidentKeyRequirement::kRequired) { PublicKeyCredentialCreationOptionsPtr options = UVAuthenticatorImplTest::make_credential_options(); - options->authenticator_selection->SetResidentKeyForTesting(resident_key); + options->authenticator_selection->resident_key = resident_key; options->user.id = {1, 2, 3, 4}; return options; } @@ -7074,14 +7061,14 @@ << "support=" << test.supported_by_authenticator); PublicKeyCredentialCreationOptionsPtr options = make_credential_options(); - options->authenticator_selection->SetResidentKeyForTesting( + options->authenticator_selection->resident_key = test.is_resident ? device::ResidentKeyRequirement::kRequired - : device::ResidentKeyRequirement::kDiscouraged); + : device::ResidentKeyRequirement::kDiscouraged; options->protection_policy = test.protection; options->enforce_protection_policy = test.enforce; - options->authenticator_selection->SetUserVerificationRequirementForTesting( + options->authenticator_selection->user_verification_requirement = test.uv ? device::UserVerificationRequirement::kRequired - : device::UserVerificationRequirement::kDiscouraged); + : device::UserVerificationRequirement::kDiscouraged; AuthenticatorStatus status = AuthenticatorMakeCredential(std::move(options)).status; @@ -7152,12 +7139,11 @@ virtual_device_factory_->mutable_state()->registrations.clear(); PublicKeyCredentialCreationOptionsPtr options = make_credential_options(); - options->authenticator_selection->SetResidentKeyForTesting( - device::ResidentKeyRequirement::kRequired); + options->authenticator_selection->resident_key = + device::ResidentKeyRequirement::kRequired; options->protection_policy = kMojoLevels[requested_level]; - options->authenticator_selection - ->SetUserVerificationRequirementForTesting( - device::UserVerificationRequirement::kRequired); + options->authenticator_selection->user_verification_requirement = + device::UserVerificationRequirement::kRequired; AuthenticatorStatus status = AuthenticatorMakeCredential(std::move(options)).status; @@ -7243,11 +7229,11 @@ << ProtectionPolicyDescription(test.requested_level)); PublicKeyCredentialCreationOptionsPtr options = make_credential_options(); - options->authenticator_selection->SetResidentKeyForTesting( - device::ResidentKeyRequirement::kRequired); + options->authenticator_selection->resident_key = + device::ResidentKeyRequirement::kRequired; options->protection_policy = test.requested_level; - options->authenticator_selection->SetUserVerificationRequirementForTesting( - device::UserVerificationRequirement::kRequired); + options->authenticator_selection->user_verification_requirement = + device::UserVerificationRequirement::kRequired; EXPECT_EQ(AuthenticatorMakeCredential(std::move(options)).status, AuthenticatorStatus::SUCCESS); @@ -7282,7 +7268,7 @@ PublicKeyCredentialRequestOptionsPtr options = get_credential_options(); options->allow_credentials = GetTestCredentials(5); - options->allow_credentials[0].GetIdForTesting() = {4, 3, 2, 1}; + options->allow_credentials[0].id = {4, 3, 2, 1}; GetAssertionResult result = AuthenticatorGetAssertion(std::move(options)); @@ -7335,10 +7321,10 @@ options->relying_party = device::PublicKeyCredentialRpEntity(); options->relying_party.id = device::test_data::kRelyingPartyId; options->relying_party.name = ""; - options->authenticator_selection->SetUserVerificationRequirementForTesting( - device::UserVerificationRequirement::kRequired); - options->authenticator_selection->SetResidentKeyForTesting( - device::ResidentKeyRequirement::kRequired); + options->authenticator_selection->user_verification_requirement = + device::UserVerificationRequirement::kRequired; + options->authenticator_selection->resident_key = + device::ResidentKeyRequirement::kRequired; options->protection_policy = blink::mojom::ProtectionPolicy::UV_OR_CRED_ID_REQUIRED; options->enforce_protection_policy = true; @@ -7369,9 +7355,9 @@ PublicKeyCredentialCreationOptionsPtr options = GetTestPublicKeyCredentialCreationOptions(); options->prf_enable = true; - options->authenticator_selection->SetResidentKeyForTesting( + options->authenticator_selection->resident_key = hmac_secret_supported ? device::ResidentKeyRequirement::kRequired - : device::ResidentKeyRequirement::kDiscouraged); + : device::ResidentKeyRequirement::kDiscouraged; options->user.id = {1, 2, 3, 4}; options->user.name = "name"; options->user.display_name = "displayName"; @@ -7470,7 +7456,7 @@ // Should still trigger if the credential ID is specified { auto prf_value = blink::mojom::PRFValues::New(); - prf_value->id.emplace(credential->id()); + prf_value->id.emplace(credential->id); prf_value->first = salt1; prf_value->second = salt2; std::vector<blink::mojom::PRFValuesPtr> inputs; @@ -7486,7 +7472,7 @@ auto prf_value1 = blink::mojom::PRFValues::New(); prf_value1->first = std::vector<uint8_t>(32, 3); auto prf_value2 = blink::mojom::PRFValues::New(); - prf_value2->id.emplace(credential->id()); + prf_value2->id.emplace(credential->id); prf_value2->first = salt1; prf_value2->second = salt2; std::vector<blink::mojom::PRFValuesPtr> inputs; @@ -7503,7 +7489,7 @@ // that this will cause multiple batches. { auto prf_value = blink::mojom::PRFValues::New(); - prf_value->id.emplace(credential->id()); + prf_value->id.emplace(credential->id); prf_value->first = salt1; prf_value->second = salt2; std::vector<blink::mojom::PRFValuesPtr> inputs; @@ -7725,7 +7711,7 @@ ResetVirtualDevice(); ASSERT_TRUE(virtual_device_factory_->mutable_state()->InjectRegistration( - options->allow_credentials[0].id(), test_case.claimed_authority)); + options->allow_credentials[0].id, test_case.claimed_authority)); TestGetAssertionCallback callback_receiver; authenticator->GetAssertion(std::move(options), callback_receiver.callback());
diff --git a/content/browser/webauth/authenticator_mojom_traits_unittest.cc b/content/browser/webauth/authenticator_mojom_traits_unittest.cc index 2e1d7a8a..9242062 100644 --- a/content/browser/webauth/authenticator_mojom_traits_unittest.cc +++ b/content/browser/webauth/authenticator_mojom_traits_unittest.cc
@@ -84,17 +84,15 @@ PublicKeyCredentialDescriptor(CredentialType::kPublicKey, kDescriptorId), PublicKeyCredentialDescriptor(CredentialType::kPublicKey, kDescriptorId), PublicKeyCredentialDescriptor(CredentialType::kPublicKey, kDescriptorId)}; - success_cases[1].GetTransportsForTesting().emplace( - FidoTransportProtocol::kInternal); - success_cases[2].GetTransportsForTesting().emplace( - FidoTransportProtocol::kInternal); - success_cases[2].GetTransportsForTesting().emplace( + success_cases[1].transports.emplace(FidoTransportProtocol::kInternal); + success_cases[2].transports.emplace(FidoTransportProtocol::kInternal); + success_cases[2].transports.emplace( FidoTransportProtocol::kUsbHumanInterfaceDevice); - success_cases[2].GetTransportsForTesting().emplace( + success_cases[2].transports.emplace( FidoTransportProtocol::kNearFieldCommunication); - success_cases[2].GetTransportsForTesting().emplace( + success_cases[2].transports.emplace( FidoTransportProtocol::kCloudAssistedBluetoothLowEnergy); - success_cases[2].GetTransportsForTesting().emplace( + success_cases[2].transports.emplace( FidoTransportProtocol::kBluetoothLowEnergy); AssertSerializeAndDeserializeSucceeds<
diff --git a/content/browser/webauth/webauth_request_security_checker.cc b/content/browser/webauth/webauth_request_security_checker.cc index fa0cb13..84a8136 100644 --- a/content/browser/webauth/webauth_request_security_checker.cc +++ b/content/browser/webauth/webauth_request_security_checker.cc
@@ -215,8 +215,8 @@ auto credential_descriptor_compare_without_transport = [](const device::PublicKeyCredentialDescriptor& a, const device::PublicKeyCredentialDescriptor& b) { - return a.credential_type() < b.credential_type() || - (a.credential_type() == b.credential_type() && a.id() < b.id()); + return a.credential_type < b.credential_type || + (a.credential_type == b.credential_type && a.id < b.id); }; std::set<device::PublicKeyCredentialDescriptor, decltype(credential_descriptor_compare_without_transport)> @@ -231,15 +231,15 @@ // transport list means _any_ transport, so the union should still be // empty. base::flat_set<device::FidoTransportProtocol> merged_transports; - if (!it->transports().empty() && - !credential_descriptor.transports().empty()) { + if (!it->transports.empty() && + !credential_descriptor.transports.empty()) { base::ranges::set_union( - it->transports(), credential_descriptor.transports(), + it->transports, credential_descriptor.transports, std::inserter(merged_transports, merged_transports.begin())); } unique_credential_descriptors.erase(it); unique_credential_descriptors.insert( - {credential_descriptor.credential_type(), credential_descriptor.id(), + {credential_descriptor.credential_type, credential_descriptor.id, std::move(merged_transports)}); } }
diff --git a/content/public/browser/web_contents_user_data.h b/content/public/browser/web_contents_user_data.h index 7803f4d..cdd4347 100644 --- a/content/public/browser/web_contents_user_data.h +++ b/content/public/browser/web_contents_user_data.h
@@ -81,6 +81,12 @@ CHECK(web_contents_); return *web_contents_; } + const content::WebContents& GetWebContents() const { + // TODO(crbug.com/1268914) : Remove when we can't call the default + // constructor. + CHECK(web_contents_); + return *web_contents_; + } private: // This is a pointer (rather than a reference) to ensure that go/miracleptr
diff --git a/content/test/data/accessibility/accname/name-text-label-with-input-expected-blink.txt b/content/test/data/accessibility/accname/name-text-label-with-input-expected-blink.txt index 044a728..4ab4297 100644 --- a/content/test/data/accessibility/accname/name-text-label-with-input-expected-blink.txt +++ b/content/test/data/accessibility/accname/name-text-label-with-input-expected-blink.txt
@@ -1 +1,2 @@ +# Must match the expectation from NameTextLabelWithReadonlyInput textField name='foo bar baz' nameFrom=relatedElement
diff --git a/content/test/data/accessibility/accname/name-text-label-with-readonly-input-expected-blink.txt b/content/test/data/accessibility/accname/name-text-label-with-readonly-input-expected-blink.txt new file mode 100644 index 0000000..9089f00a --- /dev/null +++ b/content/test/data/accessibility/accname/name-text-label-with-readonly-input-expected-blink.txt
@@ -0,0 +1,2 @@ +# Must match the expectation from NameTextLabelWithInput +textField name='foo bar baz' nameFrom=relatedElement
diff --git a/content/test/data/accessibility/accname/name-text-label-with-readonly-input.html b/content/test/data/accessibility/accname/name-text-label-with-readonly-input.html new file mode 100644 index 0000000..b638c9a --- /dev/null +++ b/content/test/data/accessibility/accname/name-text-label-with-readonly-input.html
@@ -0,0 +1,10 @@ +<!-- +@BLINK-DENY:descri* +--> +<!doctype html> +<html> +<body> +<input type="text" id="test"> +<label for="test">foo<input type="text" readonly value="bar">baz</label> +</body> +</html>
diff --git a/content/test/data/accessibility/accname/name-text-labelledby-hidden-different-visibility-types-expected-blink.txt b/content/test/data/accessibility/accname/name-text-labelledby-hidden-different-visibility-types-expected-blink.txt new file mode 100644 index 0000000..bc71c6b --- /dev/null +++ b/content/test/data/accessibility/accname/name-text-labelledby-hidden-different-visibility-types-expected-blink.txt
@@ -0,0 +1,2 @@ +#FIXME(crbug.com/1276936): expect 'b c d e' +textField name='b cd e' nameFrom=relatedElement
diff --git a/content/test/data/accessibility/accname/name-text-labelledby-hidden-different-visibility-types.html b/content/test/data/accessibility/accname/name-text-labelledby-hidden-different-visibility-types.html new file mode 100644 index 0000000..dead5d5 --- /dev/null +++ b/content/test/data/accessibility/accname/name-text-labelledby-hidden-different-visibility-types.html
@@ -0,0 +1,16 @@ +<!-- +@BLINK-DENY:description +--> +<!DOCTYPE html> +<html> +<body> + <input id="test" aria-labelledby="t1"> + <div id="t1" style="visibility:hidden"> + <span aria-hidden="true">a</span> + <span style="display:none">b</span> + <span style="visibility:hidden">c</span> + <span>d</span> + e + </div> +</body> +</html>
diff --git a/content/test/data/accessibility/accname/name-text-labelledby-hidden-multiple-levels-expected-blink.txt b/content/test/data/accessibility/accname/name-text-labelledby-hidden-multiple-levels-expected-blink.txt new file mode 100644 index 0000000..29ce4e6 --- /dev/null +++ b/content/test/data/accessibility/accname/name-text-labelledby-hidden-multiple-levels-expected-blink.txt
@@ -0,0 +1 @@ +textField name='two three' nameFrom=relatedElement
diff --git a/content/test/data/accessibility/accname/name-text-labelledby-hidden-multiple-levels.html b/content/test/data/accessibility/accname/name-text-labelledby-hidden-multiple-levels.html new file mode 100644 index 0000000..9f200230 --- /dev/null +++ b/content/test/data/accessibility/accname/name-text-labelledby-hidden-multiple-levels.html
@@ -0,0 +1,16 @@ +<!-- +@BLINK-DENY:description +--> +<!DOCTYPE html> +<html> +<body> + <input id="test" aria-labelledby="t2"> + <div id="t1" style="visibility:hidden"> + one + <div id="t2"> + two + <div id="t3">three</div> + </div> + </div> +</body> +</html>
diff --git a/content/test/test_render_view_host.cc b/content/test/test_render_view_host.cc index 488f5e5..fda9f84 100644 --- a/content/test/test_render_view_host.cc +++ b/content/test/test_render_view_host.cc
@@ -155,7 +155,13 @@ delete this; } -void TestRenderWidgetHostView::Destroy() { delete this; } +void TestRenderWidgetHostView::Destroy() { + // Call this here in case any observers need access to the `this` before + // this derived class runs its destructor. + NotifyObserversAboutShutdown(); + + delete this; +} gfx::Rect TestRenderWidgetHostView::GetViewBounds() { return gfx::Rect();
diff --git a/device/fido/authenticator_selection_criteria.cc b/device/fido/authenticator_selection_criteria.cc index aa23d1c..0817053e 100644 --- a/device/fido/authenticator_selection_criteria.cc +++ b/device/fido/authenticator_selection_criteria.cc
@@ -12,9 +12,9 @@ AuthenticatorAttachment authenticator_attachment, ResidentKeyRequirement resident_key, UserVerificationRequirement user_verification_requirement) - : authenticator_attachment_(authenticator_attachment), - resident_key_(resident_key), - user_verification_requirement_(user_verification_requirement) {} + : authenticator_attachment(authenticator_attachment), + resident_key(resident_key), + user_verification_requirement(user_verification_requirement) {} AuthenticatorSelectionCriteria::AuthenticatorSelectionCriteria( AuthenticatorSelectionCriteria&& other) = default; @@ -30,9 +30,9 @@ bool AuthenticatorSelectionCriteria::operator==( const AuthenticatorSelectionCriteria& other) const { - return authenticator_attachment_ == other.authenticator_attachment_ && - resident_key_ == other.resident_key_ && - user_verification_requirement_ == other.user_verification_requirement_; + return authenticator_attachment == other.authenticator_attachment && + resident_key == other.resident_key && + user_verification_requirement == other.user_verification_requirement; } AuthenticatorSelectionCriteria::~AuthenticatorSelectionCriteria() = default;
diff --git a/device/fido/authenticator_selection_criteria.h b/device/fido/authenticator_selection_criteria.h index d809eb3..766da111 100644 --- a/device/fido/authenticator_selection_criteria.h +++ b/device/fido/authenticator_selection_criteria.h
@@ -31,33 +31,10 @@ bool operator==(const AuthenticatorSelectionCriteria& other) const; ~AuthenticatorSelectionCriteria(); - AuthenticatorAttachment authenticator_attachment() const { - return authenticator_attachment_; - } - - ResidentKeyRequirement resident_key() const { return resident_key_; } - - UserVerificationRequirement user_verification_requirement() const { - return user_verification_requirement_; - } - - void SetAuthenticatorAttachmentForTesting( - AuthenticatorAttachment attachment) { - authenticator_attachment_ = attachment; - } - void SetResidentKeyForTesting(ResidentKeyRequirement resident_key) { - resident_key_ = resident_key; - } - void SetUserVerificationRequirementForTesting( - UserVerificationRequirement uv) { - user_verification_requirement_ = uv; - } - - private: - AuthenticatorAttachment authenticator_attachment_ = + AuthenticatorAttachment authenticator_attachment = AuthenticatorAttachment::kAny; - ResidentKeyRequirement resident_key_ = ResidentKeyRequirement::kDiscouraged; - UserVerificationRequirement user_verification_requirement_ = + ResidentKeyRequirement resident_key = ResidentKeyRequirement::kDiscouraged; + UserVerificationRequirement user_verification_requirement = UserVerificationRequirement::kPreferred; };
diff --git a/device/fido/cros/authenticator.cc b/device/fido/cros/authenticator.cc index 21c4c52..3b3af85 100644 --- a/device/fido/cros/authenticator.cc +++ b/device/fido/cros/authenticator.cc
@@ -123,8 +123,8 @@ req.set_request_id(current_request_id_); for (const PublicKeyCredentialDescriptor& descriptor : request.exclude_list) { - const std::vector<uint8_t>& id = descriptor.id(); - req.add_excluded_credential_id(std::string(id.begin(), id.end())); + req.add_excluded_credential_id( + std::string(descriptor.id.begin(), descriptor.id.end())); } if (request.app_id_exclude) { req.set_app_id_exclude(*request.app_id_exclude); @@ -207,8 +207,8 @@ req.set_request_id(current_request_id_); for (const PublicKeyCredentialDescriptor& descriptor : request.allow_list) { - const std::vector<uint8_t>& id = descriptor.id(); - req.add_allowed_credential_id(std::string(id.begin(), id.end())); + req.add_allowed_credential_id( + std::string(descriptor.id.begin(), descriptor.id.end())); } chromeos::U2FClient::Get()->GetAssertion( @@ -271,8 +271,8 @@ } for (const PublicKeyCredentialDescriptor& descriptor : request.allow_list) { - const std::vector<uint8_t>& id = descriptor.id(); - req.add_credential_id(std::string(id.begin(), id.end())); + req.add_credential_id( + std::string(descriptor.id.begin(), descriptor.id.end())); } chromeos::U2FClient::Get()->HasCredentials( @@ -299,8 +299,8 @@ } for (const PublicKeyCredentialDescriptor& descriptor : request.allow_list) { - const std::vector<uint8_t>& id = descriptor.id(); - req.add_credential_id(std::string(id.begin(), id.end())); + req.add_credential_id( + std::string(descriptor.id.begin(), descriptor.id.end())); } chromeos::U2FClient::Get()->HasLegacyU2FCredentials(
diff --git a/device/fido/ctap_make_credential_request.cc b/device/fido/ctap_make_credential_request.cc index 6c52282..970a155 100644 --- a/device/fido/ctap_make_credential_request.cc +++ b/device/fido/ctap_make_credential_request.cc
@@ -354,10 +354,10 @@ MakeCredentialOptions::MakeCredentialOptions( const AuthenticatorSelectionCriteria& authenticator_selection_criteria) : authenticator_attachment( - authenticator_selection_criteria.authenticator_attachment()), - resident_key(authenticator_selection_criteria.resident_key()), + authenticator_selection_criteria.authenticator_attachment), + resident_key(authenticator_selection_criteria.resident_key), user_verification( - authenticator_selection_criteria.user_verification_requirement()) {} + authenticator_selection_criteria.user_verification_requirement) {} MakeCredentialOptions::MakeCredentialOptions(MakeCredentialOptions&&) = default; MakeCredentialOptions& MakeCredentialOptions::operator=( const MakeCredentialOptions&) = default;
diff --git a/device/fido/ctap_response_unittest.cc b/device/fido/ctap_response_unittest.cc index 23954f6..1bdbdae 100644 --- a/device/fido/ctap_response_unittest.cc +++ b/device/fido/ctap_response_unittest.cc
@@ -648,7 +648,7 @@ test_data::kApplicationParameter, GetTestSignResponse(), GetTestCredentialRawIdBytes()); ASSERT_TRUE(response); - EXPECT_EQ(GetTestCredentialRawIdBytes(), response->credential->id()); + EXPECT_EQ(GetTestCredentialRawIdBytes(), response->credential->id); EXPECT_THAT( response->authenticator_data.SerializeToByteArray(), ::testing::ElementsAreArray(test_data::kTestSignAuthenticatorData));
diff --git a/device/fido/get_assertion_handler_unittest.cc b/device/fido/get_assertion_handler_unittest.cc index 253ad89d..9af00e2 100644 --- a/device/fido/get_assertion_handler_unittest.cc +++ b/device/fido/get_assertion_handler_unittest.cc
@@ -349,7 +349,7 @@ ASSERT_EQ(1u, response->size()); EXPECT_TRUE(response.value()[0].credential); EXPECT_THAT( - response.value()[0].credential->id(), + response.value()[0].credential->id, ::testing::ElementsAreArray(test_data::kTestGetAssertionCredentialId)); }
diff --git a/device/fido/get_assertion_request_handler.cc b/device/fido/get_assertion_request_handler.cc index bde53a74..488d326e 100644 --- a/device/fido/get_assertion_request_handler.cc +++ b/device/fido/get_assertion_request_handler.cc
@@ -212,11 +212,11 @@ base::flat_set<FidoTransportProtocol> transports; for (const auto& credential : allowed_list) { - if (credential.transports().empty()) { + if (credential.transports.empty()) { return kAllTransports; } - transports.insert(credential.transports().begin(), - credential.transports().end()); + transports.insert(credential.transports.begin(), + credential.transports.end()); } if (base::FeatureList::IsEnabled(device::kWebAuthPhoneSupport) || @@ -345,10 +345,10 @@ fido_filter::Operation::GET_ASSERTION, request_.rp_id, authenticator_name, std::pair<fido_filter::IDType, base::span<const uint8_t>>( - fido_filter::IDType::CREDENTIAL_ID, cred.id())) == + fido_filter::IDType::CREDENTIAL_ID, cred.id)) == fido_filter::Action::BLOCK) { FIDO_LOG(DEBUG) << "Filtered request to device " << authenticator_name - << " for credential ID " << base::HexEncode(cred.id()); + << " for credential ID " << base::HexEncode(cred.id); return; } }
diff --git a/device/fido/get_assertion_task.cc b/device/fido/get_assertion_task.cc index b770b26..5a78af9 100644 --- a/device/fido/get_assertion_task.cc +++ b/device/fido/get_assertion_task.cc
@@ -43,7 +43,7 @@ if (!allow_list.empty() && std::none_of(allow_list.cbegin(), allow_list.cend(), [&response](const auto& credential) { - return credential.id() == response->credential->id(); + return credential.id == response->credential->id; })) { return false; } @@ -332,7 +332,7 @@ *response_data->credential; request.allow_list = {matching_credential}; MaybeSetPRFParameters( - &request, GetPRFInputForCredential(options_, matching_credential.id())); + &request, GetPRFInputForCredential(options_, matching_credential.id)); sign_operation_ = std::make_unique<Ctap2DeviceOperation< CtapGetAssertionRequest, AuthenticatorGetAssertionResponse>>(
diff --git a/device/fido/mac/credential_store.mm b/device/fido/mac/credential_store.mm index 651e17e..990b56a 100644 --- a/device/fido/mac/credential_store.mm +++ b/device/fido/mac/credential_store.mm
@@ -289,11 +289,11 @@ const std::vector<PublicKeyCredentialDescriptor>& descriptors) const { std::set<std::vector<uint8_t>> credential_ids; for (const auto& descriptor : descriptors) { - if (descriptor.credential_type() == CredentialType::kPublicKey && - (descriptor.transports().empty() || - base::Contains(descriptor.transports(), + if (descriptor.credential_type == CredentialType::kPublicKey && + (descriptor.transports.empty() || + base::Contains(descriptor.transports, FidoTransportProtocol::kInternal))) { - credential_ids.insert(descriptor.id()); + credential_ids.insert(descriptor.id); } } if (credential_ids.empty()) {
diff --git a/device/fido/mac/get_assertion_operation_unittest_mac.mm b/device/fido/mac/get_assertion_operation_unittest_mac.mm index 97b2df5c..8aae5f1 100644 --- a/device/fido/mac/get_assertion_operation_unittest_mac.mm +++ b/device/fido/mac/get_assertion_operation_unittest_mac.mm
@@ -84,7 +84,7 @@ auto opt_response = std::move(std::get<1>(result)); ASSERT_TRUE(opt_response); ASSERT_TRUE(opt_response->credential); - EXPECT_FALSE(opt_response->credential->id().empty()); + EXPECT_FALSE(opt_response->credential->id.empty()); } } // namespace } // namespace mac
diff --git a/device/fido/make_credential_request_handler.cc b/device/fido/make_credential_request_handler.cc index e6d38aa..bcd0eeb 100644 --- a/device/fido/make_credential_request_handler.cc +++ b/device/fido/make_credential_request_handler.cc
@@ -436,10 +436,10 @@ fido_filter::Operation::MAKE_CREDENTIAL, request_.rp.id, authenticator_name, std::pair<fido_filter::IDType, base::span<const uint8_t>>( - fido_filter::IDType::CREDENTIAL_ID, cred.id())) == + fido_filter::IDType::CREDENTIAL_ID, cred.id)) == fido_filter::Action::BLOCK) { FIDO_LOG(DEBUG) << "Filtered request to device " << authenticator_name - << " for credential ID " << base::HexEncode(cred.id()); + << " for credential ID " << base::HexEncode(cred.id); return; } }
diff --git a/device/fido/make_credential_task.cc b/device/fido/make_credential_task.cc index c9f6397..fbb45d7 100644 --- a/device/fido/make_credential_task.cc +++ b/device/fido/make_credential_task.cc
@@ -391,7 +391,7 @@ for (const PublicKeyCredentialDescriptor& credential : in) { if (0 < max_credential_id_length && - max_credential_id_length < credential.id().size()) { + max_credential_id_length < credential.id.size()) { continue; } if (result.back().size() == max_credential_count_in_list) {
diff --git a/device/fido/public_key_credential_descriptor.cc b/device/fido/public_key_credential_descriptor.cc index c9dedd8..87b7769 100644 --- a/device/fido/public_key_credential_descriptor.cc +++ b/device/fido/public_key_credential_descriptor.cc
@@ -49,9 +49,9 @@ CredentialType credential_type, std::vector<uint8_t> id, base::flat_set<FidoTransportProtocol> transports) - : credential_type_(credential_type), - id_(std::move(id)), - transports_(std::move(transports)) {} + : credential_type(credential_type), + id(std::move(id)), + transports(std::move(transports)) {} PublicKeyCredentialDescriptor::PublicKeyCredentialDescriptor( const PublicKeyCredentialDescriptor& other) = default; @@ -69,15 +69,15 @@ bool PublicKeyCredentialDescriptor::operator==( const PublicKeyCredentialDescriptor& other) const { - return credential_type_ == other.credential_type_ && id_ == other.id_ && - transports_ == other.transports_; + return credential_type == other.credential_type && id == other.id && + transports == other.transports; } cbor::Value AsCBOR(const PublicKeyCredentialDescriptor& desc) { cbor::Value::MapValue cbor_descriptor_map; - cbor_descriptor_map[cbor::Value(kCredentialIdKey)] = cbor::Value(desc.id()); + cbor_descriptor_map[cbor::Value(kCredentialIdKey)] = cbor::Value(desc.id); cbor_descriptor_map[cbor::Value(kCredentialTypeKey)] = - cbor::Value(CredentialTypeToString(desc.credential_type())); + cbor::Value(CredentialTypeToString(desc.credential_type)); // Transports are omitted from CBOR serialization. They aren't useful for // security keys to process. Some existing devices even refuse to parse them // (see https://crbug.com/1270757).
diff --git a/device/fido/public_key_credential_descriptor.h b/device/fido/public_key_credential_descriptor.h index 63489ab..28b4d2c 100644 --- a/device/fido/public_key_credential_descriptor.h +++ b/device/fido/public_key_credential_descriptor.h
@@ -43,24 +43,9 @@ bool operator==(const PublicKeyCredentialDescriptor& other) const; ~PublicKeyCredentialDescriptor(); - CredentialType credential_type() const { return credential_type_; } - const std::vector<uint8_t>& id() const { return id_; } - const base::flat_set<FidoTransportProtocol>& transports() const { - return transports_; - } - - void SetCredentialTypeForTesting(CredentialType type) { - credential_type_ = type; - } - std::vector<uint8_t>& GetIdForTesting() { return id_; } - base::flat_set<FidoTransportProtocol>& GetTransportsForTesting() { - return transports_; - } - - private: - CredentialType credential_type_; - std::vector<uint8_t> id_; - base::flat_set<FidoTransportProtocol> transports_; + CredentialType credential_type; + std::vector<uint8_t> id; + base::flat_set<FidoTransportProtocol> transports; }; COMPONENT_EXPORT(DEVICE_FIDO)
diff --git a/device/fido/u2f_register_operation.cc b/device/fido/u2f_register_operation.cc index 15ba081..dba244b 100644 --- a/device/fido/u2f_register_operation.cc +++ b/device/fido/u2f_register_operation.cc
@@ -204,7 +204,7 @@ const std::vector<uint8_t>& U2fRegisterOperation::excluded_key_handle() const { DCHECK_LT(current_key_handle_index_, request().exclude_list.size()); - return request().exclude_list[current_key_handle_index_].id(); + return request().exclude_list[current_key_handle_index_].id; } } // namespace device
diff --git a/device/fido/u2f_sign_operation.cc b/device/fido/u2f_sign_operation.cc index 1cfe874..7ca179f 100644 --- a/device/fido/u2f_sign_operation.cc +++ b/device/fido/u2f_sign_operation.cc
@@ -195,7 +195,7 @@ const std::vector<uint8_t>& U2fSignOperation::key_handle() const { DCHECK_LT(current_key_handle_index_, request().allow_list.size()); - return request().allow_list.at(current_key_handle_index_).id(); + return request().allow_list.at(current_key_handle_index_).id; } } // namespace device
diff --git a/device/fido/u2f_sign_operation_unittest.cc b/device/fido/u2f_sign_operation_unittest.cc index 1ff785e..4dde02b5 100644 --- a/device/fido/u2f_sign_operation_unittest.cc +++ b/device/fido/u2f_sign_operation_unittest.cc
@@ -75,7 +75,7 @@ sign_callback_receiver().status()); EXPECT_THAT(sign_callback_receiver().value()->signature, ::testing::ElementsAreArray(test_data::kU2fSignature)); - EXPECT_THAT(sign_callback_receiver().value()->credential->id(), + EXPECT_THAT(sign_callback_receiver().value()->credential->id, ::testing::ElementsAreArray(test_data::kU2fSignKeyHandle)); } @@ -139,7 +139,7 @@ sign_callback_receiver().status()); EXPECT_THAT(sign_callback_receiver().value()->signature, ::testing::ElementsAreArray(test_data::kU2fSignature)); - EXPECT_THAT(sign_callback_receiver().value()->credential->id(), + EXPECT_THAT(sign_callback_receiver().value()->credential->id, ::testing::ElementsAreArray(test_data::kU2fSignKeyHandle)); } @@ -174,7 +174,7 @@ sign_callback_receiver().status()); EXPECT_THAT(sign_callback_receiver().value()->signature, ::testing::ElementsAreArray(test_data::kU2fSignature)); - EXPECT_THAT(sign_callback_receiver().value()->credential->id(), + EXPECT_THAT(sign_callback_receiver().value()->credential->id, ::testing::ElementsAreArray(test_data::kU2fSignKeyHandle)); } @@ -207,7 +207,7 @@ sign_callback_receiver().status()); EXPECT_THAT(sign_callback_receiver().value()->signature, ::testing::ElementsAreArray(test_data::kU2fSignature)); - EXPECT_THAT(sign_callback_receiver().value()->credential->id(), + EXPECT_THAT(sign_callback_receiver().value()->credential->id, ::testing::ElementsAreArray(test_data::kU2fSignKeyHandle)); } @@ -350,7 +350,7 @@ const auto& response_value = sign_callback_receiver().value(); EXPECT_THAT(response_value->signature, ::testing::ElementsAreArray(test_data::kU2fSignature)); - EXPECT_THAT(response_value->credential->id(), + EXPECT_THAT(response_value->credential->id, ::testing::ElementsAreArray(test_data::kU2fSignKeyHandle)); EXPECT_THAT(response_value->authenticator_data.application_parameter(), ::testing::ElementsAreArray(base::span<const uint8_t, 32>(
diff --git a/device/fido/virtual_ctap2_device.cc b/device/fido/virtual_ctap2_device.cc index 35dbcc3..b822e36 100644 --- a/device/fido/virtual_ctap2_device.cc +++ b/device/fido/virtual_ctap2_device.cc
@@ -1037,11 +1037,11 @@ for (const auto& excluded_credential : request.exclude_list) { if (0 < config_.max_credential_id_length && - config_.max_credential_id_length < excluded_credential.id().size()) { + config_.max_credential_id_length < excluded_credential.id.size()) { return CtapDeviceResponseCode::kCtap2ErrLimitExceeded; } const RegistrationData* found = - FindRegistrationData(excluded_credential.id(), rp_id_hash); + FindRegistrationData(excluded_credential.id, rp_id_hash); if (found) { if (found->protection == device::CredProtect::kUVRequired && !user_verified) { @@ -1345,14 +1345,14 @@ for (const auto& allowed_credential : request.allow_list) { if (0 < config_.max_credential_id_length && - config_.max_credential_id_length < allowed_credential.id().size()) { + config_.max_credential_id_length < allowed_credential.id.size()) { return CtapDeviceResponseCode::kCtap2ErrLimitExceeded; } RegistrationData* registration = - FindRegistrationData(allowed_credential.id(), rp_id_hash); + FindRegistrationData(allowed_credential.id, rp_id_hash); if (registration && !(registration->is_u2f && config_.ignore_u2f_credentials)) { - found_registrations.emplace_back(allowed_credential.id(), registration); + found_registrations.emplace_back(allowed_credential.id, registration); break; } } @@ -2112,11 +2112,10 @@ if (!credential_id) { return CtapDeviceResponseCode::kCtap2ErrCBORUnexpectedType; } - if (!base::Contains(mutable_state()->registrations, - credential_id->id())) { + if (!base::Contains(mutable_state()->registrations, credential_id->id)) { return CtapDeviceResponseCode::kCtap2ErrNoCredentials; } - mutable_state()->registrations.erase(credential_id->id()); + mutable_state()->registrations.erase(credential_id->id); *response = {}; return CtapDeviceResponseCode::kSuccess; } @@ -2155,8 +2154,7 @@ if (!credential_id) { return CtapDeviceResponseCode::kCtap2ErrMissingParameter; } - if (!base::Contains(mutable_state()->registrations, - credential_id->id())) { + if (!base::Contains(mutable_state()->registrations, credential_id->id)) { return CtapDeviceResponseCode::kCtap2ErrNoCredentials; } @@ -2172,7 +2170,7 @@ return CtapDeviceResponseCode::kCtap2ErrCBORUnexpectedType; } - mutable_state()->registrations[credential_id->id()].user = new_user; + mutable_state()->registrations[credential_id->id].user = new_user; *response = {}; return CtapDeviceResponseCode::kSuccess; }
diff --git a/device/fido/virtual_ctap2_device_unittest.cc b/device/fido/virtual_ctap2_device_unittest.cc index fb7e7ff..6efd6ab 100644 --- a/device/fido/virtual_ctap2_device_unittest.cc +++ b/device/fido/virtual_ctap2_device_unittest.cc
@@ -130,9 +130,9 @@ EXPECT_FALSE(request->user_presence_required); ASSERT_EQ(2u, request->allow_list.size()); - EXPECT_THAT(request->allow_list.at(0).id(), + EXPECT_THAT(request->allow_list.at(0).id, ::testing::ElementsAreArray(kAllowedCredentialOne)); - EXPECT_THAT(request->allow_list.at(1).id(), + EXPECT_THAT(request->allow_list.at(1).id, ::testing::ElementsAreArray(kAllowedCredentialTwo)); }
diff --git a/device/fido/win/type_conversions.cc b/device/fido/win/type_conversions.cc index 6d86548..bafc2ba7 100644 --- a/device/fido/win/type_conversions.cc +++ b/device/fido/win/type_conversions.cc
@@ -176,13 +176,13 @@ const std::vector<PublicKeyCredentialDescriptor>* credentials) { std::vector<WEBAUTHN_CREDENTIAL> result; for (const auto& credential : *credentials) { - if (credential.credential_type() != CredentialType::kPublicKey) { + if (credential.credential_type != CredentialType::kPublicKey) { continue; } result.push_back(WEBAUTHN_CREDENTIAL{ WEBAUTHN_CREDENTIAL_CURRENT_VERSION, - base::checked_cast<DWORD>(credential.id().size()), - const_cast<unsigned char*>(credential.id().data()), + base::checked_cast<DWORD>(credential.id.size()), + const_cast<unsigned char*>(credential.id.data()), WEBAUTHN_CREDENTIAL_TYPE_PUBLIC_KEY, }); } @@ -193,15 +193,15 @@ const std::vector<PublicKeyCredentialDescriptor>* credentials) { std::vector<WEBAUTHN_CREDENTIAL_EX> result; for (const auto& credential : *credentials) { - if (credential.credential_type() != CredentialType::kPublicKey) { + if (credential.credential_type != CredentialType::kPublicKey) { continue; } - result.push_back(WEBAUTHN_CREDENTIAL_EX{ - WEBAUTHN_CREDENTIAL_EX_CURRENT_VERSION, - base::checked_cast<DWORD>(credential.id().size()), - const_cast<unsigned char*>(credential.id().data()), - WEBAUTHN_CREDENTIAL_TYPE_PUBLIC_KEY, - ToWinTransportsMask(credential.transports())}); + result.push_back( + WEBAUTHN_CREDENTIAL_EX{WEBAUTHN_CREDENTIAL_EX_CURRENT_VERSION, + base::checked_cast<DWORD>(credential.id.size()), + const_cast<unsigned char*>(credential.id.data()), + WEBAUTHN_CREDENTIAL_TYPE_PUBLIC_KEY, + ToWinTransportsMask(credential.transports)}); } return result; } @@ -222,7 +222,7 @@ {u"InvalidStateError", CtapDeviceResponseCode::kCtap2ErrCredentialExcluded}, {u"ConstraintError", - CtapDeviceResponseCode::kCtap2ErrOperationDenied}, + CtapDeviceResponseCode ::kCtap2ErrOperationDenied}, {u"NotSupportedError", CtapDeviceResponseCode::kCtap2ErrOperationDenied}, {u"NotAllowedError",
diff --git a/docs/android_emulator.md b/docs/android_emulator.md index d8a1ee5..7953614 100644 --- a/docs/android_emulator.md +++ b/docs/android_emulator.md
@@ -135,6 +135,19 @@ --emulator-window ``` + * `--wipe-data` + + Since the prebuilt playstore images use adbkey from the GCE bots that created + them, they may appear to be "unauthorized" when used locally. Pass this flag + to reset the user data image locally to fix it after installing a prebuilt + image: + + ``` + $ tools/android/avd/avd.py start \ + --avd-config tools/android/avd/proto/generic_playstore_android28.textpb \ + --wipe-data + ``` + * `--no-read-only` `avd.py` runs the emulator in read-only mode by default. To run a modifiable @@ -151,6 +164,8 @@ `avd.py` disables the emulator log by default. When this option is used, emulator log will be enabled. It is useful when the emulator cannot be launched correctly. See `emulator -help-debug-tags` for a full list of tags. + Use `--debug-tags="*"` if you want to output all logs (warning: it is quite + verbose). ``` $ tools/android/avd/avd.py start \
diff --git a/fuchsia/engine/browser/frame_impl.cc b/fuchsia/engine/browser/frame_impl.cc index 39f124c0..7d9e445c8 100644 --- a/fuchsia/engine/browser/frame_impl.cc +++ b/fuchsia/engine/browser/frame_impl.cc
@@ -592,7 +592,8 @@ if (!context_->has_cast_streaming_enabled() || !receiver_session_client_) return; - mojo::AssociatedRemote<mojom::CastStreamingReceiver> cast_streaming_receiver; + mojo::AssociatedRemote<cast_streaming::mojom::CastStreamingReceiver> + cast_streaming_receiver; navigation_handle->GetRenderFrameHost() ->GetRemoteAssociatedInterfaces() ->GetInterface(&cast_streaming_receiver);
diff --git a/fuchsia/engine/browser/receiver_session_client.cc b/fuchsia/engine/browser/receiver_session_client.cc index f97ea87..a5ab0349 100644 --- a/fuchsia/engine/browser/receiver_session_client.cc +++ b/fuchsia/engine/browser/receiver_session_client.cc
@@ -21,7 +21,7 @@ ReceiverSessionClient::~ReceiverSessionClient() = default; void ReceiverSessionClient::SetCastStreamingReceiver( - mojo::AssociatedRemote<mojom::CastStreamingReceiver> + mojo::AssociatedRemote<cast_streaming::mojom::CastStreamingReceiver> cast_streaming_receiver) { DCHECK(message_port_request_);
diff --git a/fuchsia/engine/browser/receiver_session_client.h b/fuchsia/engine/browser/receiver_session_client.h index 0d745104..1d753d59 100644 --- a/fuchsia/engine/browser/receiver_session_client.h +++ b/fuchsia/engine/browser/receiver_session_client.h
@@ -25,7 +25,7 @@ ReceiverSessionClient& operator=(const ReceiverSessionClient&) = delete; void SetCastStreamingReceiver( - mojo::AssociatedRemote<mojom::CastStreamingReceiver> + mojo::AssociatedRemote<cast_streaming::mojom::CastStreamingReceiver> cast_streaming_receiver); private:
diff --git a/headless/BUILD.gn b/headless/BUILD.gn index 8d81ee6..067b40f 100644 --- a/headless/BUILD.gn +++ b/headless/BUILD.gn
@@ -839,6 +839,7 @@ sources = [ "app/headless_shell.cc", "app/headless_shell.h", + "app/headless_shell_switches.h", "lib/browser/headless_content_browser_client.cc", "lib/browser/headless_content_browser_client.h", "public/headless_shell.h", @@ -869,6 +870,7 @@ sources = [ "app/headless_shell.cc", "app/headless_shell.h", + "app/headless_shell_switches.h", "public/headless_shell.h", ] defines = []
diff --git a/headless/app/headless_shell.cc b/headless/app/headless_shell.cc index 02352ae..3d6fac8 100644 --- a/headless/app/headless_shell.cc +++ b/headless/app/headless_shell.cc
@@ -711,14 +711,6 @@ if (!ValidateCommandLine(command_line)) return EXIT_FAILURE; -// Crash reporting in headless mode is enabled by default in official builds. -#if BUILDFLAG(GOOGLE_CHROME_BRANDING) - builder.SetCrashReporterEnabled(true); - base::FilePath dumps_path; - base::PathService::Get(base::DIR_TEMP, &dumps_path); - builder.SetCrashDumpsDir(dumps_path); -#endif - #if defined(OS_MAC) command_line.AppendSwitch(os_crypt::switches::kUseMockKeychain); #endif
diff --git a/headless/lib/headless_crash_reporter_client.cc b/headless/lib/headless_crash_reporter_client.cc index 591e3c28..3896ef7 100644 --- a/headless/lib/headless_crash_reporter_client.cc +++ b/headless/lib/headless_crash_reporter_client.cc
@@ -60,6 +60,7 @@ ) { base::FilePath crash_directory = crash_dumps_dir_; if (crash_directory.empty() && + !base::PathService::Get(base::DIR_TEMP, &crash_directory) && !base::PathService::Get(base::DIR_MODULE, &crash_directory)) { return false; }
diff --git "a/infra/config/generated/builders/ci/Mac11 Tests \050dbg\051/properties.textpb" "b/infra/config/generated/builders/ci/Mac11 Tests \050dbg\051/properties.textpb" new file mode 100644 index 0000000..ae30ff3 --- /dev/null +++ "b/infra/config/generated/builders/ci/Mac11 Tests \050dbg\051/properties.textpb"
@@ -0,0 +1,14 @@ +{ + "$recipe_engine/resultdb/test_presentation": { + "column_keys": [], + "grouping_keys": [ + "status", + "v.test_suite" + ] + }, + "builder_group": "chromium.mac", + "recipe": "chromium", + "sheriff_rotations": [ + "chromium" + ] +} \ No newline at end of file
diff --git a/infra/config/generated/luci/cr-buildbucket.cfg b/infra/config/generated/luci/cr-buildbucket.cfg index 1aacc6b..4a88987 100644 --- a/infra/config/generated/luci/cr-buildbucket.cfg +++ b/infra/config/generated/luci/cr-buildbucket.cfg
@@ -16212,6 +16212,96 @@ } } builders { + name: "Mac11 Tests (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.ci" + 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/ci/Mac11 Tests (dbg)/properties.textpb",' + ' "top_level_project": {' + ' "ref": "refs/heads/main",' + ' "repo": {' + ' "host": "chromium.googlesource.com",' + ' "project": "chromium/src"' + ' }' + ' }' + ' },' + ' "builder_group": "chromium.mac",' + ' "led_builder_is_bootstrapped": true,' + ' "recipe": "chromium",' + ' "sheriff_rotations": [' + ' "chromium"' + ' ]' + '}' + execution_timeout_secs: 10800 + build_numbers: YES + service_account: "chromium-ci-builder@chops-service-accounts.iam.gserviceaccount.com" + experiments { + key: "chromium.chromium_tests.use_rdb_results" + value: 100 + } + experiments { + key: "luci.recipes.use_python3" + value: 20 + } + experiments { + key: "luci.use_realms" + value: 100 + } + resultdb { + enable: true + bq_exports { + project: "chrome-luci-data" + dataset: "chromium" + table: "ci_test_results" + test_results {} + } + bq_exports { + project: "chrome-luci-data" + dataset: "chromium" + table: "gpu_ci_test_results" + test_results { + predicate { + test_id_regexp: "ninja://(chrome/test:|content/test:fuchsia_)telemetry_gpu_integration_test[^/]*/.+" + } + } + } + bq_exports { + project: "chrome-luci-data" + dataset: "chromium" + table: "blink_web_tests_ci_test_results" + test_results { + predicate { + test_id_regexp: "ninja://[^/]*blink_web_tests/.+" + } + } + } + history_options { + use_invocation_timestamp: true + } + } + } + builders { name: "Marshmallow 64 bit Tester" swarming_host: "chromium-swarm.appspot.com" dimensions: "builderless:1" @@ -18746,6 +18836,10 @@ value: 100 } experiments { + key: "luci.recipes.use_python3" + value: 20 + } + experiments { key: "luci.use_realms" value: 100 } @@ -19447,6 +19541,10 @@ value: 100 } experiments { + key: "luci.recipes.use_python3" + value: 20 + } + experiments { key: "luci.use_realms" value: 100 } @@ -20419,6 +20517,10 @@ value: 100 } experiments { + key: "luci.recipes.use_python3" + value: 20 + } + experiments { key: "luci.use_realms" value: 100 } @@ -51010,6 +51112,10 @@ value: 100 } experiments { + key: "luci.recipes.use_python3" + value: 20 + } + experiments { key: "luci.use_realms" value: 100 } @@ -78490,6 +78596,10 @@ value: 100 } experiments { + key: "luci.recipes.use_python3" + value: 100 + } + experiments { key: "luci.use_realms" value: 100 } @@ -81426,12 +81536,12 @@ builders { name: "win_chromium_compile_dbg_ng" swarming_host: "chromium-swarm.appspot.com" - dimensions: "builderless:1" - dimensions: "cores:8" + dimensions: "builder:win_chromium_compile_dbg_ng" + dimensions: "cores:16" dimensions: "cpu:x86-64" dimensions: "os:Windows-10" dimensions: "pool:luci.chromium.try" - dimensions: "ssd:0" + dimensions: "ssd:1" exe { cipd_package: "infra/recipe_bundles/chromium.googlesource.com/chromium/tools/build" cipd_version: "refs/heads/main"
diff --git a/infra/config/generated/luci/luci-milo.cfg b/infra/config/generated/luci/luci-milo.cfg index fa8f7d337..5be07677 100644 --- a/infra/config/generated/luci/luci-milo.cfg +++ b/infra/config/generated/luci/luci-milo.cfg
@@ -226,6 +226,11 @@ short_name: "bld" } builders { + name: "buildbucket/luci.chromium.ci/Mac11 Tests (dbg)" + category: "chromium.mac|debug" + short_name: "11" + } + builders { name: "buildbucket/luci.chromium.ci/Mac10.15 Tests (dbg)" category: "chromium.mac|debug" short_name: "15" @@ -969,6 +974,11 @@ short_name: "bld" } builders { + name: "buildbucket/luci.chromium.ci/Mac11 Tests (dbg)" + category: "chromium.mac|debug" + short_name: "11" + } + builders { name: "buildbucket/luci.chromium.ci/Mac10.15 Tests (dbg)" category: "chromium.mac|debug" short_name: "15" @@ -8991,6 +9001,11 @@ short_name: "bld" } builders { + name: "buildbucket/luci.chromium.ci/Mac11 Tests (dbg)" + category: "debug" + short_name: "11" + } + builders { name: "buildbucket/luci.chromium.ci/Mac10.15 Tests (dbg)" category: "debug" short_name: "15"
diff --git a/infra/config/generated/luci/luci-notify.cfg b/infra/config/generated/luci/luci-notify.cfg index aa245cce..e0aadcd 100644 --- a/infra/config/generated/luci/luci-notify.cfg +++ b/infra/config/generated/luci/luci-notify.cfg
@@ -1644,6 +1644,24 @@ } template: "tree_closure_email_template" } + builders { + bucket: "ci" + name: "Mac11 Tests (dbg)" + } + tree_closers { + tree_status_host: "chromium-status.appspot.com" + failed_step_regexp: "\\b(bot_update|compile|gclient runhooks|runhooks|update|\\w*nocompile_test)\\b" + } +} +notifiers { + notifications { + on_occurrence: FAILURE + failed_step_regexp: "\\b(bot_update|compile|gclient runhooks|runhooks|update|\\w*nocompile_test)\\b" + email { + rotation_urls: "https://chrome-ops-rotation-proxy.appspot.com/current/oncallator:chrome-build-sheriff" + } + template: "tree_closure_email_template" + } notifications { on_occurrence: FAILURE failed_step_regexp: "\\b(bot_update|compile|gclient runhooks|runhooks|update|\\w*nocompile_test)\\b"
diff --git a/infra/config/generated/luci/luci-scheduler.cfg b/infra/config/generated/luci/luci-scheduler.cfg index f8d5e41a..5a4e93b 100644 --- a/infra/config/generated/luci/luci-scheduler.cfg +++ b/infra/config/generated/luci/luci-scheduler.cfg
@@ -2505,6 +2505,20 @@ } } job { + id: "Mac11 Tests (dbg)" + realm: "ci" + acls { + role: TRIGGERER + granted_to: "chromium-ci-builder@chops-service-accounts.iam.gserviceaccount.com" + } + acl_sets: "ci" + buildbucket { + server: "cr-buildbucket.appspot.com" + bucket: "luci.chromium.ci" + builder: "Mac11 Tests (dbg)" + } +} +job { id: "Marshmallow 64 bit Tester" realm: "ci" acls {
diff --git a/infra/config/recipes.star b/infra/config/recipes.star index d2379dc..bb4c2a50 100644 --- a/infra/config/recipes.star +++ b/infra/config/recipes.star
@@ -106,6 +106,9 @@ build_recipe( name = "recipe:binary_size_trybot", + experiments = { + "luci.recipes.use_python3": 20, + }, ) build_recipe( @@ -160,6 +163,9 @@ build_recipe( name = "recipe:chromium_clang_coverage_tot", + experiments = { + "luci.recipes.use_python3": 20, + }, ) build_recipe( @@ -261,6 +267,7 @@ build_recipe( name = "recipe:tricium_simple", + use_python3 = True, ) build_recipe(
diff --git a/infra/config/subprojects/chromium/ci.star b/infra/config/subprojects/chromium/ci.star index abebd98..14d1ae3 100644 --- a/infra/config/subprojects/chromium/ci.star +++ b/infra/config/subprojects/chromium/ci.star
@@ -6045,6 +6045,18 @@ ) ci.mac_thin_tester( + name = "Mac10.15 Tests (dbg)", + branch_selector = branches.DESKTOP_EXTENDED_STABLE_MILESTONE, + console_view_entry = consoles.console_view_entry( + category = "debug", + short_name = "15", + ), + cq_mirrors_console_view = "mirrors", + main_console_view = "main", + triggered_by = ["ci/Mac Builder (dbg)"], +) + +ci.mac_thin_tester( name = "Mac11 Tests", branch_selector = branches.DESKTOP_EXTENDED_STABLE_MILESTONE, console_view_entry = consoles.console_view_entry( @@ -6056,11 +6068,11 @@ ) ci.mac_thin_tester( - name = "Mac10.15 Tests (dbg)", + name = "Mac11 Tests (dbg)", branch_selector = branches.DESKTOP_EXTENDED_STABLE_MILESTONE, console_view_entry = consoles.console_view_entry( category = "debug", - short_name = "15", + short_name = "11", ), cq_mirrors_console_view = "mirrors", main_console_view = "main",
diff --git a/infra/config/subprojects/chromium/try.star b/infra/config/subprojects/chromium/try.star index 9ca089f..dfdaf3a2 100644 --- a/infra/config/subprojects/chromium/try.star +++ b/infra/config/subprojects/chromium/try.star
@@ -1914,6 +1914,9 @@ goma_jobs = goma.jobs.J150, main_list_view = "try", tryjob = try_.job(), + builderless = False, + cores = 16, + ssd = True, ) try_.chromium_win_builder(
diff --git a/ios/chrome/browser/flags/about_flags.mm b/ios/chrome/browser/flags/about_flags.mm index a0552ca97..979838a 100644 --- a/ios/chrome/browser/flags/about_flags.mm +++ b/ios/chrome/browser/flags/about_flags.mm
@@ -485,11 +485,6 @@ flags_ui::kOsIos, FEATURE_VALUE_TYPE( autofill::features::kAutofillSaveCardDismissOnNavigation)}, - {"default-user-agent", - flag_descriptions::kUseDefaultUserAgentInWebClientName, - flag_descriptions::kUseDefaultUserAgentInWebClientDescription, - flags_ui::kOsIos, - FEATURE_VALUE_TYPE(web::features::kUseDefaultUserAgentInWebClient)}, {"url-blocklist-ios", flag_descriptions::kURLBlocklistIOSName, flag_descriptions::kURLBlocklistIOSDescription, flags_ui::kOsIos, FEATURE_VALUE_TYPE(kURLBlocklistIOS)}, @@ -690,15 +685,6 @@ flag_descriptions::kSyncTrustedVaultPassphraseRecoveryDescription, flags_ui::kOsIos, FEATURE_VALUE_TYPE(::switches::kSyncTrustedVaultPassphraseRecovery)}, - {"enable-autofill-save-card-info-bar-account-indication-footer", - flag_descriptions:: - kEnableAutofillSaveCardInfoBarAccountIndicationFooterName, - flag_descriptions:: - kEnableAutofillSaveCardInfoBarAccountIndicationFooterDescription, - flags_ui::kOsIos, - FEATURE_VALUE_TYPE( - autofill::features:: - kAutofillEnableSaveCardInfoBarAccountIndicationFooter)}, {"wait-threshold-seconds-for-capabilities-api", flag_descriptions::kWaitThresholdMillisecondsForCapabilitiesApiName, flag_descriptions::kWaitThresholdMillisecondsForCapabilitiesApiDescription,
diff --git a/ios/chrome/browser/flags/ios_chrome_flag_descriptions.cc b/ios/chrome/browser/flags/ios_chrome_flag_descriptions.cc index 61d2ff15..a4f805c 100644 --- a/ios/chrome/browser/flags/ios_chrome_flag_descriptions.cc +++ b/ios/chrome/browser/flags/ios_chrome_flag_descriptions.cc
@@ -156,12 +156,6 @@ const char kEnableAutofillAddressSavePromptDescription[] = "Enable the Autofill address save prompts."; -const char kEnableAutofillSaveCardInfoBarAccountIndicationFooterName[] = - "Display save card infobar with account indication information"; -const char kEnableAutofillSaveCardInfoBarAccountIndicationFooterDescription[] = - "When enabled, UI indicating user's e-mail address will appear at the" - "bottom of save card infobar."; - const char kEnableDiscoverFeedDiscoFeedEndpointName[] = "Enable discover feed discofeed"; const char kEnableDiscoverFeedDiscoFeedEndpointDescription[] = @@ -536,12 +530,6 @@ "When enabled, URLs can be blocked/allowed by the URLBlocklist/URLAllowlist" "enterprise policies."; -const char kUseDefaultUserAgentInWebClientName[] = - "[Refactoring] Let the client choose default mode"; -const char kUseDefaultUserAgentInWebClientDescription[] = - "When enabled, the web client will choose the default mode. It is a " - "refactoring, no visible impact."; - const char kUseLensToSearchForImageName[] = "Use Google Lens to Search for images"; const char kUseLensToSearchForImageDescription[] =
diff --git a/ios/chrome/browser/flags/ios_chrome_flag_descriptions.h b/ios/chrome/browser/flags/ios_chrome_flag_descriptions.h index 63463f22..7706428 100644 --- a/ios/chrome/browser/flags/ios_chrome_flag_descriptions.h +++ b/ios/chrome/browser/flags/ios_chrome_flag_descriptions.h
@@ -141,12 +141,6 @@ extern const char kEnableAutofillAddressSavePromptName[]; extern const char kEnableAutofillAddressSavePromptDescription[]; -// Title and description for the flag to enable account indication in the save -// card dialog. -extern const char kEnableAutofillSaveCardInfoBarAccountIndicationFooterName[]; -extern const char - kEnableAutofillSaveCardInfoBarAccountIndicationFooterDescription[]; - // Title and description for the flag to enable the discover feed discofeed // endpoint. extern const char kEnableDiscoverFeedDiscoFeedEndpointName[]; @@ -479,11 +473,6 @@ extern const char kURLBlocklistIOSName[]; extern const char kURLBlocklistIOSDescription[]; -// Title and description for the flag to have the web client choosing the -// default user agent. -extern const char kUseDefaultUserAgentInWebClientName[]; -extern const char kUseDefaultUserAgentInWebClientDescription[]; - // Title and description for the flag to enable using Lens to search for an // image from the long press context menu. extern const char kUseLensToSearchForImageName[];
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 a218d02..0007e230 100644 --- a/ios/chrome/browser/ui/autofill/chrome_autofill_client_ios.mm +++ b/ios/chrome/browser/ui/autofill/chrome_autofill_client_ios.mm
@@ -22,7 +22,6 @@ #include "components/autofill/core/browser/payments/payments_client.h" #include "components/autofill/core/browser/ui/payments/card_unmask_prompt_view.h" #include "components/autofill/core/common/autofill_features.h" -#import "components/autofill/core/common/autofill_payments_features.h" #include "components/autofill/core/common/autofill_prefs.h" #include "components/autofill/ios/browser/autofill_util.h" #include "components/infobars/core/infobar.h" @@ -287,33 +286,8 @@ UploadSaveCardPromptCallback callback) { DCHECK(options.show_prompt); - bool sync_disabled_wallet_transport_enabled = - GetPersonalDataManager()->GetSyncSigninState() == - autofill::AutofillSyncSigninState::kSignedInAndWalletSyncTransportEnabled; - bool is_multiple_account_user = - identity_manager_->GetAccountsWithRefreshTokens().size() > 1; - AccountInfo account_info; - // AccountInfo data should be passed down only if the following conditions are - // satisfied: - // 1) kAutofillEnableSaveCardInfoBarAccountIndicationFooter is on (main flag). - // 2) Sync is off or the - // kAutofillEnableInfoBarAccountIndicationFooterForSyncUsers flag is on. - // 3) User has multiple accounts or the - // kAutofillEnableInfoBarAccountIndicationFooterForSingleAccountUsers is on. - if (base::FeatureList::IsEnabled( - features::kAutofillEnableSaveCardInfoBarAccountIndicationFooter) && - (sync_disabled_wallet_transport_enabled || - base::FeatureList::IsEnabled( - features:: - kAutofillEnableInfoBarAccountIndicationFooterForSyncUsers)) && - (is_multiple_account_user || - base::FeatureList::IsEnabled( - features:: - kAutofillEnableInfoBarAccountIndicationFooterForSingleAccountUsers))) { - account_info = identity_manager_->FindExtendedAccountInfo( - identity_manager_->GetPrimaryAccountInfo( - signin::ConsentLevel::kSignin)); - } + AccountInfo account_info = identity_manager_->FindExtendedAccountInfo( + identity_manager_->GetPrimaryAccountInfo(signin::ConsentLevel::kSignin)); infobar_manager_->AddInfoBar(CreateSaveCardInfoBarMobile( std::make_unique<AutofillSaveCardInfoBarDelegateMobile>( /*upload=*/true, options, card, legal_message_lines,
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 fe0255db..818a9f9 100644 --- a/ios/chrome/browser/ui/content_suggestions/ntp_home_egtest.mm +++ b/ios/chrome/browser/ui/content_suggestions/ntp_home_egtest.mm
@@ -974,6 +974,10 @@ // Scroll back to top of NTP. [[EarlGrey selectElementWithMatcher:chrome_test_util::NTPCollectionView()] performAction:grey_swipeFastInDirection(kGREYDirectionDown)]; + // Usually a fast swipe scrolls back up, but in case it doesn't, make sure + // by slowly scrolling to the top. + [[EarlGrey selectElementWithMatcher:chrome_test_util::NTPCollectionView()] + performAction:grey_scrollToContentEdge(kGREYContentEdgeTop)]; } - (void)showFeedFromNTPMenu {
diff --git a/ios/chrome/browser/ui/passwords/password_breach_view_controller.mm b/ios/chrome/browser/ui/passwords/password_breach_view_controller.mm index 39e1deb6..56dd314 100644 --- a/ios/chrome/browser/ui/passwords/password_breach_view_controller.mm +++ b/ios/chrome/browser/ui/passwords/password_breach_view_controller.mm
@@ -40,7 +40,7 @@ self.pinSpecificContentAboveButton = YES; UIImageView* imageView = [[UIImageView alloc] - initWithImage:[UIImage imageNamed:@"passwords_logo"]]; + initWithImage:[UIImage imageNamed:@"passwords_logo_colored"]]; imageView.contentMode = UIViewContentModeScaleAspectFit; imageView.translatesAutoresizingMaskIntoConstraints = NO; [self.specificContentView addSubview:imageView];
diff --git a/ios/chrome/browser/ui/passwords/resources/BUILD.gn b/ios/chrome/browser/ui/passwords/resources/BUILD.gn index b2cc5ec1..1cb9b5a 100644 --- a/ios/chrome/browser/ui/passwords/resources/BUILD.gn +++ b/ios/chrome/browser/ui/passwords/resources/BUILD.gn
@@ -9,7 +9,7 @@ deps = [ ":legacy_password_breach_illustration", ":password_breach_illustration", - ":passwords_logo", + ":passwords_logo_colored", ] } @@ -23,11 +23,13 @@ ] } -imageset("passwords_logo") { +imageset("passwords_logo_colored") { sources = [ - "passwords_logo.imageset/Contents.json", - "passwords_logo.imageset/passwords_logo@2x.png", - "passwords_logo.imageset/passwords_logo@3x.png", + "passwords_logo_colored.imageset/Contents.json", + "passwords_logo_colored.imageset/passwords_logo_colored@2x.png", + "passwords_logo_colored.imageset/passwords_logo_colored@3x.png", + "passwords_logo_colored.imageset/passwords_logo_colored_dark@2x.png", + "passwords_logo_colored.imageset/passwords_logo_colored_dark@3x.png", ] }
diff --git a/ios/chrome/browser/ui/passwords/resources/passwords_logo.imageset/Contents.json b/ios/chrome/browser/ui/passwords/resources/passwords_logo.imageset/Contents.json deleted file mode 100644 index d459457..0000000 --- a/ios/chrome/browser/ui/passwords/resources/passwords_logo.imageset/Contents.json +++ /dev/null
@@ -1,18 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "passwords_logo@2x.png", - "scale" : "2x" - }, - { - "idiom" : "universal", - "filename" : "passwords_logo@3x.png", - "scale" : "3x" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - } -}
diff --git a/ios/chrome/browser/ui/passwords/resources/passwords_logo.imageset/passwords_logo@2x.png b/ios/chrome/browser/ui/passwords/resources/passwords_logo.imageset/passwords_logo@2x.png deleted file mode 100644 index 9353544..0000000 --- a/ios/chrome/browser/ui/passwords/resources/passwords_logo.imageset/passwords_logo@2x.png +++ /dev/null Binary files differ
diff --git a/ios/chrome/browser/ui/passwords/resources/passwords_logo.imageset/passwords_logo@3x.png b/ios/chrome/browser/ui/passwords/resources/passwords_logo.imageset/passwords_logo@3x.png deleted file mode 100644 index 7839ced..0000000 --- a/ios/chrome/browser/ui/passwords/resources/passwords_logo.imageset/passwords_logo@3x.png +++ /dev/null Binary files differ
diff --git a/ios/chrome/browser/ui/passwords/resources/passwords_logo_colored.imageset/Contents.json b/ios/chrome/browser/ui/passwords/resources/passwords_logo_colored.imageset/Contents.json new file mode 100644 index 0000000..134dbfbd --- /dev/null +++ b/ios/chrome/browser/ui/passwords/resources/passwords_logo_colored.imageset/Contents.json
@@ -0,0 +1,40 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "passwords_logo_colored@2x.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "passwords_logo_colored_dark@2x.png", + "scale" : "2x", + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + } + ] + }, + { + "idiom" : "universal", + "filename" : "passwords_logo_colored@3x.png", + "scale" : "3x" + }, + { + "idiom" : "universal", + "filename" : "passwords_logo_colored_dark@3x.png", + "scale" : "3x", + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + } + ] + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +}
diff --git a/ios/chrome/browser/ui/passwords/resources/passwords_logo_colored.imageset/passwords_logo_colored@2x.png b/ios/chrome/browser/ui/passwords/resources/passwords_logo_colored.imageset/passwords_logo_colored@2x.png new file mode 100644 index 0000000..499705c --- /dev/null +++ b/ios/chrome/browser/ui/passwords/resources/passwords_logo_colored.imageset/passwords_logo_colored@2x.png Binary files differ
diff --git a/ios/chrome/browser/ui/passwords/resources/passwords_logo_colored.imageset/passwords_logo_colored@3x.png b/ios/chrome/browser/ui/passwords/resources/passwords_logo_colored.imageset/passwords_logo_colored@3x.png new file mode 100644 index 0000000..086aa7c --- /dev/null +++ b/ios/chrome/browser/ui/passwords/resources/passwords_logo_colored.imageset/passwords_logo_colored@3x.png Binary files differ
diff --git a/ios/chrome/browser/ui/passwords/resources/passwords_logo_colored.imageset/passwords_logo_colored_dark@2x.png b/ios/chrome/browser/ui/passwords/resources/passwords_logo_colored.imageset/passwords_logo_colored_dark@2x.png new file mode 100644 index 0000000..d694afa --- /dev/null +++ b/ios/chrome/browser/ui/passwords/resources/passwords_logo_colored.imageset/passwords_logo_colored_dark@2x.png Binary files differ
diff --git a/ios/chrome/browser/ui/passwords/resources/passwords_logo_colored.imageset/passwords_logo_colored_dark@3x.png b/ios/chrome/browser/ui/passwords/resources/passwords_logo_colored.imageset/passwords_logo_colored_dark@3x.png new file mode 100644 index 0000000..2d47cf6 --- /dev/null +++ b/ios/chrome/browser/ui/passwords/resources/passwords_logo_colored.imageset/passwords_logo_colored_dark@3x.png Binary files differ
diff --git a/ios/chrome/browser/web/chrome_web_client.mm b/ios/chrome/browser/web/chrome_web_client.mm index dc63c95..cee61542 100644 --- a/ios/chrome/browser/web/chrome_web_client.mm +++ b/ios/chrome/browser/web/chrome_web_client.mm
@@ -404,7 +404,6 @@ web::UserAgentType ChromeWebClient::GetDefaultUserAgent( id<UITraitEnvironment> web_view, const GURL& url) { - DCHECK(web::features::UseWebClientDefaultUserAgent()); return web::UserAgentType::MOBILE; }
diff --git a/ios/chrome/browser/web/chrome_web_client_unittest.mm b/ios/chrome/browser/web/chrome_web_client_unittest.mm index 2191175..dc71264 100644 --- a/ios/chrome/browser/web/chrome_web_client_unittest.mm +++ b/ios/chrome/browser/web/chrome_web_client_unittest.mm
@@ -486,10 +486,6 @@ // Tests the default user agent for different views. TEST_F(ChromeWebClientTest, DefaultUserAgent) { - base::test::ScopedFeatureList scoped_feature_list; - scoped_feature_list.InitWithFeatures( - {web::features::kUseDefaultUserAgentInWebClient}, {}); - ChromeWebClient web_client; const GURL google_url = GURL("https://www.google.com/search?q=test"); const GURL non_google_url = GURL("http://wikipedia.org");
diff --git a/ios/chrome/browser/web/web_performance_metrics/resources/web_performance_metrics.js b/ios/chrome/browser/web/web_performance_metrics/resources/web_performance_metrics.js index 1d90f56..5b9a84c 100644 --- a/ios/chrome/browser/web/web_performance_metrics/resources/web_performance_metrics.js +++ b/ios/chrome/browser/web/web_performance_metrics/resources/web_performance_metrics.js
@@ -6,9 +6,17 @@ /** Beginning of anonymous object */ (function() { + const EVENT_TYPES = [ + 'mousedown', + 'keydown', + 'touchstart', + 'pointerdown' + ]; const FIRST_CONTENTFUL_PAINT = 'first-contentful-paint'; const WEB_PERFORMANCE_METRICS_HANDLER_NAME = 'WebPerformanceMetricsHandler'; + let loadedFromCache = false; + // Sends the First Contentful Paint time for each // frame in a website to the browser. Due to WebKit's // implementation of First Contentful Paint, this @@ -18,7 +26,7 @@ function processPaintEvents(paintEvents, observer) { for (const event of paintEvents.getEntriesByName(FIRST_CONTENTFUL_PAINT)){ // The performance.timing.navigationStart property has been deprecated. - // See https://crbug.com/1273083 + // TODO(crbug.com/1273083) let response = { 'metric' : 'FirstContentfulPaint', 'frameNavigationStartTime' : performance.timing.navigationStart, @@ -33,14 +41,98 @@ } } + // Sends the First Input Delay time for + // each frame in a website to the browser. + function processInputEvent(inputEvent) { + let currentTime = performance.now(); + let delta = currentTime - inputEvent.timeStamp; + let response = { + 'metric' : 'FirstInputDelay', + 'value' : delta, + 'cached' : loadedFromCache + } + + __gCrWeb.common.sendWebKitMessage( + WEB_PERFORMANCE_METRICS_HANDLER_NAME, + response); + + EVENT_TYPES.forEach((type) => { + removeEventListenerFromWindow(type, processInputEvent, { capture: true }); + }); + } + + // Because JavaScript files are not rerun when + // a web page is loaded from the back/forward + // cache, this function re-registers the + // event listeners to capture and forward + // the Web Performance Metrics back to the + // browser. + function processPageShowEvent(pageshow) { + if (pageshow.persisted) { + loadedFromCache = true; + registerInputEventListeners(); + } + } + + // Unregisters the passive event listeners + // used for collecting the First Input Delay + // upon the user navigating away from the + // webpage + function processPageHideEvent() { + EVENT_TYPES.forEach((type) => { + removeEventListenerFromWindow(type, processInputEvent, { capture: true }); + }); + loadedFromCache = false; + } + // Register PerformanceObserver to observe 'paint' events // Once the PerformanceObserver receives the - // 'first-contentful-paint' event, capture the time of the - // event and print it out. + // 'first-contentful-paint' event, it captures the time of the + // event and forwards the result to the browser. function registerPerformanceObserver(){ let observer = new PerformanceObserver(processPaintEvents); observer.observe({ entryTypes : ['paint'] }); } + // Registers a passive event listener for each predefined + // event type. Once the event listener receives an event, + // it calculates the first input delay and forwards the + // result ot the browser. + function registerInputEventListeners() { + EVENT_TYPES.forEach((type) => { + addEventListenerToWindow(type, + processInputEvent, + {capture: true, + passive: true}); + }); + } + + // Registers passive event listeners for the pageshow + // and pagehide events + function registerPageCacheListeners() { + addEventListenerToWindow('pageshow', + processPageShowEvent, + {capture: true, + passive: true}); + + addEventListenerToWindow('pagehide', + processPageHideEvent, + { capture: true, passive: true}); + } + + // Wrapper function for adding an event listener to the + // window. + function addEventListenerToWindow(type, callback, options) { + window.addEventListener(type, callback, options); + } + + // Wrapper function for removing an event listener from the + // window. + function removeEventListenerFromWindow(type, callback, options) { + window.removeEventListener(type, callback, options); + } + registerPerformanceObserver(); + registerInputEventListeners(); + registerPageCacheListeners(); }()); \ No newline at end of file
diff --git a/ios/chrome/browser/web/web_performance_metrics/web_performance_metrics_java_script_feature.h b/ios/chrome/browser/web/web_performance_metrics/web_performance_metrics_java_script_feature.h index 5530f944..4e2bda70 100644 --- a/ios/chrome/browser/web/web_performance_metrics/web_performance_metrics_java_script_feature.h +++ b/ios/chrome/browser/web/web_performance_metrics/web_performance_metrics_java_script_feature.h
@@ -31,6 +31,11 @@ double frameNavigationStartTime, double relativeFirstContentfulPaint, bool is_main_frame); + + // Logs the First Input Delay time relative to each frame in UMA. + void LogRelativeFirstInputDelay(double value, + bool is_main_frame, + bool loaded_from_cache); }; #endif // IOS_CHROME_BROWSER_WEB_WEB_PERFORMANCE_METRICS_WEB_PERFORMANCE_METRICS_JAVA_SCRIPT_FEATURE_H_
diff --git a/ios/chrome/browser/web/web_performance_metrics/web_performance_metrics_java_script_feature.mm b/ios/chrome/browser/web/web_performance_metrics/web_performance_metrics_java_script_feature.mm index fa9cb2a..c2387456 100644 --- a/ios/chrome/browser/web/web_performance_metrics/web_performance_metrics_java_script_feature.mm +++ b/ios/chrome/browser/web/web_performance_metrics/web_performance_metrics_java_script_feature.mm
@@ -4,6 +4,7 @@ #include "ios/chrome/browser/web/web_performance_metrics/web_performance_metrics_java_script_feature.h" +#include "base/ios/ios_util.h" #include "base/logging.h" #include "base/metrics/histogram_macros.h" #include "base/no_destructor.h" @@ -65,16 +66,27 @@ return; } - absl::optional<double> frame_navigation_start_time = - message.body()->FindDoubleKey("frameNavigationStartTime"); - if (!frame_navigation_start_time) { - return; - } + if (*metric == "FirstContentfulPaint") { + absl::optional<double> frame_navigation_start_time = + message.body()->FindDoubleKey("frameNavigationStartTime"); + if (!frame_navigation_start_time) { + return; + } - LogRelativeFirstContentfulPaint(value.value(), message.is_main_frame()); - LogAggregateFirstContentfulPaint(web_state, - frame_navigation_start_time.value(), - value.value(), message.is_main_frame()); + LogRelativeFirstContentfulPaint(value.value(), message.is_main_frame()); + LogAggregateFirstContentfulPaint(web_state, + frame_navigation_start_time.value(), + value.value(), message.is_main_frame()); + } else if (*metric == "FirstInputDelay") { + absl::optional<bool> loaded_from_cache = + message.body()->FindBoolKey("cached"); + if (!loaded_from_cache.has_value()) { + return; + } + + LogRelativeFirstInputDelay(value.value(), message.is_main_frame(), + loaded_from_cache.value()); + } } void WebPerformanceMetricsJavaScriptFeature::LogRelativeFirstContentfulPaint( @@ -123,3 +135,34 @@ frame_navigation_start_time, relative_first_contentful_paint)); } } + +void WebPerformanceMetricsJavaScriptFeature::LogRelativeFirstInputDelay( + double value, + bool is_main_frame, + bool loaded_from_cache) { + base::TimeDelta delta = base::Milliseconds(value); + + // WebKit does not reliably support pageshow events + // on version iOS 14 and below. + // TODO(crbug.com/1276537) + const bool page_show_reliably_supported = + base::ios::IsRunningOnIOS15OrLater(); + + if (is_main_frame) { + if (!loaded_from_cache) { + UMA_HISTOGRAM_TIMES("IOS.Frame.FirstInputDelay.MainFrame", delta); + } else if (loaded_from_cache && page_show_reliably_supported) { + UMA_HISTOGRAM_TIMES( + "IOS.Frame.FirstInputDelay.MainFrame.AfterBackForwardCacheRestore", + delta); + } + } else { + if (!loaded_from_cache) { + UMA_HISTOGRAM_TIMES("IOS.Frame.FirstInputDelay.SubFrame", delta); + } else if (loaded_from_cache && page_show_reliably_supported) { + UMA_HISTOGRAM_TIMES( + "IOS.Frame.FirstInputDelay.SubFrame.AfterBackForwardCacheRestore", + delta); + } + } +} \ No newline at end of file
diff --git a/ios/chrome/browser/web_state_list/BUILD.gn b/ios/chrome/browser/web_state_list/BUILD.gn index 88611efb..8e6c961a 100644 --- a/ios/chrome/browser/web_state_list/BUILD.gn +++ b/ios/chrome/browser/web_state_list/BUILD.gn
@@ -22,6 +22,8 @@ "all_web_state_observation_forwarder.mm", "web_state_dependency_installation_observer.h", "web_state_dependency_installation_observer.mm", + "web_state_dependency_installer_bridge.h", + "web_state_dependency_installer_bridge.mm", "web_state_list.h", "web_state_list.mm", "web_state_list_delegate.h",
diff --git a/ios/chrome/browser/web_state_list/web_state_dependency_installation_observer.h b/ios/chrome/browser/web_state_list/web_state_dependency_installation_observer.h index 49dafbea..df419c31 100644 --- a/ios/chrome/browser/web_state_list/web_state_dependency_installation_observer.h +++ b/ios/chrome/browser/web_state_list/web_state_dependency_installation_observer.h
@@ -5,22 +5,10 @@ #ifndef IOS_CHROME_BROWSER_WEB_STATE_LIST_WEB_STATE_DEPENDENCY_INSTALLATION_OBSERVER_H_ #define IOS_CHROME_BROWSER_WEB_STATE_LIST_WEB_STATE_DEPENDENCY_INSTALLATION_OBSERVER_H_ -#import <Foundation/Foundation.h> -#import <memory> - #import "base/scoped_observation.h" #import "ios/chrome/browser/web_state_list/web_state_list.h" #import "ios/chrome/browser/web_state_list/web_state_list_observer.h" -// Objective-C version of DependencyInstaller; see docs for that class. -@protocol DependencyInstalling <NSObject> -@optional - -- (void)installDependencyForWebState:(web::WebState*)web_state; -- (void)uninstallDependencyForWebState:(web::WebState*)web_state; - -@end - // Interface for classes wishing to install and/or uninstall dependencies // (delegates, etc) for each WebState using // WebStateDependencyInstallationObserver (below). @@ -35,25 +23,6 @@ virtual ~DependencyInstaller() {} }; -// Bridge allowing Objective-C classes to act as DependencyInstaller for a -// WebStateDependencyInstallationObserver. -class DependencyInstallerBridge : public DependencyInstaller { - public: - DependencyInstallerBridge(id<DependencyInstalling> installing); - ~DependencyInstallerBridge() override {} - void InstallDependency(web::WebState* web_state) override; - void UninstallDependency(web::WebState* web_state) override; - - DependencyInstallerBridge(const DependencyInstallerBridge&) = delete; - DependencyInstallerBridge& operator=(const DependencyInstallerBridge&) = - delete; - - private: - // The Objective-C class which installs/uninstalls dependencies in response to - // forwarded messages. - id<DependencyInstalling> installing_; -}; - // Classes wishing to install/uninstall dependencies (such as delegates) for // each WebState can create an instance and pass a DependencyInstaller // configured to do the installing/uninstalling work. This class acts as a
diff --git a/ios/chrome/browser/web_state_list/web_state_dependency_installation_observer.mm b/ios/chrome/browser/web_state_list/web_state_dependency_installation_observer.mm index ad537a1..4f30012d 100644 --- a/ios/chrome/browser/web_state_list/web_state_dependency_installation_observer.mm +++ b/ios/chrome/browser/web_state_list/web_state_dependency_installation_observer.mm
@@ -8,23 +8,6 @@ #import "ios/chrome/browser/web_state_list/web_state_dependency_installation_observer.h" -DependencyInstallerBridge::DependencyInstallerBridge( - id<DependencyInstalling> installing) - : installing_(installing) {} - -void DependencyInstallerBridge::InstallDependency(web::WebState* web_state) { - if ([installing_ - respondsToSelector:@selector(installDependencyForWebState:)]) { - [installing_ installDependencyForWebState:web_state]; - } -} -void DependencyInstallerBridge::UninstallDependency(web::WebState* web_state) { - if ([installing_ - respondsToSelector:@selector(uninstallDependencyForWebState:)]) { - [installing_ uninstallDependencyForWebState:web_state]; - } -} - WebStateDependencyInstallationObserver::WebStateDependencyInstallationObserver( WebStateList* web_state_list, DependencyInstaller* dependency_installer)
diff --git a/ios/chrome/browser/web_state_list/web_state_dependency_installation_observer_unittest.mm b/ios/chrome/browser/web_state_list/web_state_dependency_installation_observer_unittest.mm index 3e1d94f..bae2e9a 100644 --- a/ios/chrome/browser/web_state_list/web_state_dependency_installation_observer_unittest.mm +++ b/ios/chrome/browser/web_state_list/web_state_dependency_installation_observer_unittest.mm
@@ -57,6 +57,9 @@ FakeDependencyInstaller installer_; }; +// Verifies that the WebStateDependencyInstallationObserver triggers the +// appropriate install/uninstall methods when a WebState is inserted, replaced, +// or removed. TEST_F(WebStateDependencyInstallationObserverTest, InsertReplaceAndRemoveWebState) { WebStateDependencyInstallationObserver observer(&web_state_list_, @@ -78,6 +81,9 @@ EXPECT_TRUE(installer_.WasInstalled(web_state_2_raw)); } +// Verifies that the WebStateDependencyInstallationObserver triggers the +// appropriate install method for any WebStates that were already in the +// WebStateList prior to its construction. TEST_F(WebStateDependencyInstallationObserverTest, RespectsPreexistingWebState) { auto web_state = std::make_unique<web::FakeWebState>();
diff --git a/ios/chrome/browser/web_state_list/web_state_dependency_installer_bridge.h b/ios/chrome/browser/web_state_list/web_state_dependency_installer_bridge.h new file mode 100644 index 0000000..0dafbdb --- /dev/null +++ b/ios/chrome/browser/web_state_list/web_state_dependency_installer_bridge.h
@@ -0,0 +1,51 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef IOS_CHROME_BROWSER_WEB_STATE_LIST_WEB_STATE_DEPENDENCY_INSTALLER_BRIDGE_H_ +#define IOS_CHROME_BROWSER_WEB_STATE_LIST_WEB_STATE_DEPENDENCY_INSTALLER_BRIDGE_H_ + +#import <Foundation/Foundation.h> + +#import "ios/chrome/browser/web_state_list/web_state_dependency_installation_observer.h" +#import "ios/chrome/browser/web_state_list/web_state_list.h" + +// Protocol for classes wishing to install and/or uninstall dependencies +// (delegates, etc) for each WebState using WebStateDependencyInstallerBridge. +// This is the Objective-C analogue to the C++ DependencyInstaller class. +@protocol DependencyInstalling <NSObject> +@optional + +- (void)installDependencyForWebState:(web::WebState*)webState; +- (void)uninstallDependencyForWebState:(web::WebState*)webState; + +@end + +// Bridge allowing Objective-C classes to install dependencies by conforming to +// DependencyInstalling protocol. +class WebStateDependencyInstallerBridge : public DependencyInstaller { + public: + WebStateDependencyInstallerBridge(id<DependencyInstalling> installing, + WebStateList* web_state_list); + ~WebStateDependencyInstallerBridge() override {} + + // DependencyInstaller: + void InstallDependency(web::WebState* web_state) override; + void UninstallDependency(web::WebState* web_state) override; + + WebStateDependencyInstallerBridge(const WebStateDependencyInstallerBridge&) = + delete; + WebStateDependencyInstallerBridge& operator=( + const WebStateDependencyInstallerBridge&) = delete; + + private: + // The Objective-C class which installs/uninstalls dependencies in response to + // forwarded messages. + id<DependencyInstalling> installing_; + + // The observer which informs this bridge that a dependency needs to be + // installed/uninstalled; those calls are then forwarded to |installing_|. + WebStateDependencyInstallationObserver observer_; +}; + +#endif // IOS_CHROME_BROWSER_WEB_STATE_LIST_WEB_STATE_DEPENDENCY_INSTALLER_BRIDGE_H_
diff --git a/ios/chrome/browser/web_state_list/web_state_dependency_installer_bridge.mm b/ios/chrome/browser/web_state_list/web_state_dependency_installer_bridge.mm new file mode 100644 index 0000000..65000ce --- /dev/null +++ b/ios/chrome/browser/web_state_list/web_state_dependency_installer_bridge.mm
@@ -0,0 +1,29 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#import "ios/chrome/browser/web_state_list/web_state_dependency_installer_bridge.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +WebStateDependencyInstallerBridge::WebStateDependencyInstallerBridge( + id<DependencyInstalling> installing, + WebStateList* web_state_list) + : installing_(installing), observer_(web_state_list, this) {} + +void WebStateDependencyInstallerBridge::InstallDependency( + web::WebState* web_state) { + if ([installing_ + respondsToSelector:@selector(installDependencyForWebState:)]) { + [installing_ installDependencyForWebState:web_state]; + } +} +void WebStateDependencyInstallerBridge::UninstallDependency( + web::WebState* web_state) { + if ([installing_ + respondsToSelector:@selector(uninstallDependencyForWebState:)]) { + [installing_ uninstallDependencyForWebState:web_state]; + } +}
diff --git a/ios/chrome/test/earl_grey/chrome_earl_grey_app_interface.mm b/ios/chrome/test/earl_grey/chrome_earl_grey_app_interface.mm index a5606fee..3da6a0f1 100644 --- a/ios/chrome/test/earl_grey/chrome_earl_grey_app_interface.mm +++ b/ios/chrome/test/earl_grey/chrome_earl_grey_app_interface.mm
@@ -990,9 +990,6 @@ } + (BOOL)isMobileModeByDefault { - if (!web::features::UseWebClientDefaultUserAgent()) - return YES; - web::UserAgentType webClientUserAgent = web::GetWebClient()->GetDefaultUserAgent( chrome_test_util::GetCurrentWebState()->GetView(), GURL());
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 f235144..e8975ad 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 @@ -136f13f384434c8957fc099be2a420f37e7ab538 \ No newline at end of file +a928b3352c3c2d868644cd1c30da91391726abca \ 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 2d429414..3109a4c0 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 @@ -8f02a2d8e5ff497fd31714369c7845ae8995ef96 \ No newline at end of file +51b9b86c9c03d353ceb693ae69dee0b8e4011fdf \ 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 a037aff..ea0dfa6 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 @@ -fb63723615197222581c8767c40c7d099ac70255 \ No newline at end of file +c413587e8d7f78b1f55a07494053c52c411d2a9e \ 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 c23586a..7fc0d70 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 @@ -b6a2fb017a8c82a2448763acbc3d80f8b54df909 \ No newline at end of file +0dbb601047e225ce401f375eed4b554f20d54ea4 \ 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 2ddf785..002b2e3 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 @@ -6c4858ecbee97aa01ec096daa5cd75721a0adaf6 \ No newline at end of file +49d1b7caadcb4276e3711c35bde90b40b1ba005c \ 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 2dee286..6eed437c 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 @@ -2a0481ef270b787f8de98e6aa1f38f6e1c91170c \ No newline at end of file +6665cafa418309af5f6d23fa0351fa455bdb239c \ 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 0ef9969e..337002b 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 @@ -3181500bc96a5b46f63af2440534f357d3b9bdfd \ No newline at end of file +53560dfa4ef268a030b7b8180df0b0d0b1dd553d \ 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 3ea0d3d..f578cb32 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 @@ -30b449970d1db4cbf4f233e16f13cf2d1ca473dc \ No newline at end of file +5f79ab2d377447d49eeca88fb536d0a419eedafd \ 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 6c29ec1..3eeba06 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 @@ -03aed931abc81fd72e86aac0257728e184cbd4e5 \ No newline at end of file +9aa7bdf6ce7fe643646e62addcf6defd2d92353a \ 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 56038f0c..e31382ef 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 @@ -2095ea9473c7ea5537c8c23f1f172fbe89789171 \ No newline at end of file +1a1951dc381badf35c21a7b667795a2c6f731b69 \ No newline at end of file
diff --git a/ios/web/browser_state.mm b/ios/web/browser_state.mm index 4119ff7a..62a487d 100644 --- a/ios/web/browser_state.mm +++ b/ios/web/browser_state.mm
@@ -114,6 +114,7 @@ network::mojom::URLLoaderFactoryParams::New(); url_loader_factory_params->process_id = network::mojom::kBrowserProcessId; url_loader_factory_params->is_corb_enabled = false; + url_loader_factory_params->is_trusted = true; network_context_->CreateURLLoaderFactory( url_loader_factory_.BindNewPipeAndPassReceiver(), std::move(url_loader_factory_params));
diff --git a/ios/web/common/features.h b/ios/web/common/features.h index bc551f5..5ab444f 100644 --- a/ios/web/common/features.h +++ b/ios/web/common/features.h
@@ -33,12 +33,6 @@ // Feature flag enabling persistent downloads. extern const base::Feature kEnablePersistentDownloads; -// When enabled, for each navigation, the default user agent is chosen by the -// WebClient GetDefaultUserAgent() method. If it is disabled, the mobile version -// is requested by default. -// Use UseWebClientDefaultUserAgent() instead of checking this variable. -extern const base::Feature kUseDefaultUserAgentInWebClient; - // When enabled, preserves properties of the UIScrollView using CRWPropertyStore // when the scroll view is recreated. When disabled, only preserve a small set // of properties using hard coded logic. @@ -81,11 +75,6 @@ // See //docs/ios/unrealized_web_state.md for more information. extern const base::Feature kEnableUnrealizedWebStates; -// When true, for each navigation, the default user agent is chosen by the -// WebClient GetDefaultUserAgent() method. If it is false, the mobile version -// is requested by default. -bool UseWebClientDefaultUserAgent(); - // When true, the native context menu for the web content are used. bool UseWebViewNativeContextMenuWeb();
diff --git a/ios/web/common/features.mm b/ios/web/common/features.mm index da01a68..f4edc81b 100644 --- a/ios/web/common/features.mm +++ b/ios/web/common/features.mm
@@ -31,9 +31,6 @@ const base::Feature kEnablePersistentDownloads{ "EnablePersistentDownloads", base::FEATURE_DISABLED_BY_DEFAULT}; -const base::Feature kUseDefaultUserAgentInWebClient{ - "UseDefaultUserAgentInWebClient", base::FEATURE_DISABLED_BY_DEFAULT}; - const base::Feature kPreserveScrollViewProperties{ "PreserveScrollViewProperties", base::FEATURE_ENABLED_BY_DEFAULT}; @@ -68,10 +65,6 @@ const base::Feature kEnableUnrealizedWebStates{ "EnableUnrealizedWebStates", base::FEATURE_DISABLED_BY_DEFAULT}; -bool UseWebClientDefaultUserAgent() { - return base::FeatureList::IsEnabled(kUseDefaultUserAgentInWebClient); -} - bool UseWebViewNativeContextMenuWeb() { return base::FeatureList::IsEnabled(kDefaultWebViewContextMenu); }
diff --git a/ios/web/common/user_agent.h b/ios/web/common/user_agent.h index fe205e7..5be17b8 100644 --- a/ios/web/common/user_agent.h +++ b/ios/web/common/user_agent.h
@@ -14,13 +14,10 @@ // Used for pages that are generated for app-specific URLs. NONE = 0, - // The default user agent type. The user agent used will depend on the size of - // the application window. + // The default user agent type. The default user agent will be determined by + // the WebClient. AUTOMATIC, - // TODO(crbug.com/1025227): Update comments. - // The default user agent type if kUseDefaultUserAgentInWebClient isn't - // enabled. // Used to specify a mobile browser user agent. MOBILE,
diff --git a/ios/web/common/user_agent.mm b/ios/web/common/user_agent.mm index 4bbc9f3..84b9d71 100644 --- a/ios/web/common/user_agent.mm +++ b/ios/web/common/user_agent.mm
@@ -54,7 +54,6 @@ std::string GetUserAgentTypeDescription(UserAgentType type) { switch (type) { case UserAgentType::AUTOMATIC: - DCHECK(features::UseWebClientDefaultUserAgent()); return std::string(kUserAgentTypeAutomaticDescription); case UserAgentType::NONE: return std::string(kUserAgentTypeNoneDescription);
diff --git a/ios/web/common/user_agent_unittest.mm b/ios/web/common/user_agent_unittest.mm index 80123d2..5c9e2a1 100644 --- a/ios/web/common/user_agent_unittest.mm +++ b/ios/web/common/user_agent_unittest.mm
@@ -37,9 +37,6 @@ // Tests conversions between UserAgentType values and their descriptions TEST_F(UserAgentTest, UserAgentTypeDescription) { - base::test::ScopedFeatureList feature; - feature.InitAndEnableFeature(features::kUseDefaultUserAgentInWebClient); - const std::string kMobileDescription("MOBILE"); const std::string kDesktopDescription("DESKTOP"); const std::string kAutomaticDescription("AUTOMATIC");
diff --git a/ios/web/navigation/crw_session_storage_unittest.mm b/ios/web/navigation/crw_session_storage_unittest.mm index 0ffa58a1..b97ebe2 100644 --- a/ios/web/navigation/crw_session_storage_unittest.mm +++ b/ios/web/navigation/crw_session_storage_unittest.mm
@@ -111,8 +111,6 @@ // Tests that unarchiving CRWSessionStorage data results in an equivalent // storage when the user agent is automatic. TEST_F(CRWNSessionStorageTest, EncodeDecodeAutomatic) { - base::test::ScopedFeatureList feature; - feature.InitAndEnableFeature(web::features::kUseDefaultUserAgentInWebClient); session_storage_.userAgentType = web::UserAgentType::AUTOMATIC; NSKeyedArchiver* archiver = [[NSKeyedArchiver alloc] initRequiringSecureCoding:NO];
diff --git a/ios/web/navigation/crw_wk_navigation_handler_inttest.mm b/ios/web/navigation/crw_wk_navigation_handler_inttest.mm index 42e518e..ede602d 100644 --- a/ios/web/navigation/crw_wk_navigation_handler_inttest.mm +++ b/ios/web/navigation/crw_wk_navigation_handler_inttest.mm
@@ -27,12 +27,6 @@ net::test_server::RegisterDefaultHandlers(&server_); } - void SetUp() override { - scoped_feature_list_.InitWithFeatures( - {features::kUseDefaultUserAgentInWebClient}, {}); - WebIntTest::SetUp(); - } - FakeWebClient* GetWebClient() override { return static_cast<FakeWebClient*>(WebIntTest::GetWebClient()); }
diff --git a/ios/web/navigation/session_storage_builder.mm b/ios/web/navigation/session_storage_builder.mm index e999795..949cf92d 100644 --- a/ios/web/navigation/session_storage_builder.mm +++ b/ios/web/navigation/session_storage_builder.mm
@@ -128,10 +128,6 @@ SerializableUserDataManager::FromWebState(&web_state) ->AddSerializableUserData(session_storage.userData); UserAgentType user_agent_type = session_storage.userAgentType; - if (user_agent_type == UserAgentType::AUTOMATIC && - !features::UseWebClientDefaultUserAgent()) { - user_agent_type = UserAgentType::MOBILE; - } web_state.SetUserAgent(user_agent_type); }
diff --git a/ios/web/session/crw_session_storage.mm b/ios/web/session/crw_session_storage.mm index fa772777..fd17768 100644 --- a/ios/web/session/crw_session_storage.mm +++ b/ios/web/session/crw_session_storage.mm
@@ -92,11 +92,7 @@ web::GetUserAgentTypeWithDescription(userAgentDescription); } else { // Prior to M85, the UserAgent wasn't stored. - if (web::features::UseWebClientDefaultUserAgent()) { - _userAgentType = web::UserAgentType::AUTOMATIC; - } else { - _userAgentType = web::UserAgentType::MOBILE; - } + _userAgentType = web::UserAgentType::AUTOMATIC; } } return self; @@ -116,10 +112,6 @@ if (_userData) _userData->Encode(coder); web::UserAgentType userAgentType = _userAgentType; - if (userAgentType == web::UserAgentType::AUTOMATIC && - !web::features::UseWebClientDefaultUserAgent()) { - userAgentType = web::UserAgentType::MOBILE; - } web::nscoder_util::EncodeString( coder, kUserAgentKey, web::GetUserAgentTypeDescription(userAgentType)); }
diff --git a/ios/web/web_state/ui/crw_web_controller.mm b/ios/web/web_state/ui/crw_web_controller.mm index 5ef9f7a..fb0b5b9 100644 --- a/ios/web/web_state/ui/crw_web_controller.mm +++ b/ios/web/web_state/ui/crw_web_controller.mm
@@ -1537,10 +1537,7 @@ - (WKWebView*)webViewWithConfiguration:(WKWebViewConfiguration*)config { // Do not attach the context menu controller immediately as the JavaScript // delegate must be specified. - web::UserAgentType defaultUserAgent = - web::features::UseWebClientDefaultUserAgent() - ? web::UserAgentType::AUTOMATIC - : web::UserAgentType::MOBILE; + web::UserAgentType defaultUserAgent = web::UserAgentType::AUTOMATIC; web::NavigationItem* item = self.currentNavItem; web::UserAgentType userAgentType = item ? item->GetUserAgentType() : defaultUserAgent;
diff --git a/ios/web/web_state/ui/crw_web_controller_unittest.mm b/ios/web/web_state/ui/crw_web_controller_unittest.mm index afbb24f1..9be980a 100644 --- a/ios/web/web_state/ui/crw_web_controller_unittest.mm +++ b/ios/web/web_state/ui/crw_web_controller_unittest.mm
@@ -273,10 +273,6 @@ // Tests that a web view is created after calling -[ensureWebViewCreated] and // check its user agent. TEST_F(CRWWebControllerTest, WebViewCreatedAfterEnsureWebViewCreated) { - base::test::ScopedFeatureList scoped_feature_list; - scoped_feature_list.InitAndEnableFeature( - features::kUseDefaultUserAgentInWebClient); - FakeWebClient* web_client = static_cast<FakeWebClient*>(GetWebClient()); [web_controller() removeWebView];
diff --git a/ios/web/web_state/web_state_impl_realized_web_state.mm b/ios/web/web_state/web_state_impl_realized_web_state.mm index be14dffc..5a8335f 100644 --- a/ios/web/web_state/web_state_impl_realized_web_state.mm +++ b/ios/web/web_state/web_state_impl_realized_web_state.mm
@@ -54,9 +54,7 @@ WebStateImpl::RealizedWebState::RealizedWebState(WebStateImpl* owner) : owner_(owner), interface_binder_(owner), - user_agent_type_(features::UseWebClientDefaultUserAgent() - ? UserAgentType::AUTOMATIC - : UserAgentType::MOBILE) { + user_agent_type_(UserAgentType::AUTOMATIC) { DCHECK(owner_); }
diff --git a/ipc/ipc_mojo_bootstrap.cc b/ipc/ipc_mojo_bootstrap.cc index 568f2c0c..a017111 100644 --- a/ipc/ipc_mojo_bootstrap.cc +++ b/ipc/ipc_mojo_bootstrap.cc
@@ -980,6 +980,11 @@ if (!client) return; + if (!endpoint->task_runner()->RunsTasksInCurrentSequence() && + !proxy_task_runner_->RunsTasksInCurrentSequence()) { + return; + } + TRACE_EVENT( TRACE_CATEGORY_OR_DISABLED_BY_DEFAULT_MOJOM("mojom"), // Using client->interface_name() is safe here because this is a static @@ -993,8 +998,6 @@ perfetto::Flow::Global(message.GetTraceId())(ctx); }); - DCHECK(endpoint->task_runner()->RunsTasksInCurrentSequence() || - proxy_task_runner_->RunsTasksInCurrentSequence()); // Sync messages should never make their way to this method. DCHECK(!message.has_flag(mojo::Message::kFlagIsSync)); @@ -1024,11 +1027,14 @@ if (!client) return; + if (!endpoint->task_runner()->RunsTasksInCurrentSequence() && + !proxy_task_runner_->RunsTasksInCurrentSequence()) { + return; + } + // Using client->interface_name() is safe here because this is a static // string defined for each mojo interface. TRACE_EVENT0("mojom", client->interface_name()); - DCHECK(endpoint->task_runner()->RunsTasksInCurrentSequence() || - proxy_task_runner_->RunsTasksInCurrentSequence()); MessageWrapper message_wrapper = endpoint->PopSyncMessage(message_id); // The message must have already been dequeued by the endpoint waking up
diff --git a/media/OWNERS b/media/OWNERS index 262c8c22..1db829b 100644 --- a/media/OWNERS +++ b/media/OWNERS
@@ -10,6 +10,7 @@ set noparent cassew@google.com +cassew@chromium.org chcunningham@chromium.org dalecurtis@chromium.org eugene@chromium.org
diff --git a/media/base/BUILD.gn b/media/base/BUILD.gn index 280ba92e..86557c5a 100644 --- a/media/base/BUILD.gn +++ b/media/base/BUILD.gn
@@ -293,7 +293,6 @@ "subsample_entry.h", "supported_types.cc", "supported_types.h", - "supported_types.h", "supported_video_decoder_config.cc", "supported_video_decoder_config.h", "svc_scalability_mode.cc",
diff --git a/media/base/video_frame_metadata.h b/media/base/video_frame_metadata.h index d4723ee..ebdb44d 100644 --- a/media/base/video_frame_metadata.h +++ b/media/base/video_frame_metadata.h
@@ -119,8 +119,8 @@ // instead. This lets us figure out when SurfaceViews are appropriate. bool texture_owner = false; - // Android only: if set, then this frame's resource would like to be - // notified about its promotability to an overlay. + // Android & Windows only: if set, then this frame's resource would like to + // be notified about its promotability to an overlay. bool wants_promotion_hint = false; // Windows only: set when frame is backed by a dcomp surface handle.
diff --git a/media/mojo/clients/win/media_foundation_renderer_client.cc b/media/mojo/clients/win/media_foundation_renderer_client.cc index 3bf9746..85cc9c9 100644 --- a/media/mojo/clients/win/media_foundation_renderer_client.cc +++ b/media/mojo/clients/win/media_foundation_renderer_client.cc
@@ -327,9 +327,14 @@ DCHECK(media_task_runner_->BelongsToCurrentThread()); DCHECK(has_video_); - video_frame->metadata().protected_video = true; video_frame->metadata().allow_overlay = true; + if (cdm_context_) { + video_frame->metadata().protected_video = true; + } else { + video_frame->metadata().wants_promotion_hint = true; + } + dcomp_video_frame_ = video_frame; sink_->PaintSingleFrame(dcomp_video_frame_, true); }
diff --git a/media/renderers/video_resource_updater.cc b/media/renderers/video_resource_updater.cc index ef51e41..ef2209a2 100644 --- a/media/renderers/video_resource_updater.cc +++ b/media/renderers/video_resource_updater.cc
@@ -61,6 +61,19 @@ // Generates process-unique IDs to use for tracing video resources. base::AtomicSequenceNumber g_next_video_resource_updater_id; +gfx::ProtectedVideoType ProtectedVideoTypeFromMetadata( + const VideoFrameMetadata& metadata) { + gfx::ProtectedVideoType video_type = gfx::ProtectedVideoType::kClear; + if (metadata.protected_video) { + if (metadata.hw_protected) { + video_type = gfx::ProtectedVideoType::kHardwareProtected; + } else { + video_type = gfx::ProtectedVideoType::kSoftwareProtected; + } + } + return video_type; +} + VideoFrameResourceType ExternalResourceTypeForHardwarePlanes( VideoPixelFormat format, GLuint target, @@ -636,15 +649,8 @@ frame_resource_multiplier_, frame_bits_per_channel_); if (frame->hdr_metadata().has_value()) yuv_video_quad->hdr_metadata = frame->hdr_metadata().value(); - if (frame->metadata().protected_video) { - if (frame->metadata().hw_protected) { - yuv_video_quad->protected_video_type = - gfx::ProtectedVideoType::kHardwareProtected; - } else { - yuv_video_quad->protected_video_type = - gfx::ProtectedVideoType::kSoftwareProtected; - } - } + yuv_video_quad->protected_video_type = + ProtectedVideoTypeFromMetadata(frame->metadata()); for (viz::ResourceId resource_id : yuv_video_quad->resources) { resource_provider_->ValidateResource(resource_id); @@ -664,14 +670,7 @@ bool flipped = !frame->metadata().texture_origin_is_top_left; bool nearest_neighbor = false; gfx::ProtectedVideoType protected_video_type = - gfx::ProtectedVideoType::kClear; - if (frame->metadata().protected_video) { - if (frame->metadata().hw_protected) - protected_video_type = gfx::ProtectedVideoType::kHardwareProtected; - else - protected_video_type = gfx::ProtectedVideoType::kSoftwareProtected; - } - + ProtectedVideoTypeFromMetadata(frame->metadata()); auto* texture_quad = render_pass->CreateAndAppendDrawQuad<viz::TextureDrawQuad>(); texture_quad->SetNew(shared_quad_state, quad_rect, visible_quad_rect, @@ -928,9 +927,13 @@ #if defined(OS_ANDROID) transfer_resource.is_backed_by_surface_texture = video_frame->metadata().texture_owner; +#endif + +#if defined(OS_ANDROID) || defined(OS_WIN) transfer_resource.wants_promotion_hint = video_frame->metadata().wants_promotion_hint; #endif + external_resources.resources.push_back(std::move(transfer_resource)); if (copy_mode == VideoFrameMetadata::CopyMode::kCopyMailboxesOnly) { // Adding a ref on |video_frame| to make sure lifetime of |video frame|
diff --git a/mojo/core/node_controller.cc b/mojo/core/node_controller.cc index 93d694c..7579258 100644 --- a/mojo/core/node_controller.cc +++ b/mojo/core/node_controller.cc
@@ -177,7 +177,7 @@ node_connection_params = ConnectionParams(node_channel.TakeLocalEndpoint()); bool channel_ok = broker_host->SendChannel( node_channel.TakeRemoteEndpoint().TakePlatformHandle()); - CHECK(channel_ok); + DCHECK(channel_ok); return node_connection_params; }
diff --git a/net/base/escape.h b/net/base/escape.h index 5d1e7d8..114a0e3 100644 --- a/net/base/escape.h +++ b/net/base/escape.h
@@ -13,6 +13,7 @@ #include "base/strings/escape.h" #include "base/strings/string_piece.h" #include "base/strings/utf_offset_string_conversions.h" +#include "build/build_config.h" #include "net/base/net_export.h" namespace net {
diff --git a/net/base/network_change_notifier_mac.mm b/net/base/network_change_notifier_mac.mm index 2cc5b56..97f1793 100644 --- a/net/base/network_change_notifier_mac.mm +++ b/net/base/network_change_notifier_mac.mm
@@ -13,6 +13,7 @@ #include "base/task/post_task.h" #include "base/task/sequenced_task_runner.h" #include "base/task/task_traits.h" +#include "build/build_config.h" #include "net/dns/dns_config_service.h" #if defined(OS_IOS)
diff --git a/net/base/platform_mime_util_mac.mm b/net/base/platform_mime_util_mac.mm index 5188bba..17f597e 100644 --- a/net/base/platform_mime_util_mac.mm +++ b/net/base/platform_mime_util_mac.mm
@@ -11,6 +11,7 @@ #include "base/mac/foundation_util.h" #include "base/mac/scoped_cftyperef.h" #include "base/strings/sys_string_conversions.h" +#include "build/build_config.h" #if defined(OS_IOS) #include <MobileCoreServices/MobileCoreServices.h>
diff --git a/net/cert/x509_util_ios_and_mac.cc b/net/cert/x509_util_ios_and_mac.cc index 4d503de1..d318230 100644 --- a/net/cert/x509_util_ios_and_mac.cc +++ b/net/cert/x509_util_ios_and_mac.cc
@@ -5,6 +5,7 @@ #include "net/cert/x509_util_ios_and_mac.h" #include "base/logging.h" +#include "build/build_config.h" #include "net/cert/x509_certificate.h" #if defined(OS_IOS) #include "net/cert/x509_util_ios.h"
diff --git a/net/cert/x509_util_ios_and_mac_unittest.cc b/net/cert/x509_util_ios_and_mac_unittest.cc index 6032dfc7..3a70873 100644 --- a/net/cert/x509_util_ios_and_mac_unittest.cc +++ b/net/cert/x509_util_ios_and_mac_unittest.cc
@@ -4,6 +4,7 @@ #include "net/cert/x509_util_ios_and_mac.h" +#include "build/build_config.h" #include "net/cert/x509_certificate.h" #include "net/cert/x509_util.h" #include "net/test/cert_test_util.h"
diff --git a/net/dns/dns_hosts_unittest.cc b/net/dns/dns_hosts_unittest.cc index e559ddc7..c9b7b8c 100644 --- a/net/dns/dns_hosts_unittest.cc +++ b/net/dns/dns_hosts_unittest.cc
@@ -5,6 +5,7 @@ #include "net/dns/dns_hosts.h" #include "base/cxx17_backports.h" +#include "build/build_config.h" #include "net/base/ip_address.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/net/http/http_auth_gssapi_posix.h b/net/http/http_auth_gssapi_posix.h index a83b0e5..b50cde5 100644 --- a/net/http/http_auth_gssapi_posix.h +++ b/net/http/http_auth_gssapi_posix.h
@@ -11,6 +11,7 @@ #include "base/native_library.h" #include "base/strings/string_piece_forward.h" #include "base/values.h" +#include "build/build_config.h" #include "net/base/completion_once_callback.h" #include "net/base/net_export.h" #include "net/http/http_auth.h"
diff --git a/net/proxy_resolution/proxy_resolver_mac.cc b/net/proxy_resolution/proxy_resolver_mac.cc index 76c55fc..d6e3aab 100644 --- a/net/proxy_resolution/proxy_resolver_mac.cc +++ b/net/proxy_resolution/proxy_resolver_mac.cc
@@ -16,6 +16,7 @@ #include "base/strings/sys_string_conversions.h" #include "base/synchronization/lock.h" #include "base/threading/thread_checker.h" +#include "build/build_config.h" #include "net/base/net_errors.h" #include "net/base/proxy_server.h" #include "net/base/proxy_string_util.h"
diff --git a/net/ssl/client_cert_identity.h b/net/ssl/client_cert_identity.h index 29840686..352f6b80 100644 --- a/net/ssl/client_cert_identity.h +++ b/net/ssl/client_cert_identity.h
@@ -6,6 +6,7 @@ #define NET_SSL_CLIENT_CERT_IDENTITY_H_ #include "base/callback.h" +#include "build/build_config.h" #include "net/base/net_export.h" #include "net/cert/x509_certificate.h"
diff --git a/net/ssl/client_cert_identity_test_util.h b/net/ssl/client_cert_identity_test_util.h index a0f31032..48dd4e6 100644 --- a/net/ssl/client_cert_identity_test_util.h +++ b/net/ssl/client_cert_identity_test_util.h
@@ -5,6 +5,7 @@ #ifndef NET_SSL_CLIENT_CERT_IDENTITY_TEST_UTIL_H_ #define NET_SSL_CLIENT_CERT_IDENTITY_TEST_UTIL_H_ +#include "build/build_config.h" #include "net/ssl/client_cert_identity.h" namespace base {
diff --git a/remoting/base/BUILD.gn b/remoting/base/BUILD.gn index 7e461c8..2295d96 100644 --- a/remoting/base/BUILD.gn +++ b/remoting/base/BUILD.gn
@@ -3,6 +3,7 @@ # found in the LICENSE file. import("//build/config/chromeos/ui_mode.gni") +import("//remoting/build/config/remoting_logging.gni") import("//third_party/protobuf/proto_library.gni") proto_library("protobuf_http_client_messages_proto") { @@ -138,7 +139,10 @@ "//remoting/build/config:version", ] - deps = [ "//services/network/public/cpp" ] + deps = [ + ":logging", + "//services/network/public/cpp", + ] public_deps = [ "//base", @@ -169,6 +173,30 @@ } } +source_set("logging") { + public = [ "logging.h" ] + + sources = [ "logging.cc" ] + + if (is_linux || is_chromeos) { + sources += [ "logging_linux.cc" ] + } + + if (is_mac) { + sources += [ "logging_mac.cc" ] + } + + if (is_win) { + sources += [ "logging_win.cc" ] + } + + if (remoting_webrtc_verbose_logging) { + defines = [ "WEBRTC_VERBOSE_LOGGING" ] + } + + deps = [ "//base" ] +} + source_set("settings") { sources = [ "host_settings.cc", @@ -177,6 +205,7 @@ "user_settings.h", ] deps = [ + ":logging", "//base", "//remoting/base", ] @@ -215,6 +244,7 @@ ] deps = [ + ":logging", ":protobuf_http_client_messages_proto", "//base/test:test_support", "//remoting/proto", @@ -275,6 +305,7 @@ ] deps = [ + ":logging", ":protobuf_http_client_messages_proto", ":run_all_unittests", ":test_proto",
diff --git a/remoting/host/logging.cc b/remoting/base/logging.cc similarity index 92% rename from remoting/host/logging.cc rename to remoting/base/logging.cc index e700505..d8abc7fd 100644 --- a/remoting/host/logging.cc +++ b/remoting/base/logging.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 "remoting/host/logging.h" +#include "remoting/base/logging.h" #include "base/command_line.h"
diff --git a/remoting/base/logging.h b/remoting/base/logging.h index 9e9a709b..2ab5c17 100644 --- a/remoting/base/logging.h +++ b/remoting/base/logging.h
@@ -6,6 +6,11 @@ #define REMOTING_BASE_LOGGING_H_ #include "base/logging.h" +#include "build/build_config.h" + +#if defined(OS_WIN) +#include <guiddef.h> +#endif namespace remoting { @@ -17,6 +22,21 @@ #define HOST_LOG LOG(INFO) #define HOST_DLOG DLOG(INFO) +#if defined(OS_WIN) +// {2db51ca1-4fd8-4b88-b5a2-fb8606b66b02} +constexpr GUID kRemotingHostLogProviderGuid = { + 0x2db51ca1, + 0x4fd8, + 0x4b88, + {0xb5, 0xa2, 0xfb, 0x86, 0x06, 0xb6, 0x6b, 0x02}}; +#endif + +// Initializes host logging. +void InitHostLogging(); + +// Common initialization for all platforms, called by InitHostLogging(). +void InitHostLoggingCommon(); + } // namespace remoting #endif // REMOTING_BASE_LOGGING_H_
diff --git a/remoting/host/logging_linux.cc b/remoting/base/logging_linux.cc similarity index 93% rename from remoting/host/logging_linux.cc rename to remoting/base/logging_linux.cc index 1fe9226..64c18fb 100644 --- a/remoting/host/logging_linux.cc +++ b/remoting/base/logging_linux.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 "remoting/host/logging.h" +#include "remoting/base/logging.h" #include "base/logging.h"
diff --git a/remoting/host/logging_mac.cc b/remoting/base/logging_mac.cc similarity index 86% rename from remoting/host/logging_mac.cc rename to remoting/base/logging_mac.cc index f644591..320f010a 100644 --- a/remoting/host/logging_mac.cc +++ b/remoting/base/logging_mac.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 "remoting/host/logging.h" +#include "remoting/base/logging.h" #include <asl.h> #include <stddef.h> @@ -21,26 +21,21 @@ // Define a scoper for objects allocated by asl_new. struct ScopedAslMsgTraits { - static aslmsg InvalidValue() { - return nullptr; - } - static void Free(aslmsg msg) { - asl_free(msg); - } + static aslmsg InvalidValue() { return nullptr; } + static void Free(aslmsg msg) { asl_free(msg); } }; typedef base::ScopedGeneric<aslmsg, ScopedAslMsgTraits> ScopedAslMsg; // Logging message handler that writes to syslog. // The log can be obtained by running the following in a terminal: // syslog -k Facility org.chromium.chromoting -bool LogMessageToAsl( - logging::LogSeverity severity, - const char* file, - int line, - size_t message_start, - const std::string& message) { +bool LogMessageToAsl(logging::LogSeverity severity, + const char* file, + int line, + size_t message_start, + const std::string& message) { int level; - switch(severity) { + switch (severity) { case logging::LOG_INFO: level = ASL_LEVEL_NOTICE; break;
diff --git a/remoting/host/logging_win.cc b/remoting/base/logging_win.cc similarity index 94% rename from remoting/host/logging_win.cc rename to remoting/base/logging_win.cc index e5f1f65..a9be831 100644 --- a/remoting/host/logging_win.cc +++ b/remoting/base/logging_win.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 "remoting/host/logging.h" +#include "remoting/base/logging.h" #include <guiddef.h>
diff --git a/remoting/host/BUILD.gn b/remoting/host/BUILD.gn index a222bec..cb1009f 100644 --- a/remoting/host/BUILD.gn +++ b/remoting/host/BUILD.gn
@@ -47,33 +47,11 @@ } source_set("host") { - public_deps = [ ":common" ] - deps = [ "//remoting/host/file_transfer" ] -} - -source_set("logging") { - sources = [ - "logging.cc", - "logging.h", + public_deps = [ + ":common", + "//remoting/host/base", ] - - if (is_linux || is_chromeos) { - sources += [ "logging_linux.cc" ] - } - - if (is_mac) { - sources += [ "logging_mac.cc" ] - } - - if (is_win) { - sources += [ "logging_win.cc" ] - } - - if (remoting_webrtc_verbose_logging) { - defines = [ "WEBRTC_VERBOSE_LOGGING" ] - } - - deps = [ "//base" ] + deps = [ "//remoting/host/file_transfer" ] } source_set("host_main_headers") { @@ -99,10 +77,7 @@ } source_set("common_headers") { - visibility = [ - ":base", - "//remoting/host/security_key:security_key", - ] + visibility = [ "//remoting/host/*" ] sources = [ "action_executor.h", "audio_capturer.h", @@ -117,8 +92,6 @@ "evaluate_capability.h", "input_injector.h", "sas_injector.h", - "screen_controls.h", - "screen_resolution.h", "worker_process_ipc_delegate.h", ] if (!is_chromeos_ash) { @@ -127,31 +100,11 @@ deps = [ "//ipc", "//remoting/base", + "//remoting/host/base", "//remoting/protocol", ] } -source_set("base") { - sources = [ - "host_exit_codes.cc", - "host_exit_codes.h", - "switches.cc", - "switches.h", - "username.cc", - "username.h", - ] - deps = [ - ":common_headers", - ":logging", - "//base", - "//remoting/base", - ] - public_deps = [ - ":common_headers", - ":logging", - ] -} - source_set("ipc_constants") { sources = [ "ipc_constants.cc", @@ -195,9 +148,9 @@ sources = [ "clipboard.h" ] deps = [ - ":base", "//base", "//remoting/base:base", + "//remoting/host/base", "//remoting/proto", "//remoting/protocol", ] @@ -390,7 +343,6 @@ "remoting_register_support_host_request.h", "resizing_host_observer.cc", "resizing_host_observer.h", - "screen_resolution.cc", "server_log_entry_host.cc", "server_log_entry_host.h", "shutdown_watchdog.cc", @@ -423,7 +375,6 @@ defines = [ "WEBRTC_CHROMIUM_BUILD" ] deps = [ - ":base", ":client_session_control", ":clipboard", ":host_main_headers", @@ -466,8 +417,10 @@ ] public_deps = [ + ":common_headers", ":host_extension", "//ipc", + "//remoting/host/base", "//remoting/proto", "//remoting/proto/remoting/v1:directory_proto", ] @@ -590,8 +543,8 @@ ] deps += [ - ":base", ":remoting_version", + "//remoting/host/base", "//remoting/host/mac:permission_checking", "//ui/events:events", ] @@ -658,10 +611,10 @@ configs += [ "//remoting/build/config:version" ] deps = [ - ":base", ":chromoting_host_services_client", ":client_session_control", "//remoting/codec:encoder", + "//remoting/host/base", "//remoting/host/file_transfer:common", "//remoting/host/mojom", "//remoting/host/remote_open_url:common", @@ -725,7 +678,6 @@ "remoting_register_support_host_request_unittest.cc", "resizing_host_observer_unittest.cc", "resources_unittest.cc", - "screen_resolution_unittest.cc", "server_log_entry_host_unittest.cc", "setup/me2me_native_messaging_host_unittest.cc", "setup/pin_validator_unittest.cc", @@ -743,7 +695,6 @@ configs += [ "//remoting/build/config:version" ] deps = [ - ":base", ":client_session_control", ":common", ":resources", @@ -752,6 +703,7 @@ "//build:chromeos_buildflags", "//net:test_support", "//remoting/codec:encoder", + "//remoting/host/base", "//remoting/host/file_transfer:unit_tests", "//remoting/host/input_monitor:input_monitor", "//remoting/host/it2me:common", @@ -941,7 +893,6 @@ ] deps = [ - ":base", ":settings", "//base", "//base:i18n", @@ -953,6 +904,7 @@ "//remoting/base", "//remoting/base:authorization", "//remoting/host", + "//remoting/host/base", "//remoting/host/mojom", "//remoting/host/security_key:security_key", "//remoting/proto", @@ -997,7 +949,6 @@ ] sources = [ "host_main.cc" ] deps = [ - ":base", ":common", ":host_main_headers", ":remoting_me2me_host_static", @@ -1006,6 +957,7 @@ "//base:debugging_buildflags", "//mojo/core/embedder:embedder", "//remoting/base:breakpad", + "//remoting/host/base", "//remoting/host/setup:common", ] }
diff --git a/remoting/host/base/BUILD.gn b/remoting/host/base/BUILD.gn new file mode 100644 index 0000000..ae9b7f8 --- /dev/null +++ b/remoting/host/base/BUILD.gn
@@ -0,0 +1,53 @@ +# Copyright 2021 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//remoting/build/config/remoting_build.gni") + +source_set("base") { + visibility = [ + "//remoting/host/*", + "//remoting/test/*", + "//remoting/tools/*", + "//tools/ipc_fuzzer/message_lib:ipc_message_lib", + ] + + public = [ + "host_exit_codes.h", + "screen_controls.h", + "screen_resolution.h", + "switches.h", + "username.h", + ] + + sources = [ + "host_exit_codes.cc", + "screen_resolution.cc", + "switches.cc", + "username.cc", + ] + + public_deps = [ "//remoting/base:logging" ] + + deps = [ + "//base", + "//remoting/base", + "//third_party/webrtc_overrides:webrtc_component", + ] +} + +# The host/base portions of the remoting unit tests. +source_set("unit_tests") { + testonly = true + + sources = [ "screen_resolution_unittest.cc" ] + + configs += [ "//remoting/build/config:version" ] + + deps = [ + ":base", + "//testing/gmock", + "//testing/gtest", + "//third_party/webrtc_overrides:webrtc_component", + ] +}
diff --git a/remoting/host/host_exit_codes.cc b/remoting/host/base/host_exit_codes.cc similarity index 96% rename from remoting/host/host_exit_codes.cc rename to remoting/host/base/host_exit_codes.cc index a60a327..3624e65 100644 --- a/remoting/host/host_exit_codes.cc +++ b/remoting/host/base/host_exit_codes.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 "remoting/host/host_exit_codes.h" +#include "remoting/host/base/host_exit_codes.h" #include "remoting/base/name_value_map.h"
diff --git a/remoting/host/host_exit_codes.h b/remoting/host/base/host_exit_codes.h similarity index 90% rename from remoting/host/host_exit_codes.h rename to remoting/host/base/host_exit_codes.h index dba6c24..8ca6bb65 100644 --- a/remoting/host/host_exit_codes.h +++ b/remoting/host/base/host_exit_codes.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 REMOTING_HOST_HOST_EXIT_CODES_H_ -#define REMOTING_HOST_HOST_EXIT_CODES_H_ +#ifndef REMOTING_HOST_BASE_HOST_EXIT_CODES_H_ +#define REMOTING_HOST_BASE_HOST_EXIT_CODES_H_ namespace remoting { @@ -43,4 +43,4 @@ } // namespace remoting -#endif // REMOTING_HOST_HOST_EXIT_CODES_H_ +#endif // REMOTING_HOST_BASE_HOST_EXIT_CODES_H_
diff --git a/remoting/host/screen_controls.h b/remoting/host/base/screen_controls.h similarity index 76% rename from remoting/host/screen_controls.h rename to remoting/host/base/screen_controls.h index eac30d4..f6cd62a 100644 --- a/remoting/host/screen_controls.h +++ b/remoting/host/base/screen_controls.h
@@ -2,9 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef REMOTING_HOST_SCREEN_CONTROLS_H_ -#define REMOTING_HOST_SCREEN_CONTROLS_H_ - +#ifndef REMOTING_HOST_BASE_SCREEN_CONTROLS_H_ +#define REMOTING_HOST_BASE_SCREEN_CONTROLS_H_ namespace remoting { @@ -13,7 +12,7 @@ // Used to change the screen resolution (both dimensions and DPI). class ScreenControls { public: - virtual ~ScreenControls() {} + virtual ~ScreenControls() = default; // If |resolution| is not empty, attempts to set new screen resolution in the // session. If |resolution| is empty, attempts to restore the original screen @@ -23,4 +22,4 @@ } // namespace remoting -#endif // REMOTING_HOST_SCREEN_CONTROLS_H_ +#endif // REMOTING_HOST_BASE_SCREEN_CONTROLS_H_
diff --git a/remoting/host/screen_resolution.cc b/remoting/host/base/screen_resolution.cc similarity index 91% rename from remoting/host/screen_resolution.cc rename to remoting/host/base/screen_resolution.cc index 2864420..db8ff4a 100644 --- a/remoting/host/screen_resolution.cc +++ b/remoting/host/base/screen_resolution.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 "remoting/host/screen_resolution.h" +#include "remoting/host/base/screen_resolution.h" #include <stdint.h> @@ -15,13 +15,11 @@ ScreenResolution::ScreenResolution() : dimensions_(webrtc::DesktopSize(0, 0)), - dpi_(webrtc::DesktopVector(0, 0)) { -} + dpi_(webrtc::DesktopVector(0, 0)) {} ScreenResolution::ScreenResolution(const webrtc::DesktopSize& dimensions, const webrtc::DesktopVector& dpi) - : dimensions_(dimensions), - dpi_(dpi) { + : dimensions_(dimensions), dpi_(dpi) { // Check that dimensions are not negative. DCHECK(!dimensions.is_empty() || dimensions.equals(webrtc::DesktopSize())); DCHECK_GE(dpi.x(), 0);
diff --git a/remoting/host/screen_resolution.h b/remoting/host/base/screen_resolution.h similarity index 89% rename from remoting/host/screen_resolution.h rename to remoting/host/base/screen_resolution.h index ffa0a0e..6c0eab7 100644 --- a/remoting/host/screen_resolution.h +++ b/remoting/host/base/screen_resolution.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 REMOTING_HOST_SCREEN_RESOLUTION_H_ -#define REMOTING_HOST_SCREEN_RESOLUTION_H_ +#ifndef REMOTING_HOST_BASE_SCREEN_RESOLUTION_H_ +#define REMOTING_HOST_BASE_SCREEN_RESOLUTION_H_ #include "base/compiler_specific.h" #include "third_party/webrtc/modules/desktop_capture/desktop_geometry.h" @@ -40,4 +40,4 @@ } // namespace remoting -#endif // REMOTING_HOST_SCREEN_RESOLUTION_H_ +#endif // REMOTING_HOST_BASE_SCREEN_RESOLUTION_H_
diff --git a/remoting/host/screen_resolution_unittest.cc b/remoting/host/base/screen_resolution_unittest.cc similarity index 96% rename from remoting/host/screen_resolution_unittest.cc rename to remoting/host/base/screen_resolution_unittest.cc index 0b66865..c59dd28 100644 --- a/remoting/host/screen_resolution_unittest.cc +++ b/remoting/host/base/screen_resolution_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 "remoting/host/screen_resolution.h" +#include "remoting/host/base/screen_resolution.h" #include <stdint.h>
diff --git a/remoting/host/switches.cc b/remoting/host/base/switches.cc similarity index 97% rename from remoting/host/switches.cc rename to remoting/host/base/switches.cc index 3584dfbd..ce9f987f 100644 --- a/remoting/host/switches.cc +++ b/remoting/host/base/switches.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 "remoting/host/switches.h" +#include "remoting/host/base/switches.h" #include "build/build_config.h"
diff --git a/remoting/host/switches.h b/remoting/host/base/switches.h similarity index 95% rename from remoting/host/switches.h rename to remoting/host/base/switches.h index b0ae9ab8..4769406 100644 --- a/remoting/host/switches.h +++ b/remoting/host/base/switches.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 REMOTING_HOST_SWITCHES_H_ -#define REMOTING_HOST_SWITCHES_H_ +#ifndef REMOTING_HOST_BASE_SWITCHES_H_ +#define REMOTING_HOST_BASE_SWITCHES_H_ #include "build/build_config.h" @@ -82,4 +82,4 @@ } // namespace remoting -#endif // REMOTING_HOST_SWITCHES_H_ +#endif // REMOTING_HOST_BASE_SWITCHES_H_
diff --git a/remoting/host/username.cc b/remoting/host/base/username.cc similarity index 95% rename from remoting/host/username.cc rename to remoting/host/base/username.cc index 34779f2..73766dde 100644 --- a/remoting/host/username.cc +++ b/remoting/host/base/username.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 "remoting/host/username.h" +#include "remoting/host/base/username.h" #include <vector>
diff --git a/remoting/host/username.h b/remoting/host/base/username.h similarity index 75% rename from remoting/host/username.h rename to remoting/host/base/username.h index 28fc2ae2..0750174d 100644 --- a/remoting/host/username.h +++ b/remoting/host/base/username.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 REMOTING_HOST_USERNAME_H_ -#define REMOTING_HOST_USERNAME_H_ +#ifndef REMOTING_HOST_BASE_USERNAME_H_ +#define REMOTING_HOST_BASE_USERNAME_H_ #include <string> @@ -15,4 +15,4 @@ } // namespace remoting -#endif // REMOTING_HOST_USERNAME_H_ +#endif // REMOTING_HOST_BASE_USERNAME_H_
diff --git a/remoting/host/basic_desktop_environment.cc b/remoting/host/basic_desktop_environment.cc index 2a7d136..ee417c5 100644 --- a/remoting/host/basic_desktop_environment.cc +++ b/remoting/host/basic_desktop_environment.cc
@@ -12,6 +12,7 @@ #include "build/build_config.h" #include "remoting/host/action_executor.h" #include "remoting/host/audio_capturer.h" +#include "remoting/host/base/screen_controls.h" #include "remoting/host/client_session_control.h" #include "remoting/host/desktop_capturer_proxy.h" #include "remoting/host/file_transfer/local_file_operations.h" @@ -19,7 +20,6 @@ #include "remoting/host/keyboard_layout_monitor.h" #include "remoting/host/mouse_cursor_monitor_proxy.h" #include "remoting/host/remote_open_url/url_forwarder_configurator.h" -#include "remoting/host/screen_controls.h" #include "remoting/protocol/capability_names.h" #include "third_party/webrtc/modules/desktop_capture/desktop_capture_options.h" #include "third_party/webrtc/modules/desktop_capture/desktop_capturer.h"
diff --git a/remoting/host/chromoting_messages.h b/remoting/host/chromoting_messages.h index 7035f77..d304e3a 100644 --- a/remoting/host/chromoting_messages.h +++ b/remoting/host/chromoting_messages.h
@@ -13,9 +13,9 @@ #include "ipc/ipc_channel_handle.h" #include "ipc/ipc_message_start.h" #include "ipc/ipc_platform_file.h" +#include "remoting/host/base/screen_resolution.h" #include "remoting/host/chromoting_param_traits.h" #include "remoting/host/desktop_environment_options.h" -#include "remoting/host/screen_resolution.h" #include "remoting/proto/action.pb.h" #include "remoting/proto/control.pb.h" #include "remoting/protocol/errors.h"
diff --git a/remoting/host/chromoting_param_traits.h b/remoting/host/chromoting_param_traits.h index 214c320..87bc30be 100644 --- a/remoting/host/chromoting_param_traits.h +++ b/remoting/host/chromoting_param_traits.h
@@ -10,8 +10,8 @@ #include "net/base/ip_address.h" #include "net/base/ip_endpoint.h" #include "remoting/base/result.h" +#include "remoting/host/base/screen_resolution.h" #include "remoting/host/desktop_environment_options.h" -#include "remoting/host/screen_resolution.h" #include "remoting/proto/action.pb.h" #include "remoting/proto/control.pb.h" #include "remoting/proto/file_transfer.pb.h"
diff --git a/remoting/host/client_session.cc b/remoting/host/client_session.cc index 1724dad..5ee5e3c 100644 --- a/remoting/host/client_session.cc +++ b/remoting/host/client_session.cc
@@ -21,6 +21,8 @@ #include "remoting/host/action_executor.h" #include "remoting/host/action_message_handler.h" #include "remoting/host/audio_capturer.h" +#include "remoting/host/base/screen_controls.h" +#include "remoting/host/base/screen_resolution.h" #include "remoting/host/desktop_environment.h" #include "remoting/host/file_transfer/file_transfer_message_handler.h" #include "remoting/host/file_transfer/rtc_log_file_operations.h" @@ -32,8 +34,6 @@ #include "remoting/host/remote_open_url/remote_open_url_message_handler.h" #include "remoting/host/remote_open_url/url_forwarder_configurator.h" #include "remoting/host/remote_open_url/url_forwarder_control_message_handler.h" -#include "remoting/host/screen_controls.h" -#include "remoting/host/screen_resolution.h" #include "remoting/host/webauthn/remote_webauthn_constants.h" #include "remoting/host/webauthn/remote_webauthn_message_handler.h" #include "remoting/proto/control.pb.h"
diff --git a/remoting/host/daemon_process.cc b/remoting/host/daemon_process.cc index 222e369..985ad74 100644 --- a/remoting/host/daemon_process.cc +++ b/remoting/host/daemon_process.cc
@@ -19,14 +19,14 @@ #include "base/task/single_thread_task_runner.h" #include "remoting/base/auto_thread_task_runner.h" #include "remoting/base/constants.h" +#include "remoting/host/base/host_exit_codes.h" +#include "remoting/host/base/screen_resolution.h" #include "remoting/host/branding.h" #include "remoting/host/chromoting_messages.h" #include "remoting/host/config_file_watcher.h" #include "remoting/host/desktop_session.h" #include "remoting/host/host_event_logger.h" -#include "remoting/host/host_exit_codes.h" #include "remoting/host/host_status_observer.h" -#include "remoting/host/screen_resolution.h" #include "remoting/protocol/transport.h" namespace remoting {
diff --git a/remoting/host/daemon_process_win.cc b/remoting/host/daemon_process_win.cc index 503e425..8138659 100644 --- a/remoting/host/daemon_process_win.cc +++ b/remoting/host/daemon_process_win.cc
@@ -33,17 +33,17 @@ #include "remoting/base/auto_thread.h" #include "remoting/base/auto_thread_task_runner.h" #include "remoting/base/scoped_sc_handle_win.h" +#include "remoting/host/base/host_exit_codes.h" +#include "remoting/host/base/screen_resolution.h" +#include "remoting/host/base/switches.h" #include "remoting/host/branding.h" #include "remoting/host/chromoting_messages.h" #include "remoting/host/desktop_session_win.h" #include "remoting/host/host_config.h" -#include "remoting/host/host_exit_codes.h" #include "remoting/host/host_main.h" #include "remoting/host/ipc_constants.h" #include "remoting/host/mojom/remoting_host.mojom.h" #include "remoting/host/pairing_registry_delegate_win.h" -#include "remoting/host/screen_resolution.h" -#include "remoting/host/switches.h" #include "remoting/host/win/etw_trace_consumer.h" #include "remoting/host/win/host_event_file_logger.h" #include "remoting/host/win/host_event_windows_event_logger.h"
diff --git a/remoting/host/desktop_process_main.cc b/remoting/host/desktop_process_main.cc index c2ef70dc..4c93ecd 100644 --- a/remoting/host/desktop_process_main.cc +++ b/remoting/host/desktop_process_main.cc
@@ -23,11 +23,11 @@ #include "mojo/public/cpp/system/invitation.h" #include "remoting/base/auto_thread.h" #include "remoting/base/auto_thread_task_runner.h" +#include "remoting/host/base/host_exit_codes.h" +#include "remoting/host/base/switches.h" #include "remoting/host/desktop_process.h" -#include "remoting/host/host_exit_codes.h" #include "remoting/host/host_main.h" #include "remoting/host/me2me_desktop_environment.h" -#include "remoting/host/switches.h" #include "remoting/host/win/session_desktop_environment.h" namespace remoting {
diff --git a/remoting/host/desktop_process_unittest.cc b/remoting/host/desktop_process_unittest.cc index 4092f05b..87110d4 100644 --- a/remoting/host/desktop_process_unittest.cc +++ b/remoting/host/desktop_process_unittest.cc
@@ -24,15 +24,15 @@ #include "ipc/ipc_message.h" #include "remoting/base/auto_thread.h" #include "remoting/base/auto_thread_task_runner.h" +#include "remoting/host/base/host_exit_codes.h" +#include "remoting/host/base/screen_resolution.h" #include "remoting/host/chromoting_messages.h" #include "remoting/host/desktop_process.h" #include "remoting/host/fake_keyboard_layout_monitor.h" #include "remoting/host/fake_mouse_cursor_monitor.h" -#include "remoting/host/host_exit_codes.h" #include "remoting/host/host_mock_objects.h" #include "remoting/host/mojom/desktop_session.mojom.h" #include "remoting/host/remote_open_url/fake_url_forwarder_configurator.h" -#include "remoting/host/screen_resolution.h" #include "remoting/protocol/fake_desktop_capturer.h" #include "remoting/protocol/protocol_mock_objects.h" #include "testing/gmock/include/gmock/gmock.h"
diff --git a/remoting/host/desktop_resizer.h b/remoting/host/desktop_resizer.h index e08dcd0..478837d 100644 --- a/remoting/host/desktop_resizer.h +++ b/remoting/host/desktop_resizer.h
@@ -8,7 +8,7 @@ #include <list> #include <memory> -#include "remoting/host/screen_resolution.h" +#include "remoting/host/base/screen_resolution.h" namespace remoting {
diff --git a/remoting/host/desktop_session_agent.cc b/remoting/host/desktop_session_agent.cc index c5f58d2..8c2378b 100644 --- a/remoting/host/desktop_session_agent.cc +++ b/remoting/host/desktop_session_agent.cc
@@ -27,6 +27,8 @@ #include "remoting/base/constants.h" #include "remoting/host/action_executor.h" #include "remoting/host/audio_capturer.h" +#include "remoting/host/base/screen_controls.h" +#include "remoting/host/base/screen_resolution.h" #include "remoting/host/chromoting_messages.h" #include "remoting/host/crash_process.h" #include "remoting/host/desktop_environment.h" @@ -35,8 +37,6 @@ #include "remoting/host/mojom/desktop_session.mojom-shared.h" #include "remoting/host/remote_input_filter.h" #include "remoting/host/remote_open_url/url_forwarder_configurator.h" -#include "remoting/host/screen_controls.h" -#include "remoting/host/screen_resolution.h" #include "remoting/proto/action.pb.h" #include "remoting/proto/audio.pb.h" #include "remoting/proto/control.pb.h"
diff --git a/remoting/host/desktop_session_agent_unittest.cc b/remoting/host/desktop_session_agent_unittest.cc index 3e3d403..d2da93f 100644 --- a/remoting/host/desktop_session_agent_unittest.cc +++ b/remoting/host/desktop_session_agent_unittest.cc
@@ -19,10 +19,10 @@ #include "ipc/ipc_channel_proxy.h" #include "ipc/ipc_listener.h" #include "remoting/base/auto_thread_task_runner.h" +#include "remoting/host/base/screen_resolution.h" #include "remoting/host/chromoting_messages.h" #include "remoting/host/desktop_environment_options.h" #include "remoting/host/fake_desktop_environment.h" -#include "remoting/host/screen_resolution.h" #include "testing/gtest/include/gtest/gtest.h" namespace remoting {
diff --git a/remoting/host/desktop_session_proxy.h b/remoting/host/desktop_session_proxy.h index 3e11756..f2d0d5b 100644 --- a/remoting/host/desktop_session_proxy.h +++ b/remoting/host/desktop_session_proxy.h
@@ -22,12 +22,12 @@ #include "mojo/public/cpp/bindings/associated_remote.h" #include "remoting/host/action_executor.h" #include "remoting/host/audio_capturer.h" +#include "remoting/host/base/screen_resolution.h" #include "remoting/host/desktop_environment.h" #include "remoting/host/file_transfer/ipc_file_operations.h" #include "remoting/host/mojom/desktop_session.mojom.h" #include "remoting/host/mojom/remoting_mojom_traits.h" #include "remoting/host/remote_open_url/url_forwarder_configurator.h" -#include "remoting/host/screen_resolution.h" #include "remoting/proto/control.pb.h" #include "remoting/proto/event.pb.h" #include "remoting/proto/url_forwarder_control.pb.h"
diff --git a/remoting/host/desktop_session_win.cc b/remoting/host/desktop_session_win.cc index 73d827a2..52439ec 100644 --- a/remoting/host/desktop_session_win.cc +++ b/remoting/host/desktop_session_win.cc
@@ -31,14 +31,14 @@ #include "ipc/ipc_message_macros.h" #include "ipc/ipc_platform_file.h" #include "remoting/base/auto_thread_task_runner.h" +#include "remoting/host/base/screen_resolution.h" +#include "remoting/host/base/switches.h" #include "remoting/host/chromoting_messages.h" #include "remoting/host/daemon_process.h" #include "remoting/host/desktop_session.h" #include "remoting/host/host_main.h" #include "remoting/host/ipc_constants.h" #include "remoting/host/sas_injector.h" -#include "remoting/host/screen_resolution.h" -#include "remoting/host/switches.h" // MIDL-generated declarations and definitions. #include "remoting/host/win/chromoting_lib.h" #include "remoting/host/win/host_service.h"
diff --git a/remoting/host/evaluate_capability.cc b/remoting/host/evaluate_capability.cc index 321aa17..3fd9edd 100644 --- a/remoting/host/evaluate_capability.cc +++ b/remoting/host/evaluate_capability.cc
@@ -16,9 +16,9 @@ #include "base/process/launch.h" #include "base/threading/thread_restrictions.h" #include "build/build_config.h" -#include "remoting/host/host_exit_codes.h" +#include "remoting/host/base/host_exit_codes.h" +#include "remoting/host/base/switches.h" #include "remoting/host/ipc_constants.h" -#include "remoting/host/switches.h" #if defined(OS_WIN) #include "remoting/host/win/evaluate_3d_display_mode.h"
diff --git a/remoting/host/evaluate_capability_unittest.cc b/remoting/host/evaluate_capability_unittest.cc index adaf1a12..e9030e61 100644 --- a/remoting/host/evaluate_capability_unittest.cc +++ b/remoting/host/evaluate_capability_unittest.cc
@@ -5,7 +5,7 @@ #include "remoting/host/evaluate_capability.h" #include "base/strings/string_util.h" -#include "remoting/host/switches.h" +#include "remoting/host/base/switches.h" #include "testing/gtest/include/gtest/gtest.h" namespace remoting {
diff --git a/remoting/host/fake_desktop_environment.h b/remoting/host/fake_desktop_environment.h index 4685513..8324dc4 100644 --- a/remoting/host/fake_desktop_environment.h +++ b/remoting/host/fake_desktop_environment.h
@@ -13,11 +13,11 @@ #include "base/memory/raw_ptr.h" #include "base/task/single_thread_task_runner.h" #include "remoting/host/action_executor.h" +#include "remoting/host/base/screen_controls.h" #include "remoting/host/desktop_environment.h" #include "remoting/host/desktop_environment_options.h" #include "remoting/host/fake_mouse_cursor_monitor.h" #include "remoting/host/input_injector.h" -#include "remoting/host/screen_controls.h" #include "remoting/protocol/fake_desktop_capturer.h" namespace remoting {
diff --git a/remoting/host/file_transfer/BUILD.gn b/remoting/host/file_transfer/BUILD.gn index 046bb3c..b899af4 100644 --- a/remoting/host/file_transfer/BUILD.gn +++ b/remoting/host/file_transfer/BUILD.gn
@@ -39,8 +39,8 @@ ] deps += [ "//ipc:ipc", - "//remoting/host:base", "//remoting/host:common", + "//remoting/host/base", "//remoting/host/win", ] } else {
diff --git a/remoting/host/file_transfer/file_chooser_win.cc b/remoting/host/file_transfer/file_chooser_win.cc index 7e49879..9ae9687 100644 --- a/remoting/host/file_transfer/file_chooser_win.cc +++ b/remoting/host/file_transfer/file_chooser_win.cc
@@ -19,11 +19,11 @@ #include "base/win/object_watcher.h" #include "base/win/scoped_handle.h" #include "ipc/ipc_message_utils.h" +#include "remoting/host/base/host_exit_codes.h" +#include "remoting/host/base/switches.h" #include "remoting/host/chromoting_param_traits.h" #include "remoting/host/chromoting_param_traits_impl.h" #include "remoting/host/file_transfer/file_chooser_common_win.h" -#include "remoting/host/host_exit_codes.h" -#include "remoting/host/switches.h" namespace remoting {
diff --git a/remoting/host/host_main.cc b/remoting/host/host_main.cc index 927dbc0..6deec87 100644 --- a/remoting/host/host_main.cc +++ b/remoting/host/host_main.cc
@@ -20,12 +20,12 @@ #include "build/build_config.h" #include "mojo/core/embedder/embedder.h" #include "remoting/base/breakpad.h" +#include "remoting/base/logging.h" +#include "remoting/host/base/host_exit_codes.h" +#include "remoting/host/base/switches.h" #include "remoting/host/evaluate_capability.h" -#include "remoting/host/host_exit_codes.h" -#include "remoting/host/logging.h" #include "remoting/host/resources.h" #include "remoting/host/setup/me2me_native_messaging_host.h" -#include "remoting/host/switches.h" #include "remoting/host/usage_stats_consent.h" #if defined(OS_APPLE)
diff --git a/remoting/host/host_mock_objects.h b/remoting/host/host_mock_objects.h index 0297332..00b0eb70 100644 --- a/remoting/host/host_mock_objects.h +++ b/remoting/host/host_mock_objects.h
@@ -11,6 +11,8 @@ #include "net/base/ip_endpoint.h" #include "remoting/host/action_executor.h" +#include "remoting/host/base/screen_controls.h" +#include "remoting/host/base/screen_resolution.h" #include "remoting/host/chromoting_host_context.h" #include "remoting/host/chromoting_host_services_provider.h" #include "remoting/host/client_session.h" @@ -21,8 +23,6 @@ #include "remoting/host/input_injector.h" #include "remoting/host/mojom/chromoting_host_services.mojom.h" #include "remoting/host/remote_open_url/url_forwarder_configurator.h" -#include "remoting/host/screen_controls.h" -#include "remoting/host/screen_resolution.h" #include "remoting/host/security_key/security_key_auth_handler.h" #include "remoting/proto/control.pb.h" #include "remoting/proto/event.pb.h"
diff --git a/remoting/host/input_monitor/local_hotkey_input_monitor_chromeos.cc b/remoting/host/input_monitor/local_hotkey_input_monitor_chromeos.cc index 13abfcc..6e4fe03 100644 --- a/remoting/host/input_monitor/local_hotkey_input_monitor_chromeos.cc +++ b/remoting/host/input_monitor/local_hotkey_input_monitor_chromeos.cc
@@ -120,8 +120,8 @@ return; } + DCHECK(event->IsKeyEvent()); ui::KeyEvent key_event(event); - DCHECK(key_event.is_char()); if (key_event.IsControlDown() && key_event.IsAltDown() && key_event.key_code() == ui::VKEY_ESCAPE) { caller_task_runner_->PostTask(FROM_HERE, std::move(disconnect_callback_));
diff --git a/remoting/host/ipc_desktop_environment.cc b/remoting/host/ipc_desktop_environment.cc index dc79fa4..6a2e7b6 100644 --- a/remoting/host/ipc_desktop_environment.cc +++ b/remoting/host/ipc_desktop_environment.cc
@@ -16,6 +16,7 @@ #include "ipc/ipc_sender.h" #include "remoting/host/action_executor.h" #include "remoting/host/audio_capturer.h" +#include "remoting/host/base/screen_controls.h" #include "remoting/host/chromoting_messages.h" #include "remoting/host/client_session_control.h" #include "remoting/host/desktop_session.h" @@ -24,7 +25,6 @@ #include "remoting/host/input_injector.h" #include "remoting/host/keyboard_layout_monitor.h" #include "remoting/host/remote_open_url/url_forwarder_configurator.h" -#include "remoting/host/screen_controls.h" #include "third_party/webrtc/modules/desktop_capture/desktop_capturer.h" #include "third_party/webrtc/modules/desktop_capture/mouse_cursor_monitor.h"
diff --git a/remoting/host/ipc_screen_controls.h b/remoting/host/ipc_screen_controls.h index 4b37626..0e32807 100644 --- a/remoting/host/ipc_screen_controls.h +++ b/remoting/host/ipc_screen_controls.h
@@ -6,7 +6,7 @@ #define REMOTING_HOST_IPC_SCREEN_CONTROLS_H_ #include "base/memory/ref_counted.h" -#include "remoting/host/screen_controls.h" +#include "remoting/host/base/screen_controls.h" namespace remoting {
diff --git a/remoting/host/it2me/BUILD.gn b/remoting/host/it2me/BUILD.gn index eac2f4c..9c884c38 100644 --- a/remoting/host/it2me/BUILD.gn +++ b/remoting/host/it2me/BUILD.gn
@@ -83,8 +83,8 @@ "//net", "//remoting/base", "//remoting/base:authorization", - "//remoting/host:base", "//remoting/host:common", + "//remoting/host/base", "//remoting/host/native_messaging:native_messaging", "//remoting/protocol", "//remoting/resources", @@ -192,10 +192,9 @@ "//remoting/base", "//remoting/base:breakpad", "//remoting/host", - "//remoting/host:base", - "//remoting/host:logging", "//remoting/host:resources", "//remoting/host:settings", + "//remoting/host/base", "//remoting/host/native_messaging", "//remoting/proto", "//third_party/webrtc_overrides:webrtc_component",
diff --git a/remoting/host/it2me/it2me_native_messaging_host.cc b/remoting/host/it2me/it2me_native_messaging_host.cc index 93ad7c1..6ceaa053 100644 --- a/remoting/host/it2me/it2me_native_messaging_host.cc +++ b/remoting/host/it2me/it2me_native_messaging_host.cc
@@ -25,8 +25,8 @@ #include "net/url_request/url_request_context_getter.h" #include "remoting/base/auto_thread_task_runner.h" #include "remoting/base/passthrough_oauth_token_getter.h" +#include "remoting/host/base/host_exit_codes.h" #include "remoting/host/chromoting_host_context.h" -#include "remoting/host/host_exit_codes.h" #include "remoting/host/it2me/it2me_confirmation_dialog.h" #include "remoting/host/it2me/it2me_constants.h" #include "remoting/host/it2me/it2me_helpers.h"
diff --git a/remoting/host/it2me/it2me_native_messaging_host_main.cc b/remoting/host/it2me/it2me_native_messaging_host_main.cc index 9632e8d2..c507991 100644 --- a/remoting/host/it2me/it2me_native_messaging_host_main.cc +++ b/remoting/host/it2me/it2me_native_messaging_host_main.cc
@@ -19,15 +19,15 @@ #include "remoting/base/auto_thread_task_runner.h" #include "remoting/base/breakpad.h" #include "remoting/base/host_settings.h" +#include "remoting/base/logging.h" +#include "remoting/host/base/host_exit_codes.h" +#include "remoting/host/base/switches.h" #include "remoting/host/chromoting_host_context.h" -#include "remoting/host/host_exit_codes.h" #include "remoting/host/it2me/it2me_native_messaging_host.h" -#include "remoting/host/logging.h" #include "remoting/host/native_messaging/native_messaging_pipe.h" #include "remoting/host/native_messaging/pipe_messaging_channel.h" #include "remoting/host/policy_watcher.h" #include "remoting/host/resources.h" -#include "remoting/host/switches.h" #include "remoting/host/usage_stats_consent.h" #if defined(OS_LINUX) || defined(OS_CHROMEOS) @@ -49,8 +49,6 @@ #include <windows.h> #include <commctrl.h> - -#include "remoting/host/switches.h" #endif // defined(OS_WIN) namespace remoting {
diff --git a/remoting/host/linux/BUILD.gn b/remoting/host/linux/BUILD.gn index e8e08c47..eb85c1a4 100644 --- a/remoting/host/linux/BUILD.gn +++ b/remoting/host/linux/BUILD.gn
@@ -97,6 +97,7 @@ deps = [ "//base", "//remoting/base", + "//remoting/base:logging", "//third_party/webrtc_overrides:webrtc_component", ] }
diff --git a/remoting/host/linux/linux_me2me_host.py b/remoting/host/linux/linux_me2me_host.py index ed7e9d1..c93ab21 100755 --- a/remoting/host/linux/linux_me2me_host.py +++ b/remoting/host/linux/linux_me2me_host.py
@@ -1896,7 +1896,7 @@ desktop.host_ready = False # These exit-codes must match the ones used by the host. - # See remoting/host/host_exit_codes.h. + # See remoting/host/base/host_exit_codes.h. # Delete the host or auth configuration depending on the returned error # code, so the next time this script is run, a new configuration # will be created and registered.
diff --git a/remoting/host/logging.h b/remoting/host/logging.h deleted file mode 100644 index b1bc2da..0000000 --- a/remoting/host/logging.h +++ /dev/null
@@ -1,34 +0,0 @@ -// Copyright (c) 2012 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 REMOTING_HOST_LOGGING_H_ -#define REMOTING_HOST_LOGGING_H_ - -#include "base/logging.h" -#include "build/build_config.h" - -#if defined(OS_WIN) -#include <guiddef.h> -#endif - -namespace remoting { - -#if defined(OS_WIN) -// {2db51ca1-4fd8-4b88-b5a2-fb8606b66b02} -constexpr GUID kRemotingHostLogProviderGuid = { - 0x2db51ca1, - 0x4fd8, - 0x4b88, - {0xb5, 0xa2, 0xfb, 0x86, 0x06, 0xb6, 0x6b, 0x02}}; -#endif - -// Initializes host logging. -void InitHostLogging(); - -// Common initialization for all platforms, called by InitHostLogging(). -void InitHostLoggingCommon(); - -} // namespace remoting - -#endif // REMOTING_HOST_LOGGING_H_
diff --git a/remoting/host/mac/BUILD.gn b/remoting/host/mac/BUILD.gn index 535d5f4..f503cec 100644 --- a/remoting/host/mac/BUILD.gn +++ b/remoting/host/mac/BUILD.gn
@@ -59,7 +59,7 @@ ":constants", "//base", "//remoting/base", - "//remoting/host:base", + "//remoting/host/base", "//remoting/host:remoting_version", ] }
diff --git a/remoting/host/mac/host_service_main.cc b/remoting/host/mac/host_service_main.cc index 490474f8..8a59c78 100644 --- a/remoting/host/mac/host_service_main.cc +++ b/remoting/host/mac/host_service_main.cc
@@ -24,11 +24,10 @@ #include "base/threading/platform_thread.h" #include "base/time/time.h" #include "remoting/base/logging.h" -#include "remoting/host/host_exit_codes.h" -#include "remoting/host/logging.h" +#include "remoting/host/base/host_exit_codes.h" +#include "remoting/host/base/switches.h" +#include "remoting/host/base/username.h" #include "remoting/host/mac/constants_mac.h" -#include "remoting/host/switches.h" -#include "remoting/host/username.h" #include "remoting/host/version.h" namespace remoting {
diff --git a/remoting/host/me2me_desktop_environment.cc b/remoting/host/me2me_desktop_environment.cc index f515efd..0559d729 100644 --- a/remoting/host/me2me_desktop_environment.cc +++ b/remoting/host/me2me_desktop_environment.cc
@@ -13,6 +13,7 @@ #include "build/build_config.h" #include "remoting/base/logging.h" #include "remoting/host/action_executor.h" +#include "remoting/host/base/screen_controls.h" #include "remoting/host/client_session_control.h" #include "remoting/host/curtain_mode.h" #include "remoting/host/desktop_resizer.h" @@ -22,7 +23,6 @@ #include "remoting/host/input_monitor/local_input_monitor.h" #include "remoting/host/remote_open_url/remote_open_url_util.h" #include "remoting/host/resizing_host_observer.h" -#include "remoting/host/screen_controls.h" #include "remoting/protocol/capability_names.h" #include "third_party/webrtc/modules/desktop_capture/desktop_capture_options.h" #include "third_party/webrtc/modules/desktop_capture/desktop_capturer.h"
diff --git a/remoting/host/pam_authorization_factory_posix.cc b/remoting/host/pam_authorization_factory_posix.cc index d1fc342..1c1ae14 100644 --- a/remoting/host/pam_authorization_factory_posix.cc +++ b/remoting/host/pam_authorization_factory_posix.cc
@@ -12,7 +12,7 @@ #include "base/callback.h" #include "base/environment.h" #include "remoting/base/logging.h" -#include "remoting/host/username.h" +#include "remoting/host/base/username.h" #include "remoting/protocol/channel_authenticator.h" #include "third_party/libjingle_xmpp/xmllite/xmlelement.h"
diff --git a/remoting/host/remote_open_url/BUILD.gn b/remoting/host/remote_open_url/BUILD.gn index ee034f9..cf7486b2 100644 --- a/remoting/host/remote_open_url/BUILD.gn +++ b/remoting/host/remote_open_url/BUILD.gn
@@ -26,10 +26,10 @@ "//mojo/public/cpp/platform", "//mojo/public/cpp/system", "//remoting/base", - "//remoting/host:base", "//remoting/host:chromoting_host_services_client", "//remoting/host:resources", "//remoting/host:settings", + "//remoting/host/base", "//remoting/host/mojom", "//remoting/protocol", "//remoting/resources", @@ -78,11 +78,10 @@ "//base:i18n", "//mojo/core/embedder", "//remoting/host", - "//remoting/host:base", "//remoting/host:chromoting_host_services_client", - "//remoting/host:logging", "//remoting/host:resources", "//remoting/host:settings", + "//remoting/host/base", "//remoting/host/mojom", "//ui/base", "//url",
diff --git a/remoting/host/remote_open_url/remote_open_url_main.cc b/remoting/host/remote_open_url/remote_open_url_main.cc index 196fe1c..66b49c1b 100644 --- a/remoting/host/remote_open_url/remote_open_url_main.cc +++ b/remoting/host/remote_open_url/remote_open_url_main.cc
@@ -15,9 +15,8 @@ #include "mojo/core/embedder/scoped_ipc_support.h" #include "remoting/base/host_settings.h" #include "remoting/base/logging.h" +#include "remoting/host/base/host_exit_codes.h" #include "remoting/host/chromoting_host_services_client.h" -#include "remoting/host/host_exit_codes.h" -#include "remoting/host/logging.h" #include "remoting/host/remote_open_url/remote_open_url_client.h" #include "remoting/host/resources.h" #include "ui/base/l10n/l10n_util.h"
diff --git a/remoting/host/remote_open_url/url_forwarder_configurator_main_win.cc b/remoting/host/remote_open_url/url_forwarder_configurator_main_win.cc index ec8be11..44bad0b 100644 --- a/remoting/host/remote_open_url/url_forwarder_configurator_main_win.cc +++ b/remoting/host/remote_open_url/url_forwarder_configurator_main_win.cc
@@ -28,8 +28,8 @@ #include "base/win/windows_types.h" #include "remoting/base/logging.h" #include "remoting/base/user_settings.h" +#include "remoting/host/base/switches.h" #include "remoting/host/remote_open_url/remote_open_url_constants.h" -#include "remoting/host/switches.h" #include "remoting/host/user_setting_keys.h" #include "remoting/host/win/core_resource.h" #include "remoting/host/win/default_apps_util.h"
diff --git a/remoting/host/remote_open_url/url_forwarder_configurator_win.cc b/remoting/host/remote_open_url/url_forwarder_configurator_win.cc index 21b52d5..927070719 100644 --- a/remoting/host/remote_open_url/url_forwarder_configurator_win.cc +++ b/remoting/host/remote_open_url/url_forwarder_configurator_win.cc
@@ -26,7 +26,7 @@ #include "base/win/scoped_handle.h" #include "base/win/windows_types.h" #include "remoting/base/logging.h" -#include "remoting/host/switches.h" +#include "remoting/host/base/switches.h" #include "remoting/host/win/wts_session_change_observer.h" namespace remoting {
diff --git a/remoting/host/remoting_me2me_host.cc b/remoting/host/remoting_me2me_host.cc index 08f1d581d..bfb7d12 100644 --- a/remoting/host/remoting_me2me_host.cc +++ b/remoting/host/remoting_me2me_host.cc
@@ -52,6 +52,9 @@ #include "remoting/base/rsa_key_pair.h" #include "remoting/base/service_urls.h" #include "remoting/base/util.h" +#include "remoting/host/base/host_exit_codes.h" +#include "remoting/host/base/switches.h" +#include "remoting/host/base/username.h" #include "remoting/host/branding.h" #include "remoting/host/chromoting_host.h" #include "remoting/host/chromoting_host_context.h" @@ -68,13 +71,11 @@ #include "remoting/host/heartbeat_sender.h" #include "remoting/host/host_config.h" #include "remoting/host/host_event_logger.h" -#include "remoting/host/host_exit_codes.h" #include "remoting/host/host_power_save_blocker.h" #include "remoting/host/host_status_logger.h" #include "remoting/host/input_injector.h" #include "remoting/host/ipc_desktop_environment.h" #include "remoting/host/ipc_host_event_logger.h" -#include "remoting/host/logging.h" #include "remoting/host/me2me_desktop_environment.h" #include "remoting/host/mojom/remoting_host.mojom.h" #include "remoting/host/pairing_registry_delegate.h" @@ -83,12 +84,10 @@ #include "remoting/host/security_key/security_key_auth_handler.h" #include "remoting/host/security_key/security_key_extension.h" #include "remoting/host/shutdown_watchdog.h" -#include "remoting/host/switches.h" #include "remoting/host/test_echo_extension.h" #include "remoting/host/third_party_auth_config.h" #include "remoting/host/token_validator_factory_impl.h" #include "remoting/host/usage_stats_consent.h" -#include "remoting/host/username.h" #include "remoting/host/zombie_host_detector.h" #include "remoting/protocol/authenticator.h" #include "remoting/protocol/channel_authenticator.h"
diff --git a/remoting/host/resizing_host_observer.cc b/remoting/host/resizing_host_observer.cc index ed5cd5d..60d87df1 100644 --- a/remoting/host/resizing_host_observer.cc +++ b/remoting/host/resizing_host_observer.cc
@@ -15,8 +15,8 @@ #include "base/logging.h" #include "base/time/default_tick_clock.h" #include "base/time/tick_clock.h" +#include "remoting/host/base/screen_resolution.h" #include "remoting/host/desktop_resizer.h" -#include "remoting/host/screen_resolution.h" namespace remoting { namespace {
diff --git a/remoting/host/resizing_host_observer.h b/remoting/host/resizing_host_observer.h index e648da7..4a1b8d1 100644 --- a/remoting/host/resizing_host_observer.h +++ b/remoting/host/resizing_host_observer.h
@@ -13,8 +13,8 @@ #include "base/memory/weak_ptr.h" #include "base/time/time.h" #include "base/timer/timer.h" -#include "remoting/host/screen_controls.h" -#include "remoting/host/screen_resolution.h" +#include "remoting/host/base/screen_controls.h" +#include "remoting/host/base/screen_resolution.h" namespace base { class TickClock;
diff --git a/remoting/host/resizing_host_observer_unittest.cc b/remoting/host/resizing_host_observer_unittest.cc index f9411cea..55a44c9 100644 --- a/remoting/host/resizing_host_observer_unittest.cc +++ b/remoting/host/resizing_host_observer_unittest.cc
@@ -13,8 +13,8 @@ #include "base/task/single_thread_task_runner.h" #include "base/test/simple_test_tick_clock.h" #include "base/test/task_environment.h" +#include "remoting/host/base/screen_resolution.h" #include "remoting/host/desktop_resizer.h" -#include "remoting/host/screen_resolution.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/webrtc/modules/desktop_capture/desktop_geometry.h"
diff --git a/remoting/host/sas_injector.h b/remoting/host/sas_injector.h index 248eb296..cb59cc37 100644 --- a/remoting/host/sas_injector.h +++ b/remoting/host/sas_injector.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 REMOTING_HOST_SAS_INJECTOR_H_ -#define REMOTING_HOST_SAS_INJECTOR_H_ +#ifndef REMOTING_HOST_BASE_SAS_INJECTOR_H_ +#define REMOTING_HOST_BASE_SAS_INJECTOR_H_ #include <memory> @@ -13,7 +13,7 @@ // sequence is Ctrl+Alt+Delete. class SasInjector { public: - virtual ~SasInjector() {} + virtual ~SasInjector() = default; // Sends Secure Attention Sequence to the console session. virtual bool InjectSas() = 0; @@ -25,4 +25,4 @@ } // namespace remoting -#endif // REMOTING_HOST_SAS_INJECTOR_H_ +#endif // REMOTING_HOST_BASE_SAS_INJECTOR_H_
diff --git a/remoting/host/security_key/BUILD.gn b/remoting/host/security_key/BUILD.gn index 0f9d17f..8423fdf3 100644 --- a/remoting/host/security_key/BUILD.gn +++ b/remoting/host/security_key/BUILD.gn
@@ -39,6 +39,7 @@ "//mojo/public/cpp/system", "//net:net", "//net/traffic_annotation:traffic_annotation", + "//remoting/base:logging", "//remoting/host:host_extension", "//remoting/host/mojom", "//remoting/proto", @@ -65,8 +66,8 @@ ":security_key", "//base:debugging_buildflags", "//mojo/core/embedder", - "//remoting/host:base", "//remoting/host:common", + "//remoting/host/base", ] if (is_win) { deps += [ "//remoting/host/win:acl_util" ]
diff --git a/remoting/host/security_key/remote_security_key_main.cc b/remoting/host/security_key/remote_security_key_main.cc index d96d6712..cdd23cd 100644 --- a/remoting/host/security_key/remote_security_key_main.cc +++ b/remoting/host/security_key/remote_security_key_main.cc
@@ -17,8 +17,8 @@ #include "build/build_config.h" #include "mojo/core/embedder/embedder.h" #include "mojo/core/embedder/scoped_ipc_support.h" -#include "remoting/host/host_exit_codes.h" -#include "remoting/host/logging.h" +#include "remoting/base/logging.h" +#include "remoting/host/base/host_exit_codes.h" #include "remoting/host/security_key/security_key_ipc_client.h" #include "remoting/host/security_key/security_key_message_handler.h"
diff --git a/remoting/host/setup/BUILD.gn b/remoting/host/setup/BUILD.gn index bf3f55f..4678df9d 100644 --- a/remoting/host/setup/BUILD.gn +++ b/remoting/host/setup/BUILD.gn
@@ -143,8 +143,8 @@ "//remoting/base:authorization", "//remoting/base:breakpad", "//remoting/host", - "//remoting/host:base", "//remoting/host:common", + "//remoting/host/base", "//remoting/host/native_messaging", "//remoting/host/setup", "//services/network:network_service",
diff --git a/remoting/host/setup/me2me_native_messaging_host_main.cc b/remoting/host/setup/me2me_native_messaging_host_main.cc index 6ee271b..6f849bb 100644 --- a/remoting/host/setup/me2me_native_messaging_host_main.cc +++ b/remoting/host/setup/me2me_native_messaging_host_main.cc
@@ -26,15 +26,15 @@ #include "remoting/base/auto_thread_task_runner.h" #include "remoting/base/breakpad.h" #include "remoting/base/gaia_oauth_client.h" +#include "remoting/base/logging.h" #include "remoting/base/url_request_context_getter.h" +#include "remoting/host/base/host_exit_codes.h" +#include "remoting/host/base/switches.h" #include "remoting/host/chromoting_host_context.h" -#include "remoting/host/host_exit_codes.h" -#include "remoting/host/logging.h" #include "remoting/host/native_messaging/native_messaging_pipe.h" #include "remoting/host/native_messaging/pipe_messaging_channel.h" #include "remoting/host/pairing_registry_delegate.h" #include "remoting/host/setup/me2me_native_messaging_host.h" -#include "remoting/host/switches.h" #include "remoting/host/usage_stats_consent.h" #include "services/network/public/cpp/shared_url_loader_factory.h" #include "services/network/transitional_url_loader_factory_owner.h"
diff --git a/remoting/host/webauthn/BUILD.gn b/remoting/host/webauthn/BUILD.gn index 7f15a12..41fb005 100644 --- a/remoting/host/webauthn/BUILD.gn +++ b/remoting/host/webauthn/BUILD.gn
@@ -39,9 +39,8 @@ ":webauthn", "//base", "//mojo/core/embedder:embedder", - "//remoting/host:base", "//remoting/host:chromoting_host_services_client", - "//remoting/host:logging", + "//remoting/host/base", "//remoting/host/native_messaging", ] }
diff --git a/remoting/host/webauthn/remote_webauthn_main.cc b/remoting/host/webauthn/remote_webauthn_main.cc index f2dfda9..b4277b1 100644 --- a/remoting/host/webauthn/remote_webauthn_main.cc +++ b/remoting/host/webauthn/remote_webauthn_main.cc
@@ -14,9 +14,9 @@ #include "build/build_config.h" #include "mojo/core/embedder/embedder.h" #include "mojo/core/embedder/scoped_ipc_support.h" +#include "remoting/base/logging.h" +#include "remoting/host/base/host_exit_codes.h" #include "remoting/host/chromoting_host_services_client.h" -#include "remoting/host/host_exit_codes.h" -#include "remoting/host/logging.h" #include "remoting/host/native_messaging/native_messaging_pipe.h" #include "remoting/host/native_messaging/pipe_messaging_channel.h" #include "remoting/host/webauthn/remote_webauthn_native_messaging_host.h"
diff --git a/remoting/host/win/BUILD.gn b/remoting/host/win/BUILD.gn index f81afd1..c0115d7d 100644 --- a/remoting/host/win/BUILD.gn +++ b/remoting/host/win/BUILD.gn
@@ -171,8 +171,8 @@ "//crypto", "//ipc", "//remoting/base", - "//remoting/host:base", "//remoting/host:ipc_constants", + "//remoting/host/base", "//remoting/host/security_key", "//remoting/host/win:messages", "//remoting/host/win:remoting_lib_idl", @@ -207,9 +207,9 @@ ":win", "//base/test:test_support", "//ipc", - "//remoting/host:base", "//remoting/host:common", "//remoting/host:test_support", + "//remoting/host/base", "//remoting/host/it2me:common", "//remoting/host/native_messaging", "//remoting/host/security_key:unit_tests", @@ -370,7 +370,7 @@ "//base", "//extensions/browser/api/messaging:native_messaging", "//ipc", - "//remoting/host:base", + "//remoting/host/base", "//remoting/host/native_messaging", ] } @@ -426,14 +426,13 @@ "//remoting/base", "//remoting/base:authorization", "//remoting/base:breakpad", - "//remoting/host:base", "//remoting/host:host", "//remoting/host:host_main_headers", "//remoting/host:implementation", "//remoting/host:ipc_constants", - "//remoting/host:logging", "//remoting/host:resources", "//remoting/host:settings", + "//remoting/host/base", "//remoting/host/it2me:common", "//remoting/host/native_messaging", "//remoting/host/remote_open_url:main",
diff --git a/remoting/host/win/chromoting_module.cc b/remoting/host/win/chromoting_module.cc index 20b82ff9..0440413 100644 --- a/remoting/host/win/chromoting_module.cc +++ b/remoting/host/win/chromoting_module.cc
@@ -13,7 +13,7 @@ #include "base/win/scoped_handle.h" #include "remoting/base/auto_thread_task_runner.h" #include "remoting/base/typed_buffer.h" -#include "remoting/host/host_exit_codes.h" +#include "remoting/host/base/host_exit_codes.h" #include "remoting/host/win/rdp_desktop_session.h" namespace remoting {
diff --git a/remoting/host/win/etw_trace_consumer.cc b/remoting/host/win/etw_trace_consumer.cc index 57dce7a..b369cf8 100644 --- a/remoting/host/win/etw_trace_consumer.cc +++ b/remoting/host/win/etw_trace_consumer.cc
@@ -14,7 +14,7 @@ #include "base/win/event_trace_consumer.h" #include "base/win/event_trace_controller.h" #include "remoting/base/auto_thread_task_runner.h" -#include "remoting/host/logging.h" +#include "remoting/base/logging.h" #include "remoting/host/win/etw_trace_controller.h" #include "remoting/host/win/event_trace_data.h" #include "remoting/host/win/host_event_logger.h"
diff --git a/remoting/host/win/etw_trace_controller.cc b/remoting/host/win/etw_trace_controller.cc index 163058bd..42854b0 100644 --- a/remoting/host/win/etw_trace_controller.cc +++ b/remoting/host/win/etw_trace_controller.cc
@@ -8,7 +8,7 @@ #include <memory> #include "base/logging.h" -#include "remoting/host/logging.h" +#include "remoting/base/logging.h" namespace remoting {
diff --git a/remoting/host/win/evaluate_3d_display_mode.cc b/remoting/host/win/evaluate_3d_display_mode.cc index 1dbee05a..6f04bf9 100644 --- a/remoting/host/win/evaluate_3d_display_mode.cc +++ b/remoting/host/win/evaluate_3d_display_mode.cc
@@ -17,9 +17,9 @@ #include "base/scoped_native_library.h" #include "base/strings/string_util.h" #include "base/win/windows_version.h" +#include "remoting/host/base/host_exit_codes.h" +#include "remoting/host/base/switches.h" #include "remoting/host/evaluate_capability.h" -#include "remoting/host/host_exit_codes.h" -#include "remoting/host/switches.h" namespace remoting {
diff --git a/remoting/host/win/evaluate_d3d.cc b/remoting/host/win/evaluate_d3d.cc index 1b1618b2..d4ef3fb2 100644 --- a/remoting/host/win/evaluate_d3d.cc +++ b/remoting/host/win/evaluate_d3d.cc
@@ -11,9 +11,9 @@ #include "base/logging.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" +#include "remoting/host/base/host_exit_codes.h" +#include "remoting/host/base/switches.h" #include "remoting/host/evaluate_capability.h" -#include "remoting/host/host_exit_codes.h" -#include "remoting/host/switches.h" #include "remoting/host/win/evaluate_3d_display_mode.h" #include "third_party/webrtc/modules/desktop_capture/win/dxgi_duplicator_controller.h" #include "third_party/webrtc/modules/desktop_capture/win/screen_capturer_win_directx.h"
diff --git a/remoting/host/win/host_service.cc b/remoting/host/win/host_service.cc index a1ea879..40fe262 100644 --- a/remoting/host/win/host_service.cc +++ b/remoting/host/win/host_service.cc
@@ -26,11 +26,11 @@ #include "base/win/scoped_com_initializer.h" #include "remoting/base/auto_thread.h" #include "remoting/base/cpu_utils.h" +#include "remoting/base/logging.h" #include "remoting/base/scoped_sc_handle_win.h" +#include "remoting/host/base/host_exit_codes.h" #include "remoting/host/branding.h" #include "remoting/host/daemon_process.h" -#include "remoting/host/host_exit_codes.h" -#include "remoting/host/logging.h" #include "remoting/host/win/com_security.h" #include "remoting/host/win/core_resource.h" #include "remoting/host/win/wts_terminal_observer.h"
diff --git a/remoting/host/win/launch_native_messaging_host_process.cc b/remoting/host/win/launch_native_messaging_host_process.cc index 2f63e4e..a52fded 100644 --- a/remoting/host/win/launch_native_messaging_host_process.cc +++ b/remoting/host/win/launch_native_messaging_host_process.cc
@@ -18,7 +18,7 @@ #include "base/strings/utf_string_conversions.h" #include "base/win/win_util.h" #include "ipc/ipc_channel.h" -#include "remoting/host/switches.h" +#include "remoting/host/base/switches.h" #include "remoting/host/win/security_descriptor.h" namespace {
diff --git a/remoting/host/win/rdp_client.cc b/remoting/host/win/rdp_client.cc index 9d476d58f..1a74212 100644 --- a/remoting/host/win/rdp_client.cc +++ b/remoting/host/win/rdp_client.cc
@@ -19,7 +19,7 @@ #include "net/base/ip_address.h" #include "net/base/ip_endpoint.h" #include "remoting/base/typed_buffer.h" -#include "remoting/host/screen_resolution.h" +#include "remoting/host/base/screen_resolution.h" #include "remoting/host/win/rdp_client_window.h" namespace remoting {
diff --git a/remoting/host/win/rdp_client_unittest.cc b/remoting/host/win/rdp_client_unittest.cc index b5d8c45..c2294688 100644 --- a/remoting/host/win/rdp_client_unittest.cc +++ b/remoting/host/win/rdp_client_unittest.cc
@@ -17,7 +17,7 @@ #include "base/win/atl.h" #include "base/win/scoped_com_initializer.h" #include "remoting/base/auto_thread_task_runner.h" -#include "remoting/host/screen_resolution.h" +#include "remoting/host/base/screen_resolution.h" #include "remoting/host/win/wts_terminal_monitor.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/remoting/host/win/rdp_client_window.h b/remoting/host/win/rdp_client_window.h index 09707ae..684ea0cc 100644 --- a/remoting/host/win/rdp_client_window.h +++ b/remoting/host/win/rdp_client_window.h
@@ -18,7 +18,7 @@ #include "base/timer/timer.h" #include "base/win/atl.h" #include "net/base/ip_endpoint.h" -#include "remoting/host/screen_resolution.h" +#include "remoting/host/base/screen_resolution.h" // The following header was generated by Visual Studio. We had to check it in // due to a bug in VS2013. See crbug.com/318952 for details. #include "remoting/host/win/com_imported_mstscax.h"
diff --git a/remoting/host/win/rdp_desktop_session.cc b/remoting/host/win/rdp_desktop_session.cc index 6b5e79f..88b3acb6 100644 --- a/remoting/host/win/rdp_desktop_session.cc +++ b/remoting/host/win/rdp_desktop_session.cc
@@ -8,7 +8,7 @@ #include "base/strings/utf_string_conversions.h" #include "remoting/base/auto_thread_task_runner.h" -#include "remoting/host/screen_resolution.h" +#include "remoting/host/base/screen_resolution.h" #include "remoting/host/win/chromoting_module.h" #include "third_party/webrtc/modules/desktop_capture/desktop_geometry.h"
diff --git a/remoting/host/win/session_desktop_environment.cc b/remoting/host/win/session_desktop_environment.cc index c39ec30..3061f02 100644 --- a/remoting/host/win/session_desktop_environment.cc +++ b/remoting/host/win/session_desktop_environment.cc
@@ -11,8 +11,8 @@ #include "base/task/single_thread_task_runner.h" #include "remoting/host/action_executor.h" #include "remoting/host/audio_capturer.h" +#include "remoting/host/base/screen_controls.h" #include "remoting/host/input_injector.h" -#include "remoting/host/screen_controls.h" #include "remoting/host/win/session_action_executor.h" #include "remoting/host/win/session_input_injector.h" #include "third_party/webrtc/modules/desktop_capture/desktop_capturer.h"
diff --git a/remoting/host/win/unprivileged_process_delegate.cc b/remoting/host/win/unprivileged_process_delegate.cc index e0b3eab..3fd6c41 100644 --- a/remoting/host/win/unprivileged_process_delegate.cc +++ b/remoting/host/win/unprivileged_process_delegate.cc
@@ -32,7 +32,7 @@ #include "mojo/public/cpp/platform/platform_channel.h" #include "mojo/public/cpp/system/invitation.h" #include "remoting/base/typed_buffer.h" -#include "remoting/host/switches.h" +#include "remoting/host/base/switches.h" #include "remoting/host/win/launch_process_with_token.h" #include "remoting/host/win/security_descriptor.h" #include "remoting/host/win/window_station_and_desktop.h"
diff --git a/remoting/host/win/worker_process_launcher.cc b/remoting/host/win/worker_process_launcher.cc index 0d9882f..e1622cb7 100644 --- a/remoting/host/win/worker_process_launcher.cc +++ b/remoting/host/win/worker_process_launcher.cc
@@ -14,8 +14,8 @@ #include "base/time/time.h" #include "ipc/ipc_message.h" #include "mojo/public/cpp/bindings/scoped_interface_endpoint_handle.h" +#include "remoting/host/base/host_exit_codes.h" #include "remoting/host/chromoting_messages.h" -#include "remoting/host/host_exit_codes.h" #include "remoting/host/worker_process_ipc_delegate.h" using base::win::ScopedHandle;
diff --git a/remoting/host/win/worker_process_launcher_unittest.cc b/remoting/host/win/worker_process_launcher_unittest.cc index d293ff0a..f9843f2 100644 --- a/remoting/host/win/worker_process_launcher_unittest.cc +++ b/remoting/host/win/worker_process_launcher_unittest.cc
@@ -24,8 +24,8 @@ #include "mojo/public/cpp/bindings/scoped_interface_endpoint_handle.h" #include "mojo/public/cpp/system/message_pipe.h" #include "remoting/base/auto_thread_task_runner.h" +#include "remoting/host/base/host_exit_codes.h" #include "remoting/host/chromoting_messages.h" -#include "remoting/host/host_exit_codes.h" #include "remoting/host/win/launch_process_with_token.h" #include "remoting/host/worker_process_ipc_delegate.h" #include "testing/gmock/include/gmock/gmock.h"
diff --git a/remoting/host/win/wts_session_process_delegate.cc b/remoting/host/win/wts_session_process_delegate.cc index 5560583a..9175a87 100644 --- a/remoting/host/win/wts_session_process_delegate.cc +++ b/remoting/host/win/wts_session_process_delegate.cc
@@ -33,9 +33,9 @@ #include "mojo/public/cpp/platform/platform_channel_server_endpoint.h" #include "mojo/public/cpp/platform/platform_handle.h" #include "mojo/public/cpp/system/invitation.h" +#include "remoting/host/base/switches.h" #include "remoting/host/host_main.h" #include "remoting/host/ipc_constants.h" -#include "remoting/host/switches.h" #include "remoting/host/win/launch_process_with_token.h" #include "remoting/host/win/security_descriptor.h" #include "remoting/host/win/worker_process_launcher.h"
diff --git a/remoting/host/xsession_chooser_linux.cc b/remoting/host/xsession_chooser_linux.cc index dc3ac8e..b9ff295 100644 --- a/remoting/host/xsession_chooser_linux.cc +++ b/remoting/host/xsession_chooser_linux.cc
@@ -34,8 +34,8 @@ #include "base/run_loop.h" #include "base/strings/string_util.h" #include "base/task/single_thread_task_executor.h" +#include "remoting/base/logging.h" #include "remoting/base/string_resources.h" -#include "remoting/host/logging.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/icu/source/common/unicode/unistr.h" #include "third_party/icu/source/i18n/unicode/coll.h"
diff --git a/remoting/protocol/BUILD.gn b/remoting/protocol/BUILD.gn index eca2c24..858bae21 100644 --- a/remoting/protocol/BUILD.gn +++ b/remoting/protocol/BUILD.gn
@@ -233,6 +233,7 @@ "//net", "//remoting/base", "//remoting/base:authorization", + "//remoting/base:logging", "//remoting/codec:decoder", "//remoting/proto/remoting/v1:network_traversal_proto", "//remoting/signaling",
diff --git a/remoting/protocol/webrtc_transport.cc b/remoting/protocol/webrtc_transport.cc index 9904270f..cc31873 100644 --- a/remoting/protocol/webrtc_transport.cc +++ b/remoting/protocol/webrtc_transport.cc
@@ -872,7 +872,7 @@ return; if (!success) { - LOG(ERROR) << "Failed to set local description: " << error; + LOG(ERROR) << "Failed to set remote description: " << error; Close(CHANNEL_CONNECTION_ERROR); return; }
diff --git a/remoting/signaling/BUILD.gn b/remoting/signaling/BUILD.gn index 9df18608..511bb29 100644 --- a/remoting/signaling/BUILD.gn +++ b/remoting/signaling/BUILD.gn
@@ -64,6 +64,7 @@ "//net", "//remoting/base", "//remoting/base:authorization", + "//remoting/base:logging", "//remoting/proto/ftl/v1:ftl_messages", "//services/network/public/cpp:cpp", ]
diff --git a/remoting/test/BUILD.gn b/remoting/test/BUILD.gn index 8208034..65cf5d10 100644 --- a/remoting/test/BUILD.gn +++ b/remoting/test/BUILD.gn
@@ -49,6 +49,7 @@ "//mojo/core/embedder", "//net", "//remoting/base", + "//remoting/base:logging", "//remoting/client", "//remoting/client/audio", "//remoting/codec:decoder", @@ -104,6 +105,7 @@ "//mojo/core/embedder", "//remoting/base", "//remoting/base:authorization", + "//remoting/base:logging", "//remoting/host", "//remoting/host:resources", "//remoting/host/it2me:common", @@ -171,7 +173,7 @@ deps = [ "//base", - "//remoting/host:base", + "//remoting/host/base", ] } } @@ -189,6 +191,7 @@ "//mojo/core/embedder", "//remoting/base", "//remoting/base:authorization", + "//remoting/base:logging", "//remoting/proto/ftl/v1:ftl_messages", "//remoting/signaling", "//services/network:network_service", @@ -209,6 +212,7 @@ "//mojo/core/embedder", "//remoting/base", "//remoting/base:authorization", + "//remoting/base:logging", "//remoting/signaling", "//services/network:network_service", ]
diff --git a/remoting/test/capability_test_stub_main.cc b/remoting/test/capability_test_stub_main.cc index a49393e..b112765 100644 --- a/remoting/test/capability_test_stub_main.cc +++ b/remoting/test/capability_test_stub_main.cc
@@ -6,7 +6,7 @@ #include "base/command_line.h" #include "base/notreached.h" -#include "remoting/host/host_exit_codes.h" +#include "remoting/host/base/host_exit_codes.h" namespace {
diff --git a/remoting/tools/BUILD.gn b/remoting/tools/BUILD.gn index 6d7c1ea..9bab9a7 100644 --- a/remoting/tools/BUILD.gn +++ b/remoting/tools/BUILD.gn
@@ -27,8 +27,9 @@ deps = [ "//base", "//build/win:default_exe_manifest", + "//remoting/base:logging", "//remoting/host", - "//remoting/host:base", + "//remoting/host/base", ] libs = [
diff --git a/remoting/tools/breakpad_tester_win.cc b/remoting/tools/breakpad_tester_win.cc index 273cf6c..9cd7118 100644 --- a/remoting/tools/breakpad_tester_win.cc +++ b/remoting/tools/breakpad_tester_win.cc
@@ -8,7 +8,7 @@ #include "base/at_exit.h" #include "base/command_line.h" #include "base/win/scoped_handle.h" -#include "remoting/host/logging.h" +#include "remoting/base/logging.h" namespace {
diff --git a/sandbox/policy/win/sandbox_win_unittest.cc b/sandbox/policy/win/sandbox_win_unittest.cc index 8d32db1a..2fd138b 100644 --- a/sandbox/policy/win/sandbox_win_unittest.cc +++ b/sandbox/policy/win/sandbox_win_unittest.cc
@@ -43,11 +43,6 @@ namespace policy { namespace { -constexpr char kAppContainerId[] = "SandboxWinTest"; -constexpr wchar_t kPackageSid[] = - L"S-1-15-2-1505217662-1870513255-555216753-1864132992-3842232122-" - L"1807018979-869957911"; - class TestTargetPolicy : public TargetPolicy { public: void AddRef() override {} @@ -199,9 +194,14 @@ &command_line); } + std::string appcontainer_id = + testing::UnitTest::GetInstance()->current_test_info()->test_case_name(); + appcontainer_id += "."; + appcontainer_id += + testing::UnitTest::GetInstance()->current_test_info()->name(); TestTargetPolicy policy; ResultCode result = SandboxWin::AddAppContainerProfileToPolicy( - command_line, sandbox_type, kAppContainerId, &policy); + command_line, sandbox_type, appcontainer_id, &policy); if (result == SBOX_ALL_OK) *profile = policy.GetAppContainerBase(); return result; @@ -246,8 +246,9 @@ command_line, false, sandbox::mojom::Sandbox::kGpu, &profile); ASSERT_EQ(SBOX_ALL_OK, result); ASSERT_NE(nullptr, profile); - absl::optional<base::win::Sid> package_sid = - base::win::Sid::FromSddlString(kPackageSid); + absl::optional<base::win::Sid> package_sid = base::win::Sid::FromSddlString( + L"S-1-15-2-2402834154-1919024995-1520873375-1190013510-771931769-" + L"834570634-3212001585"); ASSERT_TRUE(package_sid); EXPECT_EQ(package_sid, profile->GetPackageSid()); EXPECT_TRUE(profile->GetEnableLowPrivilegeAppContainer());
diff --git a/services/network/tcp_socket_unittest.cc b/services/network/tcp_socket_unittest.cc index 94940ec3..15b5872 100644 --- a/services/network/tcp_socket_unittest.cc +++ b/services/network/tcp_socket_unittest.cc
@@ -583,11 +583,8 @@ // On some macOS kernels, send() on a closing TCP socket can return // EPROTOTYPE, which is unknown to the net stack and gets mapped to // net::ERR_FAILED. - // This behavior is known to exist as late as 10.12. Whether it exists after - // that is unknown. // See https://crbug.com/1034991 - if (base::mac::IsAtMostOS10_12()) - result_ok |= result == net::ERR_FAILED; + result_ok |= result == net::ERR_FAILED; #endif EXPECT_TRUE(result_ok) << "actual result: " << result; }
diff --git a/services/viz/public/cpp/compositing/transferable_resource_mojom_traits.cc b/services/viz/public/cpp/compositing/transferable_resource_mojom_traits.cc index 53cbd1a..0235fef 100644 --- a/services/viz/public/cpp/compositing/transferable_resource_mojom_traits.cc +++ b/services/viz/public/cpp/compositing/transferable_resource_mojom_traits.cc
@@ -32,10 +32,15 @@ out->read_lock_fences_enabled = data.read_lock_fences_enabled(); out->is_software = data.is_software(); out->is_overlay_candidate = data.is_overlay_candidate(); + #if defined(OS_ANDROID) out->is_backed_by_surface_texture = data.is_backed_by_surface_texture(); +#endif + +#if defined(OS_ANDROID) || defined(OS_WIN) out->wants_promotion_hint = data.wants_promotion_hint(); #endif + return true; }
diff --git a/services/viz/public/cpp/compositing/transferable_resource_mojom_traits.h b/services/viz/public/cpp/compositing/transferable_resource_mojom_traits.h index 4f5f60a..057dedb 100644 --- a/services/viz/public/cpp/compositing/transferable_resource_mojom_traits.h +++ b/services/viz/public/cpp/compositing/transferable_resource_mojom_traits.h
@@ -67,7 +67,7 @@ } static bool wants_promotion_hint(const viz::TransferableResource& resource) { -#if defined(OS_ANDROID) +#if defined(OS_ANDROID) || defined(OS_WIN) // TransferableResource has this in an #ifdef, but mojo doesn't let us. // TODO(https://crbug.com/671901) return resource.wants_promotion_hint;
diff --git a/storage/browser/blob/blob_registry_impl.cc b/storage/browser/blob/blob_registry_impl.cc index a0dce24..f62b25a 100644 --- a/storage/browser/blob/blob_registry_impl.cc +++ b/storage/browser/blob/blob_registry_impl.cc
@@ -645,9 +645,10 @@ mojo::PendingAssociatedReceiver<blink::mojom::BlobURLStore> receiver) { Delegate* delegate = receivers_.current_context().get(); DCHECK(delegate); - if (!origin.opaque() && !delegate->CanCommitURL(origin.GetURL())) { + if (!origin.opaque() && !delegate->CanAccessDataForOrigin(origin)) { mojo::ReportBadMessage( - "Non committable origin passed to BlobRegistryImpl::URLStoreForOrigin"); + "Cannot access data for origin passed to " + "BlobRegistryImpl::URLStoreForOrigin"); } auto self_owned_associated_receiver = mojo::MakeSelfOwnedAssociatedReceiver( std::make_unique<BlobURLStoreImpl>(origin, url_registry_),
diff --git a/storage/browser/blob/blob_registry_impl.h b/storage/browser/blob/blob_registry_impl.h index 09631b09..35ae9b6 100644 --- a/storage/browser/blob/blob_registry_impl.h +++ b/storage/browser/blob/blob_registry_impl.h
@@ -14,6 +14,7 @@ #include "storage/browser/blob/blob_url_registry.h" #include "storage/browser/file_system/file_system_context.h" #include "third_party/blink/public/mojom/blob/blob_registry.mojom.h" +#include "url/origin.h" namespace storage { @@ -32,7 +33,7 @@ virtual ~Delegate() {} virtual bool CanReadFile(const base::FilePath& file) = 0; virtual bool CanReadFileSystemFile(const FileSystemURL& url) = 0; - virtual bool CanCommitURL(const GURL& url) = 0; + virtual bool CanAccessDataForOrigin(const url::Origin& origin) = 0; }; BlobRegistryImpl(base::WeakPtr<BlobStorageContext> context,
diff --git a/storage/browser/file_system/copy_or_move_operation_delegate.cc b/storage/browser/file_system/copy_or_move_operation_delegate.cc index 8b3bc2d..b3d3763 100644 --- a/storage/browser/file_system/copy_or_move_operation_delegate.cc +++ b/storage/browser/file_system/copy_or_move_operation_delegate.cc
@@ -80,6 +80,19 @@ } } + if (options_.Has(FileSystemOperation::CopyOrMoveOption:: + kRemovePartiallyCopiedFilesOnError) && + error != base::File::FILE_OK && + error != base::File::FILE_ERROR_NOT_A_FILE) { + // On error, remove the destination file. + operation_runner_->Remove( + dest_url_, /*recursive=*/false, + base::BindOnce(&CopyOrMoveImpl::DidRemoveDestOnError, + weak_factory_.GetWeakPtr(), error, + std::move(callback))); + return; + } + // The callback should be called in case of copy or error. The callback is // null if the operation type is OPERATION_MOVE (implemented as copy + // delete) and no error occurred. @@ -124,6 +137,22 @@ std::move(callback).Run(error); } + void DidRemoveDestOnError( + base::File::Error prior_error, + CopyOrMoveOperationDelegate::StatusCallback callback, + base::File::Error error) { + if (error != base::File::FILE_OK) { + VLOG(1) << "Error removing destination file after copy error or " + "cancellation: " + << error; + } + // The callback is null if the operation type is OPERATION_MOVE (implemented + // as copy + delete) and no error occurred. + if (!callback.is_null()) { + std::move(callback).Run(prior_error); + } + } + const raw_ptr<FileSystemOperationRunner> operation_runner_; const CopyOrMoveOperationDelegate::OperationType operation_type_; const FileSystemURL src_url_; @@ -132,6 +161,7 @@ private: const FileSystemOperation::CopyOrMoveProgressCallback progress_callback_; + base::WeakPtrFactory<CopyOrMoveImpl> weak_factory_{this}; }; namespace {
diff --git a/storage/browser/file_system/file_system_operation.h b/storage/browser/file_system/file_system_operation.h index 192fa55..5dc9c63 100644 --- a/storage/browser/file_system/file_system_operation.h +++ b/storage/browser/file_system/file_system_operation.h
@@ -262,8 +262,20 @@ // implementation. kForceCrossFilesystem, + // Removes copied files that result in an error (potentially a + // cancellation), as these files are potentially partial/corrupted. + // Directories are not removed recursively, as it can lead to data loss + // (e.g. user changing the content of the destination folder during a copy + // or a move). Therefore, all successfully copied entries are preserved. + // The removal is best-effort: depending on the origin of the error, + // removing the destination file can fail. + // This option can impact cross-filesystem moves since they are implemented + // as copy + delete (only the copy step is impacted), but not + // same-filesystem moves where the file paths are just renamed. + kRemovePartiallyCopiedFilesOnError, + kFirst = kPreserveLastModified, - kLast = kForceCrossFilesystem + kLast = kRemovePartiallyCopiedFilesOnError }; using CopyOrMoveOptionSet = base::EnumSet<CopyOrMoveOption,
diff --git a/storage/browser/test/mock_blob_registry_delegate.cc b/storage/browser/test/mock_blob_registry_delegate.cc index 54489261..d0316c8f 100644 --- a/storage/browser/test/mock_blob_registry_delegate.cc +++ b/storage/browser/test/mock_blob_registry_delegate.cc
@@ -12,8 +12,9 @@ bool MockBlobRegistryDelegate::CanReadFileSystemFile(const FileSystemURL& url) { return can_read_file_system_file_result; } -bool MockBlobRegistryDelegate::CanCommitURL(const GURL& url) { - return can_commit_url_result; +bool MockBlobRegistryDelegate::CanAccessDataForOrigin( + const url::Origin& origin) { + return can_access_data_for_origin; } } // namespace storage
diff --git a/storage/browser/test/mock_blob_registry_delegate.h b/storage/browser/test/mock_blob_registry_delegate.h index db68558fe..c8ec096 100644 --- a/storage/browser/test/mock_blob_registry_delegate.h +++ b/storage/browser/test/mock_blob_registry_delegate.h
@@ -16,11 +16,11 @@ bool CanReadFile(const base::FilePath& file) override; bool CanReadFileSystemFile(const FileSystemURL& url) override; - bool CanCommitURL(const GURL& url) override; + bool CanAccessDataForOrigin(const url::Origin& origin) override; bool can_read_file_result = true; bool can_read_file_system_file_result = true; - bool can_commit_url_result = true; + bool can_access_data_for_origin = true; }; } // namespace storage
diff --git a/testing/buildbot/chromium.clang.json b/testing/buildbot/chromium.clang.json index 8c8e30a0..c3578d7 100644 --- a/testing/buildbot/chromium.clang.json +++ b/testing/buildbot/chromium.clang.json
@@ -9638,8 +9638,7 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/fuchsia.net_unittests.filter", - "--use-run", - "--without-network" + "--use-run" ], "merge": { "args": [], @@ -11257,8 +11256,7 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/fuchsia.net_unittests.filter", - "--use-run", - "--without-network" + "--use-run" ], "merge": { "args": [],
diff --git a/testing/buildbot/chromium.fyi.json b/testing/buildbot/chromium.fyi.json index c6c1a09..b59338c 100644 --- a/testing/buildbot/chromium.fyi.json +++ b/testing/buildbot/chromium.fyi.json
@@ -19019,7 +19019,6 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/fuchsia.net_unittests.filter", - "--without-network", "--ram-size-mb=16384", "--code-coverage", "--code-coverage-dir=${ISOLATED_OUTDIR}" @@ -20220,8 +20219,7 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/fuchsia.net_unittests.filter", - "--use-run", - "--without-network" + "--use-run" ], "merge": { "args": [], @@ -21497,7 +21495,6 @@ "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/fuchsia.net_unittests.filter", "--use-run", - "--without-network", "--device=aemu" ], "merge": { @@ -23299,8 +23296,7 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/fuchsia.net_unittests.filter", - "--use-run", - "--without-network" + "--use-run" ], "merge": { "args": [],
diff --git a/testing/buildbot/chromium.linux.json b/testing/buildbot/chromium.linux.json index 9a4f25a..8198209 100644 --- a/testing/buildbot/chromium.linux.json +++ b/testing/buildbot/chromium.linux.json
@@ -2604,8 +2604,7 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/fuchsia.net_unittests.filter", - "--use-run", - "--without-network" + "--use-run" ], "merge": { "args": [], @@ -3889,8 +3888,7 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/fuchsia.net_unittests.filter", - "--use-run", - "--without-network" + "--use-run" ], "merge": { "args": [],
diff --git a/testing/buildbot/chromium.mac.json b/testing/buildbot/chromium.mac.json index 891384b..8b069831 100644 --- a/testing/buildbot/chromium.mac.json +++ b/testing/buildbot/chromium.mac.json
@@ -12248,6 +12248,1697 @@ } ] }, + "Mac11 Tests (dbg)": { + "gtest_tests": [ + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "absl_hardening_tests", + "test_id_prefix": "ninja://third_party/abseil-cpp:absl_hardening_tests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "accessibility_unittests", + "test_id_prefix": "ninja://ui/accessibility:accessibility_unittests/" + }, + { + "args": [ + "angle_unittests" + ], + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_isolated_script_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "angle_unittests", + "test_id_prefix": "ninja://third_party/angle/src/tests:angle_unittests/", + "use_isolated_scripts_api": true + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "app_shell_unittests", + "test_id_prefix": "ninja://extensions/shell:app_shell_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "base_unittests", + "test_id_prefix": "ninja://base:base_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "blink_common_unittests", + "test_id_prefix": "ninja://third_party/blink/common:blink_common_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "blink_fuzzer_unittests", + "test_id_prefix": "ninja://third_party/blink/renderer/platform:blink_fuzzer_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "blink_heap_unittests", + "test_id_prefix": "ninja://third_party/blink/renderer/platform/heap:blink_heap_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "blink_platform_unittests", + "test_id_prefix": "ninja://third_party/blink/renderer/platform:blink_platform_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "name": "webkit_unit_tests", + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "blink_unittests", + "test_id_prefix": "ninja://third_party/blink/renderer/controller:blink_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "boringssl_crypto_tests", + "test_id_prefix": "ninja://third_party/boringssl:boringssl_crypto_tests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "boringssl_ssl_tests", + "test_id_prefix": "ninja://third_party/boringssl:boringssl_ssl_tests/" + }, + { + "args": [ + "--gtest_filter=-*UsingRealWebcam*" + ], + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "capture_unittests", + "test_id_prefix": "ninja://media/capture:capture_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "cast_unittests", + "test_id_prefix": "ninja://media/cast:cast_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "cc_unittests", + "test_id_prefix": "ninja://cc:cc_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "chrome_app_unittests", + "test_id_prefix": "ninja://chrome/test:chrome_app_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "chromedriver_unittests", + "test_id_prefix": "ninja://chrome/test/chromedriver:chromedriver_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "color_unittests", + "test_id_prefix": "ninja://ui/color:color_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "components_browsertests", + "test_id_prefix": "ninja://components:components_browsertests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "components_unittests", + "test_id_prefix": "ninja://components:components_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", + "shards": 6 + }, + "test": "content_browsertests", + "test_id_prefix": "ninja://content/test:content_browsertests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "content_nocompile_tests", + "test_id_prefix": "ninja://content/test:content_nocompile_tests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "content_unittests", + "test_id_prefix": "ninja://content/test:content_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "crashpad_tests", + "test_id_prefix": "ninja://third_party/crashpad/crashpad:crashpad_tests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "cronet_tests", + "test_id_prefix": "ninja://components/cronet:cronet_tests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "cronet_unittests", + "test_id_prefix": "ninja://components/cronet:cronet_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "crypto_unittests", + "test_id_prefix": "ninja://crypto:crypto_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "device_unittests", + "test_id_prefix": "ninja://device:device_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "display_unittests", + "test_id_prefix": "ninja://ui/display:display_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "events_unittests", + "test_id_prefix": "ninja://ui/events:events_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "extensions_browsertests", + "test_id_prefix": "ninja://extensions:extensions_browsertests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "extensions_unittests", + "test_id_prefix": "ninja://extensions:extensions_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "filesystem_service_unittests", + "test_id_prefix": "ninja://components/services/filesystem:filesystem_service_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "gcm_unit_tests", + "test_id_prefix": "ninja://google_apis/gcm:gcm_unit_tests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "gfx_unittests", + "test_id_prefix": "ninja://ui/gfx:gfx_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "gin_unittests", + "test_id_prefix": "ninja://gin:gin_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "google_apis_unittests", + "test_id_prefix": "ninja://google_apis:google_apis_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "gpu_unittests", + "test_id_prefix": "ninja://gpu:gpu_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "gwp_asan_unittests", + "test_id_prefix": "ninja://components/gwp_asan:gwp_asan_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "headless_browsertests", + "test_id_prefix": "ninja://headless:headless_browsertests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "headless_unittests", + "test_id_prefix": "ninja://headless:headless_unittests/" + }, + { + "experiment_percentage": 100, + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", + "shards": 3 + }, + "test": "interactive_ui_tests", + "test_id_prefix": "ninja://chrome/test:interactive_ui_tests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "ipc_tests", + "test_id_prefix": "ninja://ipc:ipc_tests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "jingle_unittests", + "test_id_prefix": "ninja://jingle:jingle_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "latency_unittests", + "test_id_prefix": "ninja://ui/latency:latency_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "libjingle_xmpp_unittests", + "test_id_prefix": "ninja://third_party/libjingle_xmpp:libjingle_xmpp_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "liburlpattern_unittests", + "test_id_prefix": "ninja://third_party/liburlpattern:liburlpattern_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "media_unittests", + "test_id_prefix": "ninja://media:media_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "message_center_unittests", + "test_id_prefix": "ninja://ui/message_center:message_center_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "midi_unittests", + "test_id_prefix": "ninja://media/midi:midi_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "mojo_unittests", + "test_id_prefix": "ninja://mojo:mojo_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "nacl_loader_unittests", + "test_id_prefix": "ninja://components/nacl/loader:nacl_loader_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "native_theme_unittests", + "test_id_prefix": "ninja://ui/native_theme:native_theme_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "net_unittests", + "test_id_prefix": "ninja://net:net_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "openscreen_unittests", + "test_id_prefix": "ninja://chrome/browser/media/router:openscreen_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "pdf_unittests", + "test_id_prefix": "ninja://pdf:pdf_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "perfetto_unittests", + "test_id_prefix": "ninja://third_party/perfetto:perfetto_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "power_sampler_unittests", + "test_id_prefix": "ninja://tools/mac/power:power_sampler_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "ppapi_unittests", + "test_id_prefix": "ninja://ppapi:ppapi_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "printing_unittests", + "test_id_prefix": "ninja://printing:printing_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "remoting_unittests", + "test_id_prefix": "ninja://remoting:remoting_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "sandbox_mac_unittests", + "test_id_prefix": "ninja://sandbox/mac:sandbox_mac_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "service_manager_unittests", + "test_id_prefix": "ninja://services/service_manager/tests:service_manager_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "services_unittests", + "test_id_prefix": "ninja://services:services_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "shell_dialogs_unittests", + "test_id_prefix": "ninja://ui/shell_dialogs:shell_dialogs_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "skia_unittests", + "test_id_prefix": "ninja://skia:skia_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "snapshot_unittests", + "test_id_prefix": "ninja://ui/snapshot:snapshot_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "sql_unittests", + "test_id_prefix": "ninja://sql:sql_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "storage_unittests", + "test_id_prefix": "ninja://storage:storage_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "sync_integration_tests", + "test_id_prefix": "ninja://chrome/test:sync_integration_tests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "ui_base_unittests", + "test_id_prefix": "ninja://ui/base:ui_base_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "ui_touch_selection_unittests", + "test_id_prefix": "ninja://ui/touch_selection:ui_touch_selection_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", + "shards": 2 + }, + "test": "unit_tests", + "test_id_prefix": "ninja://chrome/test:unit_tests/" + }, + { + "args": [ + "--test-launcher-timeout=90000", + "--ui-test-action-max-timeout=45000", + "--ui-test-action-timeout=40000" + ], + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "updater_tests", + "test_id_prefix": "ninja://chrome/updater:updater_tests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "url_unittests", + "test_id_prefix": "ninja://url:url_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "views_unittests", + "test_id_prefix": "ninja://ui/views:views_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "viz_unittests", + "test_id_prefix": "ninja://components/viz:viz_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "wtf_unittests", + "test_id_prefix": "ninja://third_party/blink/renderer/platform/wtf:wtf_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "name": "xr_browser_tests", + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "xr_browser_tests", + "test_id_prefix": "ninja://chrome/test:xr_browser_tests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "zlib_unittests", + "test_id_prefix": "ninja://third_party/zlib:zlib_unittests/" + } + ], + "isolated_scripts": [ + { + "isolate_name": "blink_python_tests", + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_isolated_script_merge.py" + }, + "name": "blink_python_tests", + "resultdb": { + "enable": true + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test_id_prefix": "ninja://:blink_python_tests/" + }, + { + "args": [ + "--num-retries=3", + "--debug" + ], + "experiment_percentage": 100, + "isolate_name": "blink_web_tests", + "merge": { + "args": [ + "--verbose" + ], + "script": "//third_party/blink/tools/merge_web_test_results.py" + }, + "name": "blink_web_tests", + "resultdb": { + "enable": true + }, + "results_handler": "layout tests", + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", + "shards": 40 + }, + "test_id_prefix": "ninja://:blink_web_tests/" + }, + { + "isolate_name": "content_shell_crash_test", + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_isolated_script_merge.py" + }, + "name": "content_shell_crash_test", + "resultdb": { + "enable": true, + "result_format": "single" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test_id_prefix": "ninja://content/shell:content_shell_crash_test/" + }, + { + "isolate_name": "flatbuffers_unittests", + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_isolated_script_merge.py" + }, + "name": "flatbuffers_unittests", + "resultdb": { + "enable": true, + "result_format": "single" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test_id_prefix": "ninja://third_party/flatbuffers:flatbuffers_unittests/" + }, + { + "isolate_name": "grit_python_unittests", + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_isolated_script_merge.py" + }, + "name": "grit_python_unittests", + "resultdb": { + "enable": true + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test_id_prefix": "ninja://tools/grit:grit_python_unittests/" + }, + { + "args": [ + "--pageset-repeat=1", + "--test-shard-map-filename=smoke_test_benchmark_shard_map.json", + "--browser=debug" + ], + "isolate_name": "performance_test_suite", + "merge": { + "args": [ + "--smoke-test-mode" + ], + "script": "//tools/perf/process_perf_results.py" + }, + "name": "performance_test_suite", + "resultdb": { + "enable": true + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "hard_timeout": 960, + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", + "shards": 2 + }, + "test_id_prefix": "ninja://chrome/test:performance_test_suite/" + }, + { + "isolate_name": "telemetry_gpu_unittests", + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_isolated_script_merge.py" + }, + "name": "telemetry_gpu_unittests", + "resultdb": { + "enable": true + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "idempotent": false, + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test_id_prefix": "ninja://chrome/test:telemetry_gpu_unittests/" + }, + { + "args": [ + "--jobs=1", + "--extra-browser-args=--disable-gpu" + ], + "isolate_name": "telemetry_unittests", + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_isolated_script_merge.py" + }, + "name": "telemetry_unittests", + "resultdb": { + "enable": true + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "idempotent": false, + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", + "shards": 8 + }, + "test_id_prefix": "ninja://chrome/test:telemetry_unittests/" + }, + { + "args": [ + "--gtest-benchmark-name=views_perftests" + ], + "isolate_name": "views_perftests", + "merge": { + "args": [ + "--smoke-test-mode" + ], + "script": "//tools/perf/process_perf_results.py" + }, + "name": "views_perftests", + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-11|Mac-10.16" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test_id_prefix": "ninja://ui/views:views_perftests/" + } + ] + }, "ios-device": { "additional_compile_targets": [ "all"
diff --git a/testing/buildbot/test_suite_exceptions.pyl b/testing/buildbot/test_suite_exceptions.pyl index ae7b3d8..f03b56f 100644 --- a/testing/buildbot/test_suite_exceptions.pyl +++ b/testing/buildbot/test_suite_exceptions.pyl
@@ -274,6 +274,15 @@ 'shards': 40, }, }, + 'Mac11 Tests (dbg)': { + 'experiment_percentage': 100, + 'args': [ + '--debug', + ], + 'swarming': { + 'shards': 40, + }, + }, 'ToTFuchsia x64': { 'args': [ '--platform=fuchsia', @@ -522,6 +531,7 @@ 'Mac10.13 Tests', # https://crbug.com/1042757 'Mac10.15 Tests', # https://crbug.com/1042757 'Mac10.15 Tests (dbg)', # https://crbug.com/1201386 + 'Mac11 Tests (dbg)', # https://crbug.com/1201386 'mac-code-coverage', # https://crbug.com/1201386 'Linux TSan Tests', # https://crbug.com/368525 'Win10 Tests x64 (dbg)', @@ -636,6 +646,21 @@ 'Mac11 Tests': { 'ci_only': True, }, + 'Mac11 Tests (dbg)': { + # crbug.com/1042757 + 'swarming': { + 'dimension_sets': [ + { + # These shards are liable to time out when running on macmini7,1. + 'cores': '8|12', + } + ], + }, + # crbug.com/1196416 + 'args': [ + '--test-launcher-filter-file=../../testing/buildbot/filters/mac.mac-rel.browser_tests.filter', + ], + }, 'ToTWin(dbg)': { 'swarming': { 'shards': 20, @@ -1817,6 +1842,9 @@ 'Mac10.15 Tests (dbg)': { # https://crbug.com/1265051 'experiment_percentage': 100, }, + 'Mac11 Tests (dbg)': { # https://crbug.com/1265051 + 'experiment_percentage': 100, + }, 'ToTLinuxTSan': { # These are slow on the TSan bots for some reason, crbug.com/794372 'swarming': { @@ -2384,6 +2412,11 @@ '--browser=debug', ], }, + 'Mac11 Tests (dbg)': { + 'args': [ + '--browser=debug', + ], + }, 'Win10 Tests x64 (dbg)': { 'args': [ '--browser=debug_x64', @@ -2891,6 +2924,7 @@ # TODO crbug.com/1277277 'Mac11 Tests', 'Mac10.15 Tests (dbg)', + 'Mac11 Tests (dbg)', 'Linux - Future (dbg)', # client.v8.chromium 'Win10 Tests x64', 'Win10 Tests x64 (dbg)', @@ -2966,6 +3000,11 @@ 'shards': 2, }, }, + 'Mac11 Tests (dbg)': { + 'swarming': { + 'shards': 2, + }, + }, 'ToTLinuxASan': { 'swarming': { 'shards': 2,
diff --git a/testing/buildbot/test_suites.pyl b/testing/buildbot/test_suites.pyl index 57bedbd..32f658b 100644 --- a/testing/buildbot/test_suites.pyl +++ b/testing/buildbot/test_suites.pyl
@@ -1709,7 +1709,6 @@ '--test-launcher-filter-file=../../testing/buildbot/filters/fuchsia.net_unittests.filter', # TODO(crbug.com/1254563): Fix net_unittests to work under run-test-component. '--use-run', - '--without-network', ], }, 'ozone_gl_unittests': {
diff --git a/testing/buildbot/waterfalls.pyl b/testing/buildbot/waterfalls.pyl index 42299b0f..95e5825 100644 --- a/testing/buildbot/waterfalls.pyl +++ b/testing/buildbot/waterfalls.pyl
@@ -5057,6 +5057,15 @@ 'isolated_scripts': 'chromium_mac_rel_isolated_scripts', }, }, + 'Mac11 Tests (dbg)': { + 'mixins': [ + 'mac_11_x64', + ], + 'test_suites': { + 'gtest_tests': 'chromium_mac_gtests', + 'isolated_scripts': 'chromium_dbg_isolated_scripts', + }, + }, 'ios-device': { 'additional_compile_targets': [ 'all',
diff --git a/testing/test.gni b/testing/test.gni index 5d31c31..aceed03 100644 --- a/testing/test.gni +++ b/testing/test.gni
@@ -50,8 +50,6 @@ # use_xvfb: (optional) whether to run the executable under Xvfb. # use_raw_android_executable: Use executable() rather than android_apk(). # use_native_activity: Test implements ANativeActivity_onCreate(). -# use_cfv2: (Fuchsia, optional): build the test as a framework v2 component; -# see https://fuchsia.dev/fuchsia-src/concepts/components/v2 for details. # is_xctest: (iOS, optional) whether to build the executable as XCTest. # Similar to the GN arg 'enable_run_ios_unittests_with_xctest' but # for build targets. @@ -328,58 +326,31 @@ _pkg_target = "${_output_name}_pkg" _exec_target = "${_output_name}__exec" - if (defined(invoker.use_cfv2) && invoker.use_cfv2) { - # Generate a CML fragment that provides the program name. - _test_program_fragment_target = "${target_name}_program-fragment" - _test_program_fragment = - "${target_out_dir}/${target_name}_program.test-cml" - _program_name = get_label_info(":${_exec_target}", "name") - generated_file(_test_program_fragment_target) { - contents = "{ program: { binary: \"${_program_name}\",},}" - outputs = [ _test_program_fragment ] - } - - # Collate the complete set of elements to include in the test component's - # manifest. - _manifest_fragments = [ - "//build/config/fuchsia/test/minimum_capabilities.test-cml", - "//build/config/fuchsia/test/elf_test_runner.shard.test-cml", - _test_program_fragment, - ] - - _test_component_manifest = "${target_out_dir}/${target_name}.cml" - _merged_manifest_name = "${_output_name}.cml" - } else { - # Generate a CMX fragment that provides the program name. - _test_program_fragment_target = "${target_name}_program-fragment" - _test_program_fragment = - "${target_out_dir}/${target_name}_program.test-cmx" - _program_name = get_label_info(":${_exec_target}", "name") - generated_file(_test_program_fragment_target) { - contents = "{ \"program\": { \"binary\": \"${_program_name}\"}}" - outputs = [ _test_program_fragment ] - } - - # Collate the complete set of elements to include in the test component's - # manifest. - _manifest_fragments = [ - "//build/config/fuchsia/test/minimum_capabilities.test-cmx", - _test_program_fragment, - ] - - _test_component_manifest = "${target_out_dir}/${target_name}.cmx" - _merged_manifest_name = "${_output_name}.cmx" + # Generate a CMX fragment that provides the program name. + _test_program_fragment_target = "${target_name}_program-fragment" + _test_program_fragment = "${target_out_dir}/${target_name}_program.test-cmx" + _program_name = get_label_info(":${_exec_target}", "name") + generated_file(_test_program_fragment_target) { + contents = "{ \"program\": { \"binary\": \"${_program_name}\"}}" + outputs = [ _test_program_fragment ] } + # Collate the complete set of elements to include in the test component's + # manifest. + _manifest_fragments = [ + "//build/config/fuchsia/test/minimum_capabilities.test-cmx", + _test_program_fragment, + ] if (defined(invoker.additional_manifest_fragments)) { _manifest_fragments += invoker.additional_manifest_fragments } # Generate the test component manifest from the specified elements. _test_component_manifest_target = "${target_name}_component-manifest" + _test_component_manifest = "${target_out_dir}/${target_name}.cmx" cmc_merge(_test_component_manifest_target) { sources = _manifest_fragments - output_name = "${_merged_manifest_name}" + output_name = "${_output_name}.cmx" deps = [ ":${_test_program_fragment_target}" ] } @@ -443,7 +414,6 @@ "data", "data_deps", "package_deps", - "use_cfv2", "use_test_server", ])
diff --git a/testing/unexpected_passes_common/queries.py b/testing/unexpected_passes_common/queries.py index 177aaea..b41a64a 100644 --- a/testing/unexpected_passes_common/queries.py +++ b/testing/unexpected_passes_common/queries.py
@@ -235,8 +235,20 @@ 'results do not apply to any expectations for this suite.', builder) return results, None - expectation_files = self._GetRelevantExpectationFilesForQueryResult( - query_results[0]) + # It's possible that a builder runs multiple versions of a test with + # different expectation files for each version. So, find a result for each + # unique step and get the expectation files from all of them. + results_for_each_step = {} + for qr in query_results: + step_name = qr['step_name'] + if step_name not in results_for_each_step: + results_for_each_step[step_name] = qr + + expectation_files = [] + for qr in results_for_each_step.values(): + expectation_files.extend( + self._GetRelevantExpectationFilesForQueryResult(qr)) + expectation_files = list(set(expectation_files)) for r in query_results: if self._ShouldSkipOverResult(r):
diff --git a/testing/unexpected_passes_common/queries_unittest.py b/testing/unexpected_passes_common/queries_unittest.py index bd876a8..39f5dcc 100755 --- a/testing/unexpected_passes_common/queries_unittest.py +++ b/testing/unexpected_passes_common/queries_unittest.py
@@ -132,6 +132,59 @@ '1234')) self.assertEqual(expectation_files, ['foo_expectations']) + def testValidResultsMultipleSteps(self): + """Tests functionality when results from multiple steps are present.""" + + def SideEffect(result): + if result['step_name'] == 'a step name': + return ['foo_expectations'] + elif result['step_name'] == 'another step name': + return ['bar_expectations'] + raise RuntimeError('Unknown step %s' % result['step_name']) + + self._relevant_file_mock.side_effect = SideEffect + query_results = [ + { + 'id': 'build-1234', + 'test_id': 'ninja://:blink_web_tests/some/test/with.test_name', + 'status': 'FAIL', + 'typ_expectations': [ + 'Failure', + ], + 'typ_tags': [ + 'linux', + 'release', + ], + 'step_name': 'a step name', + }, + { + 'id': 'build-1234', + 'test_id': 'ninja://:blink_web_tests/some/test/with.test_name', + 'status': 'FAIL', + 'typ_expectations': [ + 'Crash', + ], + 'typ_tags': [ + 'linux', + 'debug', + ], + 'step_name': 'another step name', + }, + ] + self._popen_mock.return_value = unittest_utils.FakeProcess( + stdout=json.dumps(query_results)) + results, expectation_files = self._querier.QueryBuilder('builder', 'ci') + self.assertEqual(len(results), 2) + self.assertIn( + data_types.Result('test_name', ['linux', 'release'], 'Failure', + 'a step name', '1234'), results) + self.assertIn( + data_types.Result('test_name', ['linux', 'debug'], 'Failure', + 'another step name', '1234'), results) + self.assertEqual(len(expectation_files), 2) + self.assertEqual(set(expectation_files), + set(['foo_expectations', 'bar_expectations'])) + def testFilterInsertion(self): """Tests that test filters are properly inserted into the query.""" with mock.patch.object(
diff --git a/testing/variations/fieldtrial_testing_config.json b/testing/variations/fieldtrial_testing_config.json index bdff119..b333b16c 100644 --- a/testing/variations/fieldtrial_testing_config.json +++ b/testing/variations/fieldtrial_testing_config.json
@@ -3679,29 +3679,6 @@ ] } ], - "FileTypePoliciesTag": [ - { - "platforms": [ - "android", - "chromeos", - "chromeos_lacros", - "linux", - "mac", - "windows" - ], - "experiments": [ - { - "name": "Enabled_20210914", - "params": { - "policy_omaha_tag": "46" - }, - "enable_features": [ - "FileTypePoliciesTag" - ] - } - ] - } - ], "FillingAcrossAffiliatedWebsites": [ { "platforms": [ @@ -4500,21 +4477,6 @@ ] } ], - "IOSUserAgentInWebClient": [ - { - "platforms": [ - "ios" - ], - "experiments": [ - { - "name": "Enabled", - "enable_features": [ - "UseDefaultUserAgentInWebClient" - ] - } - ] - } - ], "IdentifiabilityStudy": [ { "platforms": [
diff --git a/third_party/blink/common/features.cc b/third_party/blink/common/features.cc index 1de818cd..fc85be92 100644 --- a/third_party/blink/common/features.cc +++ b/third_party/blink/common/features.cc
@@ -190,7 +190,7 @@ // allows the element to be enabled by the runtime enabled feature, for origin // trials. const base::Feature kFencedFrames{"FencedFrames", - base::FEATURE_ENABLED_BY_DEFAULT}; + base::FEATURE_DISABLED_BY_DEFAULT}; const base::FeatureParam<FencedFramesImplementationType>::Option fenced_frame_implementation_types[] = { {FencedFramesImplementationType::kShadowDOM, "shadow_dom"},
diff --git a/third_party/blink/public/mojom/authenticator_mojom_traits.h b/third_party/blink/public/mojom/authenticator_mojom_traits.h index be63c93..bf55df8 100644 --- a/third_party/blink/public/mojom/authenticator_mojom_traits.h +++ b/third_party/blink/public/mojom/authenticator_mojom_traits.h
@@ -68,18 +68,18 @@ device::PublicKeyCredentialDescriptor> { static device::CredentialType type( const device::PublicKeyCredentialDescriptor& in) { - return in.credential_type(); + return in.credential_type; } static const std::vector<uint8_t>& id( const device::PublicKeyCredentialDescriptor& in) { - return in.id(); + return in.id; } static const std::vector<device::FidoTransportProtocol> transports( const device::PublicKeyCredentialDescriptor& in) { std::vector<device::FidoTransportProtocol> protocols; - for (const auto& protocol : in.transports()) { + for (const auto& protocol : in.transports) { protocols.push_back(protocol); } return protocols; @@ -130,17 +130,17 @@ device::AuthenticatorSelectionCriteria> { static device::AuthenticatorAttachment authenticator_attachment( const device::AuthenticatorSelectionCriteria& in) { - return in.authenticator_attachment(); + return in.authenticator_attachment; } static device::ResidentKeyRequirement resident_key( const device::AuthenticatorSelectionCriteria& in) { - return in.resident_key(); + return in.resident_key; } static device::UserVerificationRequirement user_verification( const device::AuthenticatorSelectionCriteria& in) { - return in.user_verification_requirement(); + return in.user_verification_requirement; } static bool Read(blink::mojom::AuthenticatorSelectionCriteriaDataView data,
diff --git a/third_party/blink/public/mojom/web_feature/web_feature.mojom b/third_party/blink/public/mojom/web_feature/web_feature.mojom index e8250311..46894e84 100644 --- a/third_party/blink/public/mojom/web_feature/web_feature.mojom +++ b/third_party/blink/public/mojom/web_feature/web_feature.mojom
@@ -3397,6 +3397,7 @@ kCoopAndCoepIsolatedReportOnly = 4088, kCrossOriginOpenerPolicySameOriginAllowPopupsReportOnly = 4089, kCrossOriginOpenerPolicySameOriginReportOnly = 4090, + kImageLoadAtDismissalEvent = 4091, // Add new features immediately above this line. Don't change assigned // numbers of any item, and don't reuse removed slots.
diff --git a/third_party/blink/renderer/core/app_history/app_history.cc b/third_party/blink/renderer/core/app_history/app_history.cc index d8b963d..8245f1c 100644 --- a/third_party/blink/renderer/core/app_history/app_history.cc +++ b/third_party/blink/renderer/core/app_history/app_history.cc
@@ -161,8 +161,11 @@ const char AppHistory::kSupplementName[] = "AppHistory"; AppHistory* AppHistory::appHistory(LocalDOMWindow& window) { - if (!RuntimeEnabledFeatures::AppHistoryEnabled(&window)) - return nullptr; + return RuntimeEnabledFeatures::AppHistoryEnabled(&window) ? From(window) + : nullptr; +} + +AppHistory* AppHistory::From(LocalDOMWindow& window) { auto* app_history = Supplement<LocalDOMWindow>::From<AppHistory>(window); if (!app_history) { app_history = MakeGarbageCollected<AppHistory>(window); @@ -189,7 +192,7 @@ HistoryItem& current, WebFrameLoadType load_type, CommitReason commit_reason, - AppHistory& previous, + AppHistory* previous, const WebVector<WebHistoryItem>& back_entries, const WebVector<WebHistoryItem>& forward_entries) { DCHECK(entries_.IsEmpty()); @@ -209,11 +212,12 @@ // window and use the same update algorithm as same-document navigations. if (commit_reason != CommitReason::kRegular || (current.Url() == BlankURL() && !IsBackForwardLoadType(load_type)) || - (current.Url().IsAboutSrcdocURL() && !previous.entries_.IsEmpty() && - !IsBackForwardLoadType(load_type))) { - CloneFromPrevious(previous); - UpdateForNavigation(current, load_type); - return; + (current.Url().IsAboutSrcdocURL() && !IsBackForwardLoadType(load_type))) { + if (previous && !previous->entries_.IsEmpty()) { + CloneFromPrevious(*previous); + UpdateForNavigation(current, load_type); + return; + } } // Construct |entries_|. Any back entries are inserted, then the current
diff --git a/third_party/blink/renderer/core/app_history/app_history.h b/third_party/blink/renderer/core/app_history/app_history.h index 8734dd8..fbe3bccd 100644 --- a/third_party/blink/renderer/core/app_history/app_history.h +++ b/third_party/blink/renderer/core/app_history/app_history.h
@@ -47,13 +47,16 @@ public: static const char kSupplementName[]; static AppHistory* appHistory(LocalDOMWindow&); + // Unconditionally creates AppHistory, even if the RuntimeEnabledFeatures is + // disabled. + static AppHistory* From(LocalDOMWindow&); explicit AppHistory(LocalDOMWindow&); ~AppHistory() final = default; void InitializeForNewWindow(HistoryItem& current, WebFrameLoadType, CommitReason, - AppHistory& previous, + AppHistory* previous, const WebVector<WebHistoryItem>& back_entries, const WebVector<WebHistoryItem>& forward_entries); void UpdateForNavigation(HistoryItem&, WebFrameLoadType);
diff --git a/third_party/blink/renderer/core/display_lock/display_lock_utilities.cc b/third_party/blink/renderer/core/display_lock/display_lock_utilities.cc index 2636ab4..5e5058f 100644 --- a/third_party/blink/renderer/core/display_lock/display_lock_utilities.cc +++ b/third_party/blink/renderer/core/display_lock/display_lock_utilities.cc
@@ -33,11 +33,11 @@ if (!v8::Isolate::GetCurrent()->InContext()) return; String message = - "Rendering update in content-visibility:hidden subtree precluded " - "rendering optimizations."; - // Note that this is a verbose level message, since it can happen frequently - // and is not necessarily a problem if the developer is accessing - // content-visibility: hidden subtrees intentionally. + "Rendering was performed in a subtree hidden by " + "content-visibility:hidden."; + // Note that this is a verbose level message, since it can happen + // frequently and is not necessarily a problem if the developer is + // accessing content-visibility: hidden subtrees intentionally. document.AddConsoleMessage(MakeGarbageCollected<ConsoleMessage>( mojom::blink::ConsoleMessageSource::kJavaScript, mojom::blink::ConsoleMessageLevel::kVerbose, message));
diff --git a/third_party/blink/renderer/core/html/forms/html_select_menu_element.cc b/third_party/blink/renderer/core/html/forms/html_select_menu_element.cc index 07a46bf..fc6e836 100644 --- a/third_party/blink/renderer/core/html/forms/html_select_menu_element.cc +++ b/third_party/blink/renderer/core/html/forms/html_select_menu_element.cc
@@ -779,6 +779,9 @@ void HTMLSelectMenuElement::ButtonPartEventListener::Invoke(ExecutionContext*, Event* event) { + if (event->defaultPrevented()) + return; + if (event->type() == event_type_names::kClick && !select_menu_element_->open()) { select_menu_element_->OpenListbox(); @@ -805,6 +808,9 @@ void HTMLSelectMenuElement::OptionPartEventListener::Invoke(ExecutionContext*, Event* event) { + if (event->defaultPrevented()) + return; + if (event->type() == event_type_names::kClick) { auto* target_element = DynamicTo<HTMLOptionElement>(event->currentTarget()->ToNode());
diff --git a/third_party/blink/renderer/core/layout/ng/flex/ng_flex_layout_algorithm.cc b/third_party/blink/renderer/core/layout/ng/flex/ng_flex_layout_algorithm.cc index b3ae73a4..cb71150 100644 --- a/third_party/blink/renderer/core/layout/ng/flex/ng_flex_layout_algorithm.cc +++ b/third_party/blink/renderer/core/layout/ng/flex/ng_flex_layout_algorithm.cc
@@ -52,10 +52,10 @@ child_percentage_size_, &Node().GetDocument()), layout_info_for_devtools_(layout_info_for_devtools) { - // TODO(almaher): Support multi-line and row fragmentation. + // TODO(almaher): Support multi-line fragmentation. involved_in_block_fragmentation_ = InvolvedInBlockFragmentation(container_builder_) && - !is_horizontal_flow_ && !algorithm_.IsMultiline(); + !algorithm_.IsMultiline(); } bool NGFlexLayoutAlgorithm::MainAxisIsInlineAxis( @@ -1190,7 +1190,10 @@ // A child break in a parallel flow doesn't affect whether we should // break here or not. - if (container_builder_.HasInflowChildBreakInside()) { + // TODO(almaher): Once we add support for row break tokens, set + // |has_inflow_child_break_inside_| to false when adding item break tokens. + if (container_builder_.HasInflowChildBreakInside() && + !is_horizontal_flow_) { // But if the break happened in the same flow, we'll now just finish // layout of the fragment. No more siblings should be processed. break;
diff --git a/third_party/blink/renderer/core/loader/document_loader.cc b/third_party/blink/renderer/core/loader/document_loader.cc index c19e306..3d28acf0 100644 --- a/third_party/blink/renderer/core/loader/document_loader.cc +++ b/third_party/blink/renderer/core/loader/document_loader.cc
@@ -2335,12 +2335,11 @@ // documents. if (commit_reason_ != CommitReason::kInitialization && !frame_->DomWindow()->GetSecurityOrigin()->IsOpaque()) { - if (auto* app_history = AppHistory::appHistory(*frame_->DomWindow())) { - app_history->InitializeForNewWindow( - *history_item_, load_type_, commit_reason_, - *AppHistory::appHistory(*previous_window), app_history_back_entries_, - app_history_forward_entries_); - } + AppHistory::From(*frame_->DomWindow()) + ->InitializeForNewWindow(*history_item_, load_type_, commit_reason_, + AppHistory::appHistory(*previous_window), + app_history_back_entries_, + app_history_forward_entries_); // Now that appHistory's entries array is initialized, we don't need to // retain the state from which it was initialized. app_history_back_entries_.Clear();
diff --git a/third_party/blink/renderer/core/loader/image_loader.cc b/third_party/blink/renderer/core/loader/image_loader.cc index d2f9464..7cf8adf3 100644 --- a/third_party/blink/renderer/core/loader/image_loader.cc +++ b/third_party/blink/renderer/core/loader/image_loader.cc
@@ -505,6 +505,7 @@ resource_request.SetKeepalive(true); resource_request.SetRequestContext( mojom::blink::RequestContextType::PING); + UseCounter::Count(document, WebFeature::kImageLoadAtDismissalEvent); } // Plug-ins should not load via service workers as plug-ins may have their
diff --git a/third_party/blink/renderer/core/paint/box_painter_base.cc b/third_party/blink/renderer/core/paint/box_painter_base.cc index 1a26c3d..01dd03b 100644 --- a/third_party/blink/renderer/core/paint/box_painter_base.cc +++ b/third_party/blink/renderer/core/paint/box_painter_base.cc
@@ -109,9 +109,16 @@ if (shadow_offset.IsZero() && !shadow_blur && !shadow_spread) continue; - const Color& shadow_color = shadow.GetColor().Resolve( + Color resolved_shadow_color = shadow.GetColor().Resolve( style.VisitedDependentColor(GetCSSPropertyColor()), style.UsedColorScheme()); + // DarkModeFilter::ApplyToFlagsIfNeeded does not apply dark mode to the draw + // looper used for shadows so we need to apply dark mode to the color here. + const Color& shadow_color = + style.ForceDark() ? context.GetDarkModeFilter()->InvertColorIfNeeded( + resolved_shadow_color.Rgb(), + DarkModeFilter::ElementRole::kBackground) + : resolved_shadow_color; gfx::RectF fill_rect = border.Rect(); fill_rect.Outset(shadow_spread); @@ -253,17 +260,23 @@ if (!shadow.X() && !shadow.Y() && !shadow.Blur() && !shadow.Spread()) continue; - const Color& shadow_color = shadow.GetColor().Resolve( + Color resolved_shadow_color = shadow.GetColor().Resolve( style.VisitedDependentColor(GetCSSPropertyColor()), style.UsedColorScheme()); - - AutoDarkMode auto_dark_mode( - PaintAutoDarkMode(style, DarkModeFilter::ElementRole::kBackground)); + // DarkModeFilter::ApplyToFlagsIfNeeded does not apply dark mode to the draw + // looper used for shadows so we need to apply dark mode to the color here. + const Color& shadow_color = + style.ForceDark() ? context.GetDarkModeFilter()->InvertColorIfNeeded( + resolved_shadow_color.Rgb(), + DarkModeFilter::ElementRole::kBackground) + : resolved_shadow_color; gfx::RectF inner_rect = bounds.Rect(); inner_rect.Inset(shadow.Spread()); if (inner_rect.IsEmpty()) { - context.FillRoundedRect(bounds, shadow_color, auto_dark_mode); + // |AutoDarkMode::Disabled()| is used because |shadow_color| has already + // been adjusted for dark mode. + context.FillRoundedRect(bounds, shadow_color, AutoDarkMode::Disabled()); continue; } AdjustInnerRectForSideClipping(inner_rect, shadow, sides_to_include); @@ -287,8 +300,10 @@ Color fill_color(shadow_color.Red(), shadow_color.Green(), shadow_color.Blue()); gfx::RectF outer_rect = AreaCastingShadowInHole(bounds.Rect(), shadow); + // |AutoDarkMode::Disabled()| is used because |fill_color(shadow_color)| has + // already been adjusted for dark mode. context.FillRectWithRoundedHole(outer_rect, inner_rounded_rect, fill_color, - auto_dark_mode); + AutoDarkMode::Disabled()); } }
diff --git a/third_party/blink/renderer/core/paint/compositing/compositing_reason_finder.cc b/third_party/blink/renderer/core/paint/compositing/compositing_reason_finder.cc index 34749a5..92ede0ae 100644 --- a/third_party/blink/renderer/core/paint/compositing/compositing_reason_finder.cc +++ b/third_party/blink/renderer/core/paint/compositing/compositing_reason_finder.cc
@@ -394,9 +394,10 @@ static bool ObjectTypeSupportsCompositedTransformAnimation( const LayoutObject& object) { if (object.IsSVGChild()) { - // Transforms are not supported on hidden containers, inlines, or text. + // Transforms are not supported on hidden containers, inlines, text, or + // filter primitives. return !object.IsSVGHiddenContainer() && !object.IsLayoutInline() && - !object.IsText(); + !object.IsText() && !object.IsSVGFilterPrimitive(); } // Transforms don't apply on non-replaced inline elements. return object.IsBox();
diff --git a/third_party/blink/renderer/core/paint/compositing/compositing_reason_finder_test.cc b/third_party/blink/renderer/core/paint/compositing/compositing_reason_finder_test.cc index 1c38b92..fb227135 100644 --- a/third_party/blink/renderer/core/paint/compositing/compositing_reason_finder_test.cc +++ b/third_party/blink/renderer/core/paint/compositing/compositing_reason_finder_test.cc
@@ -560,6 +560,9 @@ <text id="text">text content <tspan id="tspan">tspan content</tspan> </text> + <filter> + <feBlend id="feBlend"></feBlend> + </filter> </svg> )HTML"); @@ -584,6 +587,10 @@ ASSERT_TRUE(tspan_content->IsText()); EXPECT_EQ(CompositingReason::kNone, DirectReasonsForPaintProperties(*tspan_content)); + + auto* feBlend = GetLayoutObjectByElementId("feBlend"); + EXPECT_REASONS(CompositingReason::kNone, + DirectReasonsForPaintProperties(*feBlend)); } } // namespace blink
diff --git a/third_party/blink/renderer/modules/accessibility/ax_node_object.cc b/third_party/blink/renderer/modules/accessibility/ax_node_object.cc index fc18387..4056be5 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_node_object.cc +++ b/third_party/blink/renderer/modules/accessibility/ax_node_object.cc
@@ -3438,7 +3438,8 @@ // accessible name of object inside hidden subtrees (for example, if // aria-labelledby points to an object that's hidden). if (child->AOMPropertyOrARIAAttributeIsTrue(AOMBooleanProperty::kHidden) || - child->IsHiddenForTextAlternativeCalculation()) { + child->IsHiddenForTextAlternativeCalculation( + aria_label_or_description_root)) { continue; } @@ -5733,19 +5734,17 @@ } String AXNodeObject::GetValueContributionToName() const { - if (CanSetValueAttribute()) { - if (IsTextField()) - return SlowGetValueForControlIncludingContentEditable(); + if (IsTextField()) + return SlowGetValueForControlIncludingContentEditable(); - if (IsRangeValueSupported()) { - const AtomicString& aria_valuetext = - GetAOMPropertyOrARIAAttribute(AOMStringProperty::kValueText); - if (!aria_valuetext.IsNull()) - return aria_valuetext.GetString(); - float value; - if (ValueForRange(&value)) - return String::Number(value); - } + if (IsRangeValueSupported()) { + const AtomicString& aria_valuetext = + GetAOMPropertyOrARIAAttribute(AOMStringProperty::kValueText); + if (!aria_valuetext.IsNull()) + return aria_valuetext.GetString(); + float value; + if (ValueForRange(&value)) + return String::Number(value); } // "If the embedded control has role combobox or listbox, return the text
diff --git a/third_party/blink/renderer/modules/accessibility/ax_object.cc b/third_party/blink/renderer/modules/accessibility/ax_object.cc index 745b790..5a25263a 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_object.cc +++ b/third_party/blink/renderer/modules/accessibility/ax_object.cc
@@ -3504,16 +3504,15 @@ return cached_is_hidden_via_style; } -// Return true if this should be removed from accessible name computations, -// unless it is reached by following an aria-labelledby. When that happens, this -// is not checked, because aria-labelledby can use hidden subtrees. -// Because aria-labelledby can use hidden subtrees, when it has entered a hidden -// subtree, it is not enough to check if the element was hidden by an ancestor. -// In this case, return true only if the hiding style targeted the node -// directly, as opposed to having inherited the hiding style. Using inherited -// hiding styles is problematic because it would prevent name contributions from -// deeper nodes in hidden aria-labelledby subtrees. -bool AXObject::IsHiddenForTextAlternativeCalculation() const { +// Return true if this should be removed from accessible name computations. +// We must take into account if we are traversing an aria-labelledby or +// describedby relation, because those can use hidden subtrees. When the target +// node of the aria-labelledby or describedby relation is hidden, we contribute +// all its children, because there is no way to know if they are explicitly +// hidden or they inherited the hidden value. See: +// https://github.com/w3c/accname/issues/57 +bool AXObject::IsHiddenForTextAlternativeCalculation( + const AXObject* aria_label_or_description_root) const { // aria-hidden=false allows hidden contents to be used in name from contents. if (AOMPropertyOrARIAAttributeIsFalse(AOMBooleanProperty::kHidden)) return false; @@ -3542,10 +3541,16 @@ if (IsA<SVGDescElement>(node)) return false; - // If this is hidden but its parent isn't, then it appears the hiding style - // targeted this node directly. Do not recurse into it for name from contents. - return IsHiddenViaStyle() && - (!ParentObject() || !ParentObject()->IsHiddenViaStyle()); + // Step 2A from: http://www.w3.org/TR/accname-aam-1.1 + // When traversing an aria-labelledby relation where the targeted node is + // hidden, we must contribute its children. There is no way to know if they + // are explicitly hidden or they inherited the hidden value, so we resort to + // contributing them all. See also: https://github.com/w3c/accname/issues/57 + if (aria_label_or_description_root && + aria_label_or_description_root->IsHiddenViaStyle()) + return false; + + return IsHiddenViaStyle(); } String AXObject::AriaTextAlternative( @@ -3562,8 +3567,7 @@ // Step 2A from: http://www.w3.org/TR/accname-aam-1.1 // If you change this logic, update AXNodeObject::nameFromLabelElement, too. - if (!aria_label_or_description_root && - IsHiddenForTextAlternativeCalculation()) { + if (IsHiddenForTextAlternativeCalculation(aria_label_or_description_root)) { *found_text_alternative = true; return String(); }
diff --git a/third_party/blink/renderer/modules/accessibility/ax_object.h b/third_party/blink/renderer/modules/accessibility/ax_object.h index a5b8240..a1a1e50a 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_object.h +++ b/third_party/blink/renderer/modules/accessibility/ax_object.h
@@ -1303,7 +1303,8 @@ // Blink-internal DOM Node ID. Currently used for PDF exporting. int GetDOMNodeId() const; - bool IsHiddenForTextAlternativeCalculation() const; + bool IsHiddenForTextAlternativeCalculation( + const AXObject* aria_label_or_description_root) const; // What should the role be assuming an ARIA role is not present? virtual ax::mojom::blink::Role NativeRoleIgnoringAria() const = 0;
diff --git a/third_party/blink/renderer/platform/graphics/dark_mode_filter.h b/third_party/blink/renderer/platform/graphics/dark_mode_filter.h index 2123092..6166a9cd 100644 --- a/third_party/blink/renderer/platform/graphics/dark_mode_filter.h +++ b/third_party/blink/renderer/platform/graphics/dark_mode_filter.h
@@ -30,9 +30,6 @@ explicit DarkModeFilter(const DarkModeSettings& settings); ~DarkModeFilter(); - // TODO(gilmanmh): Add a role for shadows. In general, we don't want to - // invert shadows, but we may need to do some other kind of processing for - // them. enum class ElementRole { kForeground, kListSymbol, kBackground, kSVG }; DarkModeImagePolicy GetDarkModeImagePolicy() const;
diff --git a/third_party/blink/tools/blinkpy/common/config/builders.json b/third_party/blink/tools/blinkpy/common/config/builders.json index 9de2d432..6128a221 100644 --- a/third_party/blink/tools/blinkpy/common/config/builders.json +++ b/third_party/blink/tools/blinkpy/common/config/builders.json
@@ -39,6 +39,11 @@ "port_name": "mac-mac10.15", "specifiers": ["Mac10.15", "Debug"] }, + "Mac11 Tests (dbg)": { + "master": "chromium.mac", + "port_name": "mac-mac11", + "specifiers": ["Mac11", "Debug"] + }, "Mac11.0 Tests": { "master": "chromium.fyi", "port_name": "mac-mac11",
diff --git a/third_party/blink/tools/blinkpy/w3c/test_importer.py b/third_party/blink/tools/blinkpy/w3c/test_importer.py index 7a868927..5bee21d 100644 --- a/third_party/blink/tools/blinkpy/w3c/test_importer.py +++ b/third_party/blink/tools/blinkpy/w3c/test_importer.py
@@ -182,8 +182,8 @@ _log.info('Done: no changes to import.') return 0 - if self._only_wpt_manifest_changed(): - _log.info('Only manifest was updated; skipping the import.') + if not self._has_wpt_changes(): + _log.info('Only manifest or expectations was updated; skipping the import.') return 0 with self._expectations_updater.prepare_smoke_tests(self.chromium_git): @@ -472,12 +472,14 @@ _log.info('Committing changes.') self.chromium_git.commit_locally_with_message(commit_message) - def _only_wpt_manifest_changed(self): + def _has_wpt_changes(self): changed_files = self.chromium_git.changed_files() - wpt_base_manifest = self.fs.relpath( - self.fs.join(self.dest_path, '..', BASE_MANIFEST_NAME), - self.finder.chromium_base()) - return changed_files == [wpt_base_manifest] + rel_dest_path = self.fs.relpath(self.dest_path, + self.finder.chromium_base()) + for cf in changed_files: + if cf.startswith(rel_dest_path): + return True + return False def _need_sheriff_attention(self): # Per the rules defined for the rubber-stamper, it can not auto approve
diff --git a/third_party/blink/tools/blinkpy/w3c/test_importer_unittest.py b/third_party/blink/tools/blinkpy/w3c/test_importer_unittest.py index f2ed6f2..abfff2c 100644 --- a/third_party/blink/tools/blinkpy/w3c/test_importer_unittest.py +++ b/third_party/blink/tools/blinkpy/w3c/test_importer_unittest.py
@@ -529,17 +529,22 @@ self.assertEqual(importer.chromium_git.added_paths, {MOCK_WEB_TESTS + 'external/' + BASE_MANIFEST_NAME}) - def test_only_wpt_manifest_changed(self): + def test_has_wpt_changes(self): host = self.mock_host() importer = self._get_test_importer(host) importer.chromium_git.changed_files = lambda: [ RELATIVE_WEB_TESTS + 'external/' + BASE_MANIFEST_NAME, RELATIVE_WEB_TESTS + 'external/wpt/foo/x.html'] - self.assertFalse(importer._only_wpt_manifest_changed()) + self.assertTrue(importer._has_wpt_changes()) + + importer.chromium_git.changed_files = lambda: [ + RELATIVE_WEB_TESTS + 'external/' + BASE_MANIFEST_NAME, + RELATIVE_WEB_TESTS + 'TestExpectations'] + self.assertFalse(importer._has_wpt_changes()) importer.chromium_git.changed_files = lambda: [ RELATIVE_WEB_TESTS + 'external/' + BASE_MANIFEST_NAME] - self.assertTrue(importer._only_wpt_manifest_changed()) + self.assertFalse(importer._has_wpt_changes()) def test_need_sheriff_attention(self): host = self.mock_host()
diff --git a/third_party/blink/web_tests/FlagExpectations/disable-layout-ng b/third_party/blink/web_tests/FlagExpectations/disable-layout-ng index e311d51c..a94af8e 100644 --- a/third_party/blink/web_tests/FlagExpectations/disable-layout-ng +++ b/third_party/blink/web_tests/FlagExpectations/disable-layout-ng
@@ -245,6 +245,7 @@ crbug.com/591099 external/wpt/css/css-layout-api/* [ Skip ] ### external/wpt/css/css-multicol/ +crbug.com/1221181 external/wpt/css/css-multicol/multicol-overflow-transform-001.html [ Failure ] crbug.com/591099 external/wpt/css/css-multicol/multicol-span-all-list-item-002.html [ Failure ] crbug.com/998423 external/wpt/css/css-multicol/with-custom-layout-on-same-element-crash.https.html [ Skip ] crbug.com/998423 external/wpt/css/css-multicol/with-custom-layout-on-same-element.https.html [ Skip ]
diff --git a/third_party/blink/web_tests/TestExpectations b/third_party/blink/web_tests/TestExpectations index fd24ce9..df76131 100644 --- a/third_party/blink/web_tests/TestExpectations +++ b/third_party/blink/web_tests/TestExpectations
@@ -249,6 +249,12 @@ crbug.com/1093466 virtual/portals/http/tests/portals/* [ Pass ] crbug.com/1093466 virtual/portals/wpt_internal/portals/* [ Pass ] +# These tests require fenced-frames +# Keep this in sync with VirtualTestSuites. +crbug.com/1123606 wpt_internal/fenced_frame/* [ Skip ] +crbug.com/1123606 fenced_frame/* [ Skip ] +crbug.com/1123606 virtual/fenced-frame-shadow-dom/* [ Pass ] + # These tests require the experimental prerender feature. # See https://crbug.com/1126305. crbug.com/1126305 external/wpt/speculation-rules/prerender/* [ Skip ] @@ -442,7 +448,7 @@ crbug.com/432153 external/wpt/css/css-masking/mask-image/mask-image-url-image-hash.html [ Failure ] # CSS cascade layers -crbug.com/1095765 external/wpt/css/css-cascade/layer-stylesheet-sharing.html [ Failure ] +crbug.com/1277637 external/wpt/css/css-cascade/layer-stylesheet-sharing.html [ Failure ] # Fails, at a minimum, due to lack of support for CSS mask property in html elements crbug.com/432153 external/wpt/svg/painting/reftests/display-none-mask.html [ Skip ] @@ -2984,7 +2990,7 @@ crbug.com/626703 external/wpt/preload/preload-resource-match.https.html [ Failure ] # ====== New tests from wpt-importer added here ====== -crbug.com/626703 [ Mac10.12 ] virtual/fenced-frame-mparch/wpt_internal/fenced_frame/presentation-receiver.https.html [ Failure Crash ] +crbug.com/626703 [ Mac10.12 ] virtual/fenced-frame-mparch/wpt_internal/fenced_frame/presentation-receiver.https.html [ Crash Failure ] crbug.com/626703 [ Mac10.12 ] external/wpt/websockets/constructor/009.html?wpt_flags=h2 [ Crash Failure ] crbug.com/626703 [ Mac10.13 ] external/wpt/scroll-to-text-fragment/scroll-to-text-fragment-security.sub.html [ Timeout ] crbug.com/626703 [ Mac10.13 ] virtual/threaded/external/wpt/css/css-backgrounds/animations/background-color-animation-in-body.html [ Failure ] @@ -7116,9 +7122,9 @@ crbug.com/1243568 virtual/fenced-frame-mparch/wpt_internal/fenced_frame/window-data-url-navigation.html [ Crash ] # Gesture of WPT Test Driver doesn't work well in MPArch Fenced Frame on some Mac try bots. -crbug.com/1275997 [ Mac ] virtual/fenced-frame-mparch/wpt_internal/fenced_frame/pointer-lock.https.html [ Timeout Pass ] -crbug.com/1275997 [ Mac ] virtual/fenced-frame-mparch/wpt_internal/fenced_frame/web-bluetooth.https.html [ Timeout Pass ] -crbug.com/1275997 [ Mac ] virtual/fenced-frame-mparch/wpt_internal/fenced_frame/web-share.https.html [ Timeout Pass ] +crbug.com/1275997 [ Mac ] virtual/fenced-frame-mparch/wpt_internal/fenced_frame/pointer-lock.https.html [ Pass Timeout ] +crbug.com/1275997 [ Mac ] virtual/fenced-frame-mparch/wpt_internal/fenced_frame/web-bluetooth.https.html [ Pass Timeout ] +crbug.com/1275997 [ Mac ] virtual/fenced-frame-mparch/wpt_internal/fenced_frame/web-share.https.html [ Pass Timeout ] # Sheriff 2021-10-15, 2021-12-07 crbug.com/1256763 [ Win ] virtual/gpu-rasterization/images/color-profile-image-pseudo-content.html [ Failure Pass ]
diff --git a/third_party/blink/web_tests/VirtualTestSuites b/third_party/blink/web_tests/VirtualTestSuites index 377fa8f..968fb8f 100644 --- a/third_party/blink/web_tests/VirtualTestSuites +++ b/third_party/blink/web_tests/VirtualTestSuites
@@ -1038,7 +1038,7 @@ "http/tests/inspector-protocol/target/auto-attach-auction-worklet.js" ], "args": [ - "--enable-features=InterestGroupStorage,AdInterestGroupAPI,Fledge" + "--enable-features=InterestGroupStorage,AdInterestGroupAPI,Fledge,FencedFrames:implementation_type/shadow_dom" ] }, { @@ -1078,6 +1078,14 @@ "args": ["--enable-features=FencedFrames:implementation_type/mparch,Prerender2"] }, { + "prefix": "fenced-frame-shadow-dom", + "bases": [ + "fenced_frame", + "wpt_internal/fenced_frame" + ], + "args": ["--enable-features=FencedFrames:implementation_type/shadow_dom,Prerender2"] + }, + { "prefix": "disable-custom-element-default-style", "bases": ["external/wpt/css/css-cascade/presentational-hints-cascade.html"], "args": ["--disable-blink-features=CustomElementDefaultStyle"]
diff --git a/third_party/blink/web_tests/compositing/perpendicular-layer-sorting-expected.png b/third_party/blink/web_tests/compositing/perpendicular-layer-sorting-expected.png deleted file mode 100644 index b0185ea06..0000000 --- a/third_party/blink/web_tests/compositing/perpendicular-layer-sorting-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/dark-mode/images/shadow-expected.png b/third_party/blink/web_tests/dark-mode/images/shadow-expected.png new file mode 100644 index 0000000..140fa443 --- /dev/null +++ b/third_party/blink/web_tests/dark-mode/images/shadow-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/dark-mode/images/shadow.html b/third_party/blink/web_tests/dark-mode/images/shadow.html new file mode 100644 index 0000000..c7d6e00 --- /dev/null +++ b/third_party/blink/web_tests/dark-mode/images/shadow.html
@@ -0,0 +1,27 @@ +<!DOCTYPE html> +<style> +.box { + margin: auto; + padding: 50px; + height: 50px; + width: 200px; +} + +.white-on-black { + background-color: black; +} + +.black-on-white { + background-color: white; +} + +.white-on-black .shadow { + box-shadow: 0 20px 10px 40px #fff; +} + +.black-on-white .shadow{ + box-shadow: 0 20px 10px 40px #000; +} +</style> +<div class="box white-on-black"><div class="shadow"></div></div> +<div class="box black-on-white"><div class="shadow"></div></div> \ No newline at end of file
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 8133766..dd475f31 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
@@ -2455,6 +2455,13 @@ {} ] ], + "modified-details-crash.html": [ + "35ddca1fa620e4df4a208b7316df8eede0664200", + [ + null, + {} + ] + ], "nested-details-crash.html": [ "f3e821a950588d6b374c4338c5ab89e0f8d9f0d0", [ @@ -78678,6 +78685,45 @@ ], {} ] + ], + "single-line-column-flex-fragmentation-027.html": [ + "38ab5e427ee25d37f312165aba75a50b3780bda9", + [ + null, + [ + [ + "/css/reference/ref-filled-green-100px-square.xht", + "==" + ] + ], + {} + ] + ], + "single-line-column-flex-fragmentation-028.html": [ + "80562c57cbc3c0bb7dd74fdc702a0a9fbd48fcb8", + [ + null, + [ + [ + "/css/reference/ref-filled-green-100px-square.xht", + "==" + ] + ], + {} + ] + ], + "single-line-column-flex-fragmentation-029.html": [ + "a24f735f77364d104e7441f710ca3e0df1fee0a9", + [ + null, + [ + [ + "/css/reference/ref-filled-green-100px-square.xht", + "==" + ] + ], + {} + ] ] }, "float-000.html": [ @@ -78928,6 +78974,58 @@ {} ] ], + "grid-container-fragmentation-006.html": [ + "2c25d1f35cf574b4c7dd4af5022b877f7327be8f", + [ + null, + [ + [ + "/css/reference/ref-filled-green-100px-square.xht", + "==" + ] + ], + {} + ] + ], + "grid-container-fragmentation-007.html": [ + "86323ee57a1b7575eb661a1ddff8694e8a54acce", + [ + null, + [ + [ + "/css/reference/ref-filled-green-100px-square.xht", + "==" + ] + ], + {} + ] + ], + "grid-container-fragmentation-008.html": [ + "38392afc6064b266bcab9a728e53b9eb2e1f5e16", + [ + null, + [ + [ + "/css/reference/ref-filled-green-100px-square.xht", + "==" + ] + ], + {} + ] + ], + "grid-container-fragmentation-009.html": [ + "c4148bb22689ec87442bf0b929819124b7225cd9", + [ + null, + [ + [ + "/css/reference/ref-filled-green-100px-square-only.html", + "==" + ] + ], + {} + ] + ], "grid-item-fragmentation-001.html": [ "1e2d41775ef84bbabca12f41c4c65a8a4c0f2187", [ @@ -89097,6 +89195,19 @@ {} ] ], + "fieldset-legend-change.html": [ + "dee6a960ad4712e4af4c446d6551bdc350483fc4", + [ + null, + [ + [ + "/css/css-contain/container-queries/fieldset-legend-change-ref.html", + "==" + ] + ], + {} + ] + ], "pseudo-elements-002.tentative.html": [ "e46d25cf8754bd1ec277dda727fc88018af65126", [ @@ -212780,7 +212891,7 @@ ] ], "iframe-same-origin.html": [ - "51a64a06043e8ee776c75f72aca8640fecf6b302", + "22d8399b23127354a5d711615fd44d7c37240773", [ null, [ @@ -235388,7 +235499,7 @@ [] ], "container-for-shadow-dom.tentative-expected.txt": [ - "f837f30255ef5680ecbc974f0caa0e7f688c2815", + "5d5c990f1ea97e6939452cccfcd8aae5223d0674", [] ], "container-name-parsing-expected.txt": [ @@ -235411,6 +235522,10 @@ "fd8e9ef0c10f523ff3347d5a71530f0adca66b4e", [] ], + "fieldset-legend-change-ref.html": [ + "b6e8dc603849e6691dc509b6c7085ea7a23d46b6", + [] + ], "pseudo-elements-002.tentative-ref.html": [ "66bddf379d133e6c541c003c8e7a280118b678a4", [] @@ -287116,7 +287231,7 @@ [] ], "show-picker-child-iframe.html": [ - "f298c3a9376dad75916920d421ae99ec863399cb", + "07b72f02cb69f2cb3af049a4f9cb65128428e4a4", [] ], "text-restore-events.html": [ @@ -295127,6 +295242,10 @@ "889e4578a9395fb058a05d413fda634066239f01", [] ], + "MediaRecorder-start-expected.txt": [ + "c7381df2d8f856218b1e3b2a07d86e09dbdbdf64", + [] + ], "MediaRecorder-stop-expected.txt": [ "ad4d44b24755b2e26f7ce22669edd930647ddc67", [] @@ -304272,39 +304391,21 @@ [] ], "idlharness.any-expected.txt": [ - "1120aa0f810e0e4573493ab8b9df5d8f4496405b", + "a815d7e755432b949a01e52188f3d35936ac6520", [] ], "idlharness.any.serviceworker-expected.txt": [ - "1120aa0f810e0e4573493ab8b9df5d8f4496405b", + "a815d7e755432b949a01e52188f3d35936ac6520", [] ], "idlharness.any.sharedworker-expected.txt": [ - "1120aa0f810e0e4573493ab8b9df5d8f4496405b", + "a815d7e755432b949a01e52188f3d35936ac6520", [] ], "idlharness.any.worker-expected.txt": [ - "1120aa0f810e0e4573493ab8b9df5d8f4496405b", + "a815d7e755432b949a01e52188f3d35936ac6520", [] ], - "piping": { - "abort.any-expected.txt": [ - "c1473ced17447056a37c631fea3796c54727cc06", - [] - ], - "abort.any.serviceworker-expected.txt": [ - "c1473ced17447056a37c631fea3796c54727cc06", - [] - ], - "abort.any.sharedworker-expected.txt": [ - "c1473ced17447056a37c631fea3796c54727cc06", - [] - ], - "abort.any.worker-expected.txt": [ - "c1473ced17447056a37c631fea3796c54727cc06", - [] - ] - }, "readable-byte-streams": { "tee.any-expected.txt": [ "a804638a686da4e7bbf52fb3e49a65ce1f7c4bf8", @@ -304454,24 +304555,6 @@ [] ] } - }, - "writable-streams": { - "aborting.any-expected.txt": [ - "e0989af9fcc26765b0b05113800353d2594b41d7", - [] - ], - "aborting.any.serviceworker-expected.txt": [ - "e0989af9fcc26765b0b05113800353d2594b41d7", - [] - ], - "aborting.any.sharedworker-expected.txt": [ - "e0989af9fcc26765b0b05113800353d2594b41d7", - [] - ], - "aborting.any.worker-expected.txt": [ - "e0989af9fcc26765b0b05113800353d2594b41d7", - [] - ] } }, "subresource-integrity": { @@ -308492,7 +308575,7 @@ }, "webdriver": { "META.yml": [ - "a397b497c32234d3889c738f51b96a3ba3b2a96f", + "a41161df8662d958b8741ab94bc00cddfdaa8229", [] ], "README.md": [ @@ -308532,6 +308615,18 @@ "e69de29bb2d1d6434b8b29ae775ad8c2e48c5391", [] ] + }, + "session_subscribe": { + "__init__.py": [ + "e69de29bb2d1d6434b8b29ae775ad8c2e48c5391", + [] + ] + }, + "session_unsubscribe": { + "__init__.py": [ + "e69de29bb2d1d6434b8b29ae775ad8c2e48c5391", + [] + ] } }, "close_window": { @@ -308625,6 +308720,10 @@ ] }, "find_element_from_shadow_root": { + "__init__.py": [ + "e69de29bb2d1d6434b8b29ae775ad8c2e48c5391", + [] + ], "conftest.py": [ "b8fc93319f43a9f427ab9ce25fd863620559c4a6", [] @@ -308643,6 +308742,10 @@ ] }, "find_elements_from_shadow_root": { + "__init__.py": [ + "e69de29bb2d1d6434b8b29ae775ad8c2e48c5391", + [] + ], "conftest.py": [ "b8fc93319f43a9f427ab9ce25fd863620559c4a6", [] @@ -308719,6 +308822,10 @@ ] }, "get_element_shadow_root": { + "__init__.py": [ + "e69de29bb2d1d6434b8b29ae775ad8c2e48c5391", + [] + ], "conftest.py": [ "afc0c91c3d3f2fcfe237e845bd1375124f8ebc56", [] @@ -308878,6 +308985,12 @@ ] } }, + "permissions": { + "__init__.py": [ + "e69de29bb2d1d6434b8b29ae775ad8c2e48c5391", + [] + ] + }, "print": { "__init__.py": [ "788c0e1a3179280604a8634d4db43b4a8db6880a", @@ -332038,39 +332151,139 @@ }, "requestDevice": { "acceptAllDevices": { - "device-with-empty-name.https.html": [ - "a47ee603f84287a0f0d22f1c9101ebf0c0bc718c", + "device-with-empty-name.https.window.js": [ + "df168797bf7f3f08dd3063b6cd9b33a5965dd9a5", [ - null, + "bluetooth/requestDevice/acceptAllDevices/device-with-empty-name.https.window.html", { - "testdriver": true + "script_metadata": [ + [ + "script", + "/resources/testharness.js" + ], + [ + "script", + "/resources/testharnessreport.js" + ], + [ + "script", + "/resources/testdriver.js" + ], + [ + "script", + "/resources/testdriver-vendor.js" + ], + [ + "script", + "/bluetooth/resources/bluetooth-test.js" + ], + [ + "script", + "/bluetooth/resources/bluetooth-fake-devices.js" + ] + ] } ] ], - "device-with-name.https.html": [ - "a69b313b51e92474338fc17aaa86b6e65096efc0", + "device-with-name.https.window.js": [ + "bde64a9bc9707722f2221fbac57c81e8c0356ecd", [ - null, + "bluetooth/requestDevice/acceptAllDevices/device-with-name.https.window.html", { - "testdriver": true + "script_metadata": [ + [ + "script", + "/resources/testharness.js" + ], + [ + "script", + "/resources/testharnessreport.js" + ], + [ + "script", + "/resources/testdriver.js" + ], + [ + "script", + "/resources/testdriver-vendor.js" + ], + [ + "script", + "/bluetooth/resources/bluetooth-test.js" + ], + [ + "script", + "/bluetooth/resources/bluetooth-fake-devices.js" + ] + ] } ] ], - "optional-services-missing.https.html": [ - "5d1fec3342ef7c68dcf743e49bd94bc739c6603a", + "optional-services-missing.https.window.js": [ + "3eb338663799279e1790ff298199a2da92cbbb23", [ - null, + "bluetooth/requestDevice/acceptAllDevices/optional-services-missing.https.window.html", { - "testdriver": true + "script_metadata": [ + [ + "script", + "/resources/testharness.js" + ], + [ + "script", + "/resources/testharnessreport.js" + ], + [ + "script", + "/resources/testdriver.js" + ], + [ + "script", + "/resources/testdriver-vendor.js" + ], + [ + "script", + "/bluetooth/resources/bluetooth-test.js" + ], + [ + "script", + "/bluetooth/resources/bluetooth-fake-devices.js" + ] + ] } ] ], - "optional-services-present.https.html": [ - "06897f809929db1a2a8d52742126d7e4a8b38d93", + "optional-services-present.https.window.js": [ + "0edf3a2d85818996ff08647748a80ee968f20f85", [ - null, + "bluetooth/requestDevice/acceptAllDevices/optional-services-present.https.window.html", { - "testdriver": true + "script_metadata": [ + [ + "script", + "/resources/testharness.js" + ], + [ + "script", + "/resources/testharnessreport.js" + ], + [ + "script", + "/resources/testdriver.js" + ], + [ + "script", + "/resources/testdriver-vendor.js" + ], + [ + "script", + "/bluetooth/resources/bluetooth-test.js" + ], + [ + "script", + "/bluetooth/resources/bluetooth-fake-devices.js" + ] + ] } ] ] @@ -348406,7 +348619,7 @@ ] ], "container-for-shadow-dom.tentative.html": [ - "4ec10bec477dd991815a1d6f5fc156e4a72eb97f", + "6c1dbbdf7671d1d3277d73a40baf62eec5eb80dc", [ null, {} @@ -361313,6 +361526,20 @@ {} ] ], + "auto-004.html": [ + "a70e70cb9c521c99677d83f28cf5b3b90309515b", + [ + null, + {} + ] + ], + "auto-005.html": [ + "4a920ac806006524bea9f12f3e0d41ff4aa5d4dc", + [ + null, + {} + ] + ], "parsing": { "contain-intrinsic-size-computed.html": [ "c03b282699777728e36dba774ecd455d98745532", @@ -374558,7 +374785,7 @@ ] ], "ElementInternals-validation.html": [ - "6b2ef8739795cea2b069253977b2c3e2395d6bec", + "c52473f5276ed2490711fb695e9e18e003895e00", [ null, {} @@ -442023,7 +442250,7 @@ ] ], "show-picker-cross-origin-iframe.tentative.html": [ - "4dd9dfce0ccab826a178aa04668fa46837dddf95", + "3a1c14efeeb0165596f22cddd2f3dd5f290b50cb", [ null, {} @@ -458412,6 +458639,13 @@ } ] ], + "MediaRecorder-start.html": [ + "ef2fe69719eb9d82b61e94529bf7fb2e5204d13b", + [ + null, + {} + ] + ], "MediaRecorder-stop.html": [ "73eb2999adb238f49f886d5de0dbe8f5eebae63f", [
diff --git a/third_party/blink/web_tests/external/wpt/css/css-break/flexbox/single-line-row-flex-fragmentation-001.html b/third_party/blink/web_tests/external/wpt/css/css-break/flexbox/single-line-row-flex-fragmentation-001.html new file mode 100644 index 0000000..379327a --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-break/flexbox/single-line-row-flex-fragmentation-001.html
@@ -0,0 +1,33 @@ +<!DOCTYPE html> +<title> + Simple single-line row flex fragmentation. +</title> +<link rel="help" href="https://drafts.csswg.org/css-flexbox-1/#pagination"> +<link rel="match" href="../../reference/ref-filled-green-100px-square.xht"> +<style> + .multicol { + background: red; + column-count: 5; + column-fill:auto; + column-gap: 0px; + height: 100px; + width: 100px; + } + .flex { + display: flex; + height: 500px; + width: 20px; + } + .flex > div { + background: green; + height: 500px; + width: 10px; + } +</style> +<p>Test passes if there is a filled green square and <strong>no red</strong>.</p> +<div class="multicol"> + <div class="flex"> + <div></div> + <div></div> + </div> +</div>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-break/flexbox/single-line-row-flex-fragmentation-002.html b/third_party/blink/web_tests/external/wpt/css/css-break/flexbox/single-line-row-flex-fragmentation-002.html new file mode 100644 index 0000000..bcfd587e --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-break/flexbox/single-line-row-flex-fragmentation-002.html
@@ -0,0 +1,37 @@ +<!DOCTYPE html> +<title> + Single-line row flex fragmentation with item overflow. +</title> +<link rel="help" href="https://drafts.csswg.org/css-flexbox-1/#pagination"> +<link rel="match" href="../../reference/ref-filled-green-100px-square.xht"> +<style> + .multicol { + column-count: 2; + column-fill:auto; + column-gap: 0px; + height: 100px; + width: 100px; + background: red; + } + .flex { + display: flex; + height: 200px; + width: 50px; + } + .flex > div { + height: 10px; + width: 50px; + } + .flex > div > div { + background: green; + } +</style> +<p>Test passes if there is a filled green square and <strong>no red</strong>.</p> +<div class="multicol"> + <div class="flex"> + <div> + <div style="height: 10px;"></div> + <div style="height: 190px;"></div> + </div> + </div> +</div>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-break/flexbox/single-line-row-flex-fragmentation-003.html b/third_party/blink/web_tests/external/wpt/css/css-break/flexbox/single-line-row-flex-fragmentation-003.html new file mode 100644 index 0000000..8b2736f --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-break/flexbox/single-line-row-flex-fragmentation-003.html
@@ -0,0 +1,31 @@ +<!DOCTYPE html> +<title> + Single-line row flex fragmentation intrinsic block size. +</title> +<link rel="help" href="https://drafts.csswg.org/css-flexbox-1/#pagination"> +<link rel="match" href="../../reference/ref-filled-green-100px-square.xht"> +<style> + .multicol { + background: red; + column-count: 5; + column-fill: auto; + column-gap: 0px; + height: 100px; + width: 100px; + } + .flex { + display: flex; + width: 20px; + background: green; + } + .flex > div { + width: 10px; + } +</style> +<p>Test passes if there is a filled green square and <strong>no red</strong>.</p> +<div class="multicol"> + <div class="flex"> + <div style="height: 50px;"></div> + <div style="height: 500px;"></div> + </div> +</div>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-break/flexbox/single-line-row-flex-fragmentation-004.html b/third_party/blink/web_tests/external/wpt/css/css-break/flexbox/single-line-row-flex-fragmentation-004.html new file mode 100644 index 0000000..d1f143b --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-break/flexbox/single-line-row-flex-fragmentation-004.html
@@ -0,0 +1,34 @@ +<!DOCTYPE html> +<title> + Single-line row flex fragmentation. +</title> +<link rel="help" href="https://drafts.csswg.org/css-flexbox-1/#pagination"> +<link rel="match" href="../../reference/ref-filled-green-100px-square.xht"> +<style> + .multicol { + background: red; + column-count: 5; + column-fill: auto; + column-gap: 0px; + height: 100px; + width: 100px; + } + .flex { + display: flex; + width: 20px; + } + .flex > div { + background: green; + width: 5px; + height: 500px; + } +</style> +<p>Test passes if there is a filled green square and <strong>no red</strong>.</p> +<div class="multicol"> + <div class="flex"> + <div></div> + <div></div> + <div></div> + <div></div> + </div> +</div>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-break/flexbox/single-line-row-flex-fragmentation-005.html b/third_party/blink/web_tests/external/wpt/css/css-break/flexbox/single-line-row-flex-fragmentation-005.html new file mode 100644 index 0000000..05ec215 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-break/flexbox/single-line-row-flex-fragmentation-005.html
@@ -0,0 +1,37 @@ +<!DOCTYPE html> +<title> + Single-line row flex fragmentation with nested OOF. +</title> +<link rel="help" href="https://drafts.csswg.org/css-flexbox-1/#pagination"> +<link rel="match" href="../../reference/ref-filled-green-100px-square.xht"> +<style> + .multicol { + background: red; + column-count: 4; + column-fill: auto; + column-gap: 0px; + height: 100px; + width: 100px; + } + .flex { + display: flex; + position: relative; + height: 400px; + width: 25px; + } + .abs { + background: green; + position: absolute; + width: 25px; + top: 0; + bottom: 0; + } +</style> +<p>Test passes if there is a filled green square and <strong>no red</strong>.</p> +<div class="multicol"> + <div class="flex"> + <div> + <div class="abs"></div> + </div> + </div> +</div>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-break/flexbox/single-line-row-flex-fragmentation-006.html b/third_party/blink/web_tests/external/wpt/css/css-break/flexbox/single-line-row-flex-fragmentation-006.html new file mode 100644 index 0000000..e8a2f40 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-break/flexbox/single-line-row-flex-fragmentation-006.html
@@ -0,0 +1,32 @@ +<!DOCTYPE html> +<title> + Simple single-line row flex fragmentation with items that stretch. +</title> +<link rel="help" href="https://drafts.csswg.org/css-flexbox-1/#pagination"> +<link rel="match" href="../../reference/ref-filled-green-100px-square.xht"> +<style> + .multicol { + background: red; + column-count: 5; + column-fill:auto; + column-gap: 0px; + height: 100px; + width: 100px; + } + .flex { + display: flex; + height: 500px; + width: 20px; + } + .flex > div { + background: green; + width: 10px; + } +</style> +<p>Test passes if there is a filled green square and <strong>no red</strong>.</p> +<div class="multicol"> + <div class="flex"> + <div></div> + <div></div> + </div> +</div>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/animation-container-size.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/animation-container-size.html index 02b8e639..909e75b 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/animation-container-size.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/animation-container-size.html
@@ -3,6 +3,7 @@ <link rel="help" href="https://drafts.csswg.org/css-contain-3/#animated-containers"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="support/testcommon.js"></script> <style> @keyframes anim { from { width: 200px; } @@ -28,6 +29,8 @@ </div> </div> <script> + setup(() => assert_implements_container_queries()); + test(() => { assert_equals(getComputedStyle(target).backgroundColor, 'rgb(0, 0, 255)');
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/animation-container-type-dynamic.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/animation-container-type-dynamic.html index 58dd78a..d885cd70 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/animation-container-type-dynamic.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/animation-container-type-dynamic.html
@@ -3,6 +3,7 @@ <link rel="help" href="https://drafts.csswg.org/css-contain-3/#animated-containers"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="support/testcommon.js"></script> <style> @keyframes anim { from { width: 200px; } @@ -48,6 +49,8 @@ </div> </div> <script> + setup(() => assert_implements_container_queries()); + test(() => { assert_equals(getComputedStyle(target).backgroundColor, 'rgb(0, 0, 255)');
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/animation-nested-animation.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/animation-nested-animation.html index 2c4ae8b..79c1330 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/animation-nested-animation.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/animation-nested-animation.html
@@ -3,6 +3,7 @@ <link rel="help" href="https://drafts.csswg.org/css-contain-3/#animated-containers"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="support/testcommon.js"></script> <style> @keyframes outer { from { width: 100px; } @@ -32,6 +33,8 @@ </div> </div> <script> + setup(() => assert_implements_container_queries()); + test(() => { assert_equals(getComputedStyle(target).backgroundColor, 'rgb(0, 128, 0)');
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/animation-nested-transition.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/animation-nested-transition.html index de305d0..85f5358 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/animation-nested-transition.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/animation-nested-transition.html
@@ -3,6 +3,7 @@ <link rel="help" href="https://drafts.csswg.org/css-contain-3/#animated-containers"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="support/testcommon.js"></script> <style> @keyframes outer { from { width: 100px; } @@ -29,6 +30,8 @@ </div> </div> <script> + setup(() => assert_implements_container_queries()); + test(() => { assert_equals(getComputedStyle(target).backgroundColor, 'rgb(100, 100, 100)');
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/aspect-ratio-feature-evaluation.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/aspect-ratio-feature-evaluation.html index ee34c54f..4a0916dd 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/aspect-ratio-feature-evaluation.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/aspect-ratio-feature-evaluation.html
@@ -3,6 +3,7 @@ <link rel="help" href="https://drafts.csswg.org/css-contain-3/#aspect-ratio"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="support/testcommon.js"></script> <style> .container { width: 100px; @@ -21,6 +22,8 @@ <div id="inline-size" class="container"><span></span></div> <div id="size" class="container"><span></span></div> <script> + setup(() => assert_implements_container_queries()); + const red = "rgb(255, 0, 0)"; const green = "rgb(0, 128, 0)"; const lime = "rgb(0, 255, 0)";
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/at-container-parsing.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/at-container-parsing.html index 5c2b26f..f6c27ec 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/at-container-parsing.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/at-container-parsing.html
@@ -3,10 +3,12 @@ <link rel="help" href="https://drafts.csswg.org/css-contain-3/#container-rule"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="support/testcommon.js"></script> <div style="container:size; width:100px; height:100px"> <main id=main></main> </div> <script> + setup(() => assert_implements_container_queries()); function cleanup_main() { while (main.firstChild)
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/auto-scrollbars.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/auto-scrollbars.html index 5542442..2dea807 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/auto-scrollbars.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/auto-scrollbars.html
@@ -4,6 +4,7 @@ <link rel="help" href="https://drafts.csswg.org/css-overflow-3/#scrollbar-layout"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="support/testcommon.js"></script> <style> #scroller { height: 100px; @@ -31,6 +32,7 @@ </div> <script> setup(() => { + assert_implements_container_queries(); assert_implements_optional(precondition.clientWidth < 100, "Tests do not work with overlay scrollbars"); });
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/backdrop-invalidation.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/backdrop-invalidation.html index 778d640..47d41fdb8 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/backdrop-invalidation.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/backdrop-invalidation.html
@@ -3,6 +3,7 @@ <link rel="help" href="https://drafts.csswg.org/css-contain-3/#size-container"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="support/testcommon.js"></script> <style> :root { color: black; @@ -28,6 +29,8 @@ <dialog>test</dialog> </main> <script> + setup(() => assert_implements_container_queries()); + let dialog = document.querySelector('dialog'); test(function() {
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/conditional-container-status.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/conditional-container-status.html index 8b5bb9b..c082a08 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/conditional-container-status.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/conditional-container-status.html
@@ -3,6 +3,7 @@ <link rel="help" href="https://drafts.csswg.org/css-contain-3/#container-type"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="support/testcommon.js"></script> <style> .parent { width: 300px; } .child { width: 100px; } @@ -18,6 +19,8 @@ </div> </div> <script> + setup(() => assert_implements_container_queries()); + test(function() { let s = getComputedStyle(document.querySelector('.grandchild')); assert_equals(s.getPropertyValue('border-color'), 'rgb(0, 128, 0)');
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-computed.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-computed.html index 3485e2f8..97c5cf5 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-computed.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-computed.html
@@ -6,8 +6,11 @@ <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/css/support/computed-testcommon.js"></script> +<script src="support/testcommon.js"></script> <div id="target"></div> <script> +setup(() => assert_implements_container_queries()); + test_computed_value('container', 'initial', 'none'); test_computed_value('container', 'inherit', 'none'); test_computed_value('container', 'unset', 'none');
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-for-shadow-dom.tentative.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-for-shadow-dom.tentative.html index 6c1dbbd..54e31ef3 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-for-shadow-dom.tentative.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-for-shadow-dom.tentative.html
@@ -5,6 +5,7 @@ <link rel="help" href="https://drafts.csswg.org/css-contain-3/#query-container"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="support/testcommon.js"></script> <style> #inclusive-ancestor-across-root, #inclusive-ancestor-skip-slotting, @@ -210,6 +211,8 @@ </div> <script> + setup(() => assert_implements_container_queries()); + const green = "rgb(0, 128, 0)"; test(() => {
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-inheritance.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-inheritance.html index 0dda54a..7bdbcdc 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-inheritance.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-inheritance.html
@@ -6,10 +6,13 @@ <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/css/support/inheritance-testcommon.js"></script> +<script src="support/testcommon.js"></script> <div id="container"> <div id="target"></div> </div> <script> +setup(() => assert_implements_container_queries()); + assert_not_inherited('container-name', 'none', 'foo'); assert_not_inherited('container-type', 'none', 'inline-size'); </script>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-name-computed.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-name-computed.html index dfd00a0..01ebb8b6 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-name-computed.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-name-computed.html
@@ -5,8 +5,11 @@ <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/css/support/computed-testcommon.js"></script> +<script src="support/testcommon.js"></script> <div id="target"></div> <script> +setup(() => assert_implements_container_queries()); + test_computed_value('container-name', 'initial', 'none'); test_computed_value('container-name', 'unset', 'none'); test_computed_value('container-name', 'foo');
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-name-invalidation.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-name-invalidation.html index 2017f7b..4dfd24c 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-name-invalidation.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-name-invalidation.html
@@ -3,6 +3,7 @@ <link rel="help" href="https://drafts.csswg.org/css-contain-3/#container-name"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="support/testcommon.js"></script> <style> div { color: black; @@ -37,6 +38,8 @@ </div> </div> <script> + setup(() => assert_implements_container_queries()); + test(function(t) { t.add_cleanup(() => { outer.style = ''; });
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-name-parsing.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-name-parsing.html index de408dd..810a0c5 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-name-parsing.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-name-parsing.html
@@ -5,8 +5,11 @@ <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/css/support/parsing-testcommon.js"></script> +<script src="support/testcommon.js"></script> <div id="target"></div> <script> +setup(() => assert_implements_container_queries()); + test_valid_value('container-name', 'initial'); test_valid_value('container-name', 'inherit'); test_valid_value('container-name', 'unset');
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-parsing.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-parsing.html index 9ec72b2f..d9c1b2d 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-parsing.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-parsing.html
@@ -6,8 +6,11 @@ <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/css/support/parsing-testcommon.js"></script> +<script src="support/testcommon.js"></script> <div id="target"></div> <script> +setup(() => assert_implements_container_queries()); + test_valid_value('container', 'initial'); test_valid_value('container', 'inherit'); test_valid_value('container', 'unset');
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-selection.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-selection.html index 8e721c4..b08df66c 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-selection.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-selection.html
@@ -3,6 +3,7 @@ <link rel="help" href="https://drafts.csswg.org/css-contain-3/#container-rule"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="support/testcommon.js"></script> <style> main { background-color: lightgray; } @@ -100,6 +101,7 @@ </main> <script> + setup(() => assert_implements_container_queries()); function test_query(prelude, selector, expected) { test(t => {
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-size-invalidation.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-size-invalidation.html index bf9d64f..b7a5d65 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-size-invalidation.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-size-invalidation.html
@@ -3,6 +3,7 @@ <link rel="help" href="https://drafts.csswg.org/css-contain-3/#size-container"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="support/testcommon.js"></script> <style> #container { container-type: size; @@ -21,6 +22,8 @@ </div> </main> <script> + setup(() => assert_implements_container_queries()); + test(function() { assert_equals(getComputedStyle(child).color, 'rgb(255, 0, 0)'); container.style.width = '300px';
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-type-computed.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-type-computed.html index edcd057..7b3e718 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-type-computed.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-type-computed.html
@@ -5,8 +5,11 @@ <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/css/support/computed-testcommon.js"></script> +<script src="support/testcommon.js"></script> <div id="target"></div> <script> +setup(() => assert_implements_container_queries()); + test_computed_value('container-type', 'initial', 'none'); test_computed_value('container-type', 'unset', 'none'); test_computed_value('container-type', 'inline-size');
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-type-containment.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-type-containment.html index 3ee5aa0b..42a42eac 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-type-containment.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-type-containment.html
@@ -3,6 +3,11 @@ <link rel="help" href="https://drafts.csswg.org/css-contain-3/#container-type"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="support/testcommon.js"></script> +<script> + setup(() => assert_implements_container_queries()); +</script> + <style> /* Note: background colors have no impact on the test result. They are present to make it easier to visually verify that the test
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-type-invalidation.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-type-invalidation.html index f4b1bf8..209c77f 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-type-invalidation.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-type-invalidation.html
@@ -3,6 +3,7 @@ <link rel="help" href="https://drafts.csswg.org/css-contain-3/#container-type"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="support/testcommon.js"></script> <style> div { color: black; @@ -36,6 +37,8 @@ </div> </div> <script> + setup(() => assert_implements_container_queries()); + test(function(t) { t.add_cleanup(() => { for (let e of [outer, intermediate, inner])
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-type-layout-invalidation.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-type-layout-invalidation.html index 57fbc5a..60b8d10 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-type-layout-invalidation.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-type-layout-invalidation.html
@@ -3,6 +3,7 @@ <link rel="help" href="https://drafts.csswg.org/css-contain-3/#size-container"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="support/testcommon.js"></script> <style> #div { width: fit-content; @@ -12,6 +13,8 @@ content </div> <script> + setup(() => assert_implements_container_queries()); + test(function(t) { t.add_cleanup(() => { div.style = ''; });
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-type-parsing.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-type-parsing.html index 7a2e2d6..6395389 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-type-parsing.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-type-parsing.html
@@ -5,8 +5,11 @@ <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/css/support/parsing-testcommon.js"></script> +<script src="support/testcommon.js"></script> <div id="target"></div> <script> +setup(() => assert_implements_container_queries()); + test_valid_value('container-type', 'initial'); test_valid_value('container-type', 'inherit'); test_valid_value('container-type', 'unset');
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-units-animation.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-units-animation.html index c938ca43..28413092 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-units-animation.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-units-animation.html
@@ -3,6 +3,7 @@ <link rel="help" href="https://drafts.csswg.org/css-contain-3/#container-lengths"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="support/testcommon.js"></script> <style> #container { container-type: size; @@ -41,6 +42,8 @@ <div id=element_qmax></div> </div> <script> + setup(() => assert_implements_container_queries()); + const units = ['qw', 'qh', 'qi', 'qb', 'qmin', 'qmax']; for (let unit of units) {
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-units-basic.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-units-basic.html index e54f02f..abe3eaf 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-units-basic.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-units-basic.html
@@ -3,6 +3,7 @@ <link rel="help" href="https://drafts.csswg.org/css-contain-3/#container-lengths"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="support/testcommon.js"></script> <style> .inline { container-type: inline-size; } .size { container-type: size; } @@ -19,6 +20,7 @@ </div> </div> <script> + setup(() => assert_implements_container_queries()); function assert_unit_equals(element, actual, expected) { try {
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-units-computational-independence.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-units-computational-independence.html index b26e25d..42c9e6e 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-units-computational-independence.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-units-computational-independence.html
@@ -4,7 +4,10 @@ <link rel="help" href="https://drafts.css-houdini.org/css-properties-values-api-1/#computationally-independent"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="support/testcommon.js"></script> <script> + setup(() => assert_implements_container_queries()); + const units = ['qw', 'qh', 'qi', 'qb', 'qmin', 'qmax']; for (let unit of units) {
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-units-invalidation.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-units-invalidation.html index 2c1cc2e..2ddc2756 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-units-invalidation.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-units-invalidation.html
@@ -3,6 +3,7 @@ <link rel="help" href="https://drafts.csswg.org/css-contain-3/#container-lengths"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="support/testcommon.js"></script> <style> #inline { container-type: inline-size; } #size, #outer { container-type: size; } @@ -24,6 +25,7 @@ </div> </div> <script> + setup(() => assert_implements_container_queries()); function assert_qi_equals(element, expected) { assert_equals(getComputedStyle(element).paddingLeft, expected);
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-units-selection.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-units-selection.html index f5ae011..ef05ba8 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-units-selection.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-units-selection.html
@@ -3,6 +3,7 @@ <link rel="help" href="https://drafts.csswg.org/css-contain-3/#container-lengths"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="support/testcommon.js"></script> <style> * { writing-mode: initial; } .inline { container-type: inline-size; } @@ -25,6 +26,7 @@ </div> </div> <script> + setup(() => assert_implements_container_queries()); function assert_unit_equals(element, actual, expected) { try {
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-units-typed-om.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-units-typed-om.html index 286df7c0d..6f3d758 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-units-typed-om.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/container-units-typed-om.html
@@ -4,8 +4,11 @@ <link rel="help" href="https://drafts.css-houdini.org/css-typed-om-1/#stylepropertymap"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="support/testcommon.js"></script> <div id=element></div> <script> + setup(() => assert_implements_container_queries()); + const units = ['qw', 'qh', 'qi', 'qb', 'qmin', 'qmax']; const functions = { qw: CSS.qw,
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/counters-flex-circular.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/counters-flex-circular.html index 28be7df..31741e5c 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/counters-flex-circular.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/counters-flex-circular.html
@@ -4,6 +4,7 @@ <link rel="stylesheet" href="/fonts/ahem.css"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="support/testcommon.js"></script> <style> #flex { width: 200px; @@ -48,6 +49,8 @@ <div id="item2"></div> </div> <script> + setup(() => assert_implements_container_queries()); + const item1_width = parseInt(getComputedStyle(item1).width); const item2_width = parseInt(getComputedStyle(item2).width); const container_width = parseInt(getComputedStyle(container).width);
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/display-contents.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/display-contents.html index 4df979e..4be3e79 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/display-contents.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/display-contents.html
@@ -4,6 +4,10 @@ <link rel="help" href="https://drafts.csswg.org/css-contain-2/#containment-size"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="support/testcommon.js"></script> +<script> + setup(() => assert_implements_container_queries()); +</script> <style> .container { container-type: inline-size;
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/display-none.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/display-none.html index d6511c2..8341b364 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/display-none.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/display-none.html
@@ -4,6 +4,10 @@ <link rel="help" href="https://drafts.csswg.org/css-contain-2/#containment-size"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="support/testcommon.js"></script> +<script> + setup(() => assert_implements_container_queries()); +</script> <style> .container { container-type: size;
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/font-relative-units-dynamic.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/font-relative-units-dynamic.html index 3c8e9c7..f50614c4 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/font-relative-units-dynamic.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/font-relative-units-dynamic.html
@@ -3,6 +3,7 @@ <link rel="help" href="https://drafts.csswg.org/css-contain-3/#size-container"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="support/testcommon.js"></script> <style> :root { font-size: 10px; } :root.larger { font-size: 50px; } @@ -32,6 +33,8 @@ <div id="ch_test"></div> </div> <script> + setup(() => assert_implements_container_queries()); + const green = "rgb(0, 128, 0)"; const red = "rgb(255, 0, 0)";
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/font-relative-units.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/font-relative-units.html index 3919f81..670629d 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/font-relative-units.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/font-relative-units.html
@@ -3,6 +3,7 @@ <link rel="help" href="https://drafts.csswg.org/css-contain-3/#size-container"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="support/testcommon.js"></script> <style> :root { font-size: 10px; } #em_container { @@ -44,6 +45,8 @@ <div id="ch_test"></div> </div> <script> + setup(() => assert_implements_container_queries()); + const green = "rgb(0, 128, 0)"; test(() => assert_equals(getComputedStyle(em_test).color, green), "em relative inline-size"); test(() => assert_equals(getComputedStyle(rem_test).color, green), "rem relative inline-size");
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/get-animations.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/get-animations.html index 72cc64f..4c7489c 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/get-animations.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/get-animations.html
@@ -3,6 +3,7 @@ <link rel="help" href="https://drafts.csswg.org/css-contain-3/#animated-containers"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="support/testcommon.js"></script> <style> #container { container-type: inline-size; @@ -21,6 +22,8 @@ <div id=div>Green</div> </div> <script> + setup(() => assert_implements_container_queries()); + test(() => { assert_equals(getComputedStyle(div).color, 'rgb(255, 0, 0)');
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/iframe-invalidation.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/iframe-invalidation.html index 90513fe..09adf705 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/iframe-invalidation.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/iframe-invalidation.html
@@ -3,6 +3,7 @@ <link rel="help" href="https://drafts.csswg.org/css-contain-3/#size-container"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="support/testcommon.js"></script> <style> iframe { width: 200px; @@ -25,6 +26,7 @@ </div> "></iframe> <script> + setup(() => assert_implements_container_queries()); function waitForLoad(w) { return new Promise(resolve => w.addEventListener('load', resolve));
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/ineligible-containment.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/ineligible-containment.html index f9ea1e2..c041acd 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/ineligible-containment.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/ineligible-containment.html
@@ -4,6 +4,7 @@ <link rel="help" href="https://drafts.csswg.org/css-contain-2/#containment-size"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="support/testcommon.js"></script> <style> #outer, #inner1, #inner2 { width: 200px; @@ -28,6 +29,7 @@ </div> </main> <script> + setup(() => assert_implements_container_queries()); test(function(t) { // #inner1 is the container, but it does not satisfy the containment
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/inline-size-and-min-width.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/inline-size-and-min-width.html index e35c6dd..8d72729 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/inline-size-and-min-width.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/inline-size-and-min-width.html
@@ -3,6 +3,7 @@ <link rel="help" href="https://drafts.csswg.org/css-contain-3/#container-queries"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="support/testcommon.js"></script> <style> #container { container-type: inline-size; @@ -17,6 +18,8 @@ <div id="child">Green</div> </div> <script> + setup(() => assert_implements_container_queries()); + test(() => { assert_equals(getComputedStyle(child).color, "rgb(0, 128, 0)"); }, "min-width of inline-size container affects container size");
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/inline-size-containment-vertical-rl.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/inline-size-containment-vertical-rl.html index 5782a89..cfc0206 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/inline-size-containment-vertical-rl.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/inline-size-containment-vertical-rl.html
@@ -21,7 +21,10 @@ </div> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="support/testcommon.js"></script> <script> + setup(() => assert_implements_container_queries()); + test(()=> { ancestry.style.height = "100px"; assert_equals(keg.offsetWidth, 400);
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/inline-size-containment.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/inline-size-containment.html index 466766e..d600fa0 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/inline-size-containment.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/inline-size-containment.html
@@ -20,7 +20,10 @@ </div> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="support/testcommon.js"></script> <script> + setup(() => assert_implements_container_queries()); + test(()=> { ancestry.style.width = "100px"; assert_equals(keg.offsetHeight, 400);
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/orthogonal-wm-container-query.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/orthogonal-wm-container-query.html index 1aa748a3..3147a429 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/orthogonal-wm-container-query.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/orthogonal-wm-container-query.html
@@ -3,6 +3,7 @@ <link rel="help" href="https://drafts.csswg.org/css-contain-3/#size-container"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="support/testcommon.js"></script> <link rel="stylesheet" href="/fonts/ahem.css"> <style> #container { @@ -23,6 +24,8 @@ <div id="orthogonal">XX</div> </div> <script> + setup(() => assert_implements_container_queries()); + test(() => { assert_equals(orthogonal.offsetWidth, container.offsetWidth); }, "Initial non-orthogonal width");
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/pseudo-elements-001.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/pseudo-elements-001.html index 6917a8aa..35a6759c 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/pseudo-elements-001.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/pseudo-elements-001.html
@@ -3,6 +3,7 @@ <link rel="help" href="https://drafts.csswg.org/css-contain-3/#query-container"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="support/testcommon.js"></script> <style> :root { color: black; @@ -29,6 +30,8 @@ </ol> </main> <script> + setup(() => assert_implements_container_queries()); + test(function() { let div = document.querySelector('#container1 > div'); assert_equals(getComputedStyle(div, '::before').content, 'none');
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/pseudo-elements-003.tentative.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/pseudo-elements-003.tentative.html index 6201211..68fd06fa 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/pseudo-elements-003.tentative.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/pseudo-elements-003.tentative.html
@@ -3,6 +3,7 @@ <link rel="help" href="https://github.com/w3c/csswg-drafts/issues/6711"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="support/testcommon.js"></script> <style> .container { container-type: inline-size; } #target { display: list-item; } @@ -33,6 +34,8 @@ </div> </div> <script> + setup(() => assert_implements_container_queries()); + const green = "rgb(0, 128, 0)"; const lime = "rgb(0, 255, 0)";
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/query-evaluation.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/query-evaluation.html index 7c28c24..e8952b2 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/query-evaluation.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/query-evaluation.html
@@ -3,6 +3,7 @@ <link rel="help" href="https://drafts.csswg.org/css-contain-3/#container-rule"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="support/testcommon.js"></script> <style> #container { width: 1px; @@ -15,6 +16,7 @@ <div id=inner></div> </div> <script> + setup(() => assert_implements_container_queries()); function test_query(query, expected) { test((t) => {
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/reattach-container-with-dirty-child.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/reattach-container-with-dirty-child.html index 1d8c294..ab4cc22 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/reattach-container-with-dirty-child.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/reattach-container-with-dirty-child.html
@@ -3,6 +3,7 @@ <link rel="help" href="https://drafts.csswg.org/css-contain-3/#size-container"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="support/testcommon.js"></script> <style> #container { container-type: inline-size; @@ -18,6 +19,8 @@ <div id="child"><span id="inner">XXX</span></div> </div> <script> + setup(() => assert_implements_container_queries()); + test(() => { container.offsetTop; assert_equals(getComputedStyle(child).color, "rgb(255, 0, 0)");
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/size-container-no-principal-box.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/size-container-no-principal-box.html index 91d4330..c26dfdd1 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/size-container-no-principal-box.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/size-container-no-principal-box.html
@@ -3,6 +3,7 @@ <link rel="help" href="https://drafts.csswg.org/css-contain-3/#size-container"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="support/testcommon.js"></script> <style> #outer { container-type: inline-size; @@ -28,6 +29,8 @@ <div id="inner_contents"><span></span></div> </div> <script> + setup(() => assert_implements_container_queries()); + test(() => { assert_equals(getComputedStyle(ref).color, "rgb(0, 128, 0)"); }, "Check that container queries is supported");
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/size-feature-evaluation.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/size-feature-evaluation.html index 390f7caf..763ac196f 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/size-feature-evaluation.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/size-feature-evaluation.html
@@ -3,6 +3,7 @@ <link rel="help" href="https://drafts.csswg.org/css-contain-3/#size-container"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="support/testcommon.js"></script> <div id=container> <div id=target> @@ -11,6 +12,7 @@ </div> <script> +setup(() => assert_implements_container_queries()); function test_evaluation(container_class, query, expected) { test(function(t) {
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/style-change-in-container.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/style-change-in-container.html index 6b8a6c7..d2c6ff3 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/style-change-in-container.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/style-change-in-container.html
@@ -3,6 +3,7 @@ <link rel="help" href="https://drafts.csswg.org/css-contain-3/#container-queries"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="support/testcommon.js"></script> <style> #container { container-type: size; } @container size(min-width: 1px) { @@ -13,6 +14,8 @@ <div id="content"></div> </div> <script> + setup(() => assert_implements_container_queries()); + test(() => { assert_equals(getComputedStyle(content).color, "rgb(0, 128, 0)");
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/support/testcommon.js b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/support/testcommon.js new file mode 100644 index 0000000..2eaca1d --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/support/testcommon.js
@@ -0,0 +1,3 @@ +function assert_implements_container_queries() { + assert_implements(CSS.supports("container-type:size"), "Basic support for container queries required"); +}
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/top-layer-dialog-container.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/top-layer-dialog-container.html index 06e6b6e..f3799fe 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/top-layer-dialog-container.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/top-layer-dialog-container.html
@@ -3,6 +3,7 @@ <link rel="help" href="https://drafts.csswg.org/css-contain-3/#container-queries"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="support/testcommon.js"></script> <style> #parent { width: 100px; } #dialog { @@ -19,6 +20,8 @@ <dialog id="dialog"><span id="child"></span></dialog> </div> <script> + setup(() => assert_implements_container_queries()); + test(() => { assert_equals(getComputedStyle(child).color, "rgb(255, 0, 0)"); }, "#dialog initially sized by #containing-block");
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/top-layer-dialog.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/top-layer-dialog.html index dc8dc9c..54ba22e 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/top-layer-dialog.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/top-layer-dialog.html
@@ -3,6 +3,7 @@ <link rel="help" href="https://drafts.csswg.org/css-contain-3/#container-queries"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="support/testcommon.js"></script> <style> #container { container-type: inline-size; @@ -21,6 +22,8 @@ <dialog id="dialog"></dialog> </div> <script> + setup(() => assert_implements_container_queries()); + test(() => { assert_equals(getComputedStyle(dialog).color, "rgb(255, 0, 0)"); }, "#container initially wider than 200px");
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/top-layer-nested-dialog.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/top-layer-nested-dialog.html index 6cf65d04..34904706 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/top-layer-nested-dialog.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/top-layer-nested-dialog.html
@@ -3,6 +3,7 @@ <link rel="help" href="https://drafts.csswg.org/css-contain-3/#container-queries"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="support/testcommon.js"></script> <style> dialog { color: red; } #container { width: 100px; } @@ -20,6 +21,8 @@ </dialog> </div> <script> + setup(() => assert_implements_container_queries()); + test(() => { assert_equals(getComputedStyle(outer).color, "rgb(255, 0, 0)"); assert_equals(getComputedStyle(inner).color, "rgb(255, 0, 0)");
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/transition-scrollbars.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/transition-scrollbars.html index 934a6cb..816ae06 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/transition-scrollbars.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/transition-scrollbars.html
@@ -4,6 +4,7 @@ <link rel="help" href="https://drafts.csswg.org/css-contain-3/#animated-containers"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="support/testcommon.js"></script> <style> #scrollable { overflow: auto; @@ -45,6 +46,8 @@ </div> </div> <script> + setup(() => assert_implements_container_queries()); + test(() => { // Whether or not a scrollbar appeared is out of scope for this test. // The only thing we care about is that no transition was triggered.
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/transition-style-change-event.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/transition-style-change-event.html index 52fc67ac..b5ae21f 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/transition-style-change-event.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/transition-style-change-event.html
@@ -5,6 +5,7 @@ <link rel="help" href="https://drafts.csswg.org/css-contain-3/#animated-containers"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="support/testcommon.js"></script> <style> .container { container-type: size } #outer { @@ -28,6 +29,8 @@ </div> </div> <script> + setup(() => assert_implements_container_queries()); + const t = async_test(""); const event_handler = t.step_func_done((e) => { assert_unreached("Transition event incorrectly triggered: " + e.type);
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/unsupported-axis.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/unsupported-axis.html index 35ccfa2..757b62d 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/unsupported-axis.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/unsupported-axis.html
@@ -3,6 +3,11 @@ <link rel="help" href="https://drafts.csswg.org/css-contain-3/#size-container"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="support/testcommon.js"></script> +<script> + setup(() => assert_implements_container_queries()); +</script> + <style> #container { width: 200px;
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/viewport-units-dynamic.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/viewport-units-dynamic.html index 93b5509..72b1c4be 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/viewport-units-dynamic.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/viewport-units-dynamic.html
@@ -3,6 +3,7 @@ <link rel="help" href="https://drafts.csswg.org/css-contain-3/#size-container"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="support/testcommon.js"></script> <style> iframe { width: 100px; @@ -33,6 +34,8 @@ <div id=vh><span>Green</span></div> "></iframe> <script> + setup(() => assert_implements_container_queries()); + function waitForLoad(w) { return new Promise(resolve => w.addEventListener('load', resolve)); }
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/viewport-units.html b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/viewport-units.html index 76f255c..6cf1d204 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/viewport-units.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/container-queries/viewport-units.html
@@ -3,6 +3,7 @@ <link rel="help" href="https://drafts.csswg.org/css-contain-3/#size-container"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="support/testcommon.js"></script> <style> #vw { container-type: inline-size; width: 10vw; } #vh { container-type: inline-size; width: 10vh; } @@ -23,6 +24,8 @@ <div id="vw"><span>Green</span></div> <div id="vh"><span>Green</span></div> <script> + setup(() => assert_implements_container_queries()); + const green = "rgb(0, 128, 0)"; test(() => assert_equals(getComputedStyle(vw.firstChild).color, green), "Match width with vw");
diff --git a/third_party/blink/web_tests/external/wpt/css/css-scroll-snap/input/snap-area-overflow-boundary-expected.txt b/third_party/blink/web_tests/external/wpt/css/css-scroll-snap/input/snap-area-overflow-boundary-expected.txt new file mode 100644 index 0000000..59ec6bf --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-scroll-snap/input/snap-area-overflow-boundary-expected.txt
@@ -0,0 +1,5 @@ +This is a testharness.js-based test. +FAIL Keyboard scrolling with vertical snap-area overflow assert_equals: End boundary of snap-area is valid snap target expected 39 but got 449 +FAIL Mouse-wheel scrolling with vertical snap-area overflow assert_equals: End boundary of snap-area is valid snap target expected 100 but got 0 +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/css/css-scroll-snap/input/snap-area-overflow-boundary.html b/third_party/blink/web_tests/external/wpt/css/css-scroll-snap/input/snap-area-overflow-boundary.html new file mode 100644 index 0000000..ce9f73ef --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-scroll-snap/input/snap-area-overflow-boundary.html
@@ -0,0 +1,150 @@ +<!DOCTYPE html> +<link rel="help" href="https://www.w3.org/TR/css-scroll-snap-1/#snap-overflow" /> +<title></title> +<meta name="assert" content="Test passes if snap is to the nearest edge"> +<style> + #scroller { + scroll-snap-type: block mandatory; + overflow-y: scroll; + height: 400px; + width: 400px + } + #space { + width: 200px; + height: 4000px; + } + .box { + scroll-snap-align: start; + background: #ccccff; + margin-bottom: 10px; + width: 300px; + height: 500px; + position: relative; + } + .header { + top: 0; + position: absolute; + } + .footer { + bottom: 0; + position: absolute; + } +</style> +<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/testdriver-actions.js"></script> +<script src="../support/common.js"></script> + +<div id="scroller"> + <div id="target" class="box"> + <div class="header">Header 1</div> + <div class="footer">Footer 1</div> + </div> + <div id="next" class="box"> + <div class="header">Header 2</div> + <div class="footer">Footer 2</div> + </div> + <div id="space"></div> +</div> + +<script> +// If all of the following conditions are met: +// 1. the snap area is larger than the snapport along the scroll axis, and +// 2. the distance between the previous and subsequent snap positions along +// the axis is greater then the snapport size. +// +// Then any scroll position in which the snap area covers the snapport is +// valid snap position. This rule facilitates scrolling around in oversized +// elements. +// +// These test covers edge cases with snap-areas that overflow the snapport. +// It should be possible to scroll to the end of an oversized snap-area. + +const scroller = document.getElementById("scroller"); +const target = document.getElementById("target"); +const next = document.getElementById("next"); +const scrollTop = () => { + return scroller.scrollTop; +}; +const cleanup = () => { + target.style.height = '500px'; +}; + +promise_test(async t => { + t.add_cleanup(cleanup); + scroller.scrollTo(0, 0); + assert_equals(scroller.scrollTop, 0, "verify test pre-condition"); + + // Ensure we can freely scroll in an oversized element. + const scrollPromise = waitForScrollEvent(scroller); + await keyPress(scroller, "ArrowDown"); + await scrollPromise; + await waitForAnimationEnd(scrollTop); + assert_greater_than(scroller.scrollTop, 0, + 'Arrowkey scroll moved scroll position'); + assert_less_than_equal(scroller.scrollTop, target.clientHeight, + 'Scroll within snap-area overflow'); + + // Resize the element so it is oversized by less than the line scroll amount. + // The next keyboard-triggered scroll should stop at the end of the snap-area. + // Otherwise it is not possible to scroll to the last line of the snap-area + // via keyboard. + const scrollAmount = scroller.scrollTop; + target.style.height = `${scroller.clientHeight + scrollAmount - 1}px`; + assert_equals(scroller.scrollTop, 0, "Verify snap on relayout"); + await keyPress(scroller, "ArrowDown"); + await waitForAnimationEnd(scrollTop); + assert_equals(scroller.scrollTop, + target.clientHeight - scroller.clientHeight, + 'End boundary of snap-area is valid snap target'); + + // Must not get stuck at a snap position. Since already at the end of the + // snap area, we should advance to the next. + await keyPress(scroller, "ArrowDown"); + await waitForAnimationEnd(scrollTop); + assert_equals(scroller.scrollTop, + next.clientTop, + 'Advance to next snap-area'); + +}, "Keyboard scrolling with vertical snap-area overflow"); + +promise_test(async t => { + scroller.scrollTo(0, 0); + assert_equals(scroller.scrollTop, 0, "verify test pre-condition"); + + // Ensure we can freely scroll in an oversized element. + const scrollPromise = waitForScrollEvent(scroller); + await new test_driver.Actions() + .scroll(50, 50, 0, 50, {origin: scroller}) + .send(); + await scrollPromise; + await waitForAnimationEnd(scrollTop); + assert_equals(scroller.scrollTop, 50, + 'Wheel-scroll moved scroll position'); + + // Target position for wheel scroll overshoots the boundary of the snap-area. + // Ensure that we stop at the boundary. + const scrollAmount = + target.clientHeight - scroller.clientHeight - scroller.scrollTop + 1; + + await new test_driver.Actions() + .scroll(50, 50, 0, scrollAmount, {origin: scroller}) + .send(); + await waitForAnimationEnd(scrollTop); + assert_equals(scroller.scrollTop, 100, + 'End boundary of snap-area is valid snap target'); + + // Must not get stuck at a snap position. Since already at the end of the + // snap area, we should advance to the next. + await new test_driver.Actions() + .scroll(50, 50, 0, 50, {origin: scroller}) + .send(); + await waitForAnimationEnd(scrollTop); + assert_equals(scroller.scrollTop, + next.clientTop, + 'Advance to next snap-area'); + +}, "Mouse-wheel scrolling with vertical snap-area overflow"); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/custom-elements/form-associated/ElementInternals-validation.html b/third_party/blink/web_tests/external/wpt/custom-elements/form-associated/ElementInternals-validation.html index 6b2ef87..c52473f 100644 --- a/third_party/blink/web_tests/external/wpt/custom-elements/form-associated/ElementInternals-validation.html +++ b/third_party/blink/web_tests/external/wpt/custom-elements/form-associated/ElementInternals-validation.html
@@ -205,6 +205,11 @@ }, '"anchor" argument of setValidity()'); test(() => { + const element = new NotFormAssociatedElement(); + assert_throws_dom('NotSupportedError', () => element.i.checkValidity()); +}, "checkValidity() should throw NotSupportedError if the target element is not a form-associated custom element"); + +test(() => { const control = document.createElement('my-control'); let invalidCount = 0; control.addEventListener('invalid', e => {
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/forms/the-selectmenu-element/selectmenu-events.tentative.html b/third_party/blink/web_tests/external/wpt/html/semantics/forms/the-selectmenu-element/selectmenu-events.tentative.html new file mode 100644 index 0000000..89069e4 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/semantics/forms/the-selectmenu-element/selectmenu-events.tentative.html
@@ -0,0 +1,99 @@ +<!DOCTYPE html> +<title>HTMLSelectMenuElement Test: events</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/resources/testdriver.js"></script> +<script src="/resources/testdriver-actions.js"></script> +<script src="/resources/testdriver-vendor.js"></script> + +<selectmenu id="selectMenu0"> + <div slot="button" behavior="button"> + <span behavior="selected-value"></span> + <button id="selectMenu0-button">selectMenu0-button</button> + </div> + <option>one</option> + <option>two</option> + <option>three</option> +</selectmenu> + +<selectmenu id="selectMenu1"> + <option>one</option> + <option> + two + <button id="selectMenu1-button">selectMenu1-button</button> + </option> + <option>three</option> +</selectmenu> + +<script> + + function clickOn(element) { + const actions = new test_driver.Actions(); + return actions.pointerMove(0, 0, {origin: element}) + .pointerDown({button: actions.ButtonType.LEFT}) + .pointerUp({button: actions.ButtonType.LEFT}) + .send(); + } + + promise_test(async () => { + const selectMenu = document.getElementById("selectMenu0"); + const selectMenuButton = document.getElementById("selectMenu0-button"); + assert_false(selectMenu.open); + const selectMenuButtonPromise = new Promise(async resolve => { + selectMenuButton.addEventListener("click", (e) => { + assert_false(selectMenu.open, "Listbox shouldn't have opened yet"); + // PreventDefaulting the event here should prevent UA controller code + // on the button part from opening the listbox. + e.preventDefault(); + resolve(); + }); + }); + + const selectMenuPromise = new Promise(async resolve => { + selectMenu.addEventListener("click", (e) => { + assert_true(e.defaultPrevented, "Event should have been defaultPrevented by selectMenuButton click handler"); + assert_false(selectMenu.open, "Listbox shouldn't have opened, because click event was defaultPrevented."); + resolve(); + }); + }); + + await clickOn(selectMenuButton); + return Promise.all([selectMenuButtonPromise, selectMenuPromise]); + }, "Button controller code should not run if the click event is preventDefaulted."); + + // See https://w3c.github.io/webdriver/#keyboard-actions + const KEY_CODE_MAP = { + 'Enter': '\uE007', + 'Space': '\uE00D', + 'ArrowUp': '\uE013', + 'ArrowDown': '\uE015' + }; + + promise_test(async () => { + const selectMenu = document.getElementById("selectMenu1"); + const selectMenuButton = document.getElementById("selectMenu1-button"); + await clickOn(selectMenu); + assert_true(selectMenu.open); + const selectMenuButtonPromise = new Promise(async resolve => { + selectMenuButton.addEventListener("click", (e) => { + assert_true(selectMenu.open, "Listbox shouldn't have closed yet"); + // PreventDefaulting the event here should prevent UA controller code + // on the listbox part from selecting the option and closing the listbox. + e.preventDefault(); + resolve(); + }); + }); + + const selectMenuPromise = new Promise(async resolve => { + selectMenu.addEventListener("click", (e) => { + assert_true(e.defaultPrevented, "Event should have been defaultPrevented by selectMenuButton click handler"); + assert_true(selectMenu.open, "Listbox shouldn't have closed, because keydown event was defaultPrevented."); + assert_equals(selectMenu.value, "one", "<selectmenu> shouldn't have changed value, because keydown event was defaultPrevented."); + resolve(); + }); + }); + + await clickOn(selectMenuButton); + return Promise.all([selectMenuButtonPromise, selectMenuPromise]); + }, "Listbox controller code should not run if the click event is preventDefaulted."); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/mediacapture-record/MediaRecorder-start-expected.txt b/third_party/blink/web_tests/external/wpt/mediacapture-record/MediaRecorder-start-expected.txt new file mode 100644 index 0000000..c7381df --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/mediacapture-record/MediaRecorder-start-expected.txt
@@ -0,0 +1,4 @@ +This is a testharness.js-based test. +FAIL MediaRecorder cannot record the stream using the current configuration assert_throws_dom: function "() => mediaRecorder.start()" did not throw +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/mediacapture-record/MediaRecorder-start.html b/third_party/blink/web_tests/external/wpt/mediacapture-record/MediaRecorder-start.html new file mode 100644 index 0000000..ef2fe69 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/mediacapture-record/MediaRecorder-start.html
@@ -0,0 +1,25 @@ +<!doctype html> +<html> +<head> + <title>MediaRecorder Start</title> + <link rel="help" href="https://w3c.github.io/mediacapture-record/MediaRecorder.html#dom-mediarecorder-start"> + <script src="/resources/testharness.js"></script> + <script src="/resources/testharnessreport.js"></script> +</head> +<body> +<canvas id="canvas" width="200" height="200"> +</canvas> +<script> + function createVideoStream() { + canvas.getContext('2d'); + return canvas.captureStream(); + } + + test(t => { + const mimeType = [ 'audio/aac', 'audio/ogg', 'audio/webm' ].find(MediaRecorder.isTypeSupported); + const mediaRecorder = new MediaRecorder(createVideoStream(), {mimeType}); + assert_throws_dom("NotSupportedError", () => mediaRecorder.start()); + }, "MediaRecorder cannot record the stream using the current configuration"); +</script> +</body> +</html>
diff --git a/third_party/blink/web_tests/external/wpt/serial/serialPort_writable.https.any.js b/third_party/blink/web_tests/external/wpt/serial/serialPort_writable.https.any.js index 5e3b8548..19829e91 100644 --- a/third_party/blink/web_tests/external/wpt/serial/serialPort_writable.https.any.js +++ b/third_party/blink/web_tests/external/wpt/serial/serialPort_writable.https.any.js
@@ -155,9 +155,8 @@ const data = new Uint8Array(1024); // Much larger than bufferSize above. for (let i = 0; i < data.byteLength; ++i) data[i] = i & 0xff; - let writePromise = writer.write(data).catch(reason => { - assert_equals(reason, 'Aborting.'); - }); + const writePromise = + promise_rejects_exactly(t, 'Aborting.', writer.write(data)); await writer.abort('Aborting.'); await writePromise; @@ -174,15 +173,11 @@ const data = new Uint8Array(1024); // Much larger than bufferSize above. for (let i = 0; i < data.byteLength; ++i) data[i] = i & 0xff; - let closed = (async () => { - try { - await writer.write(data); - } catch (reason) { - assert_equals(reason, 'Aborting.'); - writer.releaseLock(); - await port.close(); - assert_equals(port.writable, null); - } + const closed = (async () => { + await promise_rejects_exactly(t, 'Aborting.', writer.write(data)); + writer.releaseLock(); + await port.close(); + assert_equals(port.writable, null); })(); await writer.abort('Aborting.');
diff --git a/third_party/blink/web_tests/external/wpt/webdriver/META.yml b/third_party/blink/web_tests/external/wpt/webdriver/META.yml index a397b49..a41161d 100644 --- a/third_party/blink/web_tests/external/wpt/webdriver/META.yml +++ b/third_party/blink/web_tests/external/wpt/webdriver/META.yml
@@ -1,7 +1,8 @@ spec: https://w3c.github.io/webdriver/ suggested_reviewers: - AutomatedTester - - andreastt - - mjzffr + - jgraham + - juliandescottes + - sadym-chromium - shs96c - whimboo
diff --git a/third_party/blink/web_tests/external/wpt/webdriver/tests/bidi/session_subscribe/__init__.py b/third_party/blink/web_tests/external/wpt/webdriver/tests/bidi/session_subscribe/__init__.py new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/webdriver/tests/bidi/session_subscribe/__init__.py
diff --git a/third_party/blink/web_tests/external/wpt/webdriver/tests/bidi/session_unsubscribe/__init__.py b/third_party/blink/web_tests/external/wpt/webdriver/tests/bidi/session_unsubscribe/__init__.py new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/webdriver/tests/bidi/session_unsubscribe/__init__.py
diff --git a/third_party/blink/web_tests/external/wpt/webdriver/tests/find_element_from_shadow_root/__init__.py b/third_party/blink/web_tests/external/wpt/webdriver/tests/find_element_from_shadow_root/__init__.py new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/webdriver/tests/find_element_from_shadow_root/__init__.py
diff --git a/third_party/blink/web_tests/external/wpt/webdriver/tests/find_elements_from_shadow_root/__init__.py b/third_party/blink/web_tests/external/wpt/webdriver/tests/find_elements_from_shadow_root/__init__.py new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/webdriver/tests/find_elements_from_shadow_root/__init__.py
diff --git a/third_party/blink/web_tests/external/wpt/webdriver/tests/get_element_shadow_root/__init__.py b/third_party/blink/web_tests/external/wpt/webdriver/tests/get_element_shadow_root/__init__.py new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/webdriver/tests/get_element_shadow_root/__init__.py
diff --git a/third_party/blink/web_tests/external/wpt/webdriver/tests/permissions/__init__.py b/third_party/blink/web_tests/external/wpt/webdriver/tests/permissions/__init__.py new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/webdriver/tests/permissions/__init__.py
diff --git a/third_party/blink/web_tests/flag-specific/highdpi/external/wpt/mediacapture-record/MediaRecorder-start-expected.txt b/third_party/blink/web_tests/flag-specific/highdpi/external/wpt/mediacapture-record/MediaRecorder-start-expected.txt new file mode 100644 index 0000000..c7381df --- /dev/null +++ b/third_party/blink/web_tests/flag-specific/highdpi/external/wpt/mediacapture-record/MediaRecorder-start-expected.txt
@@ -0,0 +1,4 @@ +This is a testharness.js-based test. +FAIL MediaRecorder cannot record the stream using the current configuration assert_throws_dom: function "() => mediaRecorder.start()" did not throw +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/http/tests/inspector-protocol/target/auto-attach-service-worker-multiple-sessions-expected.txt b/third_party/blink/web_tests/http/tests/inspector-protocol/target/auto-attach-service-worker-multiple-sessions-expected.txt new file mode 100644 index 0000000..7ba8430 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/inspector-protocol/target/auto-attach-service-worker-multiple-sessions-expected.txt
@@ -0,0 +1,5 @@ +Tests that browser.Target.setAutoAttach() only throttles service worker for sessions that asked for it. +session 1 attached, waiting: true +session 2 attached, waiting: false +PASSED: service worker URL http://127.0.0.1:8000/inspector-protocol/service-worker/resources/blank-service-worker.js +
diff --git a/third_party/blink/web_tests/http/tests/inspector-protocol/target/auto-attach-service-worker-multiple-sessions.js b/third_party/blink/web_tests/http/tests/inspector-protocol/target/auto-attach-service-worker-multiple-sessions.js new file mode 100644 index 0000000..3ea141a --- /dev/null +++ b/third_party/blink/web_tests/http/tests/inspector-protocol/target/auto-attach-service-worker-multiple-sessions.js
@@ -0,0 +1,29 @@ +(async function(testRunner) { + const {page, session, dp} = await testRunner.startURL( + '/inspector-protocol/resources/empty.html', + `Tests that browser.Target.setAutoAttach() only throttles service worker for sessions that asked for it.`); + const swHelper = (await testRunner.loadScript('../service-worker/resources/service-worker-helper.js'))(dp, session); + + const attachedToPage = (await testRunner.browserP().Target.attachToTarget({targetId: page.targetId(), flatten: true})).result; + const session2 = new TestRunner.Session(testRunner, attachedToPage.sessionId); + const dp2 = session2.protocol; + + dp.Target.onAttachedToTarget(event => { + testRunner.log(`session 1 attached, waiting: ${event.params.waitingForDebugger}`); + const swSession = new TestRunner.Session(testRunner, event.params.sessionId); + swSession.protocol.Runtime.runIfWaitingForDebugger(); + }) + await dp.Target.setAutoAttach({autoAttach: true, waitForDebuggerOnStart: true, flatten: true}); + await dp2.Target.setAutoAttach({autoAttach: true, waitForDebuggerOnStart: false, flatten: true}); + + const workerReady = swHelper.installSWAndWaitForActivated('/inspector-protocol/service-worker/resources/blank-service-worker.js'); + + const attachedToSW = (await dp2.Target.onceAttachedToTarget(event => event.params.targetInfo.type === "service_worker")).params; + testRunner.log(`session 2 attached, waiting: ${attachedToSW.waitingForDebugger}`); + const swSession = new TestRunner.Session(testRunner, attachedToSW.sessionId); + swSession.protocol.Runtime.runIfWaitingForDebugger(); + await workerReady; + const href = await swSession.evaluate(`location.href`); + testRunner.log(`PASSED: service worker URL ${href}`); + testRunner.completeTest(); +})
diff --git a/third_party/blink/web_tests/http/tests/origin_trials/webexposed/app-history-origin-trial.html b/third_party/blink/web_tests/http/tests/origin_trials/webexposed/app-history-origin-trial.html new file mode 100644 index 0000000..1c4ca66 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/origin_trials/webexposed/app-history-origin-trial.html
@@ -0,0 +1,15 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<!-- Generate token with the command: +generate_token.py http://127.0.0.1:8000 AppHistory --expire-timestamp=2000000000 +-- --> +<meta http-equiv="origin-trial" content="A+XNvNEjHaWhHcc4SQ0nNvrywJerpyfiZw5SEB7RLT/fnFZo5o1o7s+ORGAOi495CPCmfwuGAUpq0XB9TXcg/QUAAABSeyJvcmlnaW4iOiAiaHR0cDovLzEyNy4wLjAuMTo4MDAwIiwgImZlYXR1cmUiOiAiQXBwSGlzdG9yeSIsICJleHBpcnkiOiAyMDAwMDAwMDAwfQ==" /> +<title>AppHistory API - interfaces and properties exposed by origin trial</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script> +test(t => { + assert_not_equals(window.appHistory, undefined); + assert_not_equals(window.appHistory.current, null); +}, 'AppHistory API interfaces and properties in Origin-Trial enabled document.'); +</script>
diff --git a/third_party/blink/web_tests/platform/mac/compositing/perpendicular-layer-sorting-expected.png b/third_party/blink/web_tests/platform/mac/compositing/perpendicular-layer-sorting-expected.png new file mode 100644 index 0000000..1e7fc25 --- /dev/null +++ b/third_party/blink/web_tests/platform/mac/compositing/perpendicular-layer-sorting-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/transforms/3d/point-mapping/3d-point-mapping-deep-expected.png b/third_party/blink/web_tests/platform/mac/transforms/3d/point-mapping/3d-point-mapping-deep-expected.png index 3d93ac7..7b700caa 100644 --- a/third_party/blink/web_tests/platform/mac/transforms/3d/point-mapping/3d-point-mapping-deep-expected.png +++ b/third_party/blink/web_tests/platform/mac/transforms/3d/point-mapping/3d-point-mapping-deep-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/compositing/perpendicular-layer-sorting-expected.png b/third_party/blink/web_tests/platform/win/compositing/perpendicular-layer-sorting-expected.png index 55177dec..786ecac 100644 --- a/third_party/blink/web_tests/platform/win/compositing/perpendicular-layer-sorting-expected.png +++ b/third_party/blink/web_tests/platform/win/compositing/perpendicular-layer-sorting-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/transforms/3d/point-mapping/3d-point-mapping-deep-expected.png b/third_party/blink/web_tests/platform/win/transforms/3d/point-mapping/3d-point-mapping-deep-expected.png index b37a3a0..2606eda6 100644 --- a/third_party/blink/web_tests/platform/win/transforms/3d/point-mapping/3d-point-mapping-deep-expected.png +++ b/third_party/blink/web_tests/platform/win/transforms/3d/point-mapping/3d-point-mapping-deep-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/virtual/dark-mode-default/dark-mode/images/shadow-expected.png b/third_party/blink/web_tests/virtual/dark-mode-default/dark-mode/images/shadow-expected.png new file mode 100644 index 0000000..7fe58b8 --- /dev/null +++ b/third_party/blink/web_tests/virtual/dark-mode-default/dark-mode/images/shadow-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/virtual/dark-mode-images-filter-all/dark-mode/images/shadow-expected.png b/third_party/blink/web_tests/virtual/dark-mode-images-filter-all/dark-mode/images/shadow-expected.png new file mode 100644 index 0000000..7fe58b8 --- /dev/null +++ b/third_party/blink/web_tests/virtual/dark-mode-images-filter-all/dark-mode/images/shadow-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/virtual/dark-mode-images-filter-none/dark-mode/images/shadow-expected.png b/third_party/blink/web_tests/virtual/dark-mode-images-filter-none/dark-mode/images/shadow-expected.png new file mode 100644 index 0000000..7fe58b8 --- /dev/null +++ b/third_party/blink/web_tests/virtual/dark-mode-images-filter-none/dark-mode/images/shadow-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/virtual/fenced-frame-shadow-dom/README.md b/third_party/blink/web_tests/virtual/fenced-frame-shadow-dom/README.md new file mode 100644 index 0000000..5585380 --- /dev/null +++ b/third_party/blink/web_tests/virtual/fenced-frame-shadow-dom/README.md
@@ -0,0 +1,8 @@ +# Fenced Frames + ShadowDOM + +This directory contains `wpt_internal/fenced_frame/` test expectations that are +specific to the ShadowDOM implementation of fenced frames. The tests are run with +the flag --enable-features=FencedFrames:implementation\_type/shadow\_dom. + +See crbug.com/1123606. +
diff --git a/third_party/blink/web_tests/virtual/fenced-frame-shadow-dom/fenced_frame/basic-expected.html b/third_party/blink/web_tests/virtual/fenced-frame-shadow-dom/fenced_frame/basic-expected.html new file mode 100644 index 0000000..1df34f7b --- /dev/null +++ b/third_party/blink/web_tests/virtual/fenced-frame-shadow-dom/fenced_frame/basic-expected.html
@@ -0,0 +1,5 @@ +<body> + <iframe + style="width: 100%; height: 300px; box-sizing: border-box" + srcdoc="<body style='margin: 0px'><div style='background: red; width: 20px; height: 20px'></div></body>"></iframe> +</body>
diff --git a/third_party/blink/web_tests/virtual/fenced-frame-shadow-dom/fenced_frame/visibility-changed-expected.html b/third_party/blink/web_tests/virtual/fenced-frame-shadow-dom/fenced_frame/visibility-changed-expected.html new file mode 100644 index 0000000..90f5cff --- /dev/null +++ b/third_party/blink/web_tests/virtual/fenced-frame-shadow-dom/fenced_frame/visibility-changed-expected.html
@@ -0,0 +1,5 @@ +<body> + <iframe + style="width: 100%; height: 300px; box-sizing: border-box" + srcdoc="<body style='margin: 0px'><div style='background: green; width: 20px; height: 20px'></div></body>"></iframe> +</body>
diff --git a/third_party/blink/web_tests/wpt_internal/fenced_frame/navigate-by-name-expected.txt b/third_party/blink/web_tests/virtual/fenced-frame-shadow-dom/wpt_internal/fenced_frame/navigate-by-name-expected.txt similarity index 100% rename from third_party/blink/web_tests/wpt_internal/fenced_frame/navigate-by-name-expected.txt rename to third_party/blink/web_tests/virtual/fenced-frame-shadow-dom/wpt_internal/fenced_frame/navigate-by-name-expected.txt
diff --git a/third_party/blink/web_tests/virtual/fenced-frame-shadow-dom/wpt_internal/fenced_frame/prerender.https-expected.txt b/third_party/blink/web_tests/virtual/fenced-frame-shadow-dom/wpt_internal/fenced_frame/prerender.https-expected.txt new file mode 100644 index 0000000..41b28d9 --- /dev/null +++ b/third_party/blink/web_tests/virtual/fenced-frame-shadow-dom/wpt_internal/fenced_frame/prerender.https-expected.txt
@@ -0,0 +1,4 @@ +This is a testharness.js-based test. +PASS Fenced Frame must not load prerendered page. +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/webexposed/element-instance-property-listing-expected.txt b/third_party/blink/web_tests/webexposed/element-instance-property-listing-expected.txt index 4779f44..e2a45fe 100644 --- a/third_party/blink/web_tests/webexposed/element-instance-property-listing-expected.txt +++ b/third_party/blink/web_tests/webexposed/element-instance-property-listing-expected.txt
@@ -562,10 +562,6 @@ property src property type property width -html element fencedframe - property height - property src - property width html element fieldset property checkValidity property disabled
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 171be1c1..cf414348 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
@@ -3455,15 +3455,6 @@ setter src setter type setter width -interface HTMLFencedFrameElement : HTMLElement - attribute @@toStringTag - getter height - getter src - getter width - method constructor - setter height - setter src - setter width interface HTMLFieldSetElement : HTMLElement attribute @@toStringTag getter disabled
diff --git a/third_party/freetype/README.chromium b/third_party/freetype/README.chromium index 48ee1cd1..70c0846 100644 --- a/third_party/freetype/README.chromium +++ b/third_party/freetype/README.chromium
@@ -1,7 +1,7 @@ Name: FreeType URL: http://www.freetype.org/ -Version: VER-2-11-1-2-g1f9518987 -Revision: 1f951898751365e9bd2a920ce76652f2a59c3305 +Version: VER-2-11-1-3-g012b00f3e +Revision: 012b00f3e67d8d17d411ec1c777b8672e4dffad5 CPEPrefix: cpe:/a:freetype:freetype:2.11.1 License: Custom license "inspired by the BSD, Artistic, and IJG (Independent JPEG Group) licenses"
diff --git a/tools/add_header.py b/tools/add_header.py index fc472f9..d21d0af1 100755 --- a/tools/add_header.py +++ b/tools/add_header.py
@@ -2,7 +2,7 @@ # Copyright 2021 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -"""Helper for adding an include to a source file in the "right" place. +"""Helper for adding or removing an include to/from source file(s). clang-format already provides header sorting functionality; however, the functionality is limited to sorting headers within a block of headers surrounded @@ -20,8 +20,11 @@ As a bonus, it does *also* sort the includes, though any sorting disagreements with clang-format should be resolved in favor of clang-format. +It also supports removing a header with option `--remove`. + Usage: tools/add_header.py --header '<utility>' foo/bar.cc foo/baz.cc foo/baz.h +tools/add_header.py --header '<vector>' --remove foo/bar.cc foo/baz.cc foo/baz.h """ import argparse @@ -343,16 +346,17 @@ return source -def InsertHeaderIntoSource(filename, source, decorated_name): - """Inserts the specified header into some source text, if needed. +def AddHeaderToSource(filename, source, decorated_name, remove=False): + """Adds or removes the specified header into/from the source text, if needed. Args: filename: The name of the source file. source: A string containing the contents of the source file. - decorated_name: The decorated name of the header to insert. + decorated_name: The decorated name of the header to add or remove. + remove: If true, remove instead of adding. Returns: - None on failure or the modified source text on success. + None if no changes are needed or the modified source text otherwise. """ lines = source.splitlines() begin, end = FindIncludes(lines) @@ -368,12 +372,24 @@ if not includes: print(f'Skipping {filename}: unable to parse includes!') return None - if decorated_name in [i.decorated_name for i in includes]: - # Nothing to do. - print(f'Skipping {filename}: no changes required!') - return source + + if remove: + for i in includes: + if decorated_name == i.decorated_name: + includes.remove(i) + break + else: + print(f'Skipping {filename}: unable to find {decorated_name}') + return None + else: + if decorated_name in [i.decorated_name for i in includes]: + # Nothing to do. + print(f'Skipping {filename}: no changes required!') + return None + else: + includes.append(Include(decorated_name, 'include', [], None)) + MarkPrimaryInclude(includes, filename) - includes.append(Include(decorated_name, 'include', [], None)) # TODO(dcheng): It may be worth considering adding special sorting heuristics # for windows.h, et cetera. @@ -389,11 +405,14 @@ def main(): parser = argparse.ArgumentParser( - description='Mass insert a new header into a bunch of files.') + description='Mass add (or remove) a new header into a bunch of files.') parser.add_argument( '--header', help='The decorated filename of the header to insert (e.g. "a" or <a>)', required=True) + parser.add_argument('--remove', + help='Remove the header file instead of adding it', + action='store_true') parser.add_argument('files', nargs='+') args = parser.parse_args() if ClassifyHeader(args.header) == _HEADER_TYPE_INVALID: @@ -402,11 +421,12 @@ print('or') print(' --header \'"moo.h"\'') return 1 - print(f'Inserting #include {args.header}...') + operation = 'Removing' if args.remove else 'Inserting' + print(f'{operation} #include {args.header}...') for filename in args.files: with open(filename, 'r') as f: - new_source = InsertHeaderIntoSource(os.path.normpath(filename), f.read(), - args.header) + new_source = AddHeaderToSource(os.path.normpath(filename), f.read(), + args.header, args.remove) if not new_source: continue with open(filename, 'w', newline='\n') as f:
diff --git a/tools/add_header_test.py b/tools/add_header_test.py index 0020518..453bc863 100755 --- a/tools/add_header_test.py +++ b/tools/add_header_test.py
@@ -360,9 +360,9 @@ ]) -class InsertHeaderIntoSourceTest(unittest.TestCase): +class AddHeaderToSourceTest(unittest.TestCase): def testAddInclude(self): - source = add_header.InsertHeaderIntoSource( + source = add_header.AddHeaderToSource( 'cow.cc', '\n'.join([ '// Copyright info here.', '', '#include <utility>', '// For cow speech synthesis.', @@ -388,13 +388,13 @@ '#include <memory>', '#include "cow.h"', 'namespace bovine {', '', '// TODO: Implement.', '} // namespace bovine' ]) - self.assertEqual( - add_header.InsertHeaderIntoSource('cow.cc', source, '<memory>'), source) + self.assertEqual(add_header.AddHeaderToSource('cow.cc', source, '<memory>'), + None) def testConditionalIncludesLeftALone(self): # TODO(dcheng): Conditional header handling could probably be more clever. # But for the moment, this is probably Good Enough. - source = add_header.InsertHeaderIntoSource( + source = add_header.AddHeaderToSource( 'cow.cc', '\n'.join([ '// Copyright info here.', '', '#include "cow.h"', '#include <utility>', '// For cow speech synthesis.', @@ -412,6 +412,28 @@ '#endif // defined(USE_AURA)', '' ])) + def testRemoveInclude(self): + source = add_header.AddHeaderToSource( + 'cow.cc', + '\n'.join([ + '// Copyright info here.', '', '#include <memory>', + '#include <utility>', '// For cow speech synthesis.', + '#include "moo.h" // TODO: Add Linux audio support.', + '#include <time.h>', '#include "cow.h"', 'namespace bovine {', '', + '// TODO: Implement.', '} // namespace bovine' + ]), + '<utility>', + remove=True) + self.assertEqual( + source, '\n'.join([ + '// Copyright info here.', '', '#include "cow.h"', '', + '#include <time.h>', '', '#include <memory>', '', + '// For cow speech synthesis.', + '#include "moo.h" // TODO: Add Linux audio support.', + 'namespace bovine {', '', '// TODO: Implement.', + '} // namespace bovine', '' + ])) + if __name__ == '__main__': unittest.main()
diff --git a/tools/android/avd/avd.py b/tools/android/avd/avd.py index 0620c76..bd7901e 100755 --- a/tools/android/avd/avd.py +++ b/tools/android/avd/avd.py
@@ -89,6 +89,10 @@ 'start', help='Start an AVD instance with the given config.', formatter_class=argparse.ArgumentDefaultsHelpFormatter) + start_parser.add_argument('--wipe-data', + action='store_true', + default=False, + help='Reset user data image for this emulator.') start_parser.add_argument( '--no-read-only', action='store_false', @@ -128,6 +132,7 @@ window=args.emulator_window, writable_system=args.writable_system, gpu_mode=args.gpu_mode, + wipe_data=args.wipe_data, debug_tags=args.debug_tags) print('%s started (pid: %d)' % (str(inst), inst._emulator_proc.pid)) return 0
diff --git a/tools/android/test_health/PRESUBMIT.py b/tools/android/test_health/PRESUBMIT.py new file mode 100644 index 0000000..fbec3c8 --- /dev/null +++ b/tools/android/test_health/PRESUBMIT.py
@@ -0,0 +1,36 @@ +# Copyright 2021 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. +"""Top-level presubmit script for test_health. + +See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts +for more details on the presubmit API built into depot_tools. +""" + +USE_PYTHON3 = True +PRESUBMIT_VERSION = '2.0.0' + + +def _PythonChecks(input_api, output_api): + checks = input_api.canned_checks.GetUnitTestsRecursively( + input_api, + output_api, + input_api.PresubmitLocalPath(), + files_to_check=[r'.+_unittest\.py$'], + files_to_skip=[], + run_on_python2=False, + run_on_python3=True) + + return input_api.RunTests(checks, False) + + +def CheckChangeOnUpload(input_api, output_api): + """Presubmit checks to run on upload of a CL.""" + return _PythonChecks(input_api, output_api) + + +def CheckChangeOnCommit(input_api, output_api): + """Presubmit checks to run on submission (continuous queue).""" + # Skip presubmit on CQ since the `javalang` dependency is not available in + # non-Android checkouts; see crbug.com/1093878 for more context. + return []
diff --git a/tools/android/test_health/java_test_utils.py b/tools/android/test_health/java_test_utils.py index 64c9b5e..74b6b55 100644 --- a/tools/android/test_health/java_test_utils.py +++ b/tools/android/test_health/java_test_utils.py
@@ -8,7 +8,7 @@ import pathlib import re import sys -from typing import Optional +from typing import List, Optional _TOOLS_ANDROID_PATH = pathlib.Path(__file__).parents[1].resolve(strict=True) if str(_TOOLS_ANDROID_PATH) not in sys.path: @@ -101,7 +101,7 @@ flaky_tests_count=annotation_counter[_FLAKY_TEST_ANNOTATION]) -def _count_annotations(annotations: list[Annotation]) -> collections.Counter: +def _count_annotations(annotations: List[Annotation]) -> collections.Counter: counter = collections.Counter() for annotation in annotations:
diff --git a/tools/android/test_health/java_test_utils_unittest.py b/tools/android/test_health/java_test_utils_unittest.py index 777dfc2c..b30027e7 100755 --- a/tools/android/test_health/java_test_utils_unittest.py +++ b/tools/android/test_health/java_test_utils_unittest.py
@@ -10,7 +10,8 @@ import java_test_utils -_TOOLS_ANDROID_PATH = pathlib.Path(__file__).parents[1].resolve(strict=True) +_TOOLS_ANDROID_PATH = pathlib.Path(__file__).resolve( + strict=True).parents[1].resolve(strict=True) if str(_TOOLS_ANDROID_PATH) not in sys.path: sys.path.append(str(_TOOLS_ANDROID_PATH)) from python_utils import git_metadata_utils
diff --git a/tools/ipc_fuzzer/message_lib/BUILD.gn b/tools/ipc_fuzzer/message_lib/BUILD.gn index 1f61878..458e5e6 100644 --- a/tools/ipc_fuzzer/message_lib/BUILD.gn +++ b/tools/ipc_fuzzer/message_lib/BUILD.gn
@@ -33,7 +33,7 @@ if (is_win) { public_deps += [ "//chrome/chrome_elf:test_stubs" ] } - deps = [ "//remoting/host:base" ] + deps = [ "//remoting/host/base" ] sources = [ "all_messages.h", "message_cracker.h",
diff --git a/tools/mac/power/analyze.py b/tools/mac/power/analyze.py index 5d5554f..e758d7c 100755 --- a/tools/mac/power/analyze.py +++ b/tools/mac/power/analyze.py
@@ -87,6 +87,11 @@ return results +def NormalizeMicrosecondsSampleTime(sample_time: pd.Series): + # Round sample time to .1s to aggregate similar rows across different sources. + return (sample_time / 1000000.0).round(1) + + def main(): parser = argparse.ArgumentParser( description='Parses, aggregates and summarizes power results') @@ -120,9 +125,37 @@ else: browser_identifier = None powermetrics_data = ReadPowerMetricsData(subdir, browser_identifier) - scenario_data = pd.DataFrame.from_records(powermetrics_data) + powermetrics_dataframe = pd.DataFrame.from_records(powermetrics_data) + # Add sample_time to powermetrics. + powermetrics_dataframe["sample_time"] = NormalizeMicrosecondsSampleTime( + powermetrics_dataframe['elapsed_ns'].cumsum() / 1000.0) + powermetrics_dataframe.set_index('sample_time', inplace=True) - summary_path = os.path.join(subdir, 'powermetrics_summary.csv') + with open(os.path.join(subdir, "power_sampler.json")) as power_file: + power_data = json.load(power_file) + power_dataframe = pd.DataFrame.from_records( + power_data['data_rows'], + columns=[key for key in power_data['column_labels']] + ["sample_time"]) + power_dataframe['sample_time'] = NormalizeMicrosecondsSampleTime( + power_dataframe['sample_time']) + power_dataframe.set_index('sample_time', inplace=True) + + with open(os.path.join(subdir, + "power_sampler_battery.json")) as battery_file: + battery_data = json.load(battery_file) + battery_dataframe = pd.DataFrame.from_records( + battery_data['data_rows'], + columns=[key + for key in battery_data['column_labels']] + ["sample_time"]) + battery_dataframe['sample_time'] = NormalizeMicrosecondsSampleTime( + battery_dataframe['sample_time']) + battery_dataframe.set_index('sample_time', inplace=True) + + # Join all data sources by sample_time. + scenario_data = powermetrics_dataframe.join( + power_dataframe, how='outer').join(battery_dataframe, how='outer') + + summary_path = os.path.join(subdir, 'summary.csv') logging.info(f'Outputing results in {os.path.abspath(summary_path)}') scenario_data.to_csv(summary_path)
diff --git a/tools/mb/mb_config.pyl b/tools/mb/mb_config.pyl index d578f5307..0ed13e3 100644 --- a/tools/mb/mb_config.pyl +++ b/tools/mb/mb_config.pyl
@@ -221,8 +221,8 @@ 'Dawn Linux x64 Builder': 'dawn_tests_with_desktop_gl_release_trybot_reclient', 'Dawn Linux x64 DEPS Builder': 'dawn_tests_with_desktop_gl_release_trybot_reclient', - 'Dawn Mac x64 Builder': 'dawn_tests_release_bot_dcheck_always_on', - 'Dawn Mac x64 DEPS Builder': 'dawn_tests_release_bot_dcheck_always_on', + 'Dawn Mac x64 Builder': 'dawn_tests_release_bot_dcheck_always_on_alloc_none', + 'Dawn Mac x64 DEPS Builder': 'dawn_tests_release_bot_dcheck_always_on_alloc_none', 'Dawn Win10 x86 Builder': 'dawn_tests_release_bot_dcheck_always_on_x86', 'Dawn Win10 x64 Builder': 'dawn_tests_release_bot_dcheck_always_on', @@ -971,7 +971,7 @@ 'dawn-linux-x64-deps-rel': 'dawn_tests_with_desktop_gl_release_trybot', 'dawn-mac-x64-deps-rel': 'dawn_tests_release_trybot_alloc_none', 'dawn-try-mac-amd-exp': 'dawn_tests_release_trybot_alloc_none', - 'dawn-try-mac-intel-exp': 'dawn_tests_release_trybot', + 'dawn-try-mac-intel-exp': 'dawn_tests_release_trybot_alloc_none', 'dawn-win10-x86-deps-rel': 'dawn_tests_release_trybot_x86', 'dawn-win10-x64-deps-rel': 'dawn_tests_release_trybot', 'linux-dawn-rel': 'dawn_tests_with_desktop_gl_release_trybot', @@ -2135,6 +2135,9 @@ 'dawn_tests_release_trybot_alloc_none': [ 'dawn_tests', 'release_trybot', 'padisabled', ], + 'dawn_tests_release_bot_dcheck_always_on_alloc_none': [ + 'dawn_tests', 'release_trybot_minimal_symbols', 'padisabled', + ], 'dawn_tests_release_trybot_x86': [ 'dawn_tests', 'release_trybot', 'x86',
diff --git a/tools/mb/mb_config_expectations/chromium.dawn.json b/tools/mb/mb_config_expectations/chromium.dawn.json index 6bee502..990cd3cb 100644 --- a/tools/mb/mb_config_expectations/chromium.dawn.json +++ b/tools/mb/mb_config_expectations/chromium.dawn.json
@@ -35,6 +35,7 @@ "is_component_build": false, "is_debug": false, "symbol_level": 1, + "use_allocator": "none", "use_dawn": true, "use_goma": true } @@ -47,6 +48,7 @@ "is_component_build": false, "is_debug": false, "symbol_level": 1, + "use_allocator": "none", "use_dawn": true, "use_goma": true }
diff --git a/tools/mb/mb_config_expectations/tryserver.chromium.dawn.json b/tools/mb/mb_config_expectations/tryserver.chromium.dawn.json index f6ba12d8..9728a89 100644 --- a/tools/mb/mb_config_expectations/tryserver.chromium.dawn.json +++ b/tools/mb/mb_config_expectations/tryserver.chromium.dawn.json
@@ -46,6 +46,7 @@ "is_component_build": false, "is_debug": false, "symbol_level": 0, + "use_allocator": "none", "use_dawn": true, "use_goma": true }
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index 7ac8231..847e4e47 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -8270,6 +8270,7 @@ <int value="254" label="RFH_CREATE_CHILD_FRAME_SANDBOX_FLAGS"/> <int value="255" label="RFPH_FOCUSED_FENCED_FRAME"/> <int value="256" label="WCI_REQUEST_LOCK_MOUSE_FENCED_FRAME"/> + <int value="257" label="RFH_FENCED_FRAME_MOJO_WHEN_DISABLED"/> </enum> <enum name="BadMessageReasonExtensions"> @@ -35768,6 +35769,7 @@ <int value="4089" label="CrossOriginOpenerPolicySameOriginAllowPopupsReportOnly"/> <int value="4090" label="CrossOriginOpenerPolicySameOriginReportOnly"/> + <int value="4091" label="ImageLoadAtDismissalEvent"/> </enum> <enum name="FeaturePolicyAllowlistType"> @@ -81880,7 +81882,7 @@ <int value="6" label="Child process crash count"/> <int value="15" label="Browser launch count"/> <int value="16" label="Browser crash count"/> - <int value="17" label="Incomplete shutdown count"/> + <int value="17" label="(Obsolete Dec 2021) Incomplete shutdown count"/> <int value="24" label="Renderer failed launch count"/> <int value="25" label="Extension renderer failed launch count"/> <int value="26" label="Renderer launch count"/>
diff --git a/tools/metrics/histograms/metadata/METRIC_REVIEWER_OWNERS b/tools/metrics/histograms/metadata/METRIC_REVIEWER_OWNERS index 1efc7fc..c18fc29b 100644 --- a/tools/metrics/histograms/metadata/METRIC_REVIEWER_OWNERS +++ b/tools/metrics/histograms/metadata/METRIC_REVIEWER_OWNERS
@@ -31,6 +31,7 @@ iclelland@chromium.org ioanap@chromium.org javierrobles@chromium.org +jihanli@chromium.org johnidel@chromium.org jonross@chromium.org jorgelo@chromium.org @@ -65,6 +66,7 @@ sebsg@chromium.org shaktisahu@chromium.org shend@chromium.org +smcgruer@chromium.org sophiechang@chromium.org spdonghao@chromium.org tbansal@chromium.org
diff --git a/tools/metrics/histograms/metadata/android/histograms.xml b/tools/metrics/histograms/metadata/android/histograms.xml index e562ad9..957a997 100644 --- a/tools/metrics/histograms/metadata/android/histograms.xml +++ b/tools/metrics/histograms/metadata/android/histograms.xml
@@ -2879,6 +2879,9 @@ <histogram name="Android.SeccompStatus.Syscall" enum="AndroidSeccompStatus" expires_after="M99"> + <obsolete> + Recording code deleted on 2015-04-22. + </obsolete> <owner>rsesek@chromium.org</owner> <summary> Reports the level of kernel support for the seccomp-bpf sandbox using the
diff --git a/tools/metrics/histograms/metadata/event/histograms.xml b/tools/metrics/histograms/metadata/event/histograms.xml index fce5fb1..97ce3f3 100644 --- a/tools/metrics/histograms/metadata/event/histograms.xml +++ b/tools/metrics/histograms/metadata/event/histograms.xml
@@ -815,7 +815,7 @@ <histogram name="Event.Latency.ScrollBegin.Scrollbar.BrowserNotifiedToBeforeGpuSwap2" - units="microseconds" expires_after="2021-12-01"> + units="microseconds" expires_after="2022-06-01"> <owner>flackr@chromium.org</owner> <owner>gerchiko@microsoft.com</owner> <owner>input-dev@chromium.org</owner> @@ -858,8 +858,8 @@ </histogram> <histogram name="Event.Latency.ScrollBegin.Scrollbar.HandledToRendererSwap2" - units="microseconds" expires_after="2021-12-01"> - <owner>nzolghadr@chromium.org</owner> + units="microseconds" expires_after="2022-06-01"> + <owner>flackr@chromium.org</owner> <owner>gerchiko@microsoft.com</owner> <owner>input-dev@chromium.org</owner> <summary> @@ -879,8 +879,8 @@ <histogram name="Event.Latency.ScrollBegin.Scrollbar.RendererSwapToBrowserNotified2" - units="microseconds" expires_after="2021-12-01"> - <owner>nzolghadr@chromium.org</owner> + units="microseconds" expires_after="2022-06-01"> + <owner>flackr@chromium.org</owner> <owner>gerchiko@microsoft.com</owner> <owner>input-dev@chromium.org</owner> <summary> @@ -902,8 +902,8 @@ </histogram> <histogram name="Event.Latency.ScrollBegin.Scrollbar.TimeToHandled2" - units="microseconds" expires_after="2021-12-01"> - <owner>nzolghadr@chromium.org</owner> + units="microseconds" expires_after="2022-06-01"> + <owner>flackr@chromium.org</owner> <owner>gerchiko@microsoft.com</owner> <owner>input-dev@chromium.org</owner> <summary> @@ -1036,7 +1036,7 @@ <histogram name="Event.Latency.ScrollBegin.Touch.BrowserNotifiedToBeforeGpuSwap2" - units="microseconds" expires_after="2021-12-01"> + units="microseconds" expires_after="2022-06-01"> <owner>flackr@chromium.org</owner> <owner>input-dev@chromium.org</owner> <summary> @@ -1045,12 +1045,19 @@ induced renderer swap and GPU starts to swap. Team: input-dev@chromium.org. + + Warning: This metric may include reports from clients with low-resolution + clocks (i.e. on Windows, ref. |TimeTicks::IsHighResolution()|). Such reports + will cause this metric to have an abnormal distribution. When considering + revising this histogram, see UMA_HISTOGRAM_CUSTOM_MICROSECONDS_TIMES for the + solution. </summary> </histogram> <histogram name="Event.Latency.ScrollBegin.Touch.GpuSwap2" units="microseconds" - expires_after="2021-12-12"> + expires_after="2022-06-01"> <owner>flackr@chromium.org</owner> + <owner>input-dev@chromium.org</owner> <summary> Time between gpu starts to swap the first ScrollUpdate gesture event in a given scroll gesture event sequence with touch source induced frame and the @@ -1067,7 +1074,7 @@ </histogram> <histogram name="Event.Latency.ScrollBegin.Touch.HandledToRendererSwap2" - units="microseconds" expires_after="2021-06-16"> + units="microseconds" expires_after="2022-06-01"> <owner>flackr@chromium.org</owner> <owner>input-dev@chromium.org</owner> <summary> @@ -1087,7 +1094,7 @@ <histogram name="Event.Latency.ScrollBegin.Touch.RendererSwapToBrowserNotified2" - units="microseconds" expires_after="2021-06-16"> + units="microseconds" expires_after="2022-06-01"> <owner>flackr@chromium.org</owner> <owner>input-dev@chromium.org</owner> <summary> @@ -1096,11 +1103,17 @@ touch source, and browser receives the swap notification. Team: input-dev@chromium.org. + + Warning: This metric may include reports from clients with low-resolution + clocks (i.e. on Windows, ref. |TimeTicks::IsHighResolution()|). Such reports + will cause this metric to have an abnormal distribution. When considering + revising this histogram, see UMA_HISTOGRAM_CUSTOM_MICROSECONDS_TIMES for the + solution. </summary> </histogram> <histogram name="Event.Latency.ScrollBegin.Touch.TimeToHandled2" - units="microseconds" expires_after="2021-10-25"> + units="microseconds" expires_after="2022-06-01"> <owner>flackr@chromium.org</owner> <owner>input-dev@chromium.org</owner> <summary> @@ -1121,7 +1134,7 @@ <histogram name="Event.Latency.ScrollBegin.Touch.TimeToScrollUpdateSwapBegin4{TopControlsState}" - units="microseconds" expires_after="2021-12-19"> + units="microseconds" expires_after="2022-06-01"> <owner>flackr@chromium.org</owner> <owner>input-dev@chromium.org</owner> <owner>speed-metrics-dev@chromium.org</owner> @@ -1160,7 +1173,7 @@ </histogram> <histogram name="Event.Latency.ScrollBegin.Wheel.GpuSwap2" units="microseconds" - expires_after="2021-06-16"> + expires_after="2022-06-01"> <owner>flackr@chromium.org</owner> <owner>input-dev@chromium.org</owner> <summary> @@ -1179,7 +1192,7 @@ </histogram> <histogram name="Event.Latency.ScrollBegin.Wheel.HandledToRendererSwap2" - units="microseconds" expires_after="2021-11-21"> + units="microseconds" expires_after="2022-06-01"> <owner>flackr@chromium.org</owner> <owner>input-dev@chromium.org</owner> <summary> @@ -1199,7 +1212,7 @@ <histogram name="Event.Latency.ScrollBegin.Wheel.RendererSwapToBrowserNotified2" - units="microseconds" expires_after="2021-07-13"> + units="microseconds" expires_after="2022-06-01"> <owner>flackr@chromium.org</owner> <owner>input-dev@chromium.org</owner> <summary> @@ -1208,11 +1221,17 @@ wheel source, and browser receives the swap notification. Team: input-dev@chromium.org. + + Warning: This metric may include reports from clients with low-resolution + clocks (i.e. on Windows, ref. |TimeTicks::IsHighResolution()|). Such reports + will cause this metric to have an abnormal distribution. When considering + revising this histogram, see UMA_HISTOGRAM_CUSTOM_MICROSECONDS_TIMES for the + solution. </summary> </histogram> <histogram name="Event.Latency.ScrollBegin.Wheel.TimeToHandled2" - units="microseconds" expires_after="2021-10-31"> + units="microseconds" expires_after="2022-06-01"> <owner>flackr@chromium.org</owner> <owner>input-dev@chromium.org</owner> <summary> @@ -1265,33 +1284,46 @@ </histogram> <histogram name="Event.Latency.ScrollInertial.Touch.GpuSwap2" - units="microseconds" expires_after="2021-06-16"> - <owner>nzolghadr@chromium.org</owner> + units="microseconds" expires_after="2022-06-01"> + <owner>flackr@chromium.org</owner> <owner>input-dev@chromium.org</owner> <summary> Time between gpu starts to swap a ScrollUpdate gesture event generated from a touchscreen fling induced frame and the swap finishes. Team: input-dev@chromium.org. + + Warning: This metric may include reports from clients with low-resolution + clocks (i.e. on Windows, ref. |TimeTicks::IsHighResolution()|). Such reports + will cause this metric to have an abnormal distribution. When considering + revising this histogram, see UMA_HISTOGRAM_CUSTOM_MICROSECONDS_TIMES for the + solution. </summary> </histogram> <histogram name="Event.Latency.ScrollInertial.Touch.HandledToRendererSwap2" - units="microseconds" expires_after="M80"> - <owner>nzolghadr@chromium.org</owner> + units="microseconds" expires_after="2022-06-01"> + <owner>flackr@chromium.org</owner> + <owner>input-dev@chromium.org</owner> <summary> Time between a ScrollUpdate gesture event generated from a touchscreen fling, is handled on main/impl thread (specified by suffix) and before renderer starts to swap. Team: input-dev@chromium.org. + + Warning: This metric may include reports from clients with low-resolution + clocks (i.e. on Windows, ref. |TimeTicks::IsHighResolution()|). Such reports + will cause this metric to have an abnormal distribution. When considering + revising this histogram, see UMA_HISTOGRAM_CUSTOM_MICROSECONDS_TIMES for the + solution. </summary> </histogram> <histogram name="Event.Latency.ScrollInertial.Touch.RendererSwapToBrowserNotified2" - units="microseconds" expires_after="2021-06-16"> - <owner>nzolghadr@chromium.org</owner> + units="microseconds" expires_after="2022-06-01"> + <owner>flackr@chromium.org</owner> <owner>input-dev@chromium.org</owner> <summary> Time between the renderer starts to swap a frame induced by a ScrollUpdate @@ -1299,25 +1331,39 @@ swap notification. Team: input-dev@chromium.org. + + Warning: This metric may include reports from clients with low-resolution + clocks (i.e. on Windows, ref. |TimeTicks::IsHighResolution()|). Such reports + will cause this metric to have an abnormal distribution. When considering + revising this histogram, see UMA_HISTOGRAM_CUSTOM_MICROSECONDS_TIMES for the + solution. </summary> </histogram> <histogram name="Event.Latency.ScrollInertial.Touch.TimeToHandled2" - units="microseconds" expires_after="M80"> - <owner>nzolghadr@chromium.org</owner> + units="microseconds" expires_after="2022-06-01"> + <owner>flackr@chromium.org</owner> + <owner>input-dev@chromium.org</owner> <summary> Time between initial creation of a ScrollUpdate gesture event generated from a touchscreen fling is handled on main/impl thread (specified by suffix). If no swap was induced by the ScrollUpdate gesture event, no recording is made. Team: input-dev@chromium.org. + + Warning: This metric may include reports from clients with low-resolution + clocks (i.e. on Windows, ref. |TimeTicks::IsHighResolution()|). Such reports + will cause this metric to have an abnormal distribution. When considering + revising this histogram, see UMA_HISTOGRAM_CUSTOM_MICROSECONDS_TIMES for the + solution. </summary> </histogram> <histogram name="Event.Latency.ScrollInertial.Touch.TimeToScrollUpdateSwapBegin4" - units="microseconds" expires_after="2021-01-24"> - <owner>nozlghadr@chromium.org</owner> + units="microseconds" expires_after="2022-06-01"> + <owner>flackr@chromium.org</owner> + <owner>input-dev@chromium.org</owner> <summary> Time between initial creation of a ScrollUpdate gesture event generated from a touchscreen fling and the start of the frame swap on the GPU service @@ -1325,6 +1371,12 @@ by the event, no recording is made. Team: input-dev@chromium.org. + + Warning: This metric may include reports from clients with low-resolution + clocks (i.e. on Windows, ref. |TimeTicks::IsHighResolution()|). Such reports + will cause this metric to have an abnormal distribution. When considering + revising this histogram, see UMA_HISTOGRAM_CUSTOM_MICROSECONDS_TIMES for the + solution. </summary> </histogram> @@ -1372,7 +1424,7 @@ <histogram name="Event.Latency.ScrollUpdate.Scrollbar.BrowserNotifiedToBeforeGpuSwap2" - units="microseconds" expires_after="2021-12-01"> + units="microseconds" expires_after="2022-06-01"> <owner>flackr@chromium.org</owner> <owner>arakeri@microsoft.com</owner> <owner>input-dev@chromium.org</owner> @@ -1385,11 +1437,17 @@ in the browser process. Team: input-dev@chromium.org. + + Warning: This metric may include reports from clients with low-resolution + clocks (i.e. on Windows, ref. |TimeTicks::IsHighResolution()|). Such reports + will cause this metric to have an abnormal distribution. When considering + revising this histogram, see UMA_HISTOGRAM_CUSTOM_MICROSECONDS_TIMES for the + solution. </summary> </histogram> <histogram name="Event.Latency.ScrollUpdate.Scrollbar.GpuSwap2" - units="microseconds" expires_after="2021-12-01"> + units="microseconds" expires_after="2022-06-01"> <owner>flackr@chromium.org</owner> <owner>arakeri@microsoft.com</owner> <owner>input-dev@chromium.org</owner> @@ -1408,7 +1466,7 @@ </histogram> <histogram name="Event.Latency.ScrollUpdate.Scrollbar.HandledToRendererSwap2" - units="microseconds" expires_after="2021-12-01"> + units="microseconds" expires_after="2022-06-01"> <owner>flackr@chromium.org</owner> <owner>arakeri@microsoft.com</owner> <owner>input-dev@chromium.org</owner> @@ -1429,7 +1487,7 @@ <histogram name="Event.Latency.ScrollUpdate.Scrollbar.RendererSwapToBrowserNotified2" - units="microseconds" expires_after="2021-12-01"> + units="microseconds" expires_after="2022-06-01"> <owner>flackr@chromium.org</owner> <owner>arakeri@microsoft.com</owner> <owner>input-dev@chromium.org</owner> @@ -1442,11 +1500,17 @@ historically the display compositor lived in the browser process. Team: input-dev@chromium.org. + + Warning: This metric may include reports from clients with low-resolution + clocks (i.e. on Windows, ref. |TimeTicks::IsHighResolution()|). Such reports + will cause this metric to have an abnormal distribution. When considering + revising this histogram, see UMA_HISTOGRAM_CUSTOM_MICROSECONDS_TIMES for the + solution. </summary> </histogram> <histogram name="Event.Latency.ScrollUpdate.Scrollbar.TimeToHandled2" - units="microseconds" expires_after="2021-12-01"> + units="microseconds" expires_after="2022-06-01"> <owner>flackr@chromium.org</owner> <owner>arakeri@microsoft.com</owner> <owner>input-dev@chromium.org</owner> @@ -1693,7 +1757,7 @@ <histogram name="Event.Latency.ScrollUpdate.Touch.BrowserNotifiedToBeforeGpuSwap2" - units="microseconds" expires_after="2021-12-01"> + units="microseconds" expires_after="2022-06-01"> <owner>flackr@chromium.org</owner> <owner>input-dev@chromium.org</owner> <summary> @@ -1701,11 +1765,17 @@ event with touch source induced renderer swap and GPU starts to swap. Team: input-dev@chromium.org. + + Warning: This metric may include reports from clients with low-resolution + clocks (i.e. on Windows, ref. |TimeTicks::IsHighResolution()|). Such reports + will cause this metric to have an abnormal distribution. When considering + revising this histogram, see UMA_HISTOGRAM_CUSTOM_MICROSECONDS_TIMES for the + solution. </summary> </histogram> <histogram name="Event.Latency.ScrollUpdate.Touch.GpuSwap2" - units="microseconds" expires_after="2021-10-10"> + units="microseconds" expires_after="2022-06-01"> <owner>flackr@chromium.org</owner> <owner>input-dev@chromium.org</owner> <summary> @@ -1723,7 +1793,7 @@ </histogram> <histogram name="Event.Latency.ScrollUpdate.Touch.HandledToRendererSwap2" - units="microseconds" expires_after="2021-12-01"> + units="microseconds" expires_after="2022-06-01"> <owner>flackr@chromium.org</owner> <owner>input-dev@chromium.org</owner> <summary> @@ -1743,7 +1813,7 @@ <histogram name="Event.Latency.ScrollUpdate.Touch.RendererSwapToBrowserNotified2" - units="microseconds" expires_after="2021-10-31"> + units="microseconds" expires_after="2022-06-01"> <owner>flackr@chromium.org</owner> <owner>input-dev@chromium.org</owner> <summary> @@ -1751,12 +1821,19 @@ gesture event with touch source, and browser receives the swap notification. Team: input-dev@chromium.org. + + Warning: This metric may include reports from clients with low-resolution + clocks (i.e. on Windows, ref. |TimeTicks::IsHighResolution()|). Such reports + will cause this metric to have an abnormal distribution. When considering + revising this histogram, see UMA_HISTOGRAM_CUSTOM_MICROSECONDS_TIMES for the + solution. </summary> </histogram> <histogram name="Event.Latency.ScrollUpdate.Touch.TimeToHandled2" - units="microseconds" expires_after="2021-10-17"> + units="microseconds" expires_after="2022-06-01"> <owner>flackr@chromium.org</owner> + <owner>input-dev@chromium.org</owner> <summary> Time between initial creation of a touch event and the generated ScrollUpdate gesture event is handled on main/impl thread (specified by @@ -1805,7 +1882,7 @@ <histogram name="Event.Latency.ScrollUpdate.Wheel.BrowserNotifiedToBeforeGpuSwap2" - units="microseconds" expires_after="2021-12-01"> + units="microseconds" expires_after="2022-06-01"> <owner>flackr@chromium.org</owner> <owner>input-dev@chromium.org</owner> <summary> @@ -1813,11 +1890,17 @@ event with wheel source induced renderer swap and GPU starts to swap. Team: input-dev@chromium.org. + + Warning: This metric may include reports from clients with low-resolution + clocks (i.e. on Windows, ref. |TimeTicks::IsHighResolution()|). Such reports + will cause this metric to have an abnormal distribution. When considering + revising this histogram, see UMA_HISTOGRAM_CUSTOM_MICROSECONDS_TIMES for the + solution. </summary> </histogram> <histogram name="Event.Latency.ScrollUpdate.Wheel.GpuSwap2" - units="microseconds" expires_after="2021-06-16"> + units="microseconds" expires_after="2022-06-01"> <owner>flackr@chromium.org</owner> <owner>input-dev@chromium.org</owner> <summary> @@ -1835,7 +1918,7 @@ </histogram> <histogram name="Event.Latency.ScrollUpdate.Wheel.HandledToRendererSwap2" - units="microseconds" expires_after="2021-06-16"> + units="microseconds" expires_after="2022-06-01"> <owner>flackr@chromium.org</owner> <owner>input-dev@chromium.org</owner> <summary> @@ -1856,7 +1939,7 @@ <histogram name="Event.Latency.ScrollUpdate.Wheel.RendererSwapToBrowserNotified2" - units="microseconds" expires_after="2021-07-13"> + units="microseconds" expires_after="2022-06-01"> <owner>flackr@chromium.org</owner> <owner>input-dev@chromium.org</owner> <summary> @@ -1864,11 +1947,17 @@ gesture event with wheel source, and browser receives the swap notification. Team: input-dev@chromium.org. + + Warning: This metric may include reports from clients with low-resolution + clocks (i.e. on Windows, ref. |TimeTicks::IsHighResolution()|). Such reports + will cause this metric to have an abnormal distribution. When considering + revising this histogram, see UMA_HISTOGRAM_CUSTOM_MICROSECONDS_TIMES for the + solution. </summary> </histogram> <histogram name="Event.Latency.ScrollUpdate.Wheel.TimeToHandled2" - units="microseconds" expires_after="2021-12-01"> + units="microseconds" expires_after="2022-06-01"> <owner>flackr@chromium.org</owner> <owner>input-dev@chromium.org</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/ios/histograms.xml b/tools/metrics/histograms/metadata/ios/histograms.xml index c722a8c..d1f3a78 100644 --- a/tools/metrics/histograms/metadata/ios/histograms.xml +++ b/tools/metrics/histograms/metadata/ios/histograms.xml
@@ -556,6 +556,76 @@ </summary> </histogram> +<histogram name="IOS.Frame.FirstInputDelay.MainFrame" units="ms" + expires_after="2022-11-30"> + <owner>danieltwhite@chromium.org</owner> + <owner>ajuma@chromium.org</owner> + <summary> + Many features include JavaScript injected logic that run in the WebKit + renderer process. One Web Vitals metric that evaluates user experience is + First Input Delay. First Input Delay is defined as the amount of time + between the a user's first interaction with the page and the page receiving + the input event for this interaction. This histogram captures the First + Input Delay time for every main frame. This histogram's understanding of + First Input Delay differs from the traditional understanding because it does + not aggregate and compare the First Input Delay times across the frames on a + page. + </summary> +</histogram> + +<histogram + name="IOS.Frame.FirstInputDelay.MainFrame.AfterBackForwardCacheRestore" + units="ms" expires_after="2022-11-30"> + <owner>danieltwhite@chromium.org</owner> + <owner>ajuma@chromium.org</owner> + <summary> + Many features include JavaScript injected logic that run in the WebKit + renderer process. One Web Vitals metric that evaluates user experience is + First Input Delay. First Input Delay is defined as the amount of time + between the a user's first interaction with the page and the page receiving + the input event for this interaction. This histogram captures the First + Input Delay time for user's main frame that is loaded from the Back/Forward + cache. This histogram's understanding of First Contentful Paint differs from + the traditional understanding because it does not aggregate and compare the + First Input Delay times across the frames on a page. + </summary> +</histogram> + +<histogram name="IOS.Frame.FirstInputDelay.SubFrame" units="ms" + expires_after="2022-11-30"> + <owner>danieltwhite@chromium.org</owner> + <owner>ajuma@chromium.org</owner> + <summary> + Many features include JavaScript injected logic that run in the WebKit + renderer process. One Web Vitals metric that evaluates user experience is + First Input Delay. First Input Delay is defined as the amount of time + between the a user's first interaction with the page and the page receiving + the input event for this interaction. This histogram captures the First + Input Delay time for user's subframes. This histogram's understanding of + First Contentful Paint differs from the traditional understanding because it + does not aggregate and compare the First Input Delay times across the frames + on a page. + </summary> +</histogram> + +<histogram + name="IOS.Frame.FirstInputDelay.SubFrame.AfterBackForwardCacheRestore" + units="ms" expires_after="2022-11-30"> + <owner>danieltwhite@chromium.org</owner> + <owner>ajuma@chromium.org</owner> + <summary> + Many features include JavaScript injected logic that run in the WebKit + renderer process. One Web Vitals metric that evaluates user experience is + First Input Delay. First Input Delay is defined as the amount of time + between the a user's first interaction with the page and the page receiving + the input event for this interaction. This histogram captures the First + Input Delay time for user's subframes that is loaded from the Back/Forward + cache. This histogram's understanding of First Contentful Paint differs from + the traditional understanding because it does not aggregate and compare the + First Input Delay times across the frames on a page. + </summary> +</histogram> + <histogram name="IOS.Handoff.Origin" enum="IOSHandoffOrigin" expires_after="M77"> <owner>erikchen@chromium.org</owner>
diff --git a/tools/metrics/histograms/metadata/network/histograms.xml b/tools/metrics/histograms/metadata/network/histograms.xml index 12711409..475a7d6 100644 --- a/tools/metrics/histograms/metadata/network/histograms.xml +++ b/tools/metrics/histograms/metadata/network/histograms.xml
@@ -3537,7 +3537,7 @@ </histogram> <histogram name="NetworkService.TimeToGrantDataAccess" units="ms" - expires_after="M97"> + expires_after="2022-05-01"> <owner>wfh@chromium.org</owner> <owner>mmenke@chromium.org</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/new_tab_page/histograms.xml b/tools/metrics/histograms/metadata/new_tab_page/histograms.xml index f7c9ba0..95c46885 100644 --- a/tools/metrics/histograms/metadata/new_tab_page/histograms.xml +++ b/tools/metrics/histograms/metadata/new_tab_page/histograms.xml
@@ -1444,7 +1444,7 @@ </histogram> <histogram name="NewTabPage.Promos.PromoBrowserCommand" - enum="PromoBrowserCommandEnum" expires_after="2022-01-01"> + enum="PromoBrowserCommandEnum" expires_after="2022-06-05"> <owner>mahmadi@chromium.org</owner> <owner>chrome-desktop-ntp@google.com</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/others/histograms.xml b/tools/metrics/histograms/metadata/others/histograms.xml index c566a97..df691114 100644 --- a/tools/metrics/histograms/metadata/others/histograms.xml +++ b/tools/metrics/histograms/metadata/others/histograms.xml
@@ -7744,6 +7744,17 @@ </summary> </histogram> +<histogram name="HeapProfiling.InProcess.Enabled" enum="BooleanEnabled" + expires_after="2022-12-02"> + <owner>joenotcharles@chromium.org</owner> + <owner>chrome-memory@google.com</owner> + <summary> + One metric is emitted on every Chrome launch, recording whether the + in-process heap profiler is enabled in the browser process for this Chrome + session. + </summary> +</histogram> + <histogram name="HeapProfiling.ProfiledProcess.Type" enum="HeapProfilingProcessType" expires_after="2021-12-12"> <owner>erikchen@chromium.org</owner>
diff --git a/tools/metrics/histograms/metadata/payment/OWNERS b/tools/metrics/histograms/metadata/payment/OWNERS index 6cf5377..17f10e9 100644 --- a/tools/metrics/histograms/metadata/payment/OWNERS +++ b/tools/metrics/histograms/metadata/payment/OWNERS
@@ -4,3 +4,4 @@ # Use chromium-metrics-reviews@google.com as a backup. rouslan@chromium.org maxlg@chromium.org +smcgruer@chromium.org
diff --git a/tools/metrics/histograms/metadata/sb_client/histograms.xml b/tools/metrics/histograms/metadata/sb_client/histograms.xml index 2eb383cb..3251012 100644 --- a/tools/metrics/histograms/metadata/sb_client/histograms.xml +++ b/tools/metrics/histograms/metadata/sb_client/histograms.xml
@@ -615,6 +615,9 @@ <histogram name="SBClientPhishing.ClientModelStatus" enum="SBClientPhishingClientModelStatus" expires_after="2021-12-05"> + <obsolete> + Removed 12-2021 + </obsolete> <owner>vakh@chromium.org</owner> <owner>chrome-safebrowsing-alerts@google.com</owner> <summary>
diff --git a/tools/metrics/ukm/ukm.xml b/tools/metrics/ukm/ukm.xml index 2b86fc8ec..e52d9912 100644 --- a/tools/metrics/ukm/ukm.xml +++ b/tools/metrics/ukm/ukm.xml
@@ -14938,7 +14938,7 @@ <summary> Page level pop-up statistics. </summary> - <metric name="Allowed"> + <metric name="Allowed" enum="Boolean"> <summary> Whether a user has, explicitly, allowed all popups on the last committed url of a page. The user's site level popup content setting is queried when
diff --git a/tools/perf/benchmarks/desktop_ui.py b/tools/perf/benchmarks/desktop_ui.py index 815a5dcb..bdcb035a 100644 --- a/tools/perf/benchmarks/desktop_ui.py +++ b/tools/perf/benchmarks/desktop_ui.py
@@ -43,6 +43,8 @@ options.AppendExtraBrowserArgs('--enable-benchmarking') # UIDevtools is used for driving native UI. options.AppendExtraBrowserArgs('--enable-ui-devtools=0') + options.AppendExtraBrowserArgs( + '--enable-features=ui-debug-tools-enable-synthetic-events') @classmethod def Name(cls):
diff --git a/ui/android/window_android_compositor.h b/ui/android/window_android_compositor.h index 20f07b2..c357513b 100644 --- a/ui/android/window_android_compositor.h +++ b/ui/android/window_android_compositor.h
@@ -46,6 +46,8 @@ virtual void OnUpdateRefreshRate(float refresh_rate) = 0; virtual void OnUpdateSupportedRefreshRates( const std::vector<float>& supported_refresh_rates) = 0; + virtual std::unique_ptr<ui::CompositorLock> GetCompositorLock( + base::TimeDelta timeout) = 0; }; } // namespace ui
diff --git a/ui/views/controls/button/button.cc b/ui/views/controls/button/button.cc index 726840d6..07dcb91 100644 --- a/ui/views/controls/button/button.cc +++ b/ui/views/controls/button/button.cc
@@ -171,6 +171,10 @@ return tooltip_text_; } +void Button::SetCallback(PressedCallback callback) { + callback_ = std::move(callback); +} + void Button::SetAccessibleName(const std::u16string& name) { if (name == accessible_name_) return;
diff --git a/ui/views/controls/button/button.h b/ui/views/controls/button/button.h index 0d07ab6..6879671 100644 --- a/ui/views/controls/button/button.h +++ b/ui/views/controls/button/button.h
@@ -130,9 +130,7 @@ int tag() const { return tag_; } void set_tag(int tag) { tag_ = tag; } - void SetCallback(PressedCallback callback) { - callback_ = std::move(callback); - } + virtual void SetCallback(PressedCallback callback); void SetAccessibleName(const std::u16string& name); const std::u16string& GetAccessibleName() const;
diff --git a/ui/views/controls/button/menu_button.cc b/ui/views/controls/button/menu_button.cc index bd20d92..af400bf 100644 --- a/ui/views/controls/button/menu_button.cc +++ b/ui/views/controls/button/menu_button.cc
@@ -36,6 +36,10 @@ return button_controller()->Activate(event); } +void MenuButton::SetCallback(PressedCallback callback) { + menu_button_controller_->SetCallback(std::move(callback)); +} + void MenuButton::NotifyClick(const ui::Event& event) { // Run pressed callback via MenuButtonController, instead of directly. button_controller()->Activate(&event);
diff --git a/ui/views/controls/button/menu_button.h b/ui/views/controls/button/menu_button.h index 027d7685..2c7d6bf5 100644 --- a/ui/views/controls/button/menu_button.h +++ b/ui/views/controls/button/menu_button.h
@@ -39,6 +39,9 @@ bool Activate(const ui::Event* event); + // Button: + void SetCallback(PressedCallback callback) override; + protected: // Button: void NotifyClick(const ui::Event& event) final;
diff --git a/ui/views/controls/button/menu_button_controller.h b/ui/views/controls/button/menu_button_controller.h index 5c3d75e..a061a7f 100644 --- a/ui/views/controls/button/menu_button_controller.h +++ b/ui/views/controls/button/menu_button_controller.h
@@ -6,6 +6,7 @@ #define UI_VIEWS_CONTROLS_BUTTON_MENU_BUTTON_CONTROLLER_H_ #include <memory> +#include <utility> #include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" @@ -80,6 +81,10 @@ // menu, this is distinct from IsTriggerableEvent(). bool IsTriggerableEventType(const ui::Event& event); + void SetCallback(Button::PressedCallback callback) { + callback_ = std::move(callback); + } + private: // Increment/decrement the number of "pressed" locks this button has, and // set the state accordingly. The ink drop is snapped to the final ACTIVATED
diff --git a/ui/views/metadata/view_factory.h b/ui/views/metadata/view_factory.h index 7e1ea16..4940408 100644 --- a/ui/views/metadata/view_factory.h +++ b/ui/views/metadata/view_factory.h
@@ -47,6 +47,17 @@ return std::move(this->CopyAddressTo(view_address)); } + template <typename View> + Builder& CopyAddressTo(raw_ptr<View>* view_address) & { + *view_address = view_ ? view_.get() : root_view_.get(); + return *static_cast<Builder*>(this); + } + + template <typename View> + Builder&& CopyAddressTo(raw_ptr<View>* view_address) && { + return std::move(this->CopyAddressTo(view_address)); + } + Builder& CustomConfigure(ConfigureCallback configure_callback) & { configure_callback_ = std::move(configure_callback); return *static_cast<Builder*>(this);
diff --git a/ui/webui/resources/cr_components/chromeos/bluetooth/bluetooth_base_page.html b/ui/webui/resources/cr_components/chromeos/bluetooth/bluetooth_base_page.html index c73fd109..c8c52d0 100644 --- a/ui/webui/resources/cr_components/chromeos/bluetooth/bluetooth_base_page.html +++ b/ui/webui/resources/cr_components/chromeos/bluetooth/bluetooth_base_page.html
@@ -1,7 +1,7 @@ <style include="iron-positioning"> :host ::slotted([slot='page-body']) { color: var(--cr-primary-text-color); - height: 276px; + height: 292px; } paper-progress { @@ -23,13 +23,14 @@ display: flex; flex-direction: column; height: 100%; - margin: 0, 8px, 8px, 8px; + margin: 0 8px 8px 8px; } #title { color: var(--cr-primary-text-color); font-weight: normal; line-height: 24px; + margin: 24px 0 8px 0; } .cancel-button {
diff --git a/ui/webui/resources/cr_components/chromeos/bluetooth/bluetooth_pairing_device_selection_page.html b/ui/webui/resources/cr_components/chromeos/bluetooth/bluetooth_pairing_device_selection_page.html index c87463a..24a43839 100644 --- a/ui/webui/resources/cr_components/chromeos/bluetooth/bluetooth_pairing_device_selection_page.html +++ b/ui/webui/resources/cr_components/chromeos/bluetooth/bluetooth_pairing_device_selection_page.html
@@ -1,11 +1,17 @@ <style include="cr-shared-style"> + localized-link { + color: var(--cros-text-color-secondary); + } + #container { height: 200px; - margin-top: 12px; } #deviceListTitle { - margin-top: 24px; + color: var(--cros-text-color-secondary); + font-size: 14px; + font-weight: 500; + margin: 20px 0 8px 0; } </style> <bluetooth-base-page show-scan-progress button-bar-state="[[buttonBarState_]]">
diff --git a/ui/webui/resources/cr_components/chromeos/bluetooth/bluetooth_pairing_ui.html b/ui/webui/resources/cr_components/chromeos/bluetooth/bluetooth_pairing_ui.html index 79a5435..8e0a9a4 100644 --- a/ui/webui/resources/cr_components/chromeos/bluetooth/bluetooth_pairing_ui.html +++ b/ui/webui/resources/cr_components/chromeos/bluetooth/bluetooth_pairing_ui.html
@@ -1,6 +1,6 @@ <style> #container { - height: 392px; + height: 408px; } </style> <div id="container">