diff --git a/AUTHORS b/AUTHORS index b5483b6a..112403f 100644 --- a/AUTHORS +++ b/AUTHORS
@@ -1340,6 +1340,7 @@ Mozilla Corporation <*@mozilla.com> Neverware Inc. <*@neverware.com> NIKE, Inc. <*@nike.com> +Nutanix Inc. <*nutanix.com> NVIDIA Corporation <*@nvidia.com> OpenFin Inc. <*@openfin.co> Opera Software ASA <*@opera.com>
diff --git a/DEPS b/DEPS index 0f0a3da..ce7b1d8 100644 --- a/DEPS +++ b/DEPS
@@ -245,7 +245,7 @@ # 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': '458653d9fce73db0f48d628353e50e828ad6c389', + 'skia_revision': '04151728ac473ac17384589d0492f8f899a535ff', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling V8 # and whatever else without interference from each other. @@ -261,7 +261,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling PDFium # and whatever else without interference from each other. - 'pdfium_revision': '341c836c0ba66610a12d09bc31387be00d8f0b23', + 'pdfium_revision': '707cb3745d875648c970e1f4a525ab6077794774', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling BoringSSL # and whatever else without interference from each other. @@ -276,7 +276,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling googletest # and whatever else without interference from each other. - 'googletest_revision': 'c9643a2e45ed0cb18b8409c62994be7c6e66dc1b', + 'googletest_revision': '100f6fbf5f81a82d163c1e29735e8a2936eacd4f', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling lighttpd # and whatever else without interference from each other. @@ -320,7 +320,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': '68613ab02f6d556a2c5ac68ea08f466a534c6bd9', + 'devtools_frontend_revision': '668bc7a4bc6bea854e8fc21f0e0ca3953ff5e95a', # 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. @@ -360,7 +360,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. - 'dawn_revision': 'd0530a6e035d6bbba42313b9e075672c08a89c32', + 'dawn_revision': '678dc5649baf67651e0b82608952d3bc31d501de', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. @@ -1410,7 +1410,7 @@ Var('chromium_git') + '/external/github.com/cisco/openh264' + '@' + 'b52786888ddce9d6bc06b7825ba9bffc65924e0c', 'src/third_party/openscreen/src': - Var('chromium_git') + '/openscreen' + '@' + 'eecc51cfdcc1248f892503ea66a02c97d7cb6cf3', + Var('chromium_git') + '/openscreen' + '@' + '18b812750535e0433718472f5aa35b6a18f3f310', 'src/third_party/openxr/src': { 'url': Var('chromium_git') + '/external/github.com/KhronosGroup/OpenXR-SDK' + '@' + 'bf21ccb1007bb531b45d9978919a56ea5059c245', @@ -1427,7 +1427,7 @@ }, 'src/third_party/perfetto': - Var('android_git') + '/platform/external/perfetto.git' + '@' + '56f2ccce0511ebd51e2f7d2fa659719a712a6044', + Var('android_git') + '/platform/external/perfetto.git' + '@' + '5a202e1c1c7fb14817bb4df498d5f0ea71915653', 'src/third_party/perl': { 'url': Var('chromium_git') + '/chromium/deps/perl.git' + '@' + '6f3e5028eb65d0b4c5fdd792106ac4c84eee1eb3', @@ -1524,7 +1524,7 @@ }, 'src/third_party/re2/src': - Var('chromium_git') + '/external/github.com/google/re2.git' + '@' + 'c4248946060fac5a7740971c2d584007164b30b0', + Var('chromium_git') + '/external/github.com/google/re2.git' + '@' + '918b34e6f3b4fcda8f2920dceee01d1e8c7fd380', 'src/third_party/r8': { 'packages': [ @@ -1609,7 +1609,7 @@ 'src/third_party/usrsctp/usrsctplib': Var('chromium_git') + '/external/github.com/sctplab/usrsctp' + '@' + '62d7d0c928c9a040dce96aa2f16c00e7e67d59cb', - 'src/third_party/vulkan-deps': '{chromium_git}/vulkan-deps@85f43409872d6984849dca746335747ca5b6819e', + 'src/third_party/vulkan-deps': '{chromium_git}/vulkan-deps@d1b842fca80dddd1a098bf63813386e3e44f9642', 'src/third_party/vulkan_memory_allocator': Var('chromium_git') + '/external/github.com/GPUOpen-LibrariesAndSDKs/VulkanMemoryAllocator.git' + '@' + 'ebe84bec02c041d28f902da0214bf442743fc907', @@ -1648,7 +1648,7 @@ Var('chromium_git') + '/external/github.com/gpuweb/cts.git' + '@' + 'fc207904abbb29864991c71c7156336455a3d892', 'src/third_party/webrtc': - Var('webrtc_git') + '/src.git' + '@' + 'ac506bddcfa3af906128281db6a0127f26e3ed59', + Var('webrtc_git') + '/src.git' + '@' + '3ea5f714a9c1bd94eaef75d904a9fb2041922270', 'src/third_party/libgifcodec': Var('skia_git') + '/libgifcodec' + '@'+ Var('libgifcodec_revision'), @@ -1718,7 +1718,7 @@ Var('chromium_git') + '/v8/v8.git' + '@' + Var('v8_revision'), 'src-internal': { - 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@69463595064cb645ef53552c575462495998f389', + 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@7b25b2f29a4407f353679bc8cae691aa6aefa4bd', 'condition': 'checkout_src_internal', },
diff --git a/PRESUBMIT.py b/PRESUBMIT.py index e35f5db..5e157f3 100644 --- a/PRESUBMIT.py +++ b/PRESUBMIT.py
@@ -1084,7 +1084,6 @@ 'OS_LINUX', 'OS_MAC', 'OS_NACL', - 'OS_NACL_NONSFI', 'OS_NETBSD', 'OS_OPENBSD', 'OS_POSIX',
diff --git a/android_webview/browser/aw_pdf_exporter.cc b/android_webview/browser/aw_pdf_exporter.cc index adfc9d88..0c9c3cd0 100644 --- a/android_webview/browser/aw_pdf_exporter.cc +++ b/android_webview/browser/aw_pdf_exporter.cc
@@ -86,7 +86,7 @@ namespace { // Converts from 1/1000 of inches to device units using DPI. int MilsToDots(int val, int dpi) { - return static_cast<int>(printing::ConvertUnitDouble(val, 1000.0, dpi)); + return static_cast<int>(printing::ConvertUnitFloat(val, 1000, dpi)); } } // namespace
diff --git a/ash/BUILD.gn b/ash/BUILD.gn index a290ee5..4b17289 100644 --- a/ash/BUILD.gn +++ b/ash/BUILD.gn
@@ -2771,6 +2771,7 @@ "//build:branding_buildflags", "//cc:test_support", "//chromeos:test_support", + "//chromeos/assistant:buildflags", "//chromeos/components/feature_usage", "//chromeos/components/sensors:sensors", "//chromeos/components/sensors:test_support",
diff --git a/ash/ambient/DEPS b/ash/ambient/DEPS index 6e01ae7..bfd1856 100644 --- a/ash/ambient/DEPS +++ b/ash/ambient/DEPS
@@ -3,7 +3,7 @@ "+chromeos/assistant/internal/ambient/backdrop_client_config.h", "+chromeos/assistant/internal/proto/backdrop", ], - "ambient_controller.cc": [ + "ambient_controller.*": [ "+chromeos/assistant/buildflags.h", ], ".*test.cc": [
diff --git a/ash/ambient/ambient_controller.cc b/ash/ambient/ambient_controller.cc index 5656fbe..3849970 100644 --- a/ash/ambient/ambient_controller.cc +++ b/ash/ambient/ambient_controller.cc
@@ -9,14 +9,17 @@ #include <utility> #include <vector> +#include "ash/ambient/model/ambient_animation_photo_config.h" #include "ash/ambient/model/ambient_backend_model_observer.h" #include "ash/ambient/model/ambient_slideshow_photo_config.h" +#include "ash/ambient/resources/ambient_animation_static_resources.h" #include "ash/ambient/ui/ambient_container_view.h" #include "ash/ambient/ui/ambient_view_delegate.h" #include "ash/ambient/util/ambient_util.h" #include "ash/assistant/model/assistant_interaction_model.h" #include "ash/constants/ash_features.h" #include "ash/login/ui/lock_screen.h" +#include "ash/public/cpp/ambient/ambient_animation_theme.h" #include "ash/public/cpp/ambient/ambient_backend_controller.h" #include "ash/public/cpp/ambient/ambient_client.h" #include "ash/public/cpp/ambient/ambient_metrics.h" @@ -33,10 +36,13 @@ #include "base/bind.h" #include "base/callback_helpers.h" #include "base/check.h" +#include "base/containers/span.h" +#include "base/feature_list.h" #include "base/memory/weak_ptr.h" #include "base/time/time.h" #include "base/timer/timer.h" #include "build/buildflag.h" +#include "cc/paint/skottie_wrapper.h" #include "chromeos/assistant/buildflags.h" #include "chromeos/dbus/power/power_manager_client.h" #include "chromeos/dbus/power_manager/backlight.pb.h" @@ -162,6 +168,10 @@ registry->RegisterIntegerPref( ambient::prefs::kAmbientModePhotoRefreshIntervalSeconds, kPhotoRefreshInterval.InSeconds()); + + registry->RegisterIntegerPref( + ambient::prefs::kAmbientAnimationTheme, + static_cast<int>(kDefaultAmbientAnimationTheme)); } } @@ -573,13 +583,7 @@ DCHECK(AmbientClient::Get()); ambient_photo_controller_ = std::make_unique<AmbientPhotoController>( *AmbientClient::Get(), access_token_controller_, - // TODO(esum): Read a setting here and initialize the photo controller - // with the slideshow config or the animation config based on that - // setting. When this setting is available, - // ambient_photo_controller_unittest.cc must be updated with tests for - // the animation use case; it is too difficult to add tests without that - // setting. - CreateAmbientSlideshowPhotoConfig()); + CreatePhotoConfigForCurrentTheme()); ambient_ui_model_observer_.Observe(&ambient_ui_model_); @@ -688,7 +692,8 @@ std::unique_ptr<views::Widget> AmbientController::CreateWidget( aura::Window* container) { - auto container_view = std::make_unique<AmbientContainerView>(&delegate_); + auto container_view = std::make_unique<AmbientContainerView>( + &delegate_, std::move(pending_animation_static_resources_)); auto* widget_delegate = new AmbientWidgetDelegate(); widget_delegate->SetInitiallyFocusedView(container_view.get()); @@ -730,6 +735,13 @@ void AmbientController::StartRefreshingImages() { DCHECK(ambient_photo_controller_); + // There is no use case for switching themes "on-the-fly" while ambient mode + // is rendering. Thus, it's sufficient to just reinitialize the + // model/controller with the appropriate config each time before calling + // StartScreenUpdate(). + DCHECK(!ambient_photo_controller_->IsScreenUpdateActive()); + ambient_photo_controller_->ambient_backend_model()->SetPhotoConfig( + CreatePhotoConfigForCurrentTheme()); ambient_photo_controller_->StartScreenUpdate(); } @@ -738,6 +750,50 @@ ambient_photo_controller_->StopScreenUpdate(); } +AmbientPhotoConfig AmbientController::CreatePhotoConfigForCurrentTheme() { + AmbientAnimationTheme current_theme = kDefaultAmbientAnimationTheme; + absl::optional<bool> animation_experiment_enabled = + base::FeatureList::GetStateIfOverridden( + features::kAmbientModeAnimationFeature); + if (animation_experiment_enabled.has_value()) { + // TODO(esum): Remove this block of code once the web ui that allows the + // user to select the desired theme is ready. It is currently controlled by + // an experiment flag since the feature is under active development. + current_theme = animation_experiment_enabled.value() + ? AmbientAnimationTheme::kFeelTheBreeze + : AmbientAnimationTheme::kSlideshow; + } else { + DCHECK(GetPrimaryUserPrefService()); + int current_theme_as_int = GetPrimaryUserPrefService()->GetInteger( + ambient::prefs::kAmbientAnimationTheme); + // Gracefully handle pref having invalid value in case pref storage is + // corrupted somehow. + if (current_theme_as_int < 0 || + current_theme_as_int > + static_cast<int>(AmbientAnimationTheme::kMaxValue)) { + LOG(WARNING) << "Loaded invalid ambient theme from pref storage: " + << current_theme_as_int << ". Default to " + << kDefaultAmbientAnimationTheme; + } else { + current_theme = static_cast<AmbientAnimationTheme>(current_theme_as_int); + } + } + DVLOG(4) << "Loaded ambient theme " << current_theme; + + pending_animation_static_resources_.reset(); + if (current_theme == AmbientAnimationTheme::kSlideshow) { + return CreateAmbientSlideshowPhotoConfig(); + } else { + pending_animation_static_resources_ = + AmbientAnimationStaticResources::Create(current_theme); + return CreateAmbientAnimationPhotoConfig( + cc::SkottieWrapper::CreateNonSerializable( + base::as_bytes(base::make_span( + pending_animation_static_resources_->GetLottieData()))) + ->GetImageAssetMetadata()); + } +} + void AmbientController::set_backend_controller_for_testing( std::unique_ptr<AmbientBackendController> backend_controller) { ambient_backend_controller_ = std::move(backend_controller);
diff --git a/ash/ambient/ambient_controller.h b/ash/ambient/ambient_controller.h index 3cc4d68..5c1e3cc 100644 --- a/ash/ambient/ambient_controller.h +++ b/ash/ambient/ambient_controller.h
@@ -41,6 +41,7 @@ namespace ash { +class AmbientAnimationStaticResources; class AmbientBackendController; class AmbientContainerView; class AmbientPhotoController; @@ -139,9 +140,10 @@ private: friend class AmbientAshTestBase; friend class AmbientControllerTest; - FRIEND_TEST_ALL_PREFIXES(AmbientControllerTest, + FRIEND_TEST_ALL_PREFIXES(AmbientControllerTestForAnyTheme, BindsObserversWhenAmbientEnabled); - FRIEND_TEST_ALL_PREFIXES(AmbientControllerTest, BindsObserversWhenAmbientOn); + FRIEND_TEST_ALL_PREFIXES(AmbientControllerTestForAnyTheme, + BindsObserversWhenAmbientOn); // Hide or close Ambient mode UI. void DismissUI(); @@ -156,6 +158,7 @@ void StartRefreshingImages(); void StopRefreshingImages(); + AmbientPhotoConfig CreatePhotoConfigForCurrentTheme(); // Invoked when the auto-show timer in |InactivityMonitor| gets fired after // device being inactive for a specific amount of time. @@ -231,6 +234,14 @@ // called. Used to prevent Ambient mode starting after screen is off. bool is_screen_off_ = false; + // Transient location to hold an animation's static resources while the + // model is being buffered with an initial set of topics. Once the animation + // is ready to be rendered, this gets transferred to an AmbientAnimationView. + // + // Null if the slideshow theme is active. + std::unique_ptr<AmbientAnimationStaticResources> + pending_animation_static_resources_; + base::WeakPtrFactory<AmbientController> weak_ptr_factory_{this}; };
diff --git a/ash/ambient/ambient_controller_unittest.cc b/ash/ambient/ambient_controller_unittest.cc index 5b903cb1..4fd8038 100644 --- a/ash/ambient/ambient_controller_unittest.cc +++ b/ash/ambient/ambient_controller_unittest.cc
@@ -10,8 +10,10 @@ #include "ash/ambient/test/ambient_ash_test_base.h" #include "ash/ambient/ui/ambient_container_view.h" +#include "ash/ambient/ui/ambient_view_ids.h" #include "ash/assistant/assistant_interaction_controller_impl.h" #include "ash/assistant/model/assistant_interaction_model.h" +#include "ash/public/cpp/ambient/ambient_animation_theme.h" #include "ash/public/cpp/ambient/ambient_prefs.h" #include "ash/public/cpp/ambient/ambient_ui_model.h" #include "ash/public/cpp/assistant/controller/assistant_interaction_controller.h" @@ -21,6 +23,8 @@ #include "base/run_loop.h" #include "base/test/bind.h" #include "base/time/time.h" +#include "build/buildflag.h" +#include "chromeos/assistant/buildflags.h" #include "chromeos/dbus/power/fake_power_manager_client.h" #include "chromeos/dbus/power/power_manager_client.h" #include "chromeos/dbus/power_manager/power_supply_properties.pb.h" @@ -84,7 +88,37 @@ } }; -TEST_F(AmbientControllerTest, ShowAmbientScreenUponLock) { +// Tests for behavior that are agnostic to the AmbientAnimationTheme selected by +// the user should use this test harness. +class AmbientControllerTestForAnyTheme + : public AmbientControllerTest, + public ::testing::WithParamInterface<AmbientAnimationTheme> { + protected: + void SetUp() override { + AmbientControllerTest::SetUp(); + SetAmbientAnimationTheme(GetParam()); + } +}; + +INSTANTIATE_TEST_SUITE_P( + SlideshowAndAnimationTheme, + AmbientControllerTestForAnyTheme, + // Only one lottie-animated theme is sufficient here. The main goal here is + // to make sure that fundamental behavior holds for both the slideshow and + // lottie-animated codepaths. + testing::Values(AmbientAnimationTheme::kSlideshow +// TODO(esum): Fully enable this AmbientAnimationTheme once: +// * The |include_ash_ambient_animation_resources| GN arg is true by default +// (the resources' size is currently being reduced to fit in the image). +// * The ash ambient resources are publishable (they are currently WIP). +// The tests will crash/fail without these resources available. +#if BUILDFLAG(HAS_ASH_AMBIENT_ANIMATION_RESOURCES) + , + AmbientAnimationTheme::kFeelTheBreeze +#endif // BUILDFLAG(HAS_ASH_AMBIENT_ANIMATION_RESOURCES) + )); + +TEST_P(AmbientControllerTestForAnyTheme, ShowAmbientScreenUponLock) { LockScreen(); // Lockscreen will not immediately show Ambient mode. EXPECT_FALSE(ambient_controller()->IsShown()); @@ -104,7 +138,7 @@ EXPECT_FALSE(ambient_controller()->IsShown()); } -TEST_F(AmbientControllerTest, NotShowAmbientWhenPrefNotEnabled) { +TEST_P(AmbientControllerTestForAnyTheme, NotShowAmbientWhenPrefNotEnabled) { SetAmbientModeEnabled(false); LockScreen(); @@ -126,7 +160,7 @@ EXPECT_FALSE(ambient_controller()->IsShown()); } -TEST_F(AmbientControllerTest, HideAmbientScreen) { +TEST_P(AmbientControllerTestForAnyTheme, HideAmbientScreen) { LockScreen(); FastForwardToLockScreenTimeout(); FastForwardTiny(); @@ -148,7 +182,7 @@ EXPECT_FALSE(ambient_controller()->IsShown()); } -TEST_F(AmbientControllerTest, CloseAmbientScreenUponUnlock) { +TEST_P(AmbientControllerTestForAnyTheme, CloseAmbientScreenUponUnlock) { LockScreen(); FastForwardToLockScreenTimeout(); FastForwardTiny(); @@ -168,7 +202,8 @@ EXPECT_TRUE(GetContainerViews().empty()); } -TEST_F(AmbientControllerTest, CloseAmbientScreenUponUnlockSecondaryUser) { +TEST_P(AmbientControllerTestForAnyTheme, + CloseAmbientScreenUponUnlockSecondaryUser) { // Simulate the login screen. ClearLogin(); SimulateUserLogin(kUser1); @@ -201,7 +236,7 @@ EXPECT_TRUE(GetContainerViews().empty()); } -TEST_F(AmbientControllerTest, NotShowAmbientWhenLockSecondaryUser) { +TEST_P(AmbientControllerTestForAnyTheme, NotShowAmbientWhenLockSecondaryUser) { // Simulate the login screen. ClearLogin(); SimulateUserLogin(kUser1); @@ -239,7 +274,8 @@ EXPECT_TRUE(GetContainerViews().empty()); } -TEST_F(AmbientControllerTest, ShouldRequestAccessTokenWhenLockingScreen) { +TEST_P(AmbientControllerTestForAnyTheme, + ShouldRequestAccessTokenWhenLockingScreen) { EXPECT_FALSE(IsAccessTokenRequestPending()); // Lock the screen will request a token. @@ -253,7 +289,8 @@ EXPECT_FALSE(IsAccessTokenRequestPending()); } -TEST_F(AmbientControllerTest, ShouldNotRequestAccessTokenWhenPrefNotEnabled) { +TEST_P(AmbientControllerTestForAnyTheme, + ShouldNotRequestAccessTokenWhenPrefNotEnabled) { SetAmbientModeEnabled(false); EXPECT_FALSE(IsAccessTokenRequestPending()); @@ -265,7 +302,7 @@ EXPECT_FALSE(IsAccessTokenRequestPending()); } -TEST_F(AmbientControllerTest, ShouldReturnCachedAccessToken) { +TEST_P(AmbientControllerTestForAnyTheme, ShouldReturnCachedAccessToken) { EXPECT_FALSE(IsAccessTokenRequestPending()); // Lock the screen will request a token. @@ -291,7 +328,7 @@ CloseAmbientScreen(); } -TEST_F(AmbientControllerTest, ShouldReturnEmptyAccessToken) { +TEST_P(AmbientControllerTestForAnyTheme, ShouldReturnEmptyAccessToken) { EXPECT_FALSE(IsAccessTokenRequestPending()); // Lock the screen will request a token. @@ -333,7 +370,8 @@ CloseAmbientScreen(); } -TEST_F(AmbientControllerTest, ShouldRetryRefreshAccessTokenAfterFailure) { +TEST_P(AmbientControllerTestForAnyTheme, + ShouldRetryRefreshAccessTokenAfterFailure) { EXPECT_FALSE(IsAccessTokenRequestPending()); // Lock the screen will request a token. @@ -350,7 +388,8 @@ CloseAmbientScreen(); } -TEST_F(AmbientControllerTest, ShouldRetryRefreshAccessTokenWithBackoffPolicy) { +TEST_P(AmbientControllerTestForAnyTheme, + ShouldRetryRefreshAccessTokenWithBackoffPolicy) { EXPECT_FALSE(IsAccessTokenRequestPending()); // Lock the screen will request a token. @@ -375,7 +414,8 @@ CloseAmbientScreen(); } -TEST_F(AmbientControllerTest, ShouldRetryRefreshAccessTokenOnlyThreeTimes) { +TEST_P(AmbientControllerTestForAnyTheme, + ShouldRetryRefreshAccessTokenOnlyThreeTimes) { EXPECT_FALSE(IsAccessTokenRequestPending()); // Lock the screen will request a token. @@ -409,7 +449,7 @@ CloseAmbientScreen(); } -TEST_F(AmbientControllerTest, +TEST_P(AmbientControllerTestForAnyTheme, CheckAcquireAndReleaseWakeLockWhenBatteryIsCharging) { // Simulate a device being connected to a charger initially. SetPowerStateCharging(); @@ -443,7 +483,7 @@ device::mojom::WakeLockType::kPreventDisplaySleep)); } -TEST_F(AmbientControllerTest, +TEST_P(AmbientControllerTestForAnyTheme, CheckAcquireAndReleaseWakeLockWhenBatteryBatteryIsFullAndDischarging) { SetPowerStateDischarging(); SetBatteryPercent(100.f); @@ -478,7 +518,7 @@ device::mojom::WakeLockType::kPreventDisplaySleep)); } -TEST_F(AmbientControllerTest, +TEST_P(AmbientControllerTestForAnyTheme, CheckAcquireAndReleaseWakeLockWhenBatteryStateChanged) { SetPowerStateDischarging(); SetExternalPowerConnected(); @@ -546,7 +586,7 @@ } // TODO(cowmoo): find a way to simulate events to trigger |UserActivityDetector| -TEST_F(AmbientControllerTest, ShouldDismissContainerViewOnEvents) { +TEST_P(AmbientControllerTestForAnyTheme, ShouldDismissContainerViewOnEvents) { std::vector<std::unique_ptr<ui::Event>> events; for (auto mouse_event_type : {ui::ET_MOUSE_PRESSED, ui::ET_MOUSE_MOVED}) { @@ -585,7 +625,7 @@ } } -TEST_F(AmbientControllerTest, ShouldDismissAndThenComesBack) { +TEST_P(AmbientControllerTestForAnyTheme, ShouldDismissAndThenComesBack) { LockScreen(); FastForwardToLockScreenTimeout(); FastForwardTiny(); @@ -602,7 +642,7 @@ EXPECT_TRUE(WidgetsVisible()); } -TEST_F(AmbientControllerTest, ShouldDismissContainerViewOnKeyEvent) { +TEST_P(AmbientControllerTestForAnyTheme, ShouldDismissContainerViewOnKeyEvent) { // Without user interaction, should show ambient mode. ambient_controller()->ShowUi(); EXPECT_FALSE(WidgetsVisible()); @@ -620,7 +660,7 @@ EXPECT_FALSE(ambient_controller()->IsShown()); } -TEST_F(AmbientControllerTest, +TEST_P(AmbientControllerTestForAnyTheme, ShouldDismissContainerViewOnKeyEventWhenLockScreenInBackground) { GetSessionControllerClient()->SetShouldLockScreenAutomatically(true); SetPowerStateCharging(); @@ -643,7 +683,7 @@ EXPECT_FALSE(ambient_controller()->IsShown()); } -TEST_F(AmbientControllerTest, +TEST_P(AmbientControllerTestForAnyTheme, ShouldShowAmbientScreenWithLockscreenWhenScreenIsDimmed) { GetSessionControllerClient()->SetShouldLockScreenAutomatically(true); SetPowerStateCharging(); @@ -664,7 +704,7 @@ EXPECT_FALSE(ambient_controller()->IsShown()); } -TEST_F(AmbientControllerTest, +TEST_P(AmbientControllerTestForAnyTheme, ShouldShowAmbientScreenWithLockscreenWithNoisyPowerEvents) { GetSessionControllerClient()->SetShouldLockScreenAutomatically(true); SetPowerStateCharging(); @@ -692,7 +732,7 @@ EXPECT_FALSE(ambient_controller()->IsShown()); } -TEST_F(AmbientControllerTest, +TEST_P(AmbientControllerTestForAnyTheme, ShouldShowAmbientScreenWithoutLockscreenWhenScreenIsDimmed) { GetSessionControllerClient()->SetShouldLockScreenAutomatically(true); // When power is discharging, we do not lock the screen with ambient @@ -718,7 +758,8 @@ CloseAmbientScreen(); } -TEST_F(AmbientControllerTest, ShouldShowAmbientScreenWhenScreenIsDimmed) { +TEST_P(AmbientControllerTestForAnyTheme, + ShouldShowAmbientScreenWhenScreenIsDimmed) { GetSessionControllerClient()->SetShouldLockScreenAutomatically(false); SetPowerStateCharging(); EXPECT_FALSE(ambient_controller()->IsShown()); @@ -738,7 +779,8 @@ CloseAmbientScreen(); } -TEST_F(AmbientControllerTest, ShouldHideAmbientScreenWhenDisplayIsOff) { +TEST_P(AmbientControllerTestForAnyTheme, + ShouldHideAmbientScreenWhenDisplayIsOff) { GetSessionControllerClient()->SetShouldLockScreenAutomatically(false); EXPECT_FALSE(ambient_controller()->IsShown()); @@ -761,7 +803,7 @@ EXPECT_FALSE(ambient_controller()->IsShown()); } -TEST_F(AmbientControllerTest, +TEST_P(AmbientControllerTestForAnyTheme, ShouldHideAmbientScreenWhenDisplayIsOffThenComesBackWithLockScreen) { GetSessionControllerClient()->SetShouldLockScreenAutomatically(true); SetPowerStateCharging(); @@ -795,7 +837,7 @@ EXPECT_TRUE(ambient_controller()->IsShown()); } -TEST_F(AmbientControllerTest, +TEST_P(AmbientControllerTestForAnyTheme, ShouldHideAmbientScreenWhenDisplayIsOffAndNotStartWhenLockScreen) { GetSessionControllerClient()->SetShouldLockScreenAutomatically(true); SetPowerStateDischarging(); @@ -837,7 +879,7 @@ EXPECT_TRUE(ambient_controller()->IsShown()); } -TEST_F(AmbientControllerTest, HideCursor) { +TEST_P(AmbientControllerTestForAnyTheme, HideCursor) { auto* cursor_manager = Shell::Get()->cursor_manager(); LockScreen(); @@ -858,7 +900,7 @@ EXPECT_FALSE(ambient_controller()->IsShown()); } -TEST_F(AmbientControllerTest, ShowsOnMultipleDisplays) { +TEST_P(AmbientControllerTestForAnyTheme, ShowsOnMultipleDisplays) { UpdateDisplay("800x600,800x600"); FastForwardTiny(); @@ -874,7 +916,7 @@ ctrl->ambient_widget_for_testing()->IsVisible()); } -TEST_F(AmbientControllerTest, RespondsToDisplayAdded) { +TEST_P(AmbientControllerTestForAnyTheme, RespondsToDisplayAdded) { // UpdateDisplay triggers a rogue MouseEvent that cancels Ambient mode when // testing with Xvfb. A corresponding MouseEvent is not fired on a real device // when an external display is added. Ignore this MouseEvent for testing. @@ -906,7 +948,7 @@ old_should_ignore_events); } -TEST_F(AmbientControllerTest, HandlesDisplayRemoved) { +TEST_P(AmbientControllerTestForAnyTheme, HandlesDisplayRemoved) { UpdateDisplay("800x600,800x600"); FastForwardTiny(); @@ -927,7 +969,7 @@ EXPECT_TRUE(WidgetsVisible()); } -TEST_F(AmbientControllerTest, ClosesAmbientBeforeSuspend) { +TEST_P(AmbientControllerTestForAnyTheme, ClosesAmbientBeforeSuspend) { LockScreen(); FastForwardToLockScreenTimeout(); @@ -942,7 +984,7 @@ EXPECT_FALSE(ambient_controller()->IsShown()); } -TEST_F(AmbientControllerTest, RestartsAmbientAfterSuspend) { +TEST_P(AmbientControllerTestForAnyTheme, RestartsAmbientAfterSuspend) { LockScreen(); FastForwardToLockScreenTimeout(); @@ -964,7 +1006,7 @@ EXPECT_TRUE(ambient_controller()->IsShown()); } -TEST_F(AmbientControllerTest, ObservesPrefsWhenAmbientEnabled) { +TEST_P(AmbientControllerTestForAnyTheme, ObservesPrefsWhenAmbientEnabled) { SetAmbientModeEnabled(false); // This pref is always observed. @@ -986,7 +1028,7 @@ EXPECT_TRUE(IsPrefObserved(pref_name)); } -TEST_F(AmbientControllerTest, BindsObserversWhenAmbientEnabled) { +TEST_P(AmbientControllerTestForAnyTheme, BindsObserversWhenAmbientEnabled) { auto* ctrl = ambient_controller(); SetAmbientModeEnabled(false); @@ -1005,7 +1047,8 @@ EXPECT_TRUE(AreSessionSpecificObserversBound()); } -TEST_F(AmbientControllerTest, SwitchActiveUsersDoesNotDoubleBindObservers) { +TEST_P(AmbientControllerTestForAnyTheme, + SwitchActiveUsersDoesNotDoubleBindObservers) { ClearLogin(); SimulateUserLogin(kUser1); SetAmbientModeEnabled(true); @@ -1030,7 +1073,7 @@ session->SwitchActiveUser(AccountId::FromUserEmail(kUser2)); } -TEST_F(AmbientControllerTest, BindsObserversWhenAmbientOn) { +TEST_P(AmbientControllerTestForAnyTheme, BindsObserversWhenAmbientOn) { auto* ctrl = ambient_controller(); LockScreen(); @@ -1051,7 +1094,8 @@ EXPECT_FALSE(ctrl->power_status_observer_.IsObserving()); } -TEST_F(AmbientControllerTest, ShowDismissAmbientScreenUponAssistantQuery) { +TEST_P(AmbientControllerTestForAnyTheme, + ShowDismissAmbientScreenUponAssistantQuery) { // Without user interaction, should show ambient mode. ShowAmbientScreen(); EXPECT_TRUE(ambient_controller()->IsShown()); @@ -1067,4 +1111,54 @@ EXPECT_FALSE(ambient_controller()->IsShown()); } +// TODO(esum): Fully enable this test once: +// * The |include_ash_ambient_animation_resources| GN arg is true by default +// (the resources' size is currently being reduced to fit in the image). +// * The ash ambient resources are publishable (they are currently WIP). +// This test will crash/fail without these resources available. +#if BUILDFLAG(HAS_ASH_AMBIENT_ANIMATION_RESOURCES) +#define MAYBE_RendersCorrectView RendersCorrectView +#else +#define MAYBE_RendersCorrectView DISABLED_RendersCorrectView +#endif // BUILDFLAG(HAS_ASH_AMBIENT_ANIMATION_RESOURCES) +TEST_F(AmbientControllerTest, MAYBE_RendersCorrectView) { + SetAmbientAnimationTheme(AmbientAnimationTheme::kSlideshow); + + LockScreen(); + FastForwardToLockScreenTimeout(); + FastForwardTiny(); + + ASSERT_TRUE(GetContainerView()); + EXPECT_TRUE( + GetContainerView()->GetViewByID(AmbientViewID::kAmbientPhotoView)); + EXPECT_FALSE( + GetContainerView()->GetViewByID(AmbientViewID::kAmbientAnimationView)); + + UnlockScreen(); + SetAmbientAnimationTheme(AmbientAnimationTheme::kFeelTheBreeze); + + LockScreen(); + FastForwardToLockScreenTimeout(); + FastForwardTiny(); + + ASSERT_TRUE(GetContainerView()); + EXPECT_FALSE( + GetContainerView()->GetViewByID(AmbientViewID::kAmbientPhotoView)); + EXPECT_TRUE( + GetContainerView()->GetViewByID(AmbientViewID::kAmbientAnimationView)); + + UnlockScreen(); + SetAmbientAnimationTheme(AmbientAnimationTheme::kSlideshow); + + LockScreen(); + FastForwardToLockScreenTimeout(); + FastForwardTiny(); + + ASSERT_TRUE(GetContainerView()); + EXPECT_TRUE( + GetContainerView()->GetViewByID(AmbientViewID::kAmbientPhotoView)); + EXPECT_FALSE( + GetContainerView()->GetViewByID(AmbientViewID::kAmbientAnimationView)); +} + } // namespace ash
diff --git a/ash/ambient/ambient_photo_controller.cc b/ash/ambient/ambient_photo_controller.cc index 40aee97fa..b1c295a 100644 --- a/ash/ambient/ambient_photo_controller.cc +++ b/ash/ambient/ambient_photo_controller.cc
@@ -143,7 +143,6 @@ access_token_controller)), task_runner_( base::ThreadPool::CreateSequencedTaskRunner(GetTaskTraits())) { - DCHECK(!ambient_backend_model_.photo_config().refresh_topic_markers.empty()); ambient_backend_model_observation_.Observe(&ambient_backend_model_); ScheduleFetchBackupImages(); } @@ -190,6 +189,10 @@ weak_factory_.InvalidateWeakPtrs(); } +bool AmbientPhotoController::IsScreenUpdateActive() const { + return state_ != State::kInactive; +} + void AmbientPhotoController::OnMarkerHit(AmbientPhotoConfig::Marker marker) { if (!ambient_backend_model_.photo_config().refresh_topic_markers.contains( marker)) {
diff --git a/ash/ambient/ambient_photo_controller.h b/ash/ambient/ambient_photo_controller.h index 7a79d3e6..e3368ca 100644 --- a/ash/ambient/ambient_photo_controller.h +++ b/ash/ambient/ambient_photo_controller.h
@@ -126,6 +126,7 @@ // have different refreshing intervals. void StartScreenUpdate(); void StopScreenUpdate(); + bool IsScreenUpdateActive() const; AmbientBackendModel* ambient_backend_model() { return &ambient_backend_model_;
diff --git a/ash/ambient/ambient_photo_controller_unittest.cc b/ash/ambient/ambient_photo_controller_unittest.cc index 7eef69c9..24f37f0 100644 --- a/ash/ambient/ambient_photo_controller_unittest.cc +++ b/ash/ambient/ambient_photo_controller_unittest.cc
@@ -11,7 +11,9 @@ #include "ash/ambient/ambient_controller.h" #include "ash/ambient/model/ambient_backend_model.h" #include "ash/ambient/model/ambient_backend_model_observer.h" +#include "ash/ambient/model/ambient_photo_config.h" #include "ash/ambient/test/ambient_ash_test_base.h" +#include "ash/ambient/test/ambient_test_util.h" #include "ash/public/cpp/ambient/ambient_backend_controller.h" #include "ash/public/cpp/ambient/fake_ambient_backend_controller_impl.h" #include "ash/public/cpp/ambient/proto/photo_cache_entry.pb.h" @@ -38,6 +40,12 @@ namespace ash { +using ::testing::AnyOf; +using ::testing::Contains; +using ::testing::Eq; +using ::testing::Not; +using ::testing::SizeIs; + namespace { class MockAmbientBackendModelObserver : public AmbientBackendModelObserver { public: @@ -49,6 +57,11 @@ MOCK_METHOD(void, OnImagesReady, (), (override)); }; +MATCHER_P(BackedBySameImageAs, photo_with_details, "") { + return !arg.photo.isNull() && !photo_with_details.photo.isNull() && + arg.photo.BackedBySameObjectAs(photo_with_details.photo); +} + } // namespace class AmbientPhotoControllerTest : public AmbientAshTestBase { @@ -145,6 +158,17 @@ } }; +class AmbientPhotoControllerAnimationTest : public AmbientPhotoControllerTest { + protected: + static constexpr int kNumDynamicAssets = 4; + + void SetUp() override { + AmbientAshTestBase::SetUp(); + photo_controller()->ambient_backend_model()->SetPhotoConfig( + GenerateAnimationConfigWithNAssets(kNumDynamicAssets)); + } +}; + // Test that topics are downloaded when starting screen update. TEST_F(AmbientPhotoControllerTest, ShouldStartToDownloadTopics) { auto topics = photo_controller()->ambient_backend_model()->topics(); @@ -604,4 +628,115 @@ EXPECT_LT(info.temp_f, 0); } +TEST_F(AmbientPhotoControllerTest, IsScreenUpdateActive) { + ASSERT_FALSE(photo_controller()->IsScreenUpdateActive()); + photo_controller()->StartScreenUpdate(); + EXPECT_TRUE(photo_controller()->IsScreenUpdateActive()); + photo_controller()->StopScreenUpdate(); + EXPECT_FALSE(photo_controller()->IsScreenUpdateActive()); +} + +TEST_F(AmbientPhotoControllerAnimationTest, AnimationPreparesInitialTopicSet) { + photo_controller()->StartScreenUpdate(); + RunUntilImagesReady(); + EXPECT_THAT(photo_controller()->ambient_backend_model()->all_decoded_topics(), + SizeIs(kNumDynamicAssets)); +} + +TEST_F(AmbientPhotoControllerAnimationTest, + AnimationRefreshesTopicSetEachCycle) { + photo_controller()->StartScreenUpdate(); + RunUntilImagesReady(); + base::circular_deque<PhotoWithDetails> old_photos = + photo_controller()->ambient_backend_model()->all_decoded_topics(); + + // Start rendering animation. + photo_controller()->OnMarkerHit( + AmbientPhotoConfig::Marker::kUiStartRendering); + // Simulate cycle ending. This should trigger an image refresh. + photo_controller()->OnMarkerHit(AmbientPhotoConfig::Marker::kUiCycleEnded); + RunUntilNextTopicsAdded(kNumDynamicAssets); + base::circular_deque<PhotoWithDetails> new_photos = + photo_controller()->ambient_backend_model()->all_decoded_topics(); + EXPECT_THAT(new_photos, SizeIs(kNumDynamicAssets)); + ASSERT_THAT(old_photos.size(), Eq(new_photos.size())); + + // Verify that the new set actually has different photos from the initial set. + EXPECT_THAT(new_photos, + Not(AnyOf(Contains(BackedBySameImageAs(old_photos[0])), + Contains(BackedBySameImageAs(old_photos[1])), + Contains(BackedBySameImageAs(old_photos[2])), + Contains(BackedBySameImageAs(old_photos[3]))))); + old_photos = new_photos; + + // One more cycle. + photo_controller()->OnMarkerHit(AmbientPhotoConfig::Marker::kUiCycleEnded); + RunUntilNextTopicsAdded(kNumDynamicAssets); + new_photos = + photo_controller()->ambient_backend_model()->all_decoded_topics(); + EXPECT_THAT(new_photos, SizeIs(kNumDynamicAssets)); + ASSERT_THAT(old_photos.size(), Eq(new_photos.size())); + EXPECT_THAT(new_photos, + Not(AnyOf(Contains(BackedBySameImageAs(old_photos[0])), + Contains(BackedBySameImageAs(old_photos[1])), + Contains(BackedBySameImageAs(old_photos[2])), + Contains(BackedBySameImageAs(old_photos[3]))))); +} + +TEST_F(AmbientPhotoControllerAnimationTest, + StopsRefreshingImagesAfterTargetAmountBuffered) { + photo_controller()->StartScreenUpdate(); + RunUntilImagesReady(); + + photo_controller()->OnMarkerHit( + AmbientPhotoConfig::Marker::kUiStartRendering); + photo_controller()->OnMarkerHit(AmbientPhotoConfig::Marker::kUiCycleEnded); + RunUntilNextTopicsAdded(kNumDynamicAssets); + + // Fast forward time to make sure no more images are prepared after + // |kNumDynamicAssets| has been added. + task_environment()->FastForwardBy(base::Minutes(1)); + EXPECT_THAT(photo_controller()->ambient_backend_model()->all_decoded_topics(), + SizeIs(kNumDynamicAssets)); +} + +TEST_F(AmbientPhotoControllerAnimationTest, + AnimationRefreshesAfterIncompleteTopicSet) { + photo_controller()->StartScreenUpdate(); + RunUntilImagesReady(); + base::circular_deque<PhotoWithDetails> old_photos = + photo_controller()->ambient_backend_model()->all_decoded_topics(); + + photo_controller()->OnMarkerHit( + AmbientPhotoConfig::Marker::kUiStartRendering); + photo_controller()->OnMarkerHit(AmbientPhotoConfig::Marker::kUiCycleEnded); + RunUntilNextTopicsAdded(kNumDynamicAssets / 2); + base::circular_deque<PhotoWithDetails> new_photos = + photo_controller()->ambient_backend_model()->all_decoded_topics(); + EXPECT_THAT(new_photos, SizeIs(kNumDynamicAssets)); + ASSERT_THAT(old_photos.size(), Eq(new_photos.size())); + + EXPECT_THAT(new_photos[0], BackedBySameImageAs(old_photos[2])); + EXPECT_THAT(new_photos[1], BackedBySameImageAs(old_photos[3])); + EXPECT_THAT(old_photos, Not(Contains(BackedBySameImageAs(new_photos[2])))); + EXPECT_THAT(old_photos, Not(Contains(BackedBySameImageAs(new_photos[3])))); + old_photos = new_photos; + + // Cycle ends when only half of target amount refreshed. + photo_controller()->OnMarkerHit(AmbientPhotoConfig::Marker::kUiCycleEnded); + RunUntilNextTopicsAdded(kNumDynamicAssets); + // Fast forward time to make sure no more images are prepared after + // |kNumDynamicAssets| has been added. + task_environment()->FastForwardBy(base::Minutes(1)); + new_photos = + photo_controller()->ambient_backend_model()->all_decoded_topics(); + EXPECT_THAT(new_photos, SizeIs(kNumDynamicAssets)); + ASSERT_THAT(old_photos.size(), Eq(new_photos.size())); + EXPECT_THAT(new_photos, + Not(AnyOf(Contains(BackedBySameImageAs(old_photos[0])), + Contains(BackedBySameImageAs(old_photos[1])), + Contains(BackedBySameImageAs(old_photos[2])), + Contains(BackedBySameImageAs(old_photos[3]))))); +} + } // namespace ash
diff --git a/ash/ambient/model/ambient_backend_model.cc b/ash/ambient/model/ambient_backend_model.cc index b13bf75..799fdeae 100644 --- a/ash/ambient/model/ambient_backend_model.cc +++ b/ash/ambient/model/ambient_backend_model.cc
@@ -130,9 +130,8 @@ } // AmbientBackendModel--------------------------------------------------------- -AmbientBackendModel::AmbientBackendModel(AmbientPhotoConfig photo_config) - : photo_config_(std::move(photo_config)) { - DCHECK_GT(photo_config_.GetNumDecodedTopicsToBuffer(), 0u); +AmbientBackendModel::AmbientBackendModel(AmbientPhotoConfig photo_config) { + SetPhotoConfig(std::move(photo_config)); } AmbientBackendModel::~AmbientBackendModel() = default; @@ -235,6 +234,13 @@ return AmbientUiModel::Get()->photo_refresh_interval(); } +void AmbientBackendModel::SetPhotoConfig(AmbientPhotoConfig photo_config) { + photo_config_ = std::move(photo_config); + DCHECK_GT(photo_config_.GetNumDecodedTopicsToBuffer(), 0u); + DCHECK(!photo_config_.refresh_topic_markers.empty()); + Clear(); +} + void AmbientBackendModel::Clear() { topics_.clear(); all_decoded_topics_.clear();
diff --git a/ash/ambient/model/ambient_backend_model.h b/ash/ambient/model/ambient_backend_model.h index 89a3d3e..d57c0d5 100644 --- a/ash/ambient/model/ambient_backend_model.h +++ b/ash/ambient/model/ambient_backend_model.h
@@ -86,6 +86,10 @@ // Clear local storage. void Clear(); + // Sets the new AmbientPhotoConfig to use. This automatically |Clear()|s the + // model of any existing topics. + void SetPhotoConfig(AmbientPhotoConfig photo_config); + // Returns all available decoded topics. The number of decoded topics in the // output will always be <= |AmbientPhotoConfig.num_decoded_topics_to_buffer|. // @@ -139,7 +143,7 @@ void NotifyImagesReady(); void NotifyWeatherInfoUpdated(); - const AmbientPhotoConfig photo_config_; + AmbientPhotoConfig photo_config_; std::vector<AmbientModeTopic> topics_; // All available decoded topics. The size of the ring buffer is capped
diff --git a/ash/ambient/model/ambient_backend_model_unittest.cc b/ash/ambient/model/ambient_backend_model_unittest.cc index 7ea821b9..0834301 100644 --- a/ash/ambient/model/ambient_backend_model_unittest.cc +++ b/ash/ambient/model/ambient_backend_model_unittest.cc
@@ -7,8 +7,8 @@ #include <memory> #include <string> -#include "ash/ambient/model/ambient_animation_photo_config.h" #include "ash/ambient/model/ambient_backend_model_observer.h" +#include "ash/ambient/model/ambient_photo_config.h" #include "ash/ambient/model/ambient_slideshow_photo_config.h" #include "ash/ambient/test/ambient_test_util.h" #include "ash/public/cpp/ambient/ambient_prefs.h" @@ -19,7 +19,6 @@ #include "ash/test/ash_test_base.h" #include "base/check.h" #include "base/scoped_observation.h" -#include "cc/paint/skottie_resource_metadata.h" #include "testing/gmock/include/gmock/gmock.h" #include "ui/gfx/image/image_skia.h" #include "ui/gfx/image/image_unittest_util.h" @@ -184,15 +183,8 @@ void SetUp() override { AshTestBase::SetUp(); - cc::SkottieResourceMetadataMap resource_metadata; - CHECK(resource_metadata.RegisterAsset( - "test-resource-path", "test-resource-name", - GenerateTestLottieDynamicAssetId(/*unique_id=*/0))); - CHECK(resource_metadata.RegisterAsset( - "test-resource-path", "test-resource-name", - GenerateTestLottieDynamicAssetId(/*unique_id=*/1))); ambient_backend_model_ = std::make_unique<AmbientBackendModel>( - CreateAmbientAnimationPhotoConfig(resource_metadata)); + GenerateAnimationConfigWithNAssets(kNumAssetsInAnimation)); } }; @@ -501,6 +493,31 @@ EXPECT_EQ(fetched_topics()[1 - index].related_details, ""); } +TEST_F(AmbientBackendModelTest, SwitchesBetweenConfigs) { + // Initially in slideshow config (requires 2 images to be "ready"). + AddNTestImages(1); + AddNTestImages(1); + ASSERT_TRUE(ambient_backend_model_->ImagesReady()); + + // Switch to animation config that requires 4 photos to be "ready" instead of + // 2. + ambient_backend_model_->SetPhotoConfig(GenerateAnimationConfigWithNAssets(4)); + ASSERT_FALSE(ambient_backend_model_->ImagesReady()); + AddNTestImages(1); + AddNTestImages(1); + ASSERT_FALSE(ambient_backend_model_->ImagesReady()); + AddNTestImages(1); + AddNTestImages(1); + EXPECT_TRUE(ambient_backend_model_->ImagesReady()); + + // Switch back to slideshow again. + ambient_backend_model_->SetPhotoConfig(CreateAmbientSlideshowPhotoConfig()); + ASSERT_FALSE(ambient_backend_model_->ImagesReady()); + AddNTestImages(1); + AddNTestImages(1); + EXPECT_TRUE(ambient_backend_model_->ImagesReady()); +} + TEST_F(AmbientBackendModelTestWithAnimationConfig, ImagesReady) { EXPECT_FALSE(ambient_backend_model_->ImagesReady()); AddNTestImages(1);
diff --git a/ash/ambient/test/ambient_ash_test_base.cc b/ash/ambient/test/ambient_ash_test_base.cc index fb87eb52..bf45459 100644 --- a/ash/ambient/test/ambient_ash_test_base.cc +++ b/ash/ambient/test/ambient_ash_test_base.cc
@@ -196,6 +196,11 @@ } } +void AmbientAshTestBase::SetAmbientAnimationTheme(AmbientAnimationTheme theme) { + Shell::Get()->session_controller()->GetActivePrefService()->SetInteger( + ambient::prefs::kAmbientAnimationTheme, static_cast<int>(theme)); +} + void AmbientAshTestBase::ShowAmbientScreen() { // The widget will be destroyed in |AshTestBase::TearDown()|. ambient_controller()->ShowUi();
diff --git a/ash/ambient/test/ambient_ash_test_base.h b/ash/ambient/test/ambient_ash_test_base.h index 9764894..acf0227 100644 --- a/ash/ambient/test/ambient_ash_test_base.h +++ b/ash/ambient/test/ambient_ash_test_base.h
@@ -13,6 +13,7 @@ #include "ash/ambient/ambient_controller.h" #include "ash/ambient/test/test_ambient_client.h" #include "ash/ambient/ui/ambient_background_image_view.h" +#include "ash/public/cpp/ambient/ambient_animation_theme.h" #include "ash/public/cpp/ambient/proto/photo_cache_entry.pb.h" #include "ash/public/cpp/test/test_image_downloader.h" #include "ash/test/ash_test_base.h" @@ -45,6 +46,13 @@ // Enables/disables ambient mode for the currently active user session. void SetAmbientModeEnabled(bool enabled); + // Sets the AmbientAnimationTheme to use when ShowAmbientScreen() is called. + // To reflect real world usage, the incoming |theme| does not take effect + // immediately if the test is currently displaying the ambient screen. In that + // case, the ambient screen must be closed, and the new |theme| will take + // effect with the next call to ShowAmbientScreen(). + void SetAmbientAnimationTheme(AmbientAnimationTheme theme); + // Creates ambient screen in its own widget. void ShowAmbientScreen();
diff --git a/ash/ambient/test/ambient_test_util.cc b/ash/ambient/test/ambient_test_util.cc index 0be95db..9a4962706 100644 --- a/ash/ambient/test/ambient_test_util.cc +++ b/ash/ambient/test/ambient_test_util.cc
@@ -5,8 +5,11 @@ #include "ash/ambient/test/ambient_test_util.h" #include "ash/ambient/ambient_constants.h" +#include "ash/ambient/model/ambient_animation_photo_config.h" +#include "base/check.h" #include "base/strings/strcat.h" #include "base/strings/string_number_conversions.h" +#include "cc/paint/skottie_resource_metadata.h" namespace ash { @@ -15,4 +18,14 @@ {kLottieDynamicAssetIdPrefix, base::NumberToString(unique_id)}); } +AmbientPhotoConfig GenerateAnimationConfigWithNAssets(int num_assets) { + cc::SkottieResourceMetadataMap resource_metadata; + for (int i = 0; i < num_assets; ++i) { + CHECK(resource_metadata.RegisterAsset( + "test-resource-path", "test-resource-name", + GenerateTestLottieDynamicAssetId(/*unique_id=*/i))); + } + return CreateAmbientAnimationPhotoConfig(resource_metadata); +} + } // namespace ash
diff --git a/ash/ambient/test/ambient_test_util.h b/ash/ambient/test/ambient_test_util.h index 7438199..efc38ad 100644 --- a/ash/ambient/test/ambient_test_util.h +++ b/ash/ambient/test/ambient_test_util.h
@@ -9,10 +9,16 @@ namespace ash { +struct AmbientPhotoConfig; + // Generates a dynamic asset id (see IsDynamicLottieAsset() in ambient_util.h) // that incorporates the |unique_id| in it. std::string GenerateTestLottieDynamicAssetId(int unique_id); +// Returns an AmbientPhotoConfig for a lottie animation with the number of +// assets specified by |num_assets|, +AmbientPhotoConfig GenerateAnimationConfigWithNAssets(int num_assets); + } // namespace ash #endif // ASH_AMBIENT_TEST_AMBIENT_TEST_UTIL_H_
diff --git a/ash/ambient/ui/ambient_animation_view.cc b/ash/ambient/ui/ambient_animation_view.cc index 1cda0cec..d04438a 100644 --- a/ash/ambient/ui/ambient_animation_view.cc +++ b/ash/ambient/ui/ambient_animation_view.cc
@@ -12,6 +12,7 @@ #include "ash/ambient/model/ambient_photo_config.h" #include "ash/ambient/resources/ambient_animation_static_resources.h" #include "ash/ambient/ui/ambient_view_delegate.h" +#include "ash/ambient/ui/ambient_view_ids.h" #include "base/check.h" #include "base/containers/span.h" #include "base/logging.h" @@ -32,6 +33,7 @@ : event_handler_(event_handler), static_resources_(std::move(static_resources)), animation_photo_provider_(static_resources_.get(), model) { + SetID(AmbientViewID::kAmbientAnimationView); Init(); }
diff --git a/ash/ambient/ui/ambient_container_view.cc b/ash/ambient/ui/ambient_container_view.cc index 70c97d40..cd1aaae1 100644 --- a/ash/ambient/ui/ambient_container_view.cc +++ b/ash/ambient/ui/ambient_container_view.cc
@@ -7,11 +7,14 @@ #include <memory> #include <utility> +#include "ash/ambient/resources/ambient_animation_static_resources.h" +#include "ash/ambient/ui/ambient_animation_view.h" #include "ash/ambient/ui/ambient_view_delegate.h" #include "ash/ambient/ui/ambient_view_ids.h" #include "ash/ambient/ui/photo_view.h" #include "ash/ambient/util/ambient_util.h" #include "ash/public/cpp/shell_window_ids.h" +#include "base/check.h" #include "ui/aura/window.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/views/accessibility/accessibility_paint_checks.h" @@ -22,28 +25,33 @@ namespace ash { -AmbientContainerView::AmbientContainerView(AmbientViewDelegate* delegate) - : delegate_(delegate) { +AmbientContainerView::AmbientContainerView( + AmbientViewDelegate* delegate, + std::unique_ptr<AmbientAnimationStaticResources> + animation_static_resources) { + DCHECK(delegate); // TODO(crbug.com/1218186): Remove this, this is in place temporarily to be // able to submit accessibility checks, but this focusable View needs to // add a name so that the screen reader knows what to announce. SetProperty(views::kSkipAccessibilityPaintChecks, true); SetID(AmbientViewID::kAmbientContainerView); - Init(); -} - -AmbientContainerView::~AmbientContainerView() = default; - -void AmbientContainerView::Init() { // TODO(b/139954108): Choose a better dark mode theme color. SetBackground(views::CreateSolidBackground(SK_ColorBLACK)); // Updates focus behavior to receive key press events. SetFocusBehavior(views::View::FocusBehavior::ALWAYS); SetLayoutManager(std::make_unique<views::FillLayout>()); - - photo_view_ = AddChildView(std::make_unique<PhotoView>(delegate_)); + if (animation_static_resources) { + AddChildView(std::make_unique<AmbientAnimationView>( + delegate->GetAmbientBackendModel(), + delegate->GetAmbientViewEventHandler(), + std::move(animation_static_resources))); + } else { + AddChildView(std::make_unique<PhotoView>(delegate)); + } } +AmbientContainerView::~AmbientContainerView() = default; + BEGIN_METADATA(AmbientContainerView, views::View) END_METADATA
diff --git a/ash/ambient/ui/ambient_container_view.h b/ash/ambient/ui/ambient_container_view.h index 00488e9..b2d0935 100644 --- a/ash/ambient/ui/ambient_container_view.h +++ b/ash/ambient/ui/ambient_container_view.h
@@ -10,9 +10,8 @@ namespace ash { -class AmbientAssistantContainerView; +class AmbientAnimationStaticResources; class AmbientViewDelegate; -class PhotoView; // Container view to display all Ambient Mode related views, i.e. photo frame, // weather info. @@ -20,19 +19,16 @@ public: METADATA_HEADER(AmbientContainerView); - explicit AmbientContainerView(AmbientViewDelegate* delegate); + // |animation_static_resources| contains the Lottie animation file to render + // along with its accompanying static image assets. If null, that means the + // slideshow UI should be rendered instead. + AmbientContainerView(AmbientViewDelegate* delegate, + std::unique_ptr<AmbientAnimationStaticResources> + animation_static_resources); ~AmbientContainerView() override; private: friend class AmbientAshTestBase; - - void Init(); - - AmbientViewDelegate* delegate_ = nullptr; - - // Owned by view hierarchy. - PhotoView* photo_view_ = nullptr; - AmbientAssistantContainerView* ambient_assistant_container_view_ = nullptr; }; } // namespace ash
diff --git a/ash/ambient/ui/ambient_view_ids.h b/ash/ambient/ui/ambient_view_ids.h index 1bfa98a5..a91d989 100644 --- a/ash/ambient/ui/ambient_view_ids.h +++ b/ash/ambient/ui/ambient_view_ids.h
@@ -20,6 +20,7 @@ kAmbientMediaStringView, kAmbientInfoView, kAmbientShieldView, + kAmbientAnimationView, }; } // namespace ash
diff --git a/ash/app_list/model/search/search_model.cc b/ash/app_list/model/search/search_model.cc index 58886c0..6ac5916f 100644 --- a/ash/app_list/model/search/search_model.cc +++ b/ash/app_list/model/search/search_model.cc
@@ -83,6 +83,10 @@ // Update and use the old result if it exists. std::unique_ptr<SearchResult> ui_result = std::move(ui_result_it->second); ui_result->SetMetadata(new_result->TakeMetadata()); + // TODO(crbug/1216097): Setup TextVector metadata if none is sent from the + // backend. TextVector metadata will eventually be set for all results by + // the backend but we need to do this for now to update how all search + // result views are created. results_->Add(std::move(ui_result)); // Remove the item from the map so that it ends up only with unused
diff --git a/ash/app_list/model/search/search_result.h b/ash/app_list/model/search/search_result.h index 4c1146b8..e740913 100644 --- a/ash/app_list/model/search/search_result.h +++ b/ash/app_list/model/search/search_result.h
@@ -43,6 +43,8 @@ using DisplayIndex = ash::SearchResultDisplayIndex; using IconInfo = ash::SearchResultIconInfo; using IconShape = ash::SearchResultIconShape; + using TextItem = ash::SearchResultTextItem; + using TextVector = std::vector<TextItem>; SearchResult(); SearchResult(const SearchResult&) = delete; @@ -66,6 +68,13 @@ const Tags& title_tags() const { return metadata_->title_tags; } void set_title_tags(const Tags& tags) { metadata_->title_tags = tags; } + const TextVector& title_text_vector() const { + return metadata_->title_vector; + } + void set_title_text_vector(const TextVector& vector) { + metadata_->title_vector = vector; + } + const std::u16string& details() const { return metadata_->details; } void set_details(const std::u16string& details) { metadata_->details = details; @@ -74,9 +83,18 @@ const Tags& details_tags() const { return metadata_->details_tags; } void set_details_tags(const Tags& tags) { metadata_->details_tags = tags; } - const std::u16string& big_title() const { return metadata_->big_title; } - void set_big_title(const std::u16string& big_title) { - metadata_->big_title = big_title; + const TextVector& details_text_vector() const { + return metadata_->details_vector; + } + void set_details_text_vector(const TextVector& vector) { + metadata_->details_vector = vector; + } + + const TextVector& big_title_text_vector() const { + return metadata_->big_title_vector; + } + void set_big_title_text_vector(const TextVector& vector) { + metadata_->big_title_vector = vector; } const std::u16string& accessible_name() const {
diff --git a/ash/constants/ash_features.cc b/ash/constants/ash_features.cc index 6c05a8e..83ea0d7 100644 --- a/ash/constants/ash_features.cc +++ b/ash/constants/ash_features.cc
@@ -462,6 +462,10 @@ const base::Feature kEcheSWADebugMode{"EcheSWADebugMode", base::FEATURE_DISABLED_BY_DEFAULT}; +// Enables the Eche SWA to run in the background. +const base::Feature kEcheSWAInBackground{"EcheSWAInBackground", + base::FEATURE_DISABLED_BY_DEFAULT}; + // Enables background blur for the app list, shelf, unified system tray, // autoclick menu, etc. Also enables the AppsGridView mask layer, slower devices // may have choppier app list animations while in this mode. crbug.com/765292. @@ -1507,6 +1511,10 @@ return base::FeatureList::IsEnabled(kEcheSWADebugMode); } +bool IsEcheSWAInBackgroundEnabled() { + return base::FeatureList::IsEnabled(kEcheSWAInBackground); +} + bool IsESimPolicyEnabled() { return base::FeatureList::IsEnabled(kESimPolicy); }
diff --git a/ash/constants/ash_features.h b/ash/constants/ash_features.h index eae593c..9c4e9159 100644 --- a/ash/constants/ash_features.h +++ b/ash/constants/ash_features.h
@@ -181,6 +181,7 @@ COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kEcheSWA; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kEcheSWAResizing; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kEcheSWADebugMode; +COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kEcheSWAInBackground; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kEnableBackgroundBlur; COMPONENT_EXPORT(ASH_CONSTANTS) @@ -550,6 +551,7 @@ COMPONENT_EXPORT(ASH_CONSTANTS) bool IsEcheSWAEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsEcheSWAResizingEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsEcheSWADebugModeEnabled(); +COMPONENT_EXPORT(ASH_CONSTANTS) bool IsEcheSWAInBackgroundEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsESimPolicyEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsExtendedOpenVpnSettingsEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsFamilyLinkOnSchoolDeviceEnabled();
diff --git a/ash/public/cpp/ambient/ambient_animation_theme.h b/ash/public/cpp/ambient/ambient_animation_theme.h index 80ad8de3..642feda05 100644 --- a/ash/public/cpp/ambient/ambient_animation_theme.h +++ b/ash/public/cpp/ambient/ambient_animation_theme.h
@@ -23,8 +23,12 @@ // It is currently implemented entirely as a native UI view. kSlideshow = 0, kFeelTheBreeze = 1, + kMaxValue = kFeelTheBreeze, }; +static constexpr AmbientAnimationTheme kDefaultAmbientAnimationTheme = + AmbientAnimationTheme::kSlideshow; + ASH_PUBLIC_EXPORT std::ostream& operator<<(std::ostream& os, AmbientAnimationTheme theme);
diff --git a/ash/public/cpp/ambient/ambient_prefs.cc b/ash/public/cpp/ambient/ambient_prefs.cc index ec6af23..e6eca30 100644 --- a/ash/public/cpp/ambient/ambient_prefs.cc +++ b/ash/public/cpp/ambient/ambient_prefs.cc
@@ -10,6 +10,8 @@ namespace ambient { namespace prefs { +constexpr char kAmbientAnimationTheme[] = "ash.ambient.animation_theme"; + constexpr char kAmbientBackdropClientId[] = "ash.ambient.backdrop.client.id"; constexpr char kAmbientModeEnabled[] = "settings.ambient_mode.enabled";
diff --git a/ash/public/cpp/ambient/ambient_prefs.h b/ash/public/cpp/ambient/ambient_prefs.h index e41f703..2d63b93 100644 --- a/ash/public/cpp/ambient/ambient_prefs.h +++ b/ash/public/cpp/ambient/ambient_prefs.h
@@ -11,6 +11,10 @@ namespace ambient { namespace prefs { +// Integer pref corresponding to the ambient mode theme that the user has +// selected (see AmbientAnimationTheme enum). +ASH_PUBLIC_EXPORT extern const char kAmbientAnimationTheme[]; + // A GUID for backdrop client. ASH_PUBLIC_EXPORT extern const char kAmbientBackdropClientId[];
diff --git a/ash/public/cpp/app_list/app_list_features.cc b/ash/public/cpp/app_list/app_list_features.cc index 47a63cef..fae7dbf 100644 --- a/ash/public/cpp/app_list/app_list_features.cc +++ b/ash/public/cpp/app_list/app_list_features.cc
@@ -15,8 +15,6 @@ base::FEATURE_ENABLED_BY_DEFAULT}; const base::Feature kEnableZeroStateAppsRanker{ "EnableZeroStateAppsRanker", base::FEATURE_ENABLED_BY_DEFAULT}; -const base::Feature kEnableQueryBasedMixedTypesRanker{ - "EnableQueryBasedMixedTypesRanker", base::FEATURE_DISABLED_BY_DEFAULT}; const base::Feature kEnableZeroStateMixedTypesRanker{ "EnableZeroStateMixedTypesRanker", base::FEATURE_ENABLED_BY_DEFAULT}; const base::Feature kEnableAppReinstallZeroState{ @@ -50,10 +48,6 @@ return base::FeatureList::IsEnabled(kEnableZeroStateAppsRanker); } -bool IsQueryBasedMixedTypesRankerEnabled() { - return base::FeatureList::IsEnabled(kEnableQueryBasedMixedTypesRanker); -} - bool IsZeroStateMixedTypesRankerEnabled() { return base::FeatureList::IsEnabled(kEnableZeroStateMixedTypesRanker); }
diff --git a/ash/public/cpp/app_list/app_list_features.h b/ash/public/cpp/app_list/app_list_features.h index 39ed24a..9e9b433 100644 --- a/ash/public/cpp/app_list/app_list_features.h +++ b/ash/public/cpp/app_list/app_list_features.h
@@ -27,9 +27,6 @@ // AppSearchResultRankerPredictorName. ASH_PUBLIC_EXPORT extern const base::Feature kEnableZeroStateAppsRanker; -// Enable a model that ranks query based non-apps result. -ASH_PUBLIC_EXPORT extern const base::Feature kEnableQueryBasedMixedTypesRanker; - // Enable a model that ranks zero-state files and recent queries. ASH_PUBLIC_EXPORT extern const base::Feature kEnableZeroStateMixedTypesRanker;
diff --git a/ash/public/cpp/app_list/app_list_types.h b/ash/public/cpp/app_list/app_list_types.h index 3c57ba284..71521f7e 100644 --- a/ash/public/cpp/app_list/app_list_types.h +++ b/ash/public/cpp/app_list/app_list_types.h
@@ -472,15 +472,10 @@ // The title of the result, e.g. an app's name, an autocomplete query, etc. // TODO (crbug/1216097): deprecate title text. std::u16string title; - // The title of the result, e.g. an app's name, an autocomplete query, etc. - // Supports embedded icons. - std::vector<SearchResultTextItem> title_vector; // A detail string of this result. // TODO (crbug/1216097): deprecate details text. std::u16string details; - // The title of the result, e.g. an app's name, an autocomplete query, etc. - std::vector<SearchResultTextItem> details_vector; // How the title matches the query. See the SearchResultTag section for more // details. @@ -492,8 +487,15 @@ // TODO (crbug/1216097): deprecate details_tags. std::vector<SearchResultTag> details_tags; + // The title of the result, e.g. an app's name, an autocomplete query, etc. + // Supports embedded icons. + std::vector<SearchResultTextItem> title_vector; + + // The details of the result, supports embedded icons. + std::vector<SearchResultTextItem> details_vector; + // Big title text to be displayed prominently on an answer card. - std::u16string big_title; + std::vector<SearchResultTextItem> big_title_vector; // Text to be announced by a screen reader app. std::u16string accessible_name;
diff --git a/ash/system/hps/hps_configuration.cc b/ash/system/hps/hps_configuration.cc index ed2c418d..8e263707 100644 --- a/ash/system/hps/hps_configuration.cc +++ b/ash/system/hps/hps_configuration.cc
@@ -6,84 +6,178 @@ #include "ash/constants/ash_features.h" #include "base/metrics/field_trial_params.h" +#include "base/strings/string_number_conversions.h" #include "base/time/time.h" #include "chromeos/dbus/hps/hps_service.pb.h" #include "third_party/abseil-cpp/absl/types/optional.h" namespace ash { namespace { -// Used for indicating which oneof field to construct for `filter_config` inside -// FeatureConfig. We ensure that this is a valid configuration so that passing -// empty params induces a working config (as required for, e.g., a -// chrome:://flags entry). -constexpr int kFilterConfigCaseDefault = 1; - -// Default value for `FeatureConfig.consecutive_results_filter_config.count`. -// Default 1 means the change will be notified if the inference result is -// different from last one. -constexpr int kConsecutiveResultsFilterCountDefault = 1; - -// Default value for -// `FeatureConfig.consecutive_results_filter_config.threshold`. The inference -// result is a value from [-128, 128), we use 0 as a default threshold. -constexpr int kConsecutiveResultsFilterThresholdDefault = 0; - -// Default value for -// `FeatureConfig.consecutive_results_filter_config.initial_state`. -constexpr bool kConsecutiveResultsFilterIntialStateDefault = false; // Default quick dim delay to configure power_manager. -constexpr base::TimeDelta kQuickDimDelayDefault = base::Seconds(60); +constexpr base::TimeDelta kQuickDimDelayDefault = base::Seconds(45); // Default value determines whether send feedback to configure power_manager. constexpr int kShouldSendFeedbackIfUndimmed = false; -// This function constructs a FeatureConfig proto From Finch. +// Returns either the integer parameter with the given name, or nullopt if the +// parameter can't be found or parsed. +absl::optional<int> GetIntParam(const base::FieldTrialParams& params, + const std::string& name) { + const auto it = params.find(name); + if (it == params.end()) + return absl::nullopt; + + int result; + if (!base::StringToInt(it->second, &result)) + return absl::nullopt; + + return result; +} + +// Returns either the boolean parameter with the given name, or nullopt if the +// parameter can't be found or parsed. +absl::optional<bool> GetBoolParam(const base::FieldTrialParams& params, + const std::string& name) { + const auto it = params.find(name); + if (it == params.end()) + return absl::nullopt; + + if (it->second == "true") { + return true; + } else if (it->second == "false") { + return false; + } else { + return absl::nullopt; + } +} + +// The config to use when no parameters are specified. We need to ensure that +// that empty params induce a working config (as required for, e.g., a +// chrome:://flags entry). +hps::FeatureConfig GetDefaultFeatureConfig() { + hps::FeatureConfig config; + + auto& filter_config = *config.mutable_average_filter_config(); + filter_config.set_average_window_size(3); + filter_config.set_positive_score_threshold(40); + filter_config.set_negative_score_threshold(-40); + filter_config.set_default_uncertain_score(0); + + return config; +} + +// Returns true if the given set of keys is the entire set of keys in the params +// map. +bool ParamKeysAre(const base::FieldTrialParams& params, + const std::set<std::string> keys) { + for (const std::string& key : keys) { + if (params.find(key) == params.end()) + return false; + } + + return params.size() == keys.size(); +} + +// This function constructs a FeatureConfig proto from feature parameters.. // The FeatureConfig contains one type of FilterConfig that will be used for // enabling a Hps feature. -// If filter_config_case is set to 0 (by default), absl::nullopt will be -// returned; otherwise one type of FilterConfig will be returned with each -// field getting its value from the finch params with the same name. +// +// If empty parameters are provided, a reasonable default is used. +// // More details can be found at: // src/platform2/hps/daemon/filters/filter_factory.h -absl::optional<hps::FeatureConfig> ConstructHpsFilterConfigFromFinch( +absl::optional<hps::FeatureConfig> ConstructHpsFilterConfigFromFeatureParams( const base::Feature& feature) { - const int filter_config_case = base::GetFieldTrialParamByFeatureAsInt( - feature, "filter_config_case", kFilterConfigCaseDefault); - hps::FeatureConfig config; - switch (filter_config_case) { + // Load current params map for the feature. + base::FieldTrialParams params; + base::GetFieldTrialParamsByFeature(feature, ¶ms); + + // Valid default case. + if (params.empty()) + return GetDefaultFeatureConfig(); + + const absl::optional<int> filter_config_case = + GetIntParam(params, "filter_config_case"); + if (!filter_config_case.has_value()) + return absl::nullopt; + + switch (*filter_config_case) { case hps::FeatureConfig::kBasicFilterConfig: { + // There are no parameters for the basic filter. + if (!ParamKeysAre(params, {"filter_config_case"})) + return absl::nullopt; + + hps::FeatureConfig config; config.mutable_basic_filter_config(); return config; } - case hps::FeatureConfig::kConsecutiveResultsFilterConfig: { - auto& consecutive_results_filter_config = - *config.mutable_consecutive_results_filter_config(); - consecutive_results_filter_config.set_count( - base::GetFieldTrialParamByFeatureAsInt( - feature, "count", kConsecutiveResultsFilterCountDefault)); - consecutive_results_filter_config.set_threshold( - base::GetFieldTrialParamByFeatureAsInt( - feature, "threshold", kConsecutiveResultsFilterThresholdDefault)); - consecutive_results_filter_config.set_initial_state( - base::GetFieldTrialParamByFeatureAsBool( - feature, "initial_state", - kConsecutiveResultsFilterIntialStateDefault)); + case hps::FeatureConfig::kConsecutiveResultsFilterConfig: { + const absl::optional<int> count = GetIntParam(params, "count"); + const absl::optional<int> threshold = GetIntParam(params, "threshold"); + const absl::optional<bool> initial_state = + GetBoolParam(params, "initial_state"); + + if (!count.has_value() || !threshold.has_value() || + !initial_state.has_value() || + !ParamKeysAre(params, {"filter_config_case", "count", "threshold", + "initial_state"})) { + return absl::nullopt; + } + + hps::FeatureConfig config; + auto& filter_config = *config.mutable_consecutive_results_filter_config(); + filter_config.set_count(*count); + filter_config.set_threshold(*threshold); + filter_config.set_initial_state(*initial_state); return config; } + + case hps::FeatureConfig::kAverageFilterConfig: { + const absl::optional<int> average_window_size = + GetIntParam(params, "average_window_size"); + const absl::optional<int> positive_score_threshold = + GetIntParam(params, "positive_score_threshold"); + const absl::optional<int> negative_score_threshold = + GetIntParam(params, "negative_score_threshold"); + const absl::optional<int> default_uncertain_score = + GetIntParam(params, "default_uncertain_score"); + + if (!average_window_size.has_value() || + !positive_score_threshold.has_value() || + !negative_score_threshold.has_value() || + !default_uncertain_score.has_value() || + !ParamKeysAre(params, + {"filter_config_case", "average_window_size", + "positive_score_threshold", "negative_score_threshold", + "default_uncertain_score"})) { + return absl::nullopt; + } + + hps::FeatureConfig config; + auto& filter_config = *config.mutable_average_filter_config(); + filter_config.set_average_window_size(*average_window_size); + filter_config.set_positive_score_threshold(*positive_score_threshold); + filter_config.set_negative_score_threshold(*negative_score_threshold); + filter_config.set_default_uncertain_score(*default_uncertain_score); + return config; + } + default: return absl::nullopt; } } + } // namespace absl::optional<hps::FeatureConfig> GetEnableHpsSenseConfig() { - return ConstructHpsFilterConfigFromFinch(features::kQuickDim); + return ConstructHpsFilterConfigFromFeatureParams(features::kQuickDim); } absl::optional<hps::FeatureConfig> GetEnableHpsNotifyConfig() { - return ConstructHpsFilterConfigFromFinch(features::kSnoopingProtection); + return ConstructHpsFilterConfigFromFeatureParams( + features::kSnoopingProtection); } base::TimeDelta GetQuickDimDelay() {
diff --git a/ash/system/hps/hps_configuration_unittest.cc b/ash/system/hps/hps_configuration_unittest.cc index cbf892c9..30d37ee 100644 --- a/ash/system/hps/hps_configuration_unittest.cc +++ b/ash/system/hps/hps_configuration_unittest.cc
@@ -75,8 +75,59 @@ consecutive_results_filter_config.set_threshold(4); consecutive_results_filter_config.set_initial_state(false); - EXPECT_THAT(GetEnableHpsSenseConfig().value(), ProtoEquals(expected_config)); - EXPECT_THAT(GetEnableHpsNotifyConfig().value(), ProtoEquals(expected_config)); + const auto hps_sense_config = GetEnableHpsSenseConfig(); + ASSERT_TRUE(hps_sense_config.has_value()); + EXPECT_THAT(*hps_sense_config, ProtoEquals(expected_config)); + + const auto hps_notify_config = GetEnableHpsNotifyConfig(); + ASSERT_TRUE(hps_notify_config.has_value()); + EXPECT_THAT(*hps_notify_config, ProtoEquals(expected_config)); +} + +TEST(HpsFeatureConfigTest, VerifyAverageFilterConfig) { + const std::map<std::string, std::string> params = { + {"filter_config_case", "3"}, + {"average_window_size", "4"}, + {"positive_score_threshold", "5"}, + {"negative_score_threshold", "6"}, + {"default_uncertain_score", "7"}}; + base::test::ScopedFeatureList feature_list; + feature_list.InitWithFeaturesAndParameters( + {{features::kQuickDim, params}, {features::kSnoopingProtection, params}}, + {}); + + hps::FeatureConfig expected_config; + auto& average_filter_config = + *expected_config.mutable_average_filter_config(); + average_filter_config.set_average_window_size(4); + average_filter_config.set_positive_score_threshold(5); + average_filter_config.set_negative_score_threshold(6); + average_filter_config.set_default_uncertain_score(7); + + const auto hps_sense_config = GetEnableHpsSenseConfig(); + ASSERT_TRUE(hps_sense_config.has_value()); + EXPECT_THAT(*hps_sense_config, ProtoEquals(expected_config)); + + const auto hps_notify_config = GetEnableHpsNotifyConfig(); + ASSERT_TRUE(hps_notify_config.has_value()); + EXPECT_THAT(*hps_notify_config, ProtoEquals(expected_config)); +} + +TEST(HpsFeatureConfigTest, ExtraParamsInvalid) { + // Valid params for the consecutive results filter, plus one extraneous param. + const std::map<std::string, std::string> params = { + {"filter_config_case", "2"}, + {"count", "3"}, + {"threshold", "4"}, + {"initial_state", "false"}, + {"extra_param", ""}}; + base::test::ScopedFeatureList feature_list; + feature_list.InitWithFeaturesAndParameters( + {{features::kQuickDim, params}, {features::kSnoopingProtection, params}}, + {}); + + EXPECT_FALSE(GetEnableHpsSenseConfig().has_value()); + EXPECT_FALSE(GetEnableHpsNotifyConfig().has_value()); } } // namespace ash
diff --git a/ash/webui/camera_app_ui/resources/.eslintrc.js b/ash/webui/camera_app_ui/resources/.eslintrc.js index 57d789b..7e27a24 100644 --- a/ash/webui/camera_app_ui/resources/.eslintrc.js +++ b/ash/webui/camera_app_ui/resources/.eslintrc.js
@@ -465,6 +465,15 @@ argsIgnorePattern: '^_', }, ], + // Disallow parseInt (go/tsstyle#type-coercion) + 'no-restricted-syntax': [ + 'error', + { + 'selector': 'CallExpression[callee.name="parseInt"]', + 'message': 'parseInt are not allowed, use Number() instead. ' + + '(go/tsstyle#type-coercion)', + }, + ], }, }], };
diff --git a/ash/webui/camera_app_ui/resources/js/init.ts b/ash/webui/camera_app_ui/resources/js/init.ts index 2dd2e01..96405e9 100644 --- a/ash/webui/camera_app_ui/resources/js/init.ts +++ b/ash/webui/camera_app_ui/resources/js/init.ts
@@ -21,6 +21,7 @@ // TODO(crbug.com/980846): Refactor to use a better way rather than window // properties to pass data to other modules. appWindow: Comlink.Remote<AppWindow>|null; + windowCreationTime: number; } } @@ -31,7 +32,7 @@ const testBridge = Comlink.wrap<TestBridge>(sharedWorker.port); const appWindow = await testBridge.bindWindow(window.location.href); window.appWindow = appWindow; - window['windowCreationTime'] = performance.now(); + window.windowCreationTime = performance.now(); if (appWindow !== null) { await appWindow.waitUntilReadyOnTastSide(); }
diff --git a/ash/webui/camera_app_ui/resources/js/intent.ts b/ash/webui/camera_app_ui/resources/js/intent.ts index ca0064f..f216666 100644 --- a/ash/webui/camera_app_ui/resources/js/intent.ts +++ b/ash/webui/camera_app_ui/resources/js/intent.ts
@@ -104,7 +104,7 @@ */ static create(url: URL, mode: Mode): Intent { const params = url.searchParams; - const getBool = (key) => params.get(key) === '1'; + const getBool = (key: string) => params.get(key) === '1'; const param = params.get('intentId'); if (param === null) { throw new ParseError(url);
diff --git a/ash/webui/camera_app_ui/resources/js/main.ts b/ash/webui/camera_app_ui/resources/js/main.ts index d32bcf2..4cf068e 100644 --- a/ash/webui/camera_app_ui/resources/js/main.ts +++ b/ash/webui/camera_app_ui/resources/js/main.ts
@@ -139,7 +139,7 @@ } }); - const save = (element) => { + const save = (element: HTMLInputElement) => { if (element.dataset['key'] !== undefined) { localStorage.set(element.dataset['key'], element.checked); } @@ -246,7 +246,7 @@ const cameraResourceInitialized = new WaitableEvent(); const exploitUsage = async () => { if (cameraResourceInitialized.isSignaled()) { - await this.resume(); + this.resume(); } else { // CCA must get camera usage for completing its initialization when // first launched. @@ -275,7 +275,7 @@ nav.close(ViewName.SPLASH); nav.open(ViewName.CAMERA); - const windowCreationTime = window['windowCreationTime']; + const windowCreationTime = window.windowCreationTime; this.perfLogger.start( PerfEvent.LAUNCHING_FROM_WINDOW_CREATION, windowCreationTime); this.perfLogger.stop( @@ -286,16 +286,17 @@ })(); const preloadImages = (async () => { - const loadImage = (url) => new Promise<void>((resolve, reject) => { - const link = document.createElement('link'); - link.rel = 'preload'; - link.as = 'image'; - link.href = url; - link.onload = () => resolve(); - link.onerror = () => - reject(new Error(`Failed to preload image ${url}`)); - document.head.appendChild(link); - }); + const loadImage = (url: string) => + new Promise<void>((resolve, reject) => { + const link = document.createElement('link'); + link.rel = 'preload'; + link.as = 'image'; + link.href = url; + link.onload = () => resolve(); + link.onerror = () => + reject(new Error(`Failed to preload image ${url}`)); + document.head.appendChild(link); + }); const results = await Promise.allSettled( preloadImagesList.map((name) => loadImage(`/images/${name}`))); for (const result of results) {
diff --git a/ash/webui/camera_app_ui/resources/js/metrics.ts b/ash/webui/camera_app_ui/resources/js/metrics.ts index f61c88f..2643f3b 100644 --- a/ash/webui/camera_app_ui/resources/js/metrics.ts +++ b/ash/webui/camera_app_ui/resources/js/metrics.ts
@@ -39,11 +39,15 @@ */ async function sendEvent( event: UniversalAnalytics.FieldsObject, dimen?: Map<number, unknown>) { - const assignDimension = (e, d) => { - for (const [key, value] of d.entries()) { - e[`dimension${key}`] = value; - } - }; + const assignDimension = + (e: UniversalAnalytics.FieldsObject, d: Map<number, unknown>) => { + for (const [key, value] of d.entries()) { + // The TypeScript definition for UniversalAnalytics.FieldsObject + // manually listed out dimension1 ~ dimension200, and TypeScript don't + // recognize accessing it using []. Force the type here. + (e as Record<string, unknown>)[`dimension${key}`] = value; + } + }; assert(baseDimen !== null); assignDimension(event, baseDimen); @@ -124,9 +128,18 @@ */ export async function initMetrics(): Promise<void> { const board = loadTimeData.getBoard(); - const boardName = /^(x86-)?(\w*)/.exec(board)[0]; - const match = navigator.appVersion.match(/CrOS\s+\S+\s+([\d.]+)/); - const osVer = match ? match[1] : ''; + const boardName = (() => { + const match = /^(x86-)?(\w*)/.exec(board); + assert(match !== null); + return match[0]; + })(); + const osVer = (() => { + const match = navigator.appVersion.match(/CrOS\s+\S+\s+([\d.]+)/); + if (match === null) { + return ''; + } + return match[1]; + })(); baseDimen = new Map<MetricDimension, string|number>([ [MetricDimension.BOARD, boardName], [MetricDimension.OS_VERSION, osVer], @@ -136,7 +149,7 @@ const GA_LOCAL_STORAGE_KEY = 'google-analytics.analytics.user-id'; const clientId = localStorage.getString(GA_LOCAL_STORAGE_KEY); - const setClientId = (id) => { + const setClientId = (id: string) => { localStorage.set(GA_LOCAL_STORAGE_KEY, id); }; @@ -375,7 +388,7 @@ */ export function sendIntentEvent({intent, result}: IntentEventParam): void { const {mode, shouldHandleResult, shouldDownScale, isSecure} = intent; - const getBoolValue = (b) => b ? '1' : '0'; + const getBoolValue = (b: boolean) => b ? '1' : '0'; sendEvent( { eventCategory: 'intent',
diff --git a/ash/wm/overview/overview_controller_unittest.cc b/ash/wm/overview/overview_controller_unittest.cc index 6fc3352..efe02e9 100644 --- a/ash/wm/overview/overview_controller_unittest.cc +++ b/ash/wm/overview/overview_controller_unittest.cc
@@ -24,6 +24,7 @@ #include "ash/wm/desks/desks_test_util.h" #include "ash/wm/overview/overview_observer.h" #include "ash/wm/overview/overview_session.h" +#include "ash/wm/overview/overview_test_util.h" #include "ash/wm/overview/overview_wallpaper_controller.h" #include "ash/wm/tablet_mode/tablet_mode_controller_test_api.h" #include "ash/wm/window_resizer.h" @@ -32,6 +33,7 @@ #include "base/command_line.h" #include "base/feature_list.h" #include "base/run_loop.h" +#include "ui/aura/client/aura_constants.h" #include "ui/aura/client/window_types.h" #include "ui/base/hit_test.h" #include "ui/compositor/layer.h" @@ -695,6 +697,33 @@ EXPECT_FALSE(Shell::Get()->overview_controller()->InOverviewSession()); } +// Tests that clipping the window to remove the top view inset (header) works as +// expected. +TEST_F(OverviewControllerTest, WindowClipping) { + std::unique_ptr<aura::Window> window = CreateTestWindow(); + window->SetBounds(gfx::Rect(300, 300)); + window->SetProperty(aura::client::kTopViewInset, 20); + ASSERT_EQ(gfx::Rect(), window->layer()->GetTargetClipRect()); + + ui::ScopedAnimationDurationScaleMode non_zero( + ui::ScopedAnimationDurationScaleMode::NON_ZERO_DURATION); + + // Tests that the clipping bounds in overview will clip away the top inset. + // There is a extra pixel added to account for what seems to be a rounding + // error. + EnterOverview(); + WaitForOverviewEnterAnimation(); + EXPECT_EQ(gfx::Rect(0, 21, 300, 279), window->layer()->GetTargetClipRect()); + + // Tests that we animate to the window size from the overview clip on exit. + ExitOverview(); + EXPECT_EQ(gfx::Rect(300, 300), window->layer()->GetTargetClipRect()); + + // Tests that the clipping is removed after the animation ends. + WaitForOverviewExitAnimation(); + EXPECT_EQ(gfx::Rect(), window->layer()->GetTargetClipRect()); +} + class OverviewVirtualKeyboardTest : public OverviewControllerTest { protected: void SetUp() override {
diff --git a/ash/wm/overview/overview_grid.cc b/ash/wm/overview/overview_grid.cc index f8c580e2..d47b463c 100644 --- a/ash/wm/overview/overview_grid.cc +++ b/ash/wm/overview/overview_grid.cc
@@ -753,8 +753,10 @@ } void OverviewGrid::RemoveAllItemsForDesksTemplatesLaunch() { - for (auto& item : window_list_) - item->RestoreWindow(/*reset_tranform=*/true); + for (auto& item : window_list_) { + item->RestoreWindow(/*reset_tranform=*/true, + /*was_desks_templates_grid_showing=*/true); + } window_list_.clear(); }
diff --git a/ash/wm/overview/scoped_overview_transform_window.cc b/ash/wm/overview/scoped_overview_transform_window.cc index 3e7b336..ea185dc0 100644 --- a/ash/wm/overview/scoped_overview_transform_window.cc +++ b/ash/wm/overview/scoped_overview_transform_window.cc
@@ -112,9 +112,9 @@ return; gfx::Rect new_clip_rect = clip_rect; - if (new_clip_rect.IsEmpty() && - animator->IsAnimatingProperty(ui::LayerAnimationElement::CLIP)) { - // Animate to a clip the size of |window|. Create a self deleting object + if (new_clip_rect.IsEmpty() && animator->is_animating() && + !animator->GetTransitionDuration().is_zero()) { + // Animate to a clip the size of `window`. Create a self deleting object // which removes the clip when the animation is finished. new_clip_rect = gfx::Rect(window->bounds().size()); new RemoveClipObserver(window); @@ -219,11 +219,12 @@ } ScopedOverviewTransformWindow::~ScopedOverviewTransformWindow() { - // Reset clipping in the case RestoreWindow() is not called, such as when - // |this| is dragged to another display. This is a no-op if SetClipping() was - // called in RestoreWindow(). - // See crbug.com/1140639. - SetClipping({ClippingType::kExit, gfx::SizeF()}); + // Reset clipping in the case `RestoreWindow()` is not called, such as when + // `this` is dragged to another display. Without this check, `SetClipping` + // would override the one we called in `RestoreWindow()` which would result in + // the same final clip but may remove the animation. See crbug.com/1140639. + if (reset_clip_on_shutdown_) + SetClipping({ClippingType::kExit, gfx::SizeF()}); for (auto* transient : GetTransientTreeIterator(window_)) { transient->ClearProperty(chromeos::kIsShowingInOverviewKey); @@ -265,10 +266,16 @@ if (Shell::Get()->shadow_controller()) Shell::Get()->shadow_controller()->UpdateShadowForWindow(window_); + // We will handle clipping here, no need to do anything in the destructor. + reset_clip_on_shutdown_ = false; + if (IsMinimized() || was_desk_templates_grid_showing) { // Minimized windows may have had their transforms altered by swiping up // from the shelf. + ScopedOverviewAnimationSettings animation_settings(OVERVIEW_ANIMATION_NONE, + window_); SetTransform(window_, gfx::Transform()); + SetClipping({ClippingType::kExit, gfx::SizeF()}); return; } @@ -299,11 +306,8 @@ } } - OverviewAnimationType animation_type = - was_desk_templates_grid_showing - ? OVERVIEW_ANIMATION_NONE - : overview_item_->GetExitOverviewAnimationType(); - ScopedOverviewAnimationSettings animation_settings(animation_type, window_); + ScopedOverviewAnimationSettings animation_settings( + overview_item_->GetExitOverviewAnimationType(), window_); SetOpacity(original_opacity_); SetClipping({ClippingType::kExit, gfx::SizeF()}); }
diff --git a/ash/wm/overview/scoped_overview_transform_window.h b/ash/wm/overview/scoped_overview_transform_window.h index b17ac49..984be6f 100644 --- a/ash/wm/overview/scoped_overview_transform_window.h +++ b/ash/wm/overview/scoped_overview_transform_window.h
@@ -206,6 +206,10 @@ // mode. gfx::Rect original_clip_rect_; + // Removes clipping on `window_` during destruction in the case it was not + // removed in `RestoreWindw()`. See destructor for more information. + bool reset_clip_on_shutdown_ = true; + std::unique_ptr<ScopedOverviewHideWindows> hidden_transient_children_; base::ScopedMultiSourceObservation<aura::Window, aura::WindowObserver>
diff --git a/base/allocator/partition_allocator/address_pool_manager_types.h b/base/allocator/partition_allocator/address_pool_manager_types.h index 105ab0a6..976e37c5 100644 --- a/base/allocator/partition_allocator/address_pool_manager_types.h +++ b/base/allocator/partition_allocator/address_pool_manager_types.h
@@ -5,13 +5,18 @@ #ifndef BASE_ALLOCATOR_PARTITION_ALLOCATOR_ADDRESS_POOL_MANAGER_TYPES_H_ #define BASE_ALLOCATOR_PARTITION_ALLOCATOR_ADDRESS_POOL_MANAGER_TYPES_H_ -namespace base { - -namespace internal { +namespace partition_alloc::internal { using pool_handle = unsigned; -} // namespace internal -} // namespace base +} // namespace partition_alloc::internal + +namespace base::internal { + +// TODO(https://crbug.com/1288247): Remove these 'using' declarations once +// the migration to the new namespaces gets done. +using ::partition_alloc::internal::pool_handle; + +} // namespace base::internal #endif // BASE_ALLOCATOR_PARTITION_ALLOCATOR_ADDRESS_POOL_MANAGER_TYPES_H_
diff --git a/base/allocator/partition_allocator/page_allocator_constants.h b/base/allocator/partition_allocator/page_allocator_constants.h index 4374310..12515b9a0 100644 --- a/base/allocator/partition_allocator/page_allocator_constants.h +++ b/base/allocator/partition_allocator/page_allocator_constants.h
@@ -36,7 +36,7 @@ #endif -namespace base { +namespace partition_alloc::internal { PAGE_ALLOCATOR_CONSTANTS_DECLARE_CONSTEXPR ALWAYS_INLINE size_t PageAllocationGranularityShift() { @@ -112,6 +112,23 @@ constexpr size_t kPageMetadataShift = 5; // 32 bytes per partition page. constexpr size_t kPageMetadataSize = 1 << kPageMetadataShift; +} // namespace partition_alloc::internal + +namespace base { + +// TODO(https://crbug.com/1288247): Remove these 'using' declarations once +// the migration to the new namespaces gets done. +using ::partition_alloc::internal::kPageMetadataShift; +using ::partition_alloc::internal::kPageMetadataSize; +using ::partition_alloc::internal::PageAllocationGranularity; +using ::partition_alloc::internal::PageAllocationGranularityBaseMask; +using ::partition_alloc::internal::PageAllocationGranularityOffsetMask; +using ::partition_alloc::internal::PageAllocationGranularityShift; +using ::partition_alloc::internal::SystemPageBaseMask; +using ::partition_alloc::internal::SystemPageOffsetMask; +using ::partition_alloc::internal::SystemPageShift; +using ::partition_alloc::internal::SystemPageSize; + } // namespace base #endif // BASE_ALLOCATOR_PARTITION_ALLOCATOR_PAGE_ALLOCATOR_CONSTANTS_H_
diff --git a/base/allocator/partition_allocator/partition_alloc_constants.h b/base/allocator/partition_allocator/partition_alloc_constants.h index 8163f1c..7e7943f 100644 --- a/base/allocator/partition_allocator/partition_alloc_constants.h +++ b/base/allocator/partition_allocator/partition_alloc_constants.h
@@ -22,7 +22,7 @@ #include <mach/vm_page_size.h> #endif -namespace base { +namespace partition_alloc::internal { // Size of a cache line. Not all CPUs in the world have a 64 bytes cache line // size, but as of 2021, most do. This is in particular the case for almost all @@ -219,9 +219,9 @@ #endif constexpr size_t kMaxSuperPagesInPool = kPoolMaxSize / kSuperPageSize; -static constexpr internal::pool_handle kRegularPoolHandle = 1; -static constexpr internal::pool_handle kBRPPoolHandle = 2; -static constexpr internal::pool_handle kConfigurablePoolHandle = 3; +static constexpr pool_handle kRegularPoolHandle = 1; +static constexpr pool_handle kBRPPoolHandle = 2; +static constexpr pool_handle kConfigurablePoolHandle = 3; // Slots larger than this size will not receive MTE protection. Pages intended // for allocations larger than this constant should not be backed with PROT_MTE @@ -399,6 +399,70 @@ PartitionAllocLastFlag = PartitionAllocFastPathOrReturnNull }; +} // namespace partition_alloc::internal + +namespace base { + +// TODO(https://crbug.com/1288247): Remove these 'using' declarations once +// the migration to the new namespaces gets done. +using ::partition_alloc::internal::DirectMapAllocationGranularity; +using ::partition_alloc::internal::DirectMapAllocationGranularityOffsetMask; +using ::partition_alloc::internal::DirectMapAllocationGranularityShift; +#if HAS_MEMORY_TAGGING +using ::partition_alloc::internal::HasOverflowTag; +#endif // HAS_MEMORY_TAGGING +using ::partition_alloc::internal::kBitsPerSizeT; +using ::partition_alloc::internal::kBRPPoolHandle; +using ::partition_alloc::internal::kConfigurablePoolHandle; +using ::partition_alloc::internal::kDefaultEmptySlotSpanRingSize; +using ::partition_alloc::internal::kEmptyCacheIndexBits; +using ::partition_alloc::internal::kFreedByte; +using ::partition_alloc::internal::kGiB; +using ::partition_alloc::internal::kInvalidBucketSize; +using ::partition_alloc::internal::kMaxBucketed; +using ::partition_alloc::internal::kMaxBucketedOrder; +using ::partition_alloc::internal::kMaxBucketSpacing; +using ::partition_alloc::internal::kMaxFreeableSpans; +using ::partition_alloc::internal::kMaxMemoryTaggingSize; +using ::partition_alloc::internal::kMaxPartitionPagesPerRegularSlotSpan; +using ::partition_alloc::internal::kMaxSuperPagesInPool; +using ::partition_alloc::internal::kMaxSupportedAlignment; +using ::partition_alloc::internal::kMinBucketedOrder; +using ::partition_alloc::internal::kMinDirectMappedDownsize; +using ::partition_alloc::internal::kNumBucketedOrders; +using ::partition_alloc::internal::kNumBuckets; +using ::partition_alloc::internal::kNumBucketsPerOrder; +using ::partition_alloc::internal::kNumBucketsPerOrderBits; +using ::partition_alloc::internal::kNumPools; +using ::partition_alloc::internal::kPartitionCachelineSize; +using ::partition_alloc::internal::kPoolMaxSize; +using ::partition_alloc::internal::kQuarantinedByte; +using ::partition_alloc::internal::kReasonableSizeOfUnusedPages; +using ::partition_alloc::internal::kRegularPoolHandle; +using ::partition_alloc::internal::kSmallestBucket; +using ::partition_alloc::internal::kSuperPageAlignment; +using ::partition_alloc::internal::kSuperPageBaseMask; +using ::partition_alloc::internal::kSuperPageOffsetMask; +using ::partition_alloc::internal::kSuperPageShift; +using ::partition_alloc::internal::kSuperPageSize; +using ::partition_alloc::internal::kUninitializedByte; +using ::partition_alloc::internal::MaxDirectMapped; +using ::partition_alloc::internal::MaxRegularSlotSpanSize; +using ::partition_alloc::internal::MaxSuperPagesInPool; +using ::partition_alloc::internal::MaxSystemPagesPerRegularSlotSpan; +using ::partition_alloc::internal::NumPartitionPagesPerSuperPage; +using ::partition_alloc::internal::NumSystemPagesPerPartitionPage; +using ::partition_alloc::internal::PartitionAllocFastPathOrReturnNull; +using ::partition_alloc::internal::PartitionAllocFlags; +using ::partition_alloc::internal::PartitionAllocLastFlag; +using ::partition_alloc::internal::PartitionAllocNoHooks; +using ::partition_alloc::internal::PartitionAllocReturnNull; +using ::partition_alloc::internal::PartitionAllocZeroFill; +using ::partition_alloc::internal::PartitionPageBaseMask; +using ::partition_alloc::internal::PartitionPageOffsetMask; +using ::partition_alloc::internal::PartitionPageShift; +using ::partition_alloc::internal::PartitionPageSize; + } // namespace base #endif // BASE_ALLOCATOR_PARTITION_ALLOCATOR_PARTITION_ALLOC_CONSTANTS_H_
diff --git a/base/allocator/partition_allocator/partition_alloc_forward.h b/base/allocator/partition_allocator/partition_alloc_forward.h index 6c6b7bd..9e68961 100644 --- a/base/allocator/partition_allocator/partition_alloc_forward.h +++ b/base/allocator/partition_allocator/partition_alloc_forward.h
@@ -13,7 +13,7 @@ #include "base/compiler_specific.h" #include "base/dcheck_is_on.h" -namespace base { +namespace partition_alloc::internal { // Alignment has two constraints: // - Alignment requirement for scalar types: alignof(std::max_align_t) @@ -37,6 +37,14 @@ "PartitionAlloc doesn't support a fundamental alignment larger " "than 16 bytes."); +} // namespace partition_alloc::internal + +namespace base { + +// TODO(https://crbug.com/1288247): Remove these 'using' declarations once +// the migration to the new namespaces gets done. +using ::partition_alloc::internal::kAlignment; + namespace internal { template <bool thread_safe> @@ -81,7 +89,8 @@ // kAlignment boundary. This is useful for e.g. using aligned vector // instructions in the constructor for zeroing. #if __has_attribute(assume_aligned) -#define MALLOC_ALIGNED __attribute__((assume_aligned(base::kAlignment))) +#define MALLOC_ALIGNED \ + __attribute__((assume_aligned(::partition_alloc::internal::kAlignment))) #endif #endif // defined(__has_attribute)
diff --git a/base/allocator/partition_allocator/partition_alloc_unittest.cc b/base/allocator/partition_allocator/partition_alloc_unittest.cc index fac360f..92a8f0e 100644 --- a/base/allocator/partition_allocator/partition_alloc_unittest.cc +++ b/base/allocator/partition_allocator/partition_alloc_unittest.cc
@@ -293,8 +293,8 @@ else if (i == num_slots - 1) last = allocator.root()->AdjustPointerForExtrasSubtract(ptr); } - EXPECT_EQ(SlotSpan::FromSlotStartPtr(base::memory::UnmaskPtr(first)), - SlotSpan::FromSlotStartPtr(base::memory::UnmaskPtr(last))); + EXPECT_EQ(SlotSpan::FromSlotStart(base::memory::UnmaskPtr(first)), + SlotSpan::FromSlotStart(base::memory::UnmaskPtr(last))); if (bucket->num_system_pages_per_slot_span == NumSystemPagesPerPartitionPage()) EXPECT_EQ(base::memory::UnmaskPtr(first) & PartitionPageBaseMask(), @@ -311,7 +311,7 @@ void CycleFreeCache(size_t size) { for (size_t i = 0; i < kMaxFreeableSpans; ++i) { void* ptr = allocator.root()->Alloc(size, type_name); - auto* slot_span = SlotSpan::FromSlotStartPtr( + auto* slot_span = SlotSpan::FromSlotStart( allocator.root()->AdjustPointerForExtrasSubtract(ptr)); auto* bucket = slot_span->bucket; EXPECT_EQ(1u, bucket->active_slot_spans_head->num_allocated_slots); @@ -425,12 +425,13 @@ (slot_span->bucket->num_system_pages_per_slot_span * SystemPageSize()) / size; EXPECT_EQ(num_slots, slot_span->num_allocated_slots); - char* ptr = reinterpret_cast<char*>(SlotSpan::ToSlotSpanStartPtr(slot_span)); + uintptr_t address = SlotSpan::ToSlotSpanStart(slot_span); size_t i; for (i = 0; i < num_slots; ++i) { // Remask is needed here because each slot can have a different tag. - root->Free(memory::RemaskPtr(ptr + kPointerOffset)); - ptr += size; + root->Free( + reinterpret_cast<void*>(memory::RemaskPtr(address + kPointerOffset))); + address += size; } EXPECT_TRUE(slot_span->is_empty()); } @@ -577,11 +578,8 @@ EXPECT_EQ(slot_span2, bucket->active_slot_spans_head); EXPECT_EQ(nullptr, slot_span2->next_slot_span); - EXPECT_EQ( - reinterpret_cast<uintptr_t>(SlotSpan::ToSlotSpanStartPtr(slot_span)) & - kSuperPageBaseMask, - reinterpret_cast<uintptr_t>(SlotSpan::ToSlotSpanStartPtr(slot_span2)) & - kSuperPageBaseMask); + EXPECT_EQ(SlotSpan::ToSlotSpanStart(slot_span) & kSuperPageBaseMask, + SlotSpan::ToSlotSpanStart(slot_span2) & kSuperPageBaseMask); // Fully free the non-current slot span. This will leave us with no current // active slot span because one is empty and the other is full. @@ -617,10 +615,9 @@ EXPECT_EQ(nullptr, slot_span2->next_slot_span); // Bounce slot_span1 back into the non-full list then fill it up again. - char* ptr = memory::RemaskPtr( - reinterpret_cast<char*>(SlotSpan::ToSlotSpanStartPtr(slot_span1)) + - kPointerOffset); - allocator.root()->Free(ptr); + uintptr_t address = + memory::RemaskPtr(SlotSpan::ToSlotSpanStart(slot_span1) + kPointerOffset); + allocator.root()->Free(reinterpret_cast<void*>(address)); EXPECT_EQ(slot_span1, bucket->active_slot_spans_head); (void)allocator.root()->Alloc(kTestAllocSize, type_name); EXPECT_EQ(slot_span1, bucket->active_slot_spans_head); @@ -635,28 +632,24 @@ EXPECT_EQ(nullptr, slot_span3->next_slot_span); // Work out a pointer into slot_span2 and free it. - ptr = memory::RemaskPtr( - reinterpret_cast<char*>(SlotSpan::ToSlotSpanStartPtr(slot_span2)) + - kPointerOffset); - allocator.root()->Free(ptr); + address = + memory::RemaskPtr(SlotSpan::ToSlotSpanStart(slot_span2) + kPointerOffset); + allocator.root()->Free(reinterpret_cast<void*>(address)); // Trying to allocate at this time should cause us to cycle around to // slot_span2 and find the recently freed slot. - char* new_ptr = reinterpret_cast<char*>( - allocator.root()->Alloc(kTestAllocSize, type_name)); - PA_EXPECT_PTR_EQ(ptr, new_ptr); + void* ptr = allocator.root()->Alloc(kTestAllocSize, type_name); + PA_EXPECT_PTR_EQ(reinterpret_cast<void*>(address), ptr); EXPECT_EQ(slot_span2, bucket->active_slot_spans_head); EXPECT_EQ(slot_span3, slot_span2->next_slot_span); // Work out a pointer into slot_span1 and free it. This should pull the slot // span back into the list of available slot spans. - ptr = memory::RemaskPtr( - reinterpret_cast<char*>(SlotSpan::ToSlotSpanStartPtr(slot_span1)) + - kPointerOffset); - allocator.root()->Free(ptr); + address = + memory::RemaskPtr(SlotSpan::ToSlotSpanStart(slot_span1) + kPointerOffset); + allocator.root()->Free(reinterpret_cast<void*>(address)); // This allocation should be satisfied by slot_span1. - new_ptr = reinterpret_cast<char*>( - allocator.root()->Alloc(kTestAllocSize, type_name)); - PA_EXPECT_PTR_EQ(ptr, new_ptr); + ptr = allocator.root()->Alloc(kTestAllocSize, type_name); + PA_EXPECT_PTR_EQ(reinterpret_cast<void*>(address), ptr); EXPECT_EQ(slot_span1, bucket->active_slot_spans_head); EXPECT_EQ(slot_span2, slot_span1->next_slot_span); @@ -665,8 +658,7 @@ FreeFullSlotSpan(allocator.root(), slot_span1); // Allocating whilst in this state exposed a bug, so keep the test. - ptr = reinterpret_cast<char*>( - allocator.root()->Alloc(kTestAllocSize, type_name)); + ptr = allocator.root()->Alloc(kTestAllocSize, type_name); allocator.root()->Free(ptr); } @@ -732,15 +724,13 @@ size_t i; for (i = 0; i < num_slot_spans_needed; ++i) { slot_spans[i] = GetFullSlotSpan(kTestAllocSize); - void* storage_ptr = SlotSpan::ToSlotSpanStartPtr(slot_spans[i]); + uintptr_t slot_span_start = SlotSpan::ToSlotSpanStart(slot_spans[i]); if (!i) - first_super_page_base = - reinterpret_cast<uintptr_t>(storage_ptr) & kSuperPageBaseMask; + first_super_page_base = slot_span_start & kSuperPageBaseMask; if (i == num_slot_spans_needed - 1) { - uintptr_t second_super_page_base = - reinterpret_cast<uintptr_t>(storage_ptr) & kSuperPageBaseMask; + uintptr_t second_super_page_base = slot_span_start & kSuperPageBaseMask; uintptr_t second_super_page_offset = - reinterpret_cast<uintptr_t>(storage_ptr) & kSuperPageOffsetMask; + slot_span_start & kSuperPageOffsetMask; EXPECT_FALSE(second_super_page_base == first_super_page_base); // Check that we allocated a guard page for the second page. EXPECT_EQ(PartitionPageSize(), second_super_page_offset); @@ -863,7 +853,7 @@ EXPECT_TRUE(ptr2); allocator.root()->Free(ptr); // Should be freeable at this point. - auto* slot_span = SlotSpan::FromSlotStartPtr( + auto* slot_span = SlotSpan::FromSlotStart( allocator.root()->AdjustPointerForExtrasSubtract(ptr)); EXPECT_TRUE(slot_span->in_empty_cache()); allocator.root()->Free(ptr2); @@ -886,9 +876,9 @@ EXPECT_TRUE(ptr4); auto* slot_span = - SlotSpanMetadata<base::internal::ThreadSafe>::FromSlotStartPtr( + SlotSpanMetadata<base::internal::ThreadSafe>::FromSlotStart( allocator.root()->AdjustPointerForExtrasSubtract(ptr)); - auto* slot_span2 = SlotSpan::FromSlotStartPtr( + auto* slot_span2 = SlotSpan::FromSlotStart( allocator.root()->AdjustPointerForExtrasSubtract(ptr3)); EXPECT_NE(slot_span, slot_span2); @@ -1175,7 +1165,7 @@ // realloc(0, size) should be equivalent to malloc(). void* ptr = allocator.root()->Realloc(nullptr, kTestAllocSize, type_name); memset(ptr, 'A', kTestAllocSize); - auto* slot_span = SlotSpan::FromSlotStartPtr( + auto* slot_span = SlotSpan::FromSlotStart( allocator.root()->AdjustPointerForExtrasSubtract(ptr)); // realloc(ptr, 0) should be equivalent to free(). void* ptr2 = allocator.root()->Realloc(ptr, 0, type_name); @@ -1374,7 +1364,7 @@ void* ptr = allocator.root()->Alloc(big_size, type_name); EXPECT_TRUE(ptr); - auto* slot_span = SlotSpan::FromSlotStartPtr( + auto* slot_span = SlotSpan::FromSlotStart( allocator.root()->AdjustPointerForExtrasSubtract(ptr)); size_t total_slots = (slot_span->bucket->num_system_pages_per_slot_span * SystemPageSize()) / @@ -1408,7 +1398,7 @@ void* ptr5 = allocator.root()->Alloc(big_size, type_name); EXPECT_TRUE(ptr5); - auto* slot_span2 = SlotSpan::FromSlotStartPtr( + auto* slot_span2 = SlotSpan::FromSlotStart( allocator.root()->AdjustPointerForExtrasSubtract(ptr5)); EXPECT_EQ(1u, slot_span2->num_allocated_slots); @@ -1437,7 +1427,7 @@ ptr = allocator.root()->Alloc(non_dividing_size, type_name); EXPECT_TRUE(ptr); - slot_span = SlotSpan::FromSlotStartPtr( + slot_span = SlotSpan::FromSlotStart( allocator.root()->AdjustPointerForExtrasSubtract(ptr)); total_slots = (slot_span->bucket->num_system_pages_per_slot_span * SystemPageSize()) / @@ -1479,7 +1469,7 @@ ptr = allocator.root()->Alloc(medium_size, type_name); EXPECT_TRUE(ptr); - slot_span = SlotSpan::FromSlotStartPtr( + slot_span = SlotSpan::FromSlotStart( allocator.root()->AdjustPointerForExtrasSubtract(ptr)); EXPECT_EQ(1u, slot_span->num_allocated_slots); total_slots = @@ -1500,7 +1490,7 @@ ptr = allocator.root()->Alloc(small_size, type_name); EXPECT_TRUE(ptr); - slot_span = SlotSpan::FromSlotStartPtr( + slot_span = SlotSpan::FromSlotStart( allocator.root()->AdjustPointerForExtrasSubtract(ptr)); EXPECT_EQ(1u, slot_span->num_allocated_slots); total_slots = @@ -1525,7 +1515,7 @@ ptr = allocator.root()->Alloc(very_small_size, type_name); EXPECT_TRUE(ptr); - slot_span = SlotSpan::FromSlotStartPtr( + slot_span = SlotSpan::FromSlotStart( allocator.root()->AdjustPointerForExtrasSubtract(ptr)); EXPECT_EQ(1u, slot_span->num_allocated_slots); size_t very_small_actual_size = allocator.root()->GetUsableSize(ptr); @@ -1547,7 +1537,7 @@ (SystemPageSize() + (SystemPageSize() / 2)) - kExtraAllocSize; ptr = allocator.root()->Alloc(page_and_a_half_size, type_name); EXPECT_TRUE(ptr); - slot_span = SlotSpan::FromSlotStartPtr( + slot_span = SlotSpan::FromSlotStart( allocator.root()->AdjustPointerForExtrasSubtract(ptr)); EXPECT_EQ(1u, slot_span->num_allocated_slots); // Only the first slot was provisioned, and that's the one that was just @@ -1559,7 +1549,7 @@ EXPECT_EQ(total_slots - 1, slot_span->num_unprovisioned_slots); ptr2 = allocator.root()->Alloc(page_and_a_half_size, type_name); EXPECT_TRUE(ptr); - slot_span = SlotSpan::FromSlotStartPtr( + slot_span = SlotSpan::FromSlotStart( allocator.root()->AdjustPointerForExtrasSubtract(ptr)); EXPECT_EQ(2u, slot_span->num_allocated_slots); // As above, only one slot was provisioned. @@ -1572,7 +1562,7 @@ size_t page_size = SystemPageSize() - kExtraAllocSize; ptr = allocator.root()->Alloc(page_size, type_name); EXPECT_TRUE(ptr); - slot_span = SlotSpan::FromSlotStartPtr( + slot_span = SlotSpan::FromSlotStart( allocator.root()->AdjustPointerForExtrasSubtract(ptr)); EXPECT_EQ(1u, slot_span->num_allocated_slots); EXPECT_TRUE(slot_span->get_freelist_head()); @@ -1595,19 +1585,16 @@ EXPECT_TRUE(ptr); EXPECT_NE(slot_span1, bucket->active_slot_spans_head); EXPECT_NE(slot_span2, bucket->active_slot_spans_head); - auto* slot_span = SlotSpan::FromSlotStartPtr( + auto* slot_span = SlotSpan::FromSlotStart( allocator.root()->AdjustPointerForExtrasSubtract(ptr)); EXPECT_EQ(1u, slot_span->num_allocated_slots); // Work out a pointer into slot_span2 and free it; and then slot_span1 and // free it. - char* ptr2 = - reinterpret_cast<char*>(SlotSpan::ToSlotSpanStartPtr(slot_span1)) + - kPointerOffset; - allocator.root()->Free(ptr2); - ptr2 = reinterpret_cast<char*>(SlotSpan::ToSlotSpanStartPtr(slot_span2)) + - kPointerOffset; - allocator.root()->Free(ptr2); + uintptr_t ptr2 = SlotSpan::ToSlotSpanStart(slot_span1) + kPointerOffset; + allocator.root()->Free(reinterpret_cast<void*>(ptr2)); + ptr2 = SlotSpan::ToSlotSpanStart(slot_span2) + kPointerOffset; + allocator.root()->Free(reinterpret_cast<void*>(ptr2)); // If we perform two allocations from the same bucket now, we expect to // refill both the nearly full slot spans. @@ -1662,20 +1649,21 @@ for (i = 0; i < num_partition_pages_needed; ++i) first_super_page_pages[i] = GetFullSlotSpan(kTestAllocSize); - char* page_base = reinterpret_cast<char*>( - SlotSpan::ToSlotSpanStartPtr(first_super_page_pages[0])); - EXPECT_EQ(PartitionPageSize(), - reinterpret_cast<uintptr_t>(page_base) & kSuperPageOffsetMask); - page_base -= PartitionPageSize(); + uintptr_t slot_spart_start = + SlotSpan::ToSlotSpanStart(first_super_page_pages[0]); + EXPECT_EQ(PartitionPageSize(), slot_spart_start & kSuperPageOffsetMask); + uintptr_t super_page = slot_spart_start - PartitionPageSize(); // Map a single system page either side of the mapping for our allocations, // with the goal of tripping up alignment of the next mapping. void* map1 = AllocPages( - page_base - PageAllocationGranularity(), PageAllocationGranularity(), - PageAllocationGranularity(), PageInaccessible, PageTag::kPartitionAlloc); + reinterpret_cast<void*>(super_page - PageAllocationGranularity()), + PageAllocationGranularity(), PageAllocationGranularity(), + PageInaccessible, PageTag::kPartitionAlloc); EXPECT_TRUE(map1); - void* map2 = AllocPages( - page_base + kSuperPageSize, PageAllocationGranularity(), - PageAllocationGranularity(), PageInaccessible, PageTag::kPartitionAlloc); + void* map2 = + AllocPages(reinterpret_cast<void*>(super_page + kSuperPageSize), + PageAllocationGranularity(), PageAllocationGranularity(), + PageInaccessible, PageTag::kPartitionAlloc); EXPECT_TRUE(map2); for (i = 0; i < num_partition_pages_needed; ++i) @@ -1684,20 +1672,20 @@ FreePages(map1, PageAllocationGranularity()); FreePages(map2, PageAllocationGranularity()); - page_base = reinterpret_cast<char*>( - SlotSpan::ToSlotSpanStartPtr(second_super_page_pages[0])); + super_page = SlotSpan::ToSlotSpanStart(second_super_page_pages[0]); EXPECT_EQ(PartitionPageSize(), - reinterpret_cast<uintptr_t>(page_base) & kSuperPageOffsetMask); - page_base -= PartitionPageSize(); + reinterpret_cast<uintptr_t>(super_page) & kSuperPageOffsetMask); + super_page -= PartitionPageSize(); // Map a single system page either side of the mapping for our allocations, // with the goal of tripping up alignment of the next mapping. - map1 = AllocPages(page_base - PageAllocationGranularity(), + map1 = AllocPages( + reinterpret_cast<void*>(super_page - PageAllocationGranularity()), + PageAllocationGranularity(), PageAllocationGranularity(), + PageReadWriteTagged, PageTag::kPartitionAlloc); + EXPECT_TRUE(map1); + map2 = AllocPages(reinterpret_cast<void*>(super_page + kSuperPageSize), PageAllocationGranularity(), PageAllocationGranularity(), PageReadWriteTagged, PageTag::kPartitionAlloc); - EXPECT_TRUE(map1); - map2 = AllocPages(page_base + kSuperPageSize, PageAllocationGranularity(), - PageAllocationGranularity(), PageReadWriteTagged, - PageTag::kPartitionAlloc); EXPECT_TRUE(map2); EXPECT_TRUE(TrySetSystemPagesAccess(map1, PageAllocationGranularity(), PageInaccessible)); @@ -1708,22 +1696,17 @@ FreePages(map1, PageAllocationGranularity()); FreePages(map2, PageAllocationGranularity()); - EXPECT_EQ(0u, reinterpret_cast<uintptr_t>(SlotSpan::ToSlotSpanStartPtr( - slot_span_in_third_super_page)) & + EXPECT_EQ(0u, SlotSpan::ToSlotSpanStart(slot_span_in_third_super_page) & PartitionPageOffsetMask()); // And make sure we really did get a page in a new superpage. - EXPECT_NE(reinterpret_cast<uintptr_t>( - SlotSpan::ToSlotSpanStartPtr(first_super_page_pages[0])) & + EXPECT_NE( + SlotSpan::ToSlotSpanStart(first_super_page_pages[0]) & kSuperPageBaseMask, + SlotSpan::ToSlotSpanStart(slot_span_in_third_super_page) & + kSuperPageBaseMask); + EXPECT_NE(SlotSpan::ToSlotSpanStart(second_super_page_pages[0]) & kSuperPageBaseMask, - reinterpret_cast<uintptr_t>( - SlotSpan::ToSlotSpanStartPtr(slot_span_in_third_super_page)) & - kSuperPageBaseMask); - EXPECT_NE(reinterpret_cast<uintptr_t>( - SlotSpan::ToSlotSpanStartPtr(second_super_page_pages[0])) & - kSuperPageBaseMask, - reinterpret_cast<uintptr_t>( - SlotSpan::ToSlotSpanStartPtr(slot_span_in_third_super_page)) & + SlotSpan::ToSlotSpanStart(slot_span_in_third_super_page) & kSuperPageBaseMask); FreeFullSlotSpan(allocator.root(), slot_span_in_third_super_page); @@ -1745,7 +1728,7 @@ void* ptr = allocator.root()->Alloc(big_size, type_name); EXPECT_TRUE(ptr); - auto* slot_span = SlotSpan::FromSlotStartPtr( + auto* slot_span = SlotSpan::FromSlotStart( allocator.root()->AdjustPointerForExtrasSubtract(ptr)); EXPECT_EQ(nullptr, bucket->empty_slot_spans_head); EXPECT_EQ(1u, slot_span->num_allocated_slots); @@ -1802,10 +1785,10 @@ EXPECT_TRUE(ptr2); SlotSpanMetadata<base::internal::ThreadSafe>* slot_span = - SlotSpanMetadata<base::internal::ThreadSafe>::FromSlotStartPtr( + SlotSpanMetadata<base::internal::ThreadSafe>::FromSlotStart( allocator.root()->AdjustPointerForExtrasSubtract(ptr)); SlotSpanMetadata<base::internal::ThreadSafe>* slot_span2 = - SlotSpanMetadata<base::internal::ThreadSafe>::FromSlotStartPtr( + SlotSpanMetadata<base::internal::ThreadSafe>::FromSlotStart( allocator.root()->AdjustPointerForExtrasSubtract(ptr2)); PartitionBucket<base::internal::ThreadSafe>* bucket = slot_span->bucket; @@ -2490,13 +2473,13 @@ void* ptr6 = allocator.root()->Alloc(size, type_name); SlotSpanMetadata<base::internal::ThreadSafe>* slot_span1 = - SlotSpanMetadata<base::internal::ThreadSafe>::FromSlotStartPtr( + SlotSpanMetadata<base::internal::ThreadSafe>::FromSlotStart( allocator.root()->AdjustPointerForExtrasSubtract(ptr1)); SlotSpanMetadata<base::internal::ThreadSafe>* slot_span2 = - SlotSpanMetadata<base::internal::ThreadSafe>::FromSlotStartPtr( + SlotSpanMetadata<base::internal::ThreadSafe>::FromSlotStart( allocator.root()->AdjustPointerForExtrasSubtract(ptr3)); SlotSpanMetadata<base::internal::ThreadSafe>* slot_span3 = - SlotSpanMetadata<base::internal::ThreadSafe>::FromSlotStartPtr( + SlotSpanMetadata<base::internal::ThreadSafe>::FromSlotStart( allocator.root()->AdjustPointerForExtrasSubtract(ptr6)); EXPECT_NE(slot_span1, slot_span2); EXPECT_NE(slot_span2, slot_span3); @@ -2537,7 +2520,7 @@ allocator.root()->Alloc(SystemPageSize() - kExtraAllocSize, type_name)); allocator.root()->Free(ptr2); SlotSpanMetadata<base::internal::ThreadSafe>* slot_span = - SlotSpanMetadata<base::internal::ThreadSafe>::FromSlotStartPtr( + SlotSpanMetadata<base::internal::ThreadSafe>::FromSlotStart( allocator.root()->AdjustPointerForExtrasSubtract(ptr1)); EXPECT_EQ(2u, slot_span->num_unprovisioned_slots); { @@ -2703,7 +2686,7 @@ ptr1[SystemPageSize() * 2] = 'A'; ptr1[SystemPageSize() * 3] = 'A'; SlotSpanMetadata<base::internal::ThreadSafe>* slot_span = - SlotSpanMetadata<base::internal::ThreadSafe>::FromSlotStartPtr( + SlotSpanMetadata<base::internal::ThreadSafe>::FromSlotStart( allocator.root()->AdjustPointerForExtrasSubtract(ptr1)); allocator.root()->Free(ptr2); allocator.root()->Free(ptr4); @@ -2770,7 +2753,7 @@ ptr1[SystemPageSize() * 2] = 'A'; ptr1[SystemPageSize() * 3] = 'A'; SlotSpanMetadata<base::internal::ThreadSafe>* slot_span = - SlotSpanMetadata<base::internal::ThreadSafe>::FromSlotStartPtr( + SlotSpanMetadata<base::internal::ThreadSafe>::FromSlotStart( allocator.root()->AdjustPointerForExtrasSubtract(ptr1)); allocator.root()->Free(ptr4); allocator.root()->Free(ptr3); @@ -3988,7 +3971,7 @@ allocator.root()->Free(ptr); // Free()-ing memory destroys order. Not looking at the head of the active // list, as it is not necessarily the one from which |ptr| came from. - auto* slot_span = SlotSpan::FromSlotStartPtr( + auto* slot_span = SlotSpan::FromSlotStart( allocator.root()->AdjustPointerForExtrasSubtract(ptr)); EXPECT_FALSE(slot_span->freelist_is_sorted()); }
diff --git a/base/allocator/partition_allocator/partition_bucket.cc b/base/allocator/partition_allocator/partition_bucket.cc index cd833f95..8fa6c53 100644 --- a/base/allocator/partition_allocator/partition_bucket.cc +++ b/base/allocator/partition_allocator/partition_bucket.cc
@@ -549,9 +549,9 @@ uintptr_t slot_span_start = adjusted_next_partition_page; auto* slot_span = &gap_end_page->slot_span_metadata; InitializeSlotSpan(slot_span); - // Now that slot span is initialized, it's safe to call FromSlotStartPtr. - PA_DCHECK(slot_span == SlotSpanMetadata<thread_safe>::FromSlotStartPtr( - reinterpret_cast<void*>(slot_span_start))); + // Now that slot span is initialized, it's safe to call FromSlotStart. + PA_DCHECK(slot_span == + SlotSpanMetadata<thread_safe>::FromSlotStart(slot_span_start)); // System pages in the super page come in a decommited state. Commit them // before vending them back. @@ -737,8 +737,8 @@ PA_DCHECK(!slot_span->is_full()); size_t size = slot_size; - uintptr_t slot_span_start = reinterpret_cast<uintptr_t>( - SlotSpanMetadata<thread_safe>::ToSlotSpanStartPtr(slot_span)); + uintptr_t slot_span_start = + SlotSpanMetadata<thread_safe>::ToSlotSpanStart(slot_span); // If we got here, the first unallocated slot is either partially or fully on // an uncommitted page. If the latter, it must be at the start of that page. uintptr_t return_slot = @@ -788,8 +788,8 @@ if (LIKELY(size <= kMaxMemoryTaggingSize)) { next_slot = memory::TagMemoryRangeRandomly(next_slot, size); } - auto* entry = new (reinterpret_cast<PartitionFreelistEntry*>(next_slot)) - PartitionFreelistEntry(); + auto* entry = + new (reinterpret_cast<void*>(next_slot)) PartitionFreelistEntry(); if (!slot_span->get_freelist_head()) { PA_DCHECK(!prev_entry); PA_DCHECK(!free_list_entries_added); @@ -985,15 +985,15 @@ // If lazy commit is enabled, pages will be recommitted when provisioning // slots, in ProvisionMoreSlotsAndAllocOne(), not here. if (!kUseLazyCommit) { - uintptr_t address = reinterpret_cast<uintptr_t>( - SlotSpanMetadata<thread_safe>::ToSlotSpanStartPtr(new_slot_span)); + uintptr_t slot_span_start = + SlotSpanMetadata<thread_safe>::ToSlotSpanStart(new_slot_span); // Since lazy commit isn't used, we have a guarantee that all slot span // pages have been previously committed, and then decommitted using // PageKeepPermissionsIfPossible, so use the same option as an // optimization. // TODO(lizeb): Handle commit failure. root->RecommitSystemPagesForData( - address, new_slot_span->bucket->get_bytes_per_span(), + slot_span_start, new_slot_span->bucket->get_bytes_per_span(), PageKeepPermissionsIfPossible); }
diff --git a/base/allocator/partition_allocator/partition_page.cc b/base/allocator/partition_allocator/partition_page.cc index 0cf3c2eb..e9b6976 100644 --- a/base/allocator/partition_allocator/partition_page.cc +++ b/base/allocator/partition_allocator/partition_page.cc
@@ -5,6 +5,7 @@ #include "base/allocator/partition_allocator/partition_page.h" #include <algorithm> +#include <cstdint> #include "base/allocator/buildflags.h" #include "base/allocator/partition_allocator/address_pool_manager.h" @@ -60,8 +61,8 @@ PA_DCHECK(root->total_size_of_direct_mapped_pages >= reservation_size); root->total_size_of_direct_mapped_pages -= reservation_size; - uintptr_t reservation_start = reinterpret_cast<uintptr_t>( - SlotSpanMetadata<thread_safe>::ToSlotSpanStartPtr(slot_span)); + uintptr_t reservation_start = + SlotSpanMetadata<thread_safe>::ToSlotSpanStart(slot_span); // The mapping may start at an unspecified location within a super page, but // we always reserve memory aligned to super page size. reservation_start = bits::AlignDown(reservation_start, kSuperPageSize); @@ -213,8 +214,7 @@ root->lock_.AssertAcquired(); PA_DCHECK(is_empty()); PA_DCHECK(!bucket->is_direct_mapped()); - uintptr_t slot_span_start = - reinterpret_cast<uintptr_t>(SlotSpanMetadata::ToSlotSpanStartPtr(this)); + uintptr_t slot_span_start = SlotSpanMetadata::ToSlotSpanStart(this); // If lazy commit is enabled, only provisioned slots are committed. size_t dirty_size = bits::AlignUp(GetProvisionedSize(), SystemPageSize()); size_t size_to_decommit = @@ -254,7 +254,7 @@ template <bool thread_safe> void SlotSpanMetadata<thread_safe>::SortFreelist() { std::bitset<kMaxSlotsPerSlotSpan> free_slots; - char* slot_span_base = reinterpret_cast<char*>(ToSlotSpanStartPtr(this)); + uintptr_t slot_span_start = ToSlotSpanStart(this); size_t num_provisioned_slots = bucket->get_slots_per_span() - num_unprovisioned_slots; @@ -266,7 +266,7 @@ head = head->GetNext(slot_size)) { ++num_free_slots; size_t offset_in_slot_span = - reinterpret_cast<char*>(memory::UnmaskPtr(head)) - slot_span_base; + memory::UnmaskPtr(reinterpret_cast<uintptr_t>(head)) - slot_span_start; size_t slot_number = bucket->GetSlotNumber(offset_in_slot_span); PA_DCHECK(slot_number < num_provisioned_slots); free_slots[slot_number] = true; @@ -280,9 +280,10 @@ for (size_t slot_number = 0; slot_number < num_provisioned_slots; slot_number++) { if (free_slots[slot_number]) { - char* slot_address = - memory::RemaskPtr(slot_span_base + (slot_size * slot_number)); - auto* entry = new (slot_address) PartitionFreelistEntry(); + uintptr_t slot_address = + memory::RemaskPtr(slot_span_start + (slot_size * slot_number)); + auto* entry = new (reinterpret_cast<void*>(slot_address)) + PartitionFreelistEntry(); if (!head) head = entry;
diff --git a/base/allocator/partition_allocator/partition_page.h b/base/allocator/partition_allocator/partition_page.h index ce6f5b4..3b130e9 100644 --- a/base/allocator/partition_allocator/partition_page.h +++ b/base/allocator/partition_allocator/partition_page.h
@@ -188,16 +188,13 @@ // span, and potentially shrinking the ring. void RegisterEmpty(); - // Pointer manipulation functions. These must be static as the input + // Pointer/address manipulation functions. These must be static as the input // |slot_span| pointer may be the result of an offset calculation and // therefore cannot be trusted. The objective of these functions is to // sanitize this input. - // TODO(bartekn): void* -> uintptr_t - ALWAYS_INLINE static void* ToSlotSpanStartPtr( + ALWAYS_INLINE static uintptr_t ToSlotSpanStart( const SlotSpanMetadata* slot_span); - // TODO(bartekn): Remove the void* version. Drop Ptr from the name. - ALWAYS_INLINE static SlotSpanMetadata* FromSlotStartPtr(void* slot_start); - ALWAYS_INLINE static SlotSpanMetadata* FromSlotStartPtr(uintptr_t slot_start); + ALWAYS_INLINE static SlotSpanMetadata* FromSlotStart(uintptr_t slot_start); ALWAYS_INLINE static SlotSpanMetadata* FromSlotInnerPtr(void* ptr); ALWAYS_INLINE PartitionSuperPageExtentEntry<thread_safe>* ToSuperPageExtent() @@ -358,9 +355,6 @@ uint8_t unused; ALWAYS_INLINE static PartitionPage* FromPtr(void* slot_start); - - private: - ALWAYS_INLINE static void* ToSlotSpanStartPtr(const PartitionPage* page); }; static_assert(sizeof(PartitionPage<ThreadSafe>) == kPageMetadataSize, @@ -475,18 +469,6 @@ return address >= payload_start && address < payload_end; } -// Converts from a pointer to the PartitionPage object (within super pages's -// metadata) into a pointer to the beginning of the slot span. -// |page| must be the first PartitionPage of the slot span. -template <bool thread_safe> -ALWAYS_INLINE void* PartitionPage<thread_safe>::ToSlotSpanStartPtr( - const PartitionPage* page) { - PA_DCHECK(page->is_valid); - PA_DCHECK(!page->slot_span_metadata_offset); - return SlotSpanMetadata<thread_safe>::ToSlotSpanStartPtr( - &page->slot_span_metadata); -} - // Converts from a pointer inside a super page into a pointer to the // PartitionPage object (within super pages's metadata) that describes the // partition page where |ptr| is located. |ptr| doesn't have to be located @@ -497,7 +479,7 @@ // care has to be taken with direct maps that span multiple super pages. This // function's behavior is undefined if |ptr| lies in a subsequent super page. // -// TODO(bartekn): void* -> uintptr_t, Ptr -> Addr +// TODO(bartekn): Consider void* -> uintptr_t, Ptr -> Addr template <bool thread_safe> ALWAYS_INLINE PartitionPage<thread_safe>* PartitionPage<thread_safe>::FromPtr( void* ptr) { @@ -530,10 +512,8 @@ // Converts from a pointer to the SlotSpanMetadata object (within a super // pages's metadata) into a pointer to the beginning of the slot span. This // works on direct maps too. -// -// TODO(bartekn): void* -> uintptr_t, Ptr -> Addr template <bool thread_safe> -ALWAYS_INLINE void* SlotSpanMetadata<thread_safe>::ToSlotSpanStartPtr( +ALWAYS_INLINE uintptr_t SlotSpanMetadata<thread_safe>::ToSlotSpanStart( const SlotSpanMetadata* slot_span) { uintptr_t pointer_as_uint = reinterpret_cast<uintptr_t>(slot_span); uintptr_t super_page_offset = (pointer_as_uint & kSuperPageOffsetMask); @@ -553,9 +533,7 @@ PA_DCHECK(partition_page_index); PA_DCHECK(partition_page_index < NumPartitionPagesPerSuperPage() - 1); uintptr_t super_page_base = (pointer_as_uint & kSuperPageBaseMask); - void* ret = reinterpret_cast<void*>( - super_page_base + (partition_page_index << PartitionPageShift())); - return ret; + return super_page_base + (partition_page_index << PartitionPageShift()); } // Converts from a pointer inside a slot into a pointer to the SlotSpanMetadata @@ -565,7 +543,7 @@ // CAUTION! For direct-mapped allocation, |ptr| has to be within the first // partition page. // -// TODO(bartekn): void* -> uintptr_t, Ptr -> Addr +// TODO(bartekn): Consider void* -> uintptr_t, Ptr -> Addr template <bool thread_safe> ALWAYS_INLINE SlotSpanMetadata<thread_safe>* SlotSpanMetadata<thread_safe>::FromSlotInnerPtr(void* ptr) { @@ -595,25 +573,19 @@ // Like |FromSlotInnerPtr|, but asserts that pointer points to the beginning of // the slot. This works on direct maps too. -// -// TODO(bartekn): void* -> uintptr_t, Ptr -> Addr template <bool thread_safe> ALWAYS_INLINE SlotSpanMetadata<thread_safe>* -SlotSpanMetadata<thread_safe>::FromSlotStartPtr(void* slot_start) { - auto* slot_span = FromSlotInnerPtr(slot_start); +SlotSpanMetadata<thread_safe>::FromSlotStart(uintptr_t slot_start) { + auto* slot_span = FromSlotInnerPtr(reinterpret_cast<void*>(slot_start)); +#if DCHECK_IS_ON() // Checks that the pointer is a multiple of slot size. - auto* slot_span_start = ToSlotSpanStartPtr(slot_span); + uintptr_t slot_span_start = ToSlotSpanStart(slot_span); PA_DCHECK( - !((reinterpret_cast<uintptr_t>(memory::UnmaskPtr(slot_start)) - - reinterpret_cast<uintptr_t>(memory::UnmaskPtr(slot_span_start))) % + !((memory::UnmaskPtr(slot_start) - memory::UnmaskPtr(slot_span_start)) % slot_span->bucket->slot_size)); +#endif // DCHECK_IS_ON() return slot_span; } -template <bool thread_safe> -ALWAYS_INLINE SlotSpanMetadata<thread_safe>* -SlotSpanMetadata<thread_safe>::FromSlotStartPtr(uintptr_t slot_start) { - return FromSlotStartPtr(reinterpret_cast<void*>(slot_start)); -} template <bool thread_safe> ALWAYS_INLINE void SlotSpanMetadata<thread_safe>::SetRawSize(size_t raw_size) { @@ -707,11 +679,12 @@ size_t number_of_entries = 0; for (auto* entry = head; entry; entry = entry->GetNext(bucket->slot_size), ++number_of_entries) { - auto* unmasked_entry = reinterpret_cast<char*>(memory::UnmaskPtr(entry)); + uintptr_t unmasked_entry = + memory::UnmaskPtr(reinterpret_cast<uintptr_t>(entry)); // Check that all entries belong to this slot span. - PA_DCHECK(ToSlotSpanStartPtr(this) <= unmasked_entry); - PA_DCHECK(unmasked_entry < (static_cast<char*>(ToSlotSpanStartPtr(this)) + - bucket->get_bytes_per_span())); + PA_DCHECK(ToSlotSpanStart(this) <= unmasked_entry); + PA_DCHECK(unmasked_entry < + ToSlotSpanStart(this) + bucket->get_bytes_per_span()); } PA_DCHECK(number_of_entries == number_of_freed); }
diff --git a/base/allocator/partition_allocator/partition_root.cc b/base/allocator/partition_allocator/partition_root.cc index b58e5bb..3c25895 100644 --- a/base/allocator/partition_allocator/partition_root.cc +++ b/base/allocator/partition_allocator/partition_root.cc
@@ -199,12 +199,12 @@ RoundUpToSystemPage(slot_span->GetUtilizedSlotSize())); discardable_bytes = bucket->slot_size - utilized_slot_size; if (discardable_bytes && discard) { - char* ptr = reinterpret_cast<char*>( - internal::SlotSpanMetadata<thread_safe>::ToSlotSpanStartPtr( - slot_span)); - ptr += utilized_slot_size; + uintptr_t slot_span_start = + internal::SlotSpanMetadata<thread_safe>::ToSlotSpanStart(slot_span); + uintptr_t committed_data_end = slot_span_start + utilized_slot_size; ScopedSyscallTimer<thread_safe> timer{root}; - DiscardSystemPages(ptr, discardable_bytes); + DiscardSystemPages(reinterpret_cast<void*>(committed_data_end), + discardable_bytes); } return discardable_bytes; } @@ -233,15 +233,15 @@ size_t last_slot = static_cast<size_t>(-1); #endif memset(slot_usage, 1, num_slots); - char* ptr = reinterpret_cast<char*>( - internal::SlotSpanMetadata<thread_safe>::ToSlotSpanStartPtr(slot_span)); + uintptr_t slot_span_start = + SlotSpanMetadata<thread_safe>::ToSlotSpanStart(slot_span); // First, walk the freelist for this slot span and make a bitmap of which // slots are not in use. - for (internal::PartitionFreelistEntry* entry = slot_span->get_freelist_head(); - entry; + for (PartitionFreelistEntry* entry = slot_span->get_freelist_head(); entry; /**/) { size_t slot_index = - (reinterpret_cast<char*>(base::memory::UnmaskPtr(entry)) - ptr) / + (base::memory::UnmaskPtr(reinterpret_cast<uintptr_t>(entry)) - + slot_span_start) / slot_size; PA_DCHECK(slot_index < num_slots); slot_usage[slot_index] = 0; @@ -269,17 +269,15 @@ // discard anything unless the discard flag was passed in. if (truncated_slots) { size_t unprovisioned_bytes = 0; - char* begin_ptr = ptr + (num_slots * slot_size); - char* end_ptr = begin_ptr + (slot_size * truncated_slots); - begin_ptr = reinterpret_cast<char*>( - RoundUpToSystemPage(reinterpret_cast<size_t>(begin_ptr))); - // We round the end pointer here up and not down because we're at the end of + uintptr_t begin_addr = slot_span_start + (num_slots * slot_size); + uintptr_t end_addr = begin_addr + (slot_size * truncated_slots); + begin_addr = RoundUpToSystemPage(begin_addr); + // We round the end address here up and not down because we're at the end of // a slot span, so we "own" all the way up the page boundary. - end_ptr = reinterpret_cast<char*>( - RoundUpToSystemPage(reinterpret_cast<size_t>(end_ptr))); - PA_DCHECK(end_ptr <= ptr + bucket->get_bytes_per_span()); - if (begin_ptr < end_ptr) { - unprovisioned_bytes = end_ptr - begin_ptr; + end_addr = RoundUpToSystemPage(end_addr); + PA_DCHECK(end_addr <= slot_span_start + bucket->get_bytes_per_span()); + if (begin_addr < end_addr) { + unprovisioned_bytes = end_addr - begin_addr; discardable_bytes += unprovisioned_bytes; } if (unprovisioned_bytes && discard) { @@ -297,7 +295,8 @@ if (slot_usage[slot_index]) continue; - auto* entry = new (ptr + (slot_size * slot_index)) + auto* entry = new ( + reinterpret_cast<void*>(slot_span_start + (slot_size * slot_index))) internal::PartitionFreelistEntry(); if (!head) { head = entry; @@ -317,7 +316,8 @@ PA_DCHECK(num_new_entries == num_slots - slot_span->num_allocated_slots); // Discard the memory. ScopedSyscallTimer<thread_safe> timer{root}; - DiscardSystemPages(begin_ptr, unprovisioned_bytes); + DiscardSystemPages(reinterpret_cast<void*>(begin_addr), + unprovisioned_bytes); } } @@ -330,24 +330,23 @@ // The first address we can safely discard is just after the freelist // pointer. There's one quirk: if the freelist pointer is actually nullptr, // we can discard that pointer value too. - char* begin_ptr = ptr + (i * slot_size); - char* end_ptr = begin_ptr + slot_size; + uintptr_t begin_addr = slot_span_start + (i * slot_size); + uintptr_t end_addr = begin_addr + slot_size; #if !BUILDFLAG(IS_WIN) if (i != last_slot) - begin_ptr += sizeof(internal::PartitionFreelistEntry); + begin_addr += sizeof(internal::PartitionFreelistEntry); #else - begin_ptr += sizeof(internal::PartitionFreelistEntry); + begin_addr += sizeof(internal::PartitionFreelistEntry); #endif - begin_ptr = reinterpret_cast<char*>( - RoundUpToSystemPage(reinterpret_cast<size_t>(begin_ptr))); - end_ptr = reinterpret_cast<char*>( - RoundDownToSystemPage(reinterpret_cast<size_t>(end_ptr))); - if (begin_ptr < end_ptr) { - size_t partial_slot_bytes = end_ptr - begin_ptr; + begin_addr = RoundUpToSystemPage(begin_addr); + end_addr = RoundDownToSystemPage(end_addr); + if (begin_addr < end_addr) { + size_t partial_slot_bytes = end_addr - begin_addr; discardable_bytes += partial_slot_bytes; if (discard) { ScopedSyscallTimer<thread_safe> timer{root}; - DiscardSystemPages(begin_ptr, partial_slot_bytes); + DiscardSystemPages(reinterpret_cast<void*>(begin_addr), + partial_slot_bytes); } } } @@ -737,8 +736,7 @@ // bucket->slot_size is the currently committed size of the allocation. size_t current_slot_size = slot_span->bucket->slot_size; - uintptr_t slot_start = - reinterpret_cast<uintptr_t>(SlotSpan::ToSlotSpanStartPtr(slot_span)); + uintptr_t slot_start = SlotSpan::ToSlotSpanStart(slot_span); // This is the available part of the reservation up to which the new // allocation can grow. size_t available_reservation_size =
diff --git a/base/allocator/partition_allocator/partition_root.h b/base/allocator/partition_allocator/partition_root.h index 4e081fa..1490ba0 100644 --- a/base/allocator/partition_allocator/partition_root.h +++ b/base/allocator/partition_allocator/partition_root.h
@@ -355,12 +355,12 @@ ALWAYS_INLINE static PartitionRoot* FromSlotSpan(SlotSpan* slot_span); // These two functions work unconditionally for normal buckets. // For direct map, they only work for the first super page of a reservation, - // that is the first "2MiB minus a bit" (see partition_alloc_constants.h for - // the direct map allocation layout). + // (see partition_alloc_constants.h for the direct map allocation layout). // In particular, the functions always work for a pointer to the start of a // reservation. ALWAYS_INLINE static PartitionRoot* FromFirstSuperPage(uintptr_t super_page); - ALWAYS_INLINE static PartitionRoot* FromPointerInFirstSuperpage(char* ptr); + ALWAYS_INLINE static PartitionRoot* FromAddrInFirstSuperpage( + uintptr_t address); ALWAYS_INLINE void IncreaseCommittedPages(size_t len); ALWAYS_INLINE void DecreaseCommittedPages(size_t len); @@ -785,19 +785,18 @@ auto* page = first_page + first_page->slot_span_metadata_offset; PA_DCHECK(page->is_valid); PA_DCHECK(!page->slot_span_metadata_offset); - auto* ret = SlotSpanMetadata<ThreadSafe>::ToSlotSpanStartPtr( - &page->slot_span_metadata); + uintptr_t slot_start = + SlotSpanMetadata<ThreadSafe>::ToSlotSpanStart(&page->slot_span_metadata); #if DCHECK_IS_ON() auto* metadata = reinterpret_cast<PartitionDirectMapMetadata<ThreadSafe>*>(page); size_t padding_for_alignment = metadata->direct_map_extent.padding_for_alignment; PA_DCHECK(padding_for_alignment == (page - first_page) * PartitionPageSize()); - PA_DCHECK(ret == - reinterpret_cast<void*>(reservation_start + PartitionPageSize() + - padding_for_alignment)); -#endif // DCHECK_IS_ON() - return reinterpret_cast<uintptr_t>(ret); // TODO(bartekn): Remove cast. + PA_DCHECK(slot_start == + reservation_start + PartitionPageSize() + padding_for_alignment); +#endif // DCHECK_IS_ON() + return slot_start; } // Gets the pointer to the beginning of the allocated slot. @@ -826,17 +825,14 @@ PartitionAllocGetDirectMapSlotStartInBRPPool(address); if (UNLIKELY(directmap_slot_start)) return directmap_slot_start; - auto* slot_span = - internal::PartitionAllocGetSlotSpanForSizeQuery<internal::ThreadSafe>( - address); - auto* root = PartitionRoot<internal::ThreadSafe>::FromSlotSpan(slot_span); + auto* slot_span = PartitionAllocGetSlotSpanForSizeQuery<ThreadSafe>(address); + auto* root = PartitionRoot<ThreadSafe>::FromSlotSpan(slot_span); // Double check that ref-count is indeed present. PA_DCHECK(root->brp_enabled()); // Get the offset from the beginning of the slot span. - uintptr_t slot_span_start = reinterpret_cast<uintptr_t>( - internal::SlotSpanMetadata<internal::ThreadSafe>::ToSlotSpanStartPtr( - slot_span)); + uintptr_t slot_span_start = + SlotSpanMetadata<ThreadSafe>::ToSlotSpanStart(slot_span); PA_DCHECK(slot_span_start == memory::UnmaskPtr(slot_span_start)); size_t offset_in_slot_span = address - slot_span_start; @@ -891,7 +887,7 @@ ALWAYS_INLINE void PartitionAllocFreeForRefCounting(uintptr_t slot_start) { PA_DCHECK(!internal::PartitionRefCountPointer(slot_start)->IsAlive()); - auto* slot_span = SlotSpanMetadata<ThreadSafe>::FromSlotStartPtr(slot_start); + auto* slot_span = SlotSpanMetadata<ThreadSafe>::FromSlotStart(slot_start); auto* root = PartitionRoot<ThreadSafe>::FromSlotSpan(slot_span); // PartitionRefCount is required to be allocated inside a `PartitionRoot` that // supports reference counts. @@ -966,7 +962,7 @@ if (UNLIKELY(!slot_start)) return 0; - slot_span = SlotSpan::FromSlotStartPtr(slot_start); + slot_span = SlotSpan::FromSlotStart(slot_start); // TODO(crbug.com/1257655): See if we can afford to make this a CHECK. PA_DCHECK(IsValidSlotSpan(slot_span)); // For direct mapped allocations, |bucket| is the sentinel. @@ -1029,7 +1025,7 @@ #if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && \ ((BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_CHROMECAST)) || \ (BUILDFLAG(IS_LINUX) && defined(ARCH_CPU_64_BITS))) - PA_CHECK(IsManagedByPartitionAlloc(reinterpret_cast<uintptr_t>(ptr))); + PA_CHECK(IsManagedByPartitionAlloc(address)); #endif // Fetch the root from the pointer, and not the SlotSpan. This is important, @@ -1038,12 +1034,12 @@ // traffic (since they're read on every free(), and written to on any // malloc()/free() that is not a hit in the thread cache). This way we change // the critical path from ptr -> slot_span -> root into two *parallel* ones: - // 1. ptr -> root + // 1. address -> root // 2. ptr -> slot_span - auto* root = FromPointerInFirstSuperpage(reinterpret_cast<char*>(ptr)); + auto* root = FromAddrInFirstSuperpage(address); - // Call FromSlotInnerPtr instead of FromSlotStartPtr because the pointer - // hasn't been adjusted yet. + // Call FromSlotInnerPtr instead of FromSlotStart because the pointer hasn't + // been adjusted yet. SlotSpan* slot_span = SlotSpan::FromSlotInnerPtr(ptr); // We are going to read from |*slot_span| in all branches. Since // |FromSlotSpan()| below doesn't touch *slot_span, there is some time for the @@ -1199,7 +1195,7 @@ template <bool thread_safe> ALWAYS_INLINE void PartitionRoot<thread_safe>::RawFree(uintptr_t slot_start) { - SlotSpan* slot_span = SlotSpan::FromSlotStartPtr(slot_start); + SlotSpan* slot_span = SlotSpan::FromSlotStart(slot_start); RawFree(slot_start, slot_span); } @@ -1289,7 +1285,7 @@ template <bool thread_safe> ALWAYS_INLINE void PartitionRoot<thread_safe>::RawFreeLocked( uintptr_t slot_start) { - SlotSpan* slot_span = SlotSpan::FromSlotStartPtr(slot_start); + SlotSpan* slot_span = SlotSpan::FromSlotStart(slot_start); // Direct-mapped deallocation releases then re-acquires the lock. The caller // may not expect that, but we never call this function on direct-mapped // allocations. @@ -1325,11 +1321,10 @@ return root; } -// TODO(bartekn): char* -> uintptr_t, Pointer -> Addr template <bool thread_safe> ALWAYS_INLINE PartitionRoot<thread_safe>* -PartitionRoot<thread_safe>::FromPointerInFirstSuperpage(char* ptr) { - uintptr_t super_page = reinterpret_cast<uintptr_t>(ptr) & kSuperPageBaseMask; +PartitionRoot<thread_safe>::FromAddrInFirstSuperpage(uintptr_t address) { + uintptr_t super_page = address & kSuperPageBaseMask; PA_DCHECK(internal::IsReservationStart(super_page)); return FromFirstSuperPage(super_page); } @@ -1572,7 +1567,7 @@ #if DCHECK_IS_ON() // Make sure that the allocated pointer comes from the same place it would // for a non-thread cache allocation. - SlotSpan* slot_span = SlotSpan::FromSlotStartPtr(slot_start); + SlotSpan* slot_span = SlotSpan::FromSlotStart(slot_start); PA_DCHECK(IsValidSlotSpan(slot_span)); PA_DCHECK(slot_span->bucket == &bucket_at(bucket_index)); PA_DCHECK(slot_span->bucket->slot_size == slot_size);
diff --git a/base/allocator/partition_allocator/starscan/pcscan_internal.cc b/base/allocator/partition_allocator/starscan/pcscan_internal.cc index 185d9ad..b89d1e6c 100644 --- a/base/allocator/partition_allocator/starscan/pcscan_internal.cc +++ b/base/allocator/partition_allocator/starscan/pcscan_internal.cc
@@ -242,8 +242,8 @@ if (!slot_span->bucket) return {}; PA_SCAN_DCHECK(PartitionRoot<ThreadSafe>::IsValidSlotSpan(slot_span)); - const uintptr_t slot_span_start = reinterpret_cast<uintptr_t>( - SlotSpanMetadata<ThreadSafe>::ToSlotSpanStartPtr(slot_span)); + const uintptr_t slot_span_start = + SlotSpanMetadata<ThreadSafe>::ToSlotSpanStart(slot_span); const ptrdiff_t ptr_offset = maybe_inner_address - slot_span_start; PA_SCAN_DCHECK(0 <= ptr_offset && ptr_offset < static_cast<ptrdiff_t>( @@ -434,8 +434,7 @@ IterateNonEmptySlotSpans( super_page, nonempty_slot_spans, [this, ¤t](SlotSpan* slot_span) { - const uintptr_t payload_begin = reinterpret_cast<uintptr_t>( - SlotSpan::ToSlotSpanStartPtr(slot_span)); + const uintptr_t payload_begin = SlotSpan::ToSlotSpanStart(slot_span); // For single-slot slot-spans, scan only utilized slot part. const size_t provisioned_size = UNLIKELY(slot_span->CanStoreRawSize()) ? slot_span->GetRawSize() @@ -674,8 +673,7 @@ #if !PA_STARSCAN_USE_CARD_TABLE // Pointer from a normal bucket is always in the first superpage. - auto* root = - Root::FromPointerInFirstSuperpage(reinterpret_cast<char*>(maybe_ptr)); + auto* root = Root::FromAddrInFirstSuperpage(maybe_ptr); // Without the card table, we must make sure that |maybe_ptr| doesn't point to // metadata partition. // TODO(bikineev): To speed things up, consider removing the check and @@ -1016,8 +1014,8 @@ size_t freelist_entries = 0; const auto bitmap_iterator = [&](uintptr_t address) { + SlotSpan* current_slot_span = SlotSpan::FromSlotStart(address); auto* ptr = reinterpret_cast<void*>(memory::RemaskPtr(address)); - SlotSpan* current_slot_span = SlotSpan::FromSlotStartPtr(ptr); auto* entry = new (ptr) PartitionFreelistEntry(); if (current_slot_span != previous_slot_span) {
diff --git a/base/allocator/partition_allocator/starscan/pcscan_unittest.cc b/base/allocator/partition_allocator/starscan/pcscan_unittest.cc index f970d0b..eefcacd 100644 --- a/base/allocator/partition_allocator/starscan/pcscan_unittest.cc +++ b/base/allocator/partition_allocator/starscan/pcscan_unittest.cc
@@ -150,11 +150,10 @@ last = root.AdjustPointerForExtrasSubtract(ptr); } - EXPECT_EQ(SlotSpan::FromSlotStartPtr(first), - SlotSpan::FromSlotStartPtr(last)); + EXPECT_EQ(SlotSpan::FromSlotStart(first), SlotSpan::FromSlotStart(last)); if (bucket.num_system_pages_per_slot_span == NumSystemPagesPerPartitionPage()) - PA_EXPECT_PTR_EQ(reinterpret_cast<size_t>(first) & PartitionPageBaseMask(), - reinterpret_cast<size_t>(last) & PartitionPageBaseMask()); + PA_EXPECT_PTR_EQ(first & PartitionPageBaseMask(), + last & PartitionPageBaseMask()); EXPECT_EQ(num_slots, bucket.active_slot_spans_head->num_allocated_slots); EXPECT_EQ(nullptr, bucket.active_slot_spans_head->get_freelist_head()); EXPECT_TRUE(bucket.is_valid()); @@ -167,7 +166,7 @@ bool IsInFreeList(uintptr_t slot_start) { slot_start = memory::RemaskPtr(slot_start); - auto* slot_span = SlotSpan::FromSlotStartPtr(slot_start); + auto* slot_span = SlotSpan::FromSlotStart(slot_start); for (auto* entry = slot_span->get_freelist_head(); entry; entry = entry->GetNext(slot_span->bucket->slot_size)) { if (reinterpret_cast<uintptr_t>(entry) == slot_start) @@ -244,8 +243,8 @@ void TestDanglingReference(PartitionAllocPCScanTest& test, SourceList* source, ValueList* value) { - auto* value_root = ThreadSafePartitionRoot::FromPointerInFirstSuperpage( - reinterpret_cast<char*>(value)); + auto* value_root = ThreadSafePartitionRoot::FromAddrInFirstSuperpage( + reinterpret_cast<uintptr_t>(value)); { // Free |value| and leave the dangling reference in |source|. ValueList::Destroy(*value_root, value); @@ -272,8 +271,8 @@ void TestDanglingReferenceNotVisited(PartitionAllocPCScanTest& test, void* value) { - auto* value_root = ThreadSafePartitionRoot::FromPointerInFirstSuperpage( - reinterpret_cast<char*>(value)); + auto* value_root = ThreadSafePartitionRoot::FromAddrInFirstSuperpage( + reinterpret_cast<uintptr_t>(value)); value_root->Free(value); // Check that |value| is in the quarantine now. EXPECT_TRUE(test.IsInQuarantine(value)); @@ -325,25 +324,24 @@ // Double check the setup -- make sure that exactly two slot spans were // allocated, within the same super page, with a gap in between. { - auto* value_root = ThreadSafePartitionRoot::FromPointerInFirstSuperpage( - reinterpret_cast<char*>(value)); + auto* value_root = ThreadSafePartitionRoot::FromAddrInFirstSuperpage( + reinterpret_cast<uintptr_t>(value)); ::partition_alloc::ScopedGuard guard{value_root->lock_}; auto super_page = reinterpret_cast<uintptr_t>(value) & kSuperPageBaseMask; ASSERT_EQ(super_page, reinterpret_cast<uintptr_t>(source) & kSuperPageBaseMask); size_t i = 0; - void* first_slot_span_end = nullptr; - void* second_slot_span_start = nullptr; + uintptr_t first_slot_span_end = 0; + uintptr_t second_slot_span_start = 0; IterateSlotSpans<ThreadSafe>( super_page, true, [&](SlotSpan* slot_span) -> bool { if (i == 0) { - first_slot_span_end = reinterpret_cast<char*>( - SlotSpan::ToSlotSpanStartPtr(slot_span)) + + first_slot_span_end = SlotSpan::ToSlotSpanStart(slot_span) + slot_span->bucket->get_pages_per_slot_span() * PartitionPageSize(); } else { - second_slot_span_start = SlotSpan::ToSlotSpanStartPtr(slot_span); + second_slot_span_start = SlotSpan::ToSlotSpanStart(slot_span); } ++i; return false; @@ -586,8 +584,8 @@ void TestDanglingReferenceWithSafepoint(PartitionAllocPCScanTest& test, SourceList* source, ValueList* value) { - auto* value_root = ThreadSafePartitionRoot::FromPointerInFirstSuperpage( - reinterpret_cast<char*>(value)); + auto* value_root = ThreadSafePartitionRoot::FromAddrInFirstSuperpage( + reinterpret_cast<uintptr_t>(value)); { // Free |value| and leave the dangling reference in |source|. ValueList::Destroy(*value_root, value);
diff --git a/base/atomicops.h b/base/atomicops.h index 4a30aac..f359ae5 100644 --- a/base/atomicops.h +++ b/base/atomicops.h
@@ -46,7 +46,7 @@ #ifdef ARCH_CPU_64_BITS // We need to be able to go between Atomic64 and AtomicWord implicitly. This // means Atomic64 and AtomicWord should be the same type on 64-bit. -#if defined(__ILP32__) || defined(OS_NACL) +#if defined(__ILP32__) || BUILDFLAG(IS_NACL) // NaCl's intptr_t is not actually 64-bits on 64-bit! // http://code.google.com/p/nativeclient/issues/detail?id=1162 typedef int64_t Atomic64; @@ -133,7 +133,7 @@ // On some platforms we need additional declarations to make // AtomicWord compatible with our other Atomic* types. -#if defined(OS_APPLE) || defined(OS_OPENBSD) +#if BUILDFLAG(IS_APPLE) || BUILDFLAG(IS_OPENBSD) #include "base/atomicops_internals_atomicword_compat.h" #endif
diff --git a/base/base_paths.cc b/base/base_paths.cc index 8d5defd..d6da2d3f 100644 --- a/base/base_paths.cc +++ b/base/base_paths.cc
@@ -7,6 +7,7 @@ #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/path_service.h" +#include "build/build_config.h" namespace base { @@ -19,7 +20,7 @@ return false; *result = result->DirName(); return true; -#if !defined(OS_FUCHSIA) +#if !BUILDFLAG(IS_FUCHSIA) case DIR_MODULE: if (!PathService::Get(FILE_MODULE, result)) return false; @@ -27,18 +28,18 @@ return true; case DIR_ASSETS: return PathService::Get(DIR_MODULE, result); -#endif // !defined(OS_FUCHSIA) +#endif // !BUILDFLAG(IS_FUCHSIA) case DIR_TEMP: return GetTempDir(result); case DIR_HOME: *result = GetHomeDir(); return true; case DIR_GEN_TEST_DATA_ROOT: -#if !defined(OS_FUCHSIA) +#if !BUILDFLAG(IS_FUCHSIA) // On most platforms, all build output is in the same directory, so // use DIR_MODULE to get the path to the current binary. return PathService::Get(DIR_MODULE, result); -#endif // !defined(OS_FUCHSIA) +#endif // !BUILDFLAG(IS_FUCHSIA) case DIR_TEST_DATA: { FilePath test_data_path; if (!PathService::Get(DIR_SRC_TEST_DATA_ROOT, &test_data_path))
diff --git a/base/base_paths.h b/base/base_paths.h index dba3e81..3d59041 100644 --- a/base/base_paths.h +++ b/base/base_paths.h
@@ -10,15 +10,15 @@ #include "build/build_config.h" -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) #include "base/base_paths_win.h" -#elif defined(OS_APPLE) +#elif BUILDFLAG(IS_APPLE) #include "base/base_paths_mac.h" -#elif defined(OS_ANDROID) +#elif BUILDFLAG(IS_ANDROID) #include "base/base_paths_android.h" #endif -#if defined(OS_POSIX) +#if BUILDFLAG(IS_POSIX) #include "base/base_paths_posix.h" #endif @@ -29,7 +29,7 @@ // The following refer to the current application. FILE_EXE, // Path and filename of the current executable. -#if !defined(OS_FUCHSIA) +#if !BUILDFLAG(IS_FUCHSIA) // Prefer keys (e.g., DIR_ASSETS) that are specific to the use case as the // module location may not work as expected on some platforms. For this // reason, this key is not defined on Fuchsia. See crbug.com/1263691 for @@ -40,7 +40,7 @@ // example). #endif DIR_EXE, // Directory containing FILE_EXE. -#if !defined(OS_FUCHSIA) +#if !BUILDFLAG(IS_FUCHSIA) // Prefer keys (e.g., DIR_ASSETS) that are specific to the use case as the // module location may not work as expected on some platforms. For this // reason, this key is not defined on Fuchsia. See crbug.com/1263691 for
diff --git a/base/base_paths_mac.mm b/base/base_paths_mac.mm index 4eabb96..30b7cd7 100644 --- a/base/base_paths_mac.mm +++ b/base/base_paths_mac.mm
@@ -74,15 +74,15 @@ case base::DIR_APP_DATA: { bool success = base::mac::GetUserDirectory(NSApplicationSupportDirectory, result); -#if defined(OS_IOS) +#if BUILDFLAG(IS_IOS) // On IOS, this directory does not exist unless it is created explicitly. if (success && !base::PathExists(*result)) success = base::CreateDirectory(*result); -#endif // defined(OS_IOS) +#endif // BUILDFLAG(IS_IOS) return success; } case base::DIR_SRC_TEST_DATA_ROOT: -#if defined(OS_IOS) +#if BUILDFLAG(IS_IOS) // On iOS, there is no access to source root, however, the necessary // resources are packaged into the test as assets. return PathService::Get(base::DIR_ASSETS, result); @@ -105,9 +105,9 @@ *result = result->DirName().DirName(); } return true; -#endif // !defined(OS_IOS) +#endif // BUILDFLAG(IS_IOS) case base::DIR_USER_DESKTOP: -#if defined(OS_IOS) +#if BUILDFLAG(IS_IOS) // iOS does not have desktop directories. NOTIMPLEMENTED(); return false; @@ -115,7 +115,7 @@ return base::mac::GetUserDirectory(NSDesktopDirectory, result); #endif case base::DIR_ASSETS: -#if defined(OS_IOS) +#if BUILDFLAG(IS_IOS) // On iOS, the assets are located next to the module binary. return PathService::Get(base::DIR_MODULE, result); #else @@ -125,7 +125,7 @@ *result = base::mac::FrameworkBundlePath().Append( FILE_PATH_LITERAL("Resources")); return true; -#endif // !defined(OS_IOS) +#endif // BUILDFLAG(IS_IOS) case base::DIR_CACHE: return base::mac::GetUserDirectory(NSCachesDirectory, result); default:
diff --git a/base/base_paths_posix.cc b/base/base_paths_posix.cc index dbbbf29..13ee5536 100644 --- a/base/base_paths_posix.cc +++ b/base/base_paths_posix.cc
@@ -25,10 +25,10 @@ #include "base/process/process_metrics.h" #include "build/build_config.h" -#if defined(OS_FREEBSD) +#if BUILDFLAG(IS_FREEBSD) #include <sys/param.h> #include <sys/sysctl.h> -#elif defined(OS_SOLARIS) || defined(OS_AIX) +#elif BUILDFLAG(IS_SOLARIS) || BUILDFLAG(IS_AIX) #include <stdlib.h> #endif @@ -38,7 +38,7 @@ switch (key) { case FILE_EXE: case FILE_MODULE: { // TODO(evanm): is this correct? -#if defined(OS_LINUX) || defined(OS_CHROMEOS) +#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) FilePath bin_dir; if (!ReadSymbolicLink(FilePath(kProcSelfExe), &bin_dir)) { NOTREACHED() << "Unable to resolve " << kProcSelfExe << "."; @@ -46,7 +46,7 @@ } *result = bin_dir; return true; -#elif defined(OS_FREEBSD) +#elif BUILDFLAG(IS_FREEBSD) int name[] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1 }; char bin_dir[PATH_MAX + 1]; size_t length = sizeof(bin_dir); @@ -59,7 +59,7 @@ } *result = FilePath(FilePath::StringType(bin_dir, length - 1)); return true; -#elif defined(OS_SOLARIS) +#elif BUILDFLAG(IS_SOLARIS) char bin_dir[PATH_MAX + 1]; if (realpath(getexecname(), bin_dir) == NULL) { NOTREACHED() << "Unable to resolve " << getexecname() << "."; @@ -67,7 +67,7 @@ } *result = FilePath(bin_dir); return true; -#elif defined(OS_OPENBSD) || defined(OS_AIX) +#elif BUILDFLAG(IS_OPENBSD) || BUILDFLAG(IS_AIX) // There is currently no way to get the executable path on OpenBSD char* cpath; if ((cpath = getenv("CHROME_EXE_PATH")) != NULL)
diff --git a/base/base_switches.cc b/base/base_switches.cc index 6972215..d2e03df 100644 --- a/base/base_switches.cc +++ b/base/base_switches.cc
@@ -124,7 +124,7 @@ // Will wait for 60 seconds for a debugger to come to attach to the process. const char kWaitForDebugger[] = "wait-for-debugger"; -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) // Disable high-resolution timer on Windows. const char kDisableHighResTimer[] = "disable-highres-timer"; @@ -134,7 +134,7 @@ // TODO(crbug.com/1052397): Revisit the macro expression once build flag switch // of lacros-chrome is complete. -#if defined(OS_LINUX) && !BUILDFLAG(IS_CHROMEOS_ASH) && \ +#if BUILDFLAG(IS_LINUX) && !BUILDFLAG(IS_CHROMEOS_ASH) && \ !BUILDFLAG(IS_CHROMEOS_LACROS) // The /dev/shm partition is too small in certain VM environments, causing // Chrome to fail or crash (see http://crbug.com/715363). Use this flag to @@ -143,14 +143,14 @@ const char kDisableDevShmUsage[] = "disable-dev-shm-usage"; #endif -#if defined(OS_POSIX) +#if BUILDFLAG(IS_POSIX) // Used for turning on Breakpad crash reporting in a debug environment where // crash reporting is typically compiled but disabled. const char kEnableCrashReporterForTesting[] = "enable-crash-reporter-for-testing"; #endif -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) // Enables the reached code profiler that samples all threads in all processes // to determine which functions are almost never executed. const char kEnableReachedCodeProfiler[] = "enable-reached-code-profiler"; @@ -170,7 +170,7 @@ #endif -#if defined(OS_LINUX) || defined(OS_CHROMEOS) +#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) // Controls whether or not retired instruction counts are surfaced for threads // in trace events on Linux. //
diff --git a/base/base_switches.h b/base/base_switches.h index 2285b89..8bfe4c6 100644 --- a/base/base_switches.h +++ b/base/base_switches.h
@@ -36,23 +36,23 @@ extern const char kVModule[]; extern const char kWaitForDebugger[]; -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) extern const char kDisableHighResTimer[]; extern const char kDisableUsbKeyboardDetect[]; #endif // TODO(crbug.com/1052397): Revisit the macro expression once build flag switch // of lacros-chrome is complete. -#if defined(OS_LINUX) && !BUILDFLAG(IS_CHROMEOS_ASH) && \ +#if BUILDFLAG(IS_LINUX) && !BUILDFLAG(IS_CHROMEOS_ASH) && \ !BUILDFLAG(IS_CHROMEOS_LACROS) extern const char kDisableDevShmUsage[]; #endif -#if defined(OS_POSIX) +#if BUILDFLAG(IS_POSIX) extern const char kEnableCrashReporterForTesting[]; #endif -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) extern const char kEnableReachedCodeProfiler[]; extern const char kReachedCodeSamplingIntervalUs[]; extern const char kDefaultCountryCodeAtInstall[]; @@ -60,7 +60,7 @@ extern const char kForceFieldTrialParams[]; #endif -#if defined(OS_LINUX) || defined(OS_CHROMEOS) +#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) extern const char kEnableThreadInstructionCount[]; // TODO(crbug.com/1176772): Remove kEnableCrashpad and IsCrashpadEnabled() when
diff --git a/base/bind.h b/base/bind.h index fae8cdd..5b42a2d8 100644 --- a/base/bind.h +++ b/base/bind.h
@@ -16,7 +16,7 @@ #include "base/template_util.h" #include "build/build_config.h" -#if defined(OS_APPLE) && !HAS_FEATURE(objc_arc) +#if BUILDFLAG(IS_APPLE) && !HAS_FEATURE(objc_arc) #include "base/mac/scoped_block.h" #endif @@ -302,7 +302,7 @@ return internal::IgnoreResultHelper<T>(std::move(data)); } -#if defined(OS_APPLE) && !HAS_FEATURE(objc_arc) +#if BUILDFLAG(IS_APPLE) && !HAS_FEATURE(objc_arc) // RetainBlock() is used to adapt an Objective-C block when Automated Reference // Counting (ARC) is disabled. This is unnecessary when ARC is enabled, as the @@ -320,7 +320,7 @@ base::scoped_policy::RETAIN); } -#endif // defined(OS_APPLE) && !HAS_FEATURE(objc_arc) +#endif // BUILDFLAG(IS_APPLE) && !HAS_FEATURE(objc_arc) } // namespace base
diff --git a/base/bind_internal.h b/base/bind_internal.h index 45b9c6f..772a5441 100644 --- a/base/bind_internal.h +++ b/base/bind_internal.h
@@ -25,7 +25,7 @@ #include "base/template_util.h" #include "build/build_config.h" -#if defined(OS_APPLE) && !HAS_FEATURE(objc_arc) +#if BUILDFLAG(IS_APPLE) && !HAS_FEATURE(objc_arc) #include "base/mac/scoped_block.h" #endif @@ -56,7 +56,7 @@ // BindState<> -- Stores the curried parameters, and is the main entry point // into the Bind() system. -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) namespace Microsoft { namespace WRL { template <typename> @@ -431,7 +431,7 @@ } }; -#if defined(OS_WIN) && !defined(ARCH_CPU_64_BITS) +#if BUILDFLAG(IS_WIN) && !defined(ARCH_CPU_64_BITS) // For functions. template <typename R, typename... Args> @@ -461,9 +461,9 @@ } }; -#endif // defined(OS_WIN) && !defined(ARCH_CPU_64_BITS) +#endif // BUILDFLAG(IS_WIN) && !defined(ARCH_CPU_64_BITS) -#if defined(OS_APPLE) +#if BUILDFLAG(IS_APPLE) // Support for Objective-C blocks. There are two implementation depending // on whether Automated Reference Counting (ARC) is enabled. When ARC is @@ -518,7 +518,7 @@ }; #endif // HAS_FEATURE(objc_arc) -#endif // defined(OS_APPLE) +#endif // BUILDFLAG(IS_APPLE) // For methods. template <typename R, typename Receiver, typename... Args> @@ -552,7 +552,7 @@ } }; -#if defined(OS_WIN) && !defined(ARCH_CPU_64_BITS) +#if BUILDFLAG(IS_WIN) && !defined(ARCH_CPU_64_BITS) // For __stdcall methods. template <typename R, typename Receiver, typename... Args> @@ -586,7 +586,7 @@ } }; -#endif // defined(OS_WIN) && !defined(ARCH_CPU_64_BITS) +#endif // BUILDFLAG(IS_WIN) && !defined(ARCH_CPU_64_BITS) #ifdef __cpp_noexcept_function_type // noexcept makes a distinct function type in C++17. @@ -1378,7 +1378,7 @@ static T Unwrap(const internal::PassedWrapper<T>& o) { return o.Take(); } }; -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) template <typename T> struct BindUnwrapTraits<Microsoft::WRL::ComPtr<T>> { static T* Unwrap(const Microsoft::WRL::ComPtr<T>& ptr) { return ptr.Get(); }
diff --git a/base/bind_unittest.cc b/base/bind_unittest.cc index dbf6f79..a5f681fe 100644 --- a/base/bind_unittest.cc +++ b/base/bind_unittest.cc
@@ -1624,7 +1624,7 @@ // // TODO(ajwong): Is there actually a way to test this? -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) int __fastcall FastCallFunc(int n) { return n; }
diff --git a/base/check.cc b/base/check.cc index 69c48b4..bcc48b1 100644 --- a/base/check.cc +++ b/base/check.cc
@@ -4,6 +4,8 @@ #include "base/check.h" +#include "build/build_config.h" + // check.h is a widely included header and its size has significant impact on // build time. Try not to raise this limit unless absolutely necessary. See // https://chromium.googlesource.com/chromium/src/+/HEAD/docs/wmax_tokens.md @@ -57,10 +59,10 @@ int line, const char* condition) { SystemErrorCode err_code = logging::GetLastSystemErrorCode(); -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) CheckError check_error( new Win32ErrorLogMessage(file, line, LOGGING_FATAL, err_code)); -#elif defined(OS_POSIX) || defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) CheckError check_error( new ErrnoLogMessage(file, line, LOGGING_FATAL, err_code)); #endif @@ -76,10 +78,10 @@ int line, const char* condition) { SystemErrorCode err_code = logging::GetLastSystemErrorCode(); -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) CheckError check_error( new Win32ErrorLogMessage(file, line, LOGGING_DCHECK, err_code)); -#elif defined(OS_POSIX) || defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) CheckError check_error( new ErrnoLogMessage(file, line, LOGGING_DCHECK, err_code)); #endif
diff --git a/base/check.h b/base/check.h index 8651247..6b4de3a 100644 --- a/base/check.h +++ b/base/check.h
@@ -108,6 +108,8 @@ #define CHECK(condition) \ UNLIKELY(!(condition)) ? IMMEDIATE_CRASH() : EAT_CHECK_STREAM_PARAMS() +#define CHECK_WILL_STREAM() false + #define PCHECK(condition) \ LAZY_CHECK_STREAM( \ ::logging::CheckError::PCheck(__FILE__, __LINE__).stream(), \ @@ -120,6 +122,8 @@ ::logging::CheckError::Check(__FILE__, __LINE__, #condition).stream(), \ !ANALYZER_ASSUME_TRUE(condition)) +#define CHECK_WILL_STREAM() true + #define PCHECK(condition) \ LAZY_CHECK_STREAM( \ ::logging::CheckError::PCheck(__FILE__, __LINE__, #condition).stream(), \
diff --git a/base/check_unittest.cc b/base/check_unittest.cc index 57f2c0c..03e399e 100644 --- a/base/check_unittest.cc +++ b/base/check_unittest.cc
@@ -9,6 +9,7 @@ #include "base/strings/string_piece.h" #include "base/test/gtest_util.h" #include "base/test/scoped_feature_list.h" +#include "build/build_config.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -196,7 +197,7 @@ #endif // defined(DCHECK_IS_CONFIGURABLE) // https://crbug.com/709067 tracks test flakiness on iOS. -#if defined(OS_IOS) +#if BUILDFLAG(IS_IOS) #define MAYBE_Dcheck DISABLED_Dcheck #else #define MAYBE_Dcheck Dcheck
diff --git a/base/command_line.cc b/base/command_line.cc index 0e98c3a9..8f26e95 100644 --- a/base/command_line.cc +++ b/base/command_line.cc
@@ -20,12 +20,12 @@ #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) #include <windows.h> #include <shellapi.h> #include "base/strings/string_util_win.h" -#endif // defined(OS_WIN) +#endif // BUILDFLAG(IS_WIN) namespace base { @@ -41,18 +41,18 @@ // Since we use a lazy match, make sure that longer versions (like "--") are // listed before shorter versions (like "-") of similar prefixes. -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) // By putting slash last, we can control whether it is treaded as a switch // value by changing the value of switch_prefix_count to be one less than // the array size. constexpr CommandLine::StringPieceType kSwitchPrefixes[] = {L"--", L"-", L"/"}; -#elif defined(OS_POSIX) || defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) // Unixes don't use slash as a switch. constexpr CommandLine::StringPieceType kSwitchPrefixes[] = {"--", "-"}; #endif size_t switch_prefix_count = base::size(kSwitchPrefixes); -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) // Switch string that specifies the single argument to the command line. // If present, everything after this switch is interpreted as a single // argument regardless of whitespace, quotes, etc. Used for launches from the @@ -61,7 +61,7 @@ // (https://crbug.com/937179). constexpr CommandLine::CharType kSingleArgument[] = FILE_PATH_LITERAL("single-argument"); -#endif // defined(OS_WIN) +#endif // BUILDFLAG(IS_WIN) size_t GetSwitchPrefixLength(CommandLine::StringPieceType string) { for (size_t i = 0; i < switch_prefix_count; ++i) { @@ -103,7 +103,7 @@ switch_key_without_prefix; } -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) // Quote a string as necessary for CommandLineToArgvW compatibility *on // Windows*. std::wstring QuoteForCommandLineToArgvW(const std::wstring& arg, @@ -154,7 +154,7 @@ return out; } -#endif // defined(OS_WIN) +#endif // BUILDFLAG(IS_WIN) } // namespace @@ -190,7 +190,7 @@ CommandLine::~CommandLine() = default; -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) // static void CommandLine::set_slash_is_not_a_switch() { // The last switch prefix should be slash, so adjust the size to skip it. @@ -209,7 +209,7 @@ argv_vector.push_back(UTF8ToWide(argv[i])); current_process_commandline_->InitFromArgv(argv_vector); } -#endif // defined(OS_WIN) +#endif // BUILDFLAG(IS_WIN) // static bool CommandLine::Init(int argc, const char* const* argv) { @@ -221,9 +221,9 @@ } current_process_commandline_ = new CommandLine(NO_PROGRAM); -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) current_process_commandline_->ParseFromString(::GetCommandLineW()); -#elif defined(OS_POSIX) || defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) current_process_commandline_->InitFromArgv(argc, argv); #else #error Unsupported platform @@ -250,14 +250,14 @@ return !!current_process_commandline_; } -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) // static CommandLine CommandLine::FromString(StringPieceType command_line) { CommandLine cmd(NO_PROGRAM); cmd.ParseFromString(command_line); return cmd; } -#endif // defined(OS_WIN) +#endif // BUILDFLAG(IS_WIN) void CommandLine::InitFromArgv(int argc, const CommandLine::CharType* const* argv) { @@ -280,9 +280,9 @@ } void CommandLine::SetProgram(const FilePath& program) { -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) argv_[0] = StringType(TrimWhitespace(program.value(), TRIM_ALL)); -#elif defined(OS_POSIX) || defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) TrimWhitespaceASCII(program.value(), TRIM_ALL, &argv_[0]); #else #error Unsupported platform @@ -300,17 +300,17 @@ std::string CommandLine::GetSwitchValueASCII(StringPiece switch_string) const { StringType value = GetSwitchValueNative(switch_string); -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) if (!IsStringASCII(base::AsStringPiece16(value))) { -#elif defined(OS_POSIX) || defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) if (!IsStringASCII(value)) { #endif DLOG(WARNING) << "Value of switch (" << switch_string << ") must be ASCII."; return std::string(); } -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) return WideToUTF8(value); -#elif defined(OS_POSIX) || defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) return value; #endif } @@ -337,10 +337,10 @@ void CommandLine::AppendSwitchNative(StringPiece switch_string, CommandLine::StringPieceType value) { -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) const std::string switch_key = ToLowerASCII(switch_string); StringType combined_switch_string(UTF8ToWide(switch_key)); -#elif defined(OS_POSIX) || defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) StringPiece switch_key = switch_string; StringType combined_switch_string(switch_key); #endif @@ -366,9 +366,9 @@ void CommandLine::AppendSwitchASCII(StringPiece switch_string, StringPiece value_string) { -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) AppendSwitchNative(switch_string, UTF8ToWide(value_string)); -#elif defined(OS_POSIX) || defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) AppendSwitchNative(switch_string, value_string); #else #error Unsupported platform @@ -376,9 +376,9 @@ } void CommandLine::RemoveSwitch(base::StringPiece switch_key_without_prefix) { -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) StringType switch_key_native = UTF8ToWide(switch_key_without_prefix); -#elif defined(OS_POSIX) || defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) StringType switch_key_native(switch_key_without_prefix); #endif @@ -427,10 +427,10 @@ } void CommandLine::AppendArg(StringPiece value) { -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) DCHECK(IsStringUTF8(value)); AppendArgNative(UTF8ToWide(value)); -#elif defined(OS_POSIX) || defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) AppendArgNative(value); #else #error Unsupported platform @@ -471,7 +471,7 @@ begin_args_ += wrapper_argv.size(); } -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) void CommandLine::ParseFromString(StringPieceType command_line) { command_line = TrimWhitespace(command_line, TRIM_ALL); if (command_line.empty()) @@ -507,19 +507,19 @@ if (downlevel_shell32_dll) ::FreeLibrary(downlevel_shell32_dll); } -#endif // defined(OS_WIN) +#endif // BUILDFLAG(IS_WIN) void CommandLine::AppendSwitchesAndArguments( const CommandLine::StringVector& argv) { bool parse_switches = true; -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) const bool is_parsed_from_string = !raw_command_line_string_.empty(); #endif for (size_t i = 1; i < argv.size(); ++i) { CommandLine::StringType arg = argv[i]; -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) arg = CommandLine::StringType(TrimWhitespace(arg, TRIM_ALL)); -#elif defined(OS_POSIX) || defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) TrimWhitespaceASCII(arg, TRIM_ALL, &arg); #endif @@ -527,14 +527,14 @@ CommandLine::StringType switch_value; parse_switches &= (arg != kSwitchTerminator); if (parse_switches && IsSwitch(arg, &switch_string, &switch_value)) { -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) if (is_parsed_from_string && IsSwitchWithKey(switch_string, kSingleArgument)) { ParseAsSingleArgument(switch_string); return; } AppendSwitchNative(WideToUTF8(switch_string), switch_value); -#elif defined(OS_POSIX) || defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) AppendSwitchNative(switch_string, switch_value); #else #error Unsupported platform @@ -560,14 +560,14 @@ if (parse_switches && IsSwitch(arg, &switch_string, &switch_value)) { params.append(switch_string); if (!switch_value.empty()) { -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) switch_value = QuoteForCommandLineToArgvW( switch_value, allow_unsafe_insert_sequences); #endif params.append(kSwitchValueSeparator + switch_value); } } else { -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) arg = QuoteForCommandLineToArgvW(arg, allow_unsafe_insert_sequences); #endif params.append(arg); @@ -578,7 +578,7 @@ CommandLine::StringType CommandLine::GetCommandLineString() const { StringType string(argv_[0]); -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) string = QuoteForCommandLineToArgvW(string, /*allow_unsafe_insert_sequences=*/false); #endif @@ -590,7 +590,7 @@ return string; } -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) // NOTE: this function is used to set Chrome's open command in the registry // during update. Any change to the syntax must be compatible with the prior // version (i.e., any new syntax must be understood by older browsers expecting @@ -619,13 +619,13 @@ } return string; } -#endif // defined(OS_WIN) +#endif // BUILDFLAG(IS_WIN) CommandLine::StringType CommandLine::GetArgumentsString() const { return GetArgumentsStringInternal(/*allow_unsafe_insert_sequences=*/false); } -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) void CommandLine::ParseAsSingleArgument( const CommandLine::StringType& single_arg_switch) { DCHECK(!raw_command_line_string_.empty()); @@ -652,6 +652,6 @@ AppendArgNative(arg); } } -#endif // defined(OS_WIN) +#endif // BUILDFLAG(IS_WIN) } // namespace base
diff --git a/base/command_line.h b/base/command_line.h index 6108f324..080f0b2 100644 --- a/base/command_line.h +++ b/base/command_line.h
@@ -34,10 +34,10 @@ class BASE_EXPORT CommandLine { public: -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) // The native command line string type. using StringType = std::wstring; -#elif defined(OS_POSIX) || defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) using StringType = std::string; #endif @@ -62,7 +62,7 @@ ~CommandLine(); -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) // By default this class will treat command-line arguments beginning with // slashes as switches on Windows, but not other platforms. // @@ -103,7 +103,7 @@ // Returns true if the CommandLine has been initialized for the given process. static bool InitializedForCurrentProcess(); -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) static CommandLine FromString(StringPieceType command_line); #endif @@ -118,7 +118,7 @@ // GetCommandLineStringForShell() instead. StringType GetCommandLineString() const; -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) // Returns the command-line string in the proper format for the Windows shell, // ending with the argument placeholder "--single-argument %1". The single- // argument switch prevents unexpected parsing of arguments from other @@ -204,7 +204,7 @@ // Common for debuggers, like "gdb --args". void PrependWrapper(StringPieceType wrapper); -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) // Initialize by parsing the given command line string. // The program name is assumed to be the first item in the string. void ParseFromString(StringPieceType command_line); @@ -231,7 +231,7 @@ StringType GetArgumentsStringInternal( bool allow_unsafe_insert_sequences) const; -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) // Initializes by parsing |raw_command_line_string_|, treating everything // after |single_arg_switch_string| + <a single character> as the command // line's single argument, and dropping any arguments previously parsed. The
diff --git a/base/command_line_unittest.cc b/base/command_line_unittest.cc index 1d7ac35..ec3d1bd5 100644 --- a/base/command_line_unittest.cc +++ b/base/command_line_unittest.cc
@@ -64,7 +64,7 @@ cl.GetProgram().value()); EXPECT_TRUE(cl.HasSwitch("foo")); -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) EXPECT_TRUE(cl.HasSwitch("bar")); #else EXPECT_FALSE(cl.HasSwitch("bar")); @@ -106,7 +106,7 @@ } TEST(CommandLineTest, CommandLineFromString) { -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) CommandLine cl = CommandLine::FromString( L"program --foo= -bAr /Spaetzel=pierogi /Baz flim " L"--other-switches=\"--dog=canine --cat=feline\" " @@ -170,7 +170,7 @@ // Tests behavior with an empty input string. TEST(CommandLineTest, EmptyString) { -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) CommandLine cl_from_string = CommandLine::FromString(std::wstring()); EXPECT_TRUE(cl_from_string.GetCommandLineString().empty()); EXPECT_TRUE(cl_from_string.GetProgram().empty()); @@ -201,23 +201,23 @@ cl.AppendArg(kThirdArgName); cl.AppendArg(kFourthArgName); -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) CommandLine::StringType expected_first_arg(UTF8ToWide(kFirstArgName)); CommandLine::StringType expected_second_arg(UTF8ToWide(kSecondArgName)); CommandLine::StringType expected_third_arg(UTF8ToWide(kThirdArgName)); CommandLine::StringType expected_fourth_arg(UTF8ToWide(kFourthArgName)); -#elif defined(OS_POSIX) || defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) CommandLine::StringType expected_first_arg(kFirstArgName); CommandLine::StringType expected_second_arg(kSecondArgName); CommandLine::StringType expected_third_arg(kThirdArgName); CommandLine::StringType expected_fourth_arg(kFourthArgName); #endif -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) #define QUOTE_ON_WIN FILE_PATH_LITERAL("\"") #else #define QUOTE_ON_WIN FILE_PATH_LITERAL("") -#endif // OS_WIN +#endif // BUILDFLAG(IS_WIN) CommandLine::StringType expected_str; expected_str.append(FILE_PATH_LITERAL("--")) @@ -273,7 +273,7 @@ EXPECT_TRUE(cl.HasSwitch(switch5)); EXPECT_EQ(value5, cl.GetSwitchValueNative(switch5)); -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) EXPECT_EQ( L"Program " L"--switch1 " @@ -311,7 +311,7 @@ EXPECT_EQ(FILE_PATH_LITERAL("--arg2"), cl_argv[5]); } -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) TEST(CommandLineTest, GetCommandLineStringForShell) { CommandLine cl = CommandLine::FromString( FILE_PATH_LITERAL("program --switch /switch2 --")); @@ -328,7 +328,7 @@ EXPECT_EQ(FILE_PATH_LITERAL("program --switch=%1 --%2 %3"), cl.GetCommandLineStringWithUnsafeInsertSequences()); } -#endif // defined(OS_WIN) +#endif // BUILDFLAG(IS_WIN) // Tests that when AppendArguments is called that the program is set correctly // on the target CommandLine object and the switches from the source @@ -354,7 +354,7 @@ EXPECT_TRUE(c1.HasSwitch("switch2")); } -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) // Make sure that the command line string program paths are quoted as necessary. // This only makes sense on Windows and the test is basically here to guard // against regressions. @@ -593,7 +593,7 @@ return; } if (!out_value.empty()) { -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) StrAppend(&out_value, {L";"}); #else StrAppend(&out_value, {";"}); @@ -623,7 +623,7 @@ CommandLine::SetDuplicateSwitchHandler(nullptr); } -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) TEST(CommandLineTest, ParseAsSingleArgument) { CommandLine cl = CommandLine::FromString( FILE_PATH_LITERAL("program --switch_before arg_before " @@ -643,6 +643,6 @@ cl_without_arg.GetProgram()); EXPECT_TRUE(cl_without_arg.GetArgs().empty()); } -#endif // defined(OS_WIN) +#endif // BUILDFLAG(IS_WIN) } // namespace base
diff --git a/base/compiler_specific.h b/base/compiler_specific.h index a3e0943..32cb0d9 100644 --- a/base/compiler_specific.h +++ b/base/compiler_specific.h
@@ -165,7 +165,7 @@ #endif // MemorySanitizer annotations. -#if defined(MEMORY_SANITIZER) && !defined(OS_NACL) +#if defined(MEMORY_SANITIZER) && !BUILDFLAG(IS_NACL) #include <sanitizer/msan_interface.h> // Mark a memory region fully initialized. @@ -195,7 +195,7 @@ // DISABLE_CFI_ICALL -- Disable Control Flow Integrity indirect call checks. #if !defined(DISABLE_CFI_ICALL) -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) // Windows also needs __declspec(guard(nocf)). #define DISABLE_CFI_ICALL NO_SANITIZE("cfi-icall") __declspec(guard(nocf)) #else @@ -208,11 +208,11 @@ // Macro useful for writing cross-platform function pointers. #if !defined(CDECL) -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) #define CDECL __cdecl -#else // defined(OS_WIN) +#else // BUILDFLAG(IS_WIN) #define CDECL -#endif // defined(OS_WIN) +#endif // BUILDFLAG(IS_WIN) #endif // !defined(CDECL) // Macro for hinting that an expression is likely to be false.
diff --git a/base/cpu.cc b/base/cpu.cc index 067061a..5f23e67 100644 --- a/base/cpu.cc +++ b/base/cpu.cc
@@ -16,9 +16,10 @@ #include "base/cxx17_backports.h" #include "base/no_destructor.h" +#include "build/build_config.h" -#if defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_ANDROID) || \ - defined(OS_AIX) +#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID) || \ + BUILDFLAG(IS_AIX) #include "base/containers/flat_set.h" #include "base/files/file_util.h" #include "base/notreached.h" @@ -31,7 +32,7 @@ #endif #if defined(ARCH_CPU_ARM_FAMILY) && \ - (defined(OS_ANDROID) || defined(OS_LINUX) || defined(OS_CHROMEOS)) + (BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)) #include <asm/hwcap.h> #include <sys/auxv.h> #include "base/files/file_util.h" @@ -151,7 +152,7 @@ #endif // ARCH_CPU_X86_FAMILY #if defined(ARCH_CPU_ARM_FAMILY) && \ - (defined(OS_ANDROID) || defined(OS_LINUX) || defined(OS_CHROMEOS)) + (BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)) StringPairs::const_iterator FindFirstProcCpuKey(const StringPairs& pairs, StringPiece key) { return ranges::find_if(pairs, [key](const StringPairs::value_type& pair) { @@ -215,8 +216,8 @@ return *info; } -#endif // defined(ARCH_CPU_ARM_FAMILY) && (defined(OS_ANDROID) || - // defined(OS_LINUX) || defined(OS_CHROMEOS)) +#endif // defined(ARCH_CPU_ARM_FAMILY) && (BUILDFLAG(IS_ANDROID) || + // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)) } // namespace @@ -343,7 +344,7 @@ } } #elif defined(ARCH_CPU_ARM_FAMILY) -#if defined(OS_ANDROID) || defined(OS_LINUX) || defined(OS_CHROMEOS) +#if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) if (require_branding) { const ProcCpuInfo& info = ParseProcCpu(); cpu_brand_ = info.brand; @@ -358,7 +359,7 @@ has_bti_ = hwcap2 & HWCAP2_BTI; #endif -#elif defined(OS_WIN) +#elif BUILDFLAG(IS_WIN) // Windows makes high-resolution thread timing information available in // user-space. has_non_stop_time_stamp_counter_ = true; @@ -381,8 +382,8 @@ } #endif -#if defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_ANDROID) || \ - defined(OS_AIX) +#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID) || \ + BUILDFLAG(IS_AIX) namespace { constexpr char kTimeInStatePath[] = @@ -637,8 +638,8 @@ return success; } -#endif // defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_ANDROID) || - // defined(OS_AIX) +#endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || + // BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_AIX) const CPU& CPU::GetInstanceNoAllocation() { static const base::NoDestructor<const CPU> cpu(CPU(false));
diff --git a/base/cpu.h b/base/cpu.h index 5ba4f710..44e07988 100644 --- a/base/cpu.h +++ b/base/cpu.h
@@ -107,8 +107,8 @@ #endif const std::string& cpu_brand() const { return cpu_brand_; } -#if defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_ANDROID) || \ - defined(OS_AIX) +#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID) || \ + BUILDFLAG(IS_AIX) enum class CoreType { kUnknown = 0, kOther, @@ -158,8 +158,8 @@ // cpuidle driver. using CoreIdleTimes = std::vector<TimeDelta>; static bool GetCumulativeCoreIdleTimes(CoreIdleTimes&); -#endif // defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_ANDROID) || - // defined(OS_AIX) +#endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || + // BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_AIX) private: // Query the processor for CPUID information.
diff --git a/base/cpu_affinity_posix_unittest.cc b/base/cpu_affinity_posix_unittest.cc index 86ffa04d..a364c3c 100644 --- a/base/cpu_affinity_posix_unittest.cc +++ b/base/cpu_affinity_posix_unittest.cc
@@ -74,7 +74,7 @@ } // namespace -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) #define MAYBE_SetThreadCpuAffinityMode SetThreadCpuAffinityMode #else // The test only considers Android device hardware models at the moment. Some
diff --git a/base/cpu_unittest.cc b/base/cpu_unittest.cc index a34f76c..cda5058 100644 --- a/base/cpu_unittest.cc +++ b/base/cpu_unittest.cc
@@ -196,7 +196,7 @@ #endif // defined(ARCH_CPU_X86_FAMILY) #if defined(ARCH_CPU_ARM_FAMILY) && \ - (defined(OS_LINUX) || defined(OS_ANDROID) || defined(OS_CHROMEOS)) + (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_CHROMEOS)) TEST(CPU, ARMImplementerAndPartNumber) { base::CPU cpu; @@ -208,5 +208,5 @@ EXPECT_GT(cpu.implementer(), 0u); EXPECT_GT(cpu.part_number(), 0u); } -#endif // defined(ARCH_CPU_ARM_FAMILY) && (defined(OS_LINUX) || - // defined(OS_ANDROID) || defined(OS_CHROMEOS)) +#endif // defined(ARCH_CPU_ARM_FAMILY) && (BUILDFLAG(IS_LINUX) || + // BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_CHROMEOS))
diff --git a/base/critical_closure.h b/base/critical_closure.h index 66f8303..3b41153 100644 --- a/base/critical_closure.h +++ b/base/critical_closure.h
@@ -12,7 +12,7 @@ #include "base/strings/string_piece.h" #include "build/build_config.h" -#if defined(OS_IOS) +#if BUILDFLAG(IS_IOS) #include "base/bind.h" #include "base/ios/scoped_critical_action.h" #endif @@ -21,7 +21,7 @@ namespace internal { -#if defined(OS_IOS) +#if BUILDFLAG(IS_IOS) // Returns true if multi-tasking is supported on this iOS device. bool IsMultiTaskingSupported(); @@ -40,7 +40,7 @@ ios::ScopedCriticalAction critical_action_; OnceClosure closure_; }; -#endif // defined(OS_IOS) +#endif // BUILDFLAG(IS_IOS) } // namespace internal @@ -59,7 +59,7 @@ // background running time, |MakeCriticalClosure| should be applied on them // before posting. |task_name| is used by the platform to identify any tasks // that do not complete in time for suspension. -#if defined(OS_IOS) +#if BUILDFLAG(IS_IOS) inline OnceClosure MakeCriticalClosure(StringPiece task_name, OnceClosure closure) { DCHECK(internal::IsMultiTaskingSupported()); @@ -73,7 +73,7 @@ return MakeCriticalClosure(posted_from.ToString(), std::move(closure)); } -#else // defined(OS_IOS) +#else // BUILDFLAG(IS_IOS) inline OnceClosure MakeCriticalClosure(StringPiece task_name, OnceClosure closure) { // No-op for platforms where the application does not need to acquire @@ -86,7 +86,7 @@ return closure; } -#endif // defined(OS_IOS) +#endif // BUILDFLAG(IS_IOS) } // namespace base
diff --git a/base/enterprise_util.h b/base/enterprise_util.h index 8bde3a09..47d3d7c 100644 --- a/base/enterprise_util.h +++ b/base/enterprise_util.h
@@ -16,7 +16,7 @@ // outside administrator. BASE_EXPORT bool IsMachineExternallyManaged(); -#if defined(OS_APPLE) +#if BUILDFLAG(IS_APPLE) // Returns true if the device is being managed by an MDM system. Uses an old API // not intended for the purpose. @@ -55,7 +55,7 @@ }; BASE_EXPORT DeviceUserDomainJoinState AreDeviceAndUserJoinedToDomain(); -#endif // OS_APPLE +#endif // BUILDFLAG(IS_APPLE) } // namespace base
diff --git a/base/environment.cc b/base/environment.cc index 8e3afd89..855dfd3 100644 --- a/base/environment.cc +++ b/base/environment.cc
@@ -10,9 +10,9 @@ #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) #include <windows.h> -#elif defined(OS_POSIX) || defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) #include <stdlib.h> #endif @@ -52,7 +52,7 @@ private: bool GetVarImpl(StringPiece variable_name, std::string* result) { -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) DWORD value_length = ::GetEnvironmentVariable(UTF8ToWide(variable_name).c_str(), nullptr, 0); if (value_length == 0) @@ -64,7 +64,7 @@ *result = WideToUTF8(value.get()); } return true; -#elif defined(OS_POSIX) || defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) const char* env_value = getenv(variable_name.data()); if (!env_value) return false; @@ -76,21 +76,21 @@ } bool SetVarImpl(StringPiece variable_name, const std::string& new_value) { -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) // On success, a nonzero value is returned. return !!SetEnvironmentVariable(UTF8ToWide(variable_name).c_str(), UTF8ToWide(new_value).c_str()); -#elif defined(OS_POSIX) || defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) // On success, zero is returned. return !setenv(variable_name.data(), new_value.c_str(), 1); #endif } bool UnSetVarImpl(StringPiece variable_name) { -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) // On success, a nonzero value is returned. return !!SetEnvironmentVariable(UTF8ToWide(variable_name).c_str(), nullptr); -#elif defined(OS_POSIX) || defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) // On success, zero is returned. return !unsetenv(variable_name.data()); #endif @@ -101,7 +101,7 @@ namespace env_vars { -#if defined(OS_POSIX) || defined(OS_FUCHSIA) +#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) // On Posix systems, this variable contains the location of the user's home // directory. (e.g, /home/username/). const char kHome[] = "HOME";
diff --git a/base/environment.h b/base/environment.h index 66708621..2fb2138 100644 --- a/base/environment.h +++ b/base/environment.h
@@ -17,7 +17,7 @@ namespace env_vars { -#if defined(OS_POSIX) || defined(OS_FUCHSIA) +#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) BASE_EXPORT extern const char kHome[]; #endif @@ -47,9 +47,9 @@ virtual bool UnSetVar(StringPiece variable_name) = 0; }; -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) using NativeEnvironmentString = std::wstring; -#elif defined(OS_POSIX) || defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) using NativeEnvironmentString = std::string; #endif using EnvironmentMap =
diff --git a/base/environment_unittest.cc b/base/environment_unittest.cc index f7387d4..53f546f 100644 --- a/base/environment_unittest.cc +++ b/base/environment_unittest.cc
@@ -18,7 +18,7 @@ // PATH env variable is not set on Fuchsia by default, while PWD is not set on // Windows. -#if defined(OS_FUCHSIA) +#if BUILDFLAG(IS_FUCHSIA) constexpr char kValidEnvironmentVariable[] = "PWD"; #else constexpr char kValidEnvironmentVariable[] = "PATH";
diff --git a/base/feature_list.cc b/base/feature_list.cc index f3472189..5d1fe346 100644 --- a/base/feature_list.cc +++ b/base/feature_list.cc
@@ -3,8 +3,11 @@ // found in the LICENSE file. #include "base/feature_list.h" + #include <string> +#include "build/build_config.h" + // feature_list.h is a widely included header and its size impacts build // time. Try not to raise this limit unless necessary. See // https://chromium.googlesource.com/chromium/src/+/HEAD/docs/wmax_tokens.md @@ -359,13 +362,13 @@ } void FeatureList::GetFeatureOverrides(std::string* enable_overrides, - std::string* disable_overrides) { + std::string* disable_overrides) const { GetFeatureOverridesImpl(enable_overrides, disable_overrides, false); } void FeatureList::GetCommandLineFeatureOverrides( std::string* enable_overrides, - std::string* disable_overrides) { + std::string* disable_overrides) const { GetFeatureOverridesImpl(enable_overrides, disable_overrides, true); } @@ -520,7 +523,7 @@ initialized_ = true; } -bool FeatureList::IsFeatureEnabled(const Feature& feature) { +bool FeatureList::IsFeatureEnabled(const Feature& feature) const { OverrideState overridden_state = GetOverrideState(feature); // If marked as OVERRIDE_USE_DEFAULT, simply return the default state below. @@ -531,7 +534,7 @@ } absl::optional<bool> FeatureList::IsFeatureEnabledIfOverridden( - const Feature& feature) { + const Feature& feature) const { OverrideState overridden_state = GetOverrideState(feature); // If marked as OVERRIDE_USE_DEFAULT, fall through to returning empty. @@ -542,7 +545,7 @@ } FeatureList::OverrideState FeatureList::GetOverrideState( - const Feature& feature) { + const Feature& feature) const { DCHECK(initialized_); DCHECK(IsValidFeatureOrFieldTrialName(feature.name)) << feature.name; DCHECK(CheckFeatureIdentity(feature)) << feature.name; @@ -551,7 +554,7 @@ } FeatureList::OverrideState FeatureList::GetOverrideStateByFeatureName( - StringPiece feature_name) { + StringPiece feature_name) const { DCHECK(initialized_); DCHECK(IsValidFeatureOrFieldTrialName(feature_name)) << feature_name; @@ -571,7 +574,7 @@ return OVERRIDE_USE_DEFAULT; } -FieldTrial* FeatureList::GetAssociatedFieldTrial(const Feature& feature) { +FieldTrial* FeatureList::GetAssociatedFieldTrial(const Feature& feature) const { DCHECK(initialized_); DCHECK(CheckFeatureIdentity(feature)) << feature.name; @@ -579,7 +582,7 @@ } const base::FeatureList::OverrideEntry* -FeatureList::GetOverrideEntryByFeatureName(StringPiece name) { +FeatureList::GetOverrideEntryByFeatureName(StringPiece name) const { DCHECK(initialized_); DCHECK(IsValidFeatureOrFieldTrialName(name)) << name; @@ -592,7 +595,7 @@ } FieldTrial* FeatureList::GetAssociatedFieldTrialByFeatureName( - StringPiece name) { + StringPiece name) const { DCHECK(initialized_); const base::FeatureList::OverrideEntry* entry = @@ -603,7 +606,8 @@ return nullptr; } -FieldTrial* FeatureList::GetEnabledFieldTrialByFeatureName(StringPiece name) { +FieldTrial* FeatureList::GetEnabledFieldTrialByFeatureName( + StringPiece name) const { DCHECK(initialized_); const base::FeatureList::OverrideEntry* entry = @@ -639,11 +643,11 @@ if (pos != std::string::npos) { feature_name = StringPiece(value.data(), pos); trial = FieldTrialList::Find(value.substr(pos + 1)); -#if !defined(OS_NACL) +#if !BUILDFLAG(IS_NACL) // If the below DCHECK fires, it means a non-existent trial name was // specified via the "Feature<Trial" command-line syntax. DCHECK(trial) << "trial='" << value.substr(pos + 1) << "' does not exist"; -#endif // !defined(OS_NACL) +#endif // !BUILDFLAG(IS_NACL) } RegisterOverride(feature_name, overridden_state, trial); @@ -673,7 +677,7 @@ void FeatureList::GetFeatureOverridesImpl(std::string* enable_overrides, std::string* disable_overrides, - bool command_line_only) { + bool command_line_only) const { DCHECK(initialized_); // Check that the FieldTrialList this is associated with, if any, is the @@ -719,7 +723,7 @@ } } -bool FeatureList::CheckFeatureIdentity(const Feature& feature) { +bool FeatureList::CheckFeatureIdentity(const Feature& feature) const { AutoLock auto_lock(feature_identity_tracker_lock_); auto it = feature_identity_tracker_.find(feature.name);
diff --git a/base/feature_list.h b/base/feature_list.h index 4c978ef9..50b3b2d 100644 --- a/base/feature_list.h +++ b/base/feature_list.h
@@ -257,20 +257,21 @@ // added to |enable_overrides| with a '*' character prefix. Must be called // only after the instance has been initialized and registered. void GetFeatureOverrides(std::string* enable_overrides, - std::string* disable_overrides); + std::string* disable_overrides) const; // Like GetFeatureOverrides(), but only returns overrides that were specified // explicitly on the command-line, omitting the ones from field trials. void GetCommandLineFeatureOverrides(std::string* enable_overrides, - std::string* disable_overrides); + std::string* disable_overrides) const; // Returns the field trial associated with the given feature |name|. Used for // getting the FieldTrial without requiring a struct Feature. - base::FieldTrial* GetAssociatedFieldTrialByFeatureName(StringPiece name); + base::FieldTrial* GetAssociatedFieldTrialByFeatureName( + StringPiece name) const; // Get associated field trial for the given feature |name| only if override // enables it. - FieldTrial* GetEnabledFieldTrialByFeatureName(StringPiece name); + FieldTrial* GetEnabledFieldTrialByFeatureName(StringPiece name) const; // Construct an accessor allowing access to GetOverrideStateByFeatureName(). // This can only be called before the FeatureList is initialized, and is @@ -379,7 +380,7 @@ // Returns the override for the field trial associated with the given feature // |name| or null if the feature is not found. const base::FeatureList::OverrideEntry* GetOverrideEntryByFeatureName( - StringPiece name); + StringPiece name) const; // Finalizes the initialization state of the FeatureList, so that no further // overrides can be registered. This is called by SetInstance() on the @@ -389,26 +390,27 @@ // Returns whether the given |feature| is enabled. This is invoked by the // public FeatureList::IsEnabled() static function on the global singleton. // Requires the FeatureList to have already been fully initialized. - bool IsFeatureEnabled(const Feature& feature); + bool IsFeatureEnabled(const Feature& feature) const; // Returns whether the given |feature| is enabled. This is invoked by the // public FeatureList::GetStateIfOverridden() static function on the global // singleton. Requires the FeatureList to have already been fully initialized. - absl::optional<bool> IsFeatureEnabledIfOverridden(const Feature& feature); + absl::optional<bool> IsFeatureEnabledIfOverridden( + const Feature& feature) const; // Returns the override state of a given |feature|. If the feature was not // overridden, returns OVERRIDE_USE_DEFAULT. Performs any necessary callbacks // for when the feature state has been observed, e.g. actvating field trials. - OverrideState GetOverrideState(const Feature& feature); + OverrideState GetOverrideState(const Feature& feature) const; // Same as GetOverrideState(), but without a default value. - OverrideState GetOverrideStateByFeatureName(StringPiece feature_name); + OverrideState GetOverrideStateByFeatureName(StringPiece feature_name) const; // Returns the field trial associated with the given |feature|. This is // invoked by the public FeatureList::GetFieldTrial() static function on the // global singleton. Requires the FeatureList to have already been fully // initialized. - base::FieldTrial* GetAssociatedFieldTrial(const Feature& feature); + base::FieldTrial* GetAssociatedFieldTrial(const Feature& feature) const; // For each feature name in comma-separated list of strings |feature_list|, // registers an override with the specified |overridden_state|. Also, will @@ -433,14 +435,15 @@ // function's comments for more details. void GetFeatureOverridesImpl(std::string* enable_overrides, std::string* disable_overrides, - bool command_line_only); + bool command_line_only) const; // Verifies that there's only a single definition of a Feature struct for a // given feature name. Keeps track of the first seen Feature struct for each // feature. Returns false when called on a Feature struct with a different // address than the first one it saw for that feature name. Used only from - // DCHECKs and tests. - bool CheckFeatureIdentity(const Feature& feature); + // DCHECKs and tests. This is const because it's called from const getters and + // doesn't modify externally visible state. + bool CheckFeatureIdentity(const Feature& feature) const; // Map from feature name to an OverrideEntry struct for the feature, if it // exists. @@ -448,9 +451,10 @@ // Locked map that keeps track of seen features, to ensure a single feature is // only defined once. This verification is only done in builds with DCHECKs - // enabled. - Lock feature_identity_tracker_lock_; - std::map<std::string, const Feature*> feature_identity_tracker_ + // enabled. This is mutable as it's not externally visible and needs to be + // usable from const getters. + mutable Lock feature_identity_tracker_lock_; + mutable std::map<std::string, const Feature*> feature_identity_tracker_ GUARDED_BY(feature_identity_tracker_lock_); // Tracks the associated FieldTrialList for DCHECKs. This is used to catch
diff --git a/base/file_version_info.h b/base/file_version_info.h index d65bca1..1f3b680a 100644 --- a/base/file_version_info.h +++ b/base/file_version_info.h
@@ -11,7 +11,7 @@ #include "build/build_config.h" #include "base/base_export.h" -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) #include <windows.h> #endif @@ -32,15 +32,15 @@ class BASE_EXPORT FileVersionInfo { public: virtual ~FileVersionInfo() {} -#if defined(OS_WIN) || defined(OS_APPLE) +#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_APPLE) // Creates a FileVersionInfo for the specified path. Returns nullptr if // something goes wrong (typically the file does not exit or cannot be // opened). static std::unique_ptr<FileVersionInfo> CreateFileVersionInfo( const base::FilePath& file_path); -#endif // OS_WIN || OS_APPLE +#endif // BUILDFLAG(IS_WIN) || BUILDFLAG(IS_APPLE) -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) // Creates a FileVersionInfo for the specified module. Returns nullptr in // case of error. static std::unique_ptr<FileVersionInfo> CreateFileVersionInfoForModule( @@ -50,7 +50,7 @@ // of error. static std::unique_ptr<FileVersionInfo> CreateFileVersionInfoForCurrentModule(); -#endif // OS_WIN +#endif // BUILDFLAG(IS_WIN) // Accessors to the different version properties. // Returns an empty string if the property is not found.
diff --git a/base/file_version_info_mac.mm b/base/file_version_info_mac.mm index e45979f6..600a0fa 100644 --- a/base/file_version_info_mac.mm +++ b/base/file_version_info_mac.mm
@@ -58,14 +58,14 @@ // CFBundleShortVersionString. On iOS, both have a policy-enfoced limit // of three version components, so the full version is stored in a custom // key (CrBundleVersion) falling back to CFBundleVersion if not present. -#if defined(OS_IOS) +#if BUILDFLAG(IS_IOS) std::u16string version(GetString16Value(CFSTR("CrBundleVersion"))); if (version.length() > 0) return version; return GetString16Value(CFSTR("CFBundleVersion")); #else return GetString16Value(CFSTR("CFBundleShortVersionString")); -#endif // defined(OS_IOS) +#endif // BUILDFLAG(IS_IOS) } std::u16string FileVersionInfoMac::file_description() {
diff --git a/base/format_macros.h b/base/format_macros.h index ae8d900..97c2546 100644 --- a/base/format_macros.h +++ b/base/format_macros.h
@@ -26,19 +26,20 @@ #include "build/build_config.h" -#if (defined(OS_POSIX) || defined(OS_FUCHSIA)) && \ +#if (BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)) && \ (defined(_INTTYPES_H) || defined(_INTTYPES_H_)) && !defined(PRId64) #error "inttypes.h has already been included before this header file, but " #error "without __STDC_FORMAT_MACROS defined." #endif -#if (defined(OS_POSIX) || defined(OS_FUCHSIA)) && !defined(__STDC_FORMAT_MACROS) +#if (BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)) && \ + !defined(__STDC_FORMAT_MACROS) #define __STDC_FORMAT_MACROS #endif #include <inttypes.h> -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) #if !defined(PRId64) || !defined(PRIu64) || !defined(PRIx64) #error "inttypes.h provided by win toolchain should define these." @@ -52,7 +53,7 @@ #define PRIuS "Iu" #endif -#elif defined(OS_POSIX) || defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) // GCC will concatenate wide and narrow strings correctly, so nothing needs to // be done here. @@ -64,13 +65,13 @@ #define PRIuS "zu" #endif -#endif // defined(OS_WIN) +#endif // BUILDFLAG(IS_WIN) // The size of NSInteger and NSUInteger varies between 32-bit and 64-bit // architectures and Apple does not provides standard format macros and // recommends casting. This has many drawbacks, so instead define macros // for formatting those types. -#if defined(OS_APPLE) +#if BUILDFLAG(IS_APPLE) #if defined(ARCH_CPU_64_BITS) #if !defined(PRIdNS) #define PRIdNS "ld" @@ -92,6 +93,6 @@ #define PRIxNS "x" #endif #endif -#endif // defined(OS_APPLE) +#endif // BUILDFLAG(IS_APPLE) #endif // BASE_FORMAT_MACROS_H_
diff --git a/base/immediate_crash.h b/base/immediate_crash.h index b4ce643..b6ccd54 100644 --- a/base/immediate_crash.h +++ b/base/immediate_crash.h
@@ -41,7 +41,7 @@ #if defined(COMPILER_GCC) -#if defined(OS_NACL) +#if BUILDFLAG(IS_NACL) // Crash report accuracy is not guaranteed on NaCl. #define TRAP_SEQUENCE1_() __builtin_trap() @@ -55,13 +55,13 @@ // to continue after SIGTRAP. #define TRAP_SEQUENCE1_() asm volatile("int3") -#if defined(OS_APPLE) +#if BUILDFLAG(IS_APPLE) // Intentionally empty: __builtin_unreachable() is always part of the sequence // (see IMMEDIATE_CRASH below) and already emits a ud2 on Mac. #define TRAP_SEQUENCE2_() asm volatile("") #else #define TRAP_SEQUENCE2_() asm volatile("ud2") -#endif // defined(OS_APPLE) +#endif // BUILDFLAG(IS_APPLE) #elif defined(ARCH_CPU_ARMEL)
diff --git a/base/immediate_crash_unittest.cc b/base/immediate_crash_unittest.cc index 1d767fb..1e335d8 100644 --- a/base/immediate_crash_unittest.cc +++ b/base/immediate_crash_unittest.cc
@@ -72,12 +72,12 @@ kHlt0 = 0xd4400000, }; -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) constexpr Instruction kRequiredBody[] = {kBrkF000, kBrk1}; constexpr Instruction kOptionalFooter[] = {}; -#elif defined(OS_MAC) +#elif BUILDFLAG(IS_MAC) constexpr Instruction kRequiredBody[] = {kBrk0, kHlt0}; // Some clangs emit a BRK #1 for __builtin_unreachable(), but some do not, so @@ -98,7 +98,7 @@ // whichever of those functions happens to come first in the library. void GetTestFunctionInstructions(std::vector<Instruction>* body) { FilePath helper_library_path; -#if !defined(OS_ANDROID) && !defined(OS_FUCHSIA) +#if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_FUCHSIA) // On Android M, DIR_EXE == /system/bin when running base_unittests. // On Fuchsia, NativeLibrary understands the native convention that libraries // are not colocated with the binary. @@ -106,7 +106,7 @@ #endif helper_library_path = helper_library_path.AppendASCII( GetNativeLibraryName("immediate_crash_test_helper")); -#if defined(OS_ANDROID) && defined(COMPONENT_BUILD) +#if BUILDFLAG(IS_ANDROID) && defined(COMPONENT_BUILD) helper_library_path = helper_library_path.ReplaceExtension(".cr.so"); #endif ScopedNativeLibrary helper_library(helper_library_path);
diff --git a/base/lazy_instance.h b/base/lazy_instance.h index 2e6f2ed60..88669dd 100644 --- a/base/lazy_instance.h +++ b/base/lazy_instance.h
@@ -173,7 +173,7 @@ // MSVC gives a warning that the alignment expands the size of the // LazyInstance struct to make the size a multiple of the alignment. This // is expected in this case. -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) #pragma warning(push) #pragma warning(disable: 4324) #endif @@ -186,7 +186,7 @@ // Preallocated space for the Type instance. alignas(Type) char private_buf_[sizeof(Type)]; -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) #pragma warning(pop) #endif
diff --git a/base/linux_util.cc b/base/linux_util.cc index ee511bd..b53b121 100644 --- a/base/linux_util.cc +++ b/base/linux_util.cc
@@ -97,7 +97,7 @@ char g_linux_distro[kDistroSize] = #if BUILDFLAG(IS_CHROMEOS_ASH) "CrOS"; -#elif defined(OS_ANDROID) +#elif BUILDFLAG(IS_ANDROID) "Android"; #else "Unknown";
diff --git a/base/location.cc b/base/location.cc index 144f247..c49a31d 100644 --- a/base/location.cc +++ b/base/location.cc
@@ -4,6 +4,8 @@ #include "base/location.h" +#include "build/build_config.h" + // location.h is a widely included header and its size can significantly impact // build time. Try not to raise this limit unless absolutely necessary. See // https://chromium.googlesource.com/chromium/src/+/HEAD/docs/wmax_tokens.md @@ -88,7 +90,7 @@ file_name_(file_name), line_number_(line_number), program_counter_(program_counter) { -#if !defined(OS_NACL) +#if !BUILDFLAG(IS_NACL) // The program counter should not be null except in a default constructed // (empty) Location object. This value is used for identity, so if it doesn't // uniquely identify a location, things will break. @@ -116,7 +118,7 @@ #if defined(COMPILER_MSVC) #define RETURN_ADDRESS() _ReturnAddress() -#elif defined(COMPILER_GCC) && !defined(OS_NACL) +#elif defined(COMPILER_GCC) && !BUILDFLAG(IS_NACL) #define RETURN_ADDRESS() \ __builtin_extract_return_addr(__builtin_return_address(0)) #else
diff --git a/base/logging.cc b/base/logging.cc index 6d9b6cf..a3aaaa0 100644 --- a/base/logging.cc +++ b/base/logging.cc
@@ -29,7 +29,7 @@ #include "base/trace_event/base_tracing.h" #include "build/build_config.h" -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) #include <io.h> #include <windows.h> typedef HANDLE FileHandle; @@ -38,20 +38,20 @@ // Windows doesn't define STDERR_FILENO. Define it here. #define STDERR_FILENO 2 -#elif defined(OS_APPLE) +#elif BUILDFLAG(IS_APPLE) // In MacOS 10.12 and iOS 10.0 and later ASL (Apple System Log) was deprecated // in favor of OS_LOG (Unified Logging). #include <AvailabilityMacros.h> -#if defined(OS_IOS) +#if BUILDFLAG(IS_IOS) #if !defined(__IPHONE_10_0) || __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_10_0 #define USE_ASL #endif -#else // !defined(OS_IOS) +#else // BUILDFLAG(IS_IOS) #if !defined(MAC_OS_X_VERSION_10_12) || \ MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_12 #define USE_ASL #endif -#endif // defined(OS_IOS) +#endif // BUILDFLAG(IS_IOS) #if defined(USE_ASL) #include <asl.h> @@ -64,22 +64,22 @@ #include <mach/mach_time.h> #include <mach-o/dyld.h> -#elif defined(OS_POSIX) || defined(OS_FUCHSIA) -#if defined(OS_NACL) +#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) +#if BUILDFLAG(IS_NACL) #include <sys/time.h> // timespec doesn't seem to be in <time.h> #endif #include <time.h> #endif -#if defined(OS_FUCHSIA) +#if BUILDFLAG(IS_FUCHSIA) #include "base/fuchsia/scoped_fx_logger.h" #endif -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) #include <android/log.h> #endif -#if defined(OS_POSIX) || defined(OS_FUCHSIA) +#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) #include <errno.h> #include <paths.h> #include <stdio.h> @@ -123,11 +123,11 @@ #include "base/vlog.h" #include "build/chromeos_buildflags.h" -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) #include "base/win/win_util.h" #endif -#if defined(OS_POSIX) || defined(OS_FUCHSIA) +#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) #include "base/posix/safe_strerror.h" #endif @@ -163,7 +163,7 @@ LogFormat g_log_format = LogFormat::LOG_FORMAT_SYSLOG; #endif -#if defined(OS_FUCHSIA) +#if BUILDFLAG(IS_FUCHSIA) // Retains system logging structures. base::ScopedFxLogger& GetScopedFxLogger() { static base::NoDestructor<base::ScopedFxLogger> logger; @@ -205,18 +205,18 @@ LogMessageHandlerFunction g_log_message_handler = nullptr; uint64_t TickCount() { -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) return GetTickCount(); -#elif defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_FUCHSIA) return zx_clock_get_monotonic() / static_cast<zx_time_t>(base::Time::kNanosecondsPerMicrosecond); -#elif defined(OS_APPLE) +#elif BUILDFLAG(IS_APPLE) return mach_absolute_time(); -#elif defined(OS_NACL) +#elif BUILDFLAG(IS_NACL) // NaCl sadly does not have _POSIX_TIMERS enabled in sys/features.h // So we have to use clock() for now. return clock(); -#elif defined(OS_POSIX) +#elif BUILDFLAG(IS_POSIX) struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); @@ -228,11 +228,11 @@ } void DeleteFilePath(const PathString& log_name) { -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) DeleteFile(log_name.c_str()); -#elif defined(OS_NACL) +#elif BUILDFLAG(IS_NACL) // Do nothing; unlink() isn't supported on NaCl. -#elif defined(OS_POSIX) || defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) unlink(log_name.c_str()); #else #error Unsupported platform @@ -240,7 +240,7 @@ } PathString GetDefaultLogFile() { -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) // On Windows we use the same path as the exe. wchar_t module_name[MAX_PATH]; GetModuleFileName(nullptr, module_name, MAX_PATH); @@ -251,7 +251,7 @@ log_name.erase(last_backslash + 1); log_name += FILE_PATH_LITERAL("debug.log"); return log_name; -#elif defined(OS_POSIX) || defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) // On other platforms we just use the current directory. return PathString("debug.log"); #endif @@ -259,14 +259,14 @@ // We don't need locks on Windows for atomically appending to files. The OS // provides this functionality. -#if defined(OS_POSIX) || defined(OS_FUCHSIA) +#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) base::Lock& GetLoggingLock() { static base::NoDestructor<base::Lock> lock; return *lock; } -#endif // OS_POSIX || OS_FUCHSIA +#endif // BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) // Called by logging functions to ensure that |g_log_file| is initialized // and can be used for writing. Returns false if the file could not be @@ -284,7 +284,7 @@ if ((g_logging_destination & LOG_TO_FILE) == 0) return true; -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) // The FILE_APPEND_DATA access mask ensures that the file is atomically // appended to across accesses from multiple threads. // https://msdn.microsoft.com/en-us/library/windows/desktop/aa364399(v=vs.85).aspx @@ -319,7 +319,7 @@ return false; } } -#elif defined(OS_POSIX) || defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) g_log_file = fopen(g_log_file_name->c_str(), "a"); if (g_log_file == nullptr) return false; @@ -331,9 +331,9 @@ } void CloseFile(FileHandle log) { -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) CloseHandle(log); -#elif defined(OS_POSIX) || defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) fclose(log); #else #error Unsupported platform @@ -353,7 +353,7 @@ g_logging_destination &= ~LOG_TO_FILE; } -#if defined(OS_FUCHSIA) +#if BUILDFLAG(IS_FUCHSIA) inline FuchsiaLogSeverity LogSeverityToFuchsiaLogSeverity( LogSeverity severity) { switch (severity) { @@ -391,7 +391,7 @@ std::ostream* g_swallow_stream; bool BaseInitLoggingImpl(const LoggingSettings& settings) { -#if defined(OS_NACL) +#if BUILDFLAG(IS_NACL) // Can log only to the system debug log and stderr. CHECK_EQ(settings.logging_dest & ~(LOG_TO_SYSTEM_DEBUG_LOG | LOG_TO_STDERR), 0u); @@ -422,7 +422,7 @@ g_logging_destination = settings.logging_dest; -#if defined(OS_FUCHSIA) +#if BUILDFLAG(IS_FUCHSIA) if (g_logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) { GetScopedFxLogger() = base::ScopedFxLogger::CreateForProcess(); } @@ -432,7 +432,7 @@ if ((g_logging_destination & LOG_TO_FILE) == 0) return true; -#if defined(OS_POSIX) || defined(OS_FUCHSIA) +#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) base::AutoLock guard(GetLoggingLock()); #endif @@ -553,7 +553,7 @@ if (!show_error_dialogs) return; -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) // We intentionally don't implement a dialog on other platforms. // You can just look at stderr. if (base::win::IsUser32AndGdi32Available()) { @@ -562,7 +562,7 @@ } else { OutputDebugStringW(base::as_wcstr(base::UTF8ToUTF16(str))); } -#endif // defined(OS_WIN) +#endif // BUILDFLAG(IS_WIN) } #endif // !defined(NDEBUG) @@ -579,8 +579,8 @@ LogMessage::~LogMessage() { size_t stack_start = stream_.tellp(); -#if !defined(OFFICIAL_BUILD) && !defined(OS_NACL) && !defined(__UCLIBC__) && \ - !defined(OS_AIX) +#if !defined(OFFICIAL_BUILD) && !BUILDFLAG(IS_NACL) && !defined(__UCLIBC__) && \ + !BUILDFLAG(IS_AIX) if (severity_ == LOGGING_FATAL && !base::debug::BeingDebugged()) { // Include a stack trace on a fatal, unless a debugger is attached. base::debug::StackTrace stack_trace; @@ -616,9 +616,9 @@ } if ((g_logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) != 0) { -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) OutputDebugStringA(str_newline.c_str()); -#elif defined(OS_APPLE) +#elif BUILDFLAG(IS_APPLE) // In LOG_TO_SYSTEM_DEBUG_LOG mode, log messages are always written to // stderr. If stderr is /dev/null, also log via ASL (Apple System Log) or // its successor OS_LOG. If there's something weird about stderr, assume @@ -768,7 +768,7 @@ str_newline.c_str()); #endif // defined(USE_ASL) } -#elif defined(OS_ANDROID) +#elif BUILDFLAG(IS_ANDROID) android_LogPriority priority = (severity_ < 0) ? ANDROID_LOG_VERBOSE : ANDROID_LOG_UNKNOWN; switch (severity_) { @@ -801,7 +801,7 @@ // The Android system may truncate the string if it's too long. __android_log_write(priority, kAndroidLogTag, str_newline.c_str()); #endif -#elif defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_FUCHSIA) // LogMessage() will silently drop the message if the logger is not valid. // Skip the final character of |str_newline|, since LogMessage() will add // a newline. @@ -809,7 +809,7 @@ GetScopedFxLogger().LogMessage(file_, line_, message.substr(0, message.size() - 1), LogSeverityToFuchsiaLogSeverity(severity_)); -#endif // OS_FUCHSIA +#endif // BUILDFLAG(IS_FUCHSIA) } if (ShouldLogToStderr(severity_)) { @@ -825,18 +825,18 @@ // to do this at the same time, there will be a race condition to create // the lock. This is why InitLogging should be called from the main // thread at the beginning of execution. -#if defined(OS_POSIX) || defined(OS_FUCHSIA) +#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) base::AutoLock guard(GetLoggingLock()); #endif if (InitializeLogFileHandle()) { -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) DWORD num_written; WriteFile(g_log_file, static_cast<const void*>(str_newline.c_str()), static_cast<DWORD>(str_newline.length()), &num_written, nullptr); -#elif defined(OS_POSIX) || defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) ignore_result(fwrite( str_newline.data(), str_newline.size(), 1, g_log_file)); fflush(g_log_file); @@ -915,7 +915,7 @@ if (g_log_thread_id) stream_ << base::PlatformThread::CurrentId() << ':'; if (g_log_timestamp) { -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) SYSTEMTIME local_time; GetLocalTime(&local_time); stream_ << std::setfill('0') @@ -928,7 +928,7 @@ << '.' << std::setw(3) << local_time.wMilliseconds << ':'; -#elif defined(OS_POSIX) || defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) timeval tv; gettimeofday(&tv, nullptr); time_t t = tv.tv_sec; @@ -961,7 +961,7 @@ message_start_ = stream_.str().length(); } -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) // This has already been defined in the header, but defining it again as DWORD // ensures that the type used in the header is equivalent to DWORD. If not, // the redefinition is a compile error. @@ -969,15 +969,15 @@ #endif SystemErrorCode GetLastSystemErrorCode() { -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) return ::GetLastError(); -#elif defined(OS_POSIX) || defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) return errno; #endif } BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code) { -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) const int kErrorMessageBufferSize = 256; char msgbuf[kErrorMessageBufferSize]; DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS; @@ -990,14 +990,13 @@ } return base::StringPrintf("Error (0x%lX) while retrieving error. (0x%lX)", GetLastError(), error_code); -#elif defined(OS_POSIX) || defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) return base::safe_strerror(error_code) + base::StringPrintf(" (%d)", error_code); -#endif // defined(OS_WIN) +#endif // BUILDFLAG(IS_WIN) } - -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file, int line, LogSeverity severity, @@ -1011,7 +1010,7 @@ DWORD last_error = err_; base::debug::Alias(&last_error); } -#elif defined(OS_POSIX) || defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) ErrnoLogMessage::ErrnoLogMessage(const char* file, int line, LogSeverity severity, @@ -1025,10 +1024,10 @@ int last_error = err_; base::debug::Alias(&last_error); } -#endif // defined(OS_WIN) +#endif // BUILDFLAG(IS_WIN) void CloseLogFile() { -#if defined(OS_POSIX) || defined(OS_FUCHSIA) +#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) base::AutoLock guard(GetLoggingLock()); #endif CloseLogFileUnlocked(); @@ -1136,7 +1135,7 @@ // This was defined at the beginning of this file. #undef write -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) bool IsLoggingToFileEnabled() { return g_logging_destination & LOG_TO_FILE; }
diff --git a/base/logging.h b/base/logging.h index 5ec3939..a3ff92f0 100644 --- a/base/logging.h +++ b/base/logging.h
@@ -172,9 +172,9 @@ namespace logging { // TODO(avi): do we want to do a unification of character types here? -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) typedef wchar_t PathChar; -#elif defined(OS_POSIX) || defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) typedef char PathChar; #endif @@ -185,10 +185,10 @@ // Unless destination is LOG_NONE, all logs with severity ERROR and above will // be written to stderr in addition to the specified destination. enum : uint32_t { - LOG_NONE = 0, - LOG_TO_FILE = 1 << 0, + LOG_NONE = 0, + LOG_TO_FILE = 1 << 0, LOG_TO_SYSTEM_DEBUG_LOG = 1 << 1, - LOG_TO_STDERR = 1 << 2, + LOG_TO_STDERR = 1 << 2, LOG_TO_ALL = LOG_TO_FILE | LOG_TO_SYSTEM_DEBUG_LOG | LOG_TO_STDERR, @@ -196,11 +196,11 @@ // On POSIX platforms, where it may not even be possible to locate the // executable on disk, use stderr. // On Fuchsia, use the Fuchsia logging service. -#if defined(OS_FUCHSIA) || defined(OS_NACL) +#if BUILDFLAG(IS_FUCHSIA) || BUILDFLAG(IS_NACL) LOG_DEFAULT = LOG_TO_SYSTEM_DEBUG_LOG, -#elif defined(OS_WIN) +#elif BUILDFLAG(IS_WIN) LOG_DEFAULT = LOG_TO_FILE, -#elif defined(OS_POSIX) +#elif BUILDFLAG(IS_POSIX) LOG_DEFAULT = LOG_TO_SYSTEM_DEBUG_LOG | LOG_TO_STDERR, #endif }; @@ -408,7 +408,7 @@ #define COMPACT_GOOGLE_LOG_DFATAL COMPACT_GOOGLE_LOG_EX_DFATAL(LogMessage) #define COMPACT_GOOGLE_LOG_DCHECK COMPACT_GOOGLE_LOG_EX_DCHECK(LogMessage) -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) // wingdi.h defines ERROR to be 0. When we call LOG(ERROR), it gets // substituted with 0, and it expands to COMPACT_GOOGLE_LOG_0. To allow us // to keep using this syntax, we define this macro to do the same thing @@ -469,7 +469,7 @@ #define VPLOG_STREAM(verbose_level) \ ::logging::Win32ErrorLogMessage(__FILE__, __LINE__, -(verbose_level), \ ::logging::GetLastSystemErrorCode()).stream() -#elif defined(OS_POSIX) || defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) #define VPLOG_STREAM(verbose_level) \ ::logging::ErrnoLogMessage(__FILE__, __LINE__, -(verbose_level), \ ::logging::GetLastSystemErrorCode()).stream() @@ -488,11 +488,11 @@ LOG_IF(FATAL, !(ANALYZER_ASSUME_TRUE(condition))) \ << "Assert failed: " #condition ". " -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) #define PLOG_STREAM(severity) \ COMPACT_GOOGLE_LOG_EX_ ## severity(Win32ErrorLogMessage, \ ::logging::GetLastSystemErrorCode()).stream() -#elif defined(OS_POSIX) || defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) #define PLOG_STREAM(severity) \ COMPACT_GOOGLE_LOG_EX_ ## severity(ErrnoLogMessage, \ ::logging::GetLastSystemErrorCode()).stream() @@ -634,9 +634,9 @@ void operator&(std::ostream&) { } }; -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) typedef unsigned long SystemErrorCode; -#elif defined(OS_POSIX) || defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) typedef int SystemErrorCode; #endif @@ -645,7 +645,7 @@ BASE_EXPORT SystemErrorCode GetLastSystemErrorCode(); BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code); -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) // Appends a formatted system message of the GetLastError() type. class BASE_EXPORT Win32ErrorLogMessage : public LogMessage { public: @@ -661,7 +661,7 @@ private: SystemErrorCode err_; }; -#elif defined(OS_POSIX) || defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) // Appends a formatted system message of the errno type class BASE_EXPORT ErrnoLogMessage : public LogMessage { public: @@ -677,7 +677,7 @@ private: SystemErrorCode err_; }; -#endif // OS_WIN +#endif // BUILDFLAG(IS_WIN) // Closes the log file explicitly if open. // NOTE: Since the log file is opened as necessary by the action of logging @@ -699,7 +699,7 @@ #define RAW_LOG(level, message) \ ::logging::RawLog(::logging::LOGGING_##level, message) -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) // Returns true if logging to file is enabled. BASE_EXPORT bool IsLoggingToFileEnabled();
diff --git a/base/logging_unittest.cc b/base/logging_unittest.cc index 0df1c1aa..911340d96 100644 --- a/base/logging_unittest.cc +++ b/base/logging_unittest.cc
@@ -26,22 +26,22 @@ #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" -#if defined(OS_POSIX) +#if BUILDFLAG(IS_POSIX) #include <signal.h> #include <unistd.h> #include "base/posix/eintr_wrapper.h" -#endif // OS_POSIX +#endif // BUILDFLAG(IS_POSIX) -#if defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_ANDROID) +#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID) #include <ucontext.h> #endif -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) #include <windows.h> #include <excpt.h> -#endif // OS_WIN +#endif // BUILDFLAG(IS_WIN) -#if defined(OS_FUCHSIA) +#if BUILDFLAG(IS_FUCHSIA) #include <lib/zx/channel.h> #include <lib/zx/event.h> #include <lib/zx/exception.h> @@ -49,7 +49,7 @@ #include <zircon/syscalls/debug.h> #include <zircon/syscalls/exception.h> #include <zircon/types.h> -#endif // OS_FUCHSIA +#endif // BUILDFLAG(IS_FUCHSIA) #include "third_party/abseil-cpp/absl/types/optional.h" @@ -213,7 +213,7 @@ // Check that messages with severity ERROR or higher are always logged to // stderr if no log-destinations are set, other than LOG_TO_FILE. // This test is currently only POSIX-compatible. -#if defined(OS_POSIX) || defined(OS_FUCHSIA) +#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) namespace { void TestForLogToStderr(int log_destinations, bool* did_log_info, @@ -263,7 +263,7 @@ bool did_log_error = false; // Fuchsia only logs to stderr when explicitly specified. -#if !defined(OS_FUCHSIA) +#if !BUILDFLAG(IS_FUCHSIA) // When no destinations are specified, ERRORs should still log to stderr. TestForLogToStderr(LOG_NONE, &did_log_info, &did_log_error); EXPECT_FALSE(did_log_info); @@ -286,7 +286,7 @@ EXPECT_TRUE(did_log_info); EXPECT_TRUE(did_log_error); } -#endif // defined(OS_POSIX) || defined(OS_FUCHSIA) +#endif // BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) #if BUILDFLAG(IS_CHROMEOS_ASH) TEST_F(LoggingTest, InitWithFileDescriptor) { @@ -346,7 +346,7 @@ } #endif // BUILDFLAG(IS_CHROMEOS_ASH) -#if defined(OFFICIAL_BUILD) && defined(OS_WIN) +#if defined(OFFICIAL_BUILD) && BUILDFLAG(IS_WIN) NOINLINE void CheckContainingFunc(int death_location) { CHECK(death_location != 1); CHECK(death_location != 2); @@ -397,7 +397,7 @@ EXPECT_NE(addr1, addr3); EXPECT_NE(addr2, addr3); } -#elif defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_FUCHSIA) // CHECK causes a direct crash (without jumping to another function) only in // official builds. Unfortunately, continuous test coverage on official builds @@ -541,7 +541,7 @@ ASSERT_NE(child_crash_addr_1, child_crash_addr_3); ASSERT_NE(child_crash_addr_2, child_crash_addr_3); } -#elif defined(OS_POSIX) && !defined(OS_NACL) && !defined(OS_IOS) && \ +#elif BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_NACL) && !BUILDFLAG(IS_IOS) && \ (defined(ARCH_CPU_X86_FAMILY) || defined(ARCH_CPU_ARM_FAMILY)) int g_child_crash_pipe; @@ -552,7 +552,7 @@ // need the arch-specific boilerplate below, which is inspired by breakpad. // At the same time, on OSX, ucontext.h is deprecated but si_addr works fine. uintptr_t crash_addr = 0; -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) crash_addr = reinterpret_cast<uintptr_t>(info->si_addr); #else // OS_* ucontext_t* context = reinterpret_cast<ucontext_t*>(context_ptr); @@ -635,7 +635,7 @@ ASSERT_NE(child_crash_addr_1, child_crash_addr_3); ASSERT_NE(child_crash_addr_2, child_crash_addr_3); } -#endif // OS_POSIX +#endif // BUILDFLAG(IS_POSIX) TEST_F(LoggingTest, DebugLoggingReleaseBehavior) { #if DCHECK_IS_ON()
diff --git a/base/memory/memory_pressure_listener.cc b/base/memory/memory_pressure_listener.cc index 623ae26..722c6cb 100644 --- a/base/memory/memory_pressure_listener.cc +++ b/base/memory/memory_pressure_listener.cc
@@ -4,6 +4,8 @@ #include "base/memory/memory_pressure_listener.h" +#include <atomic> + #include "base/observer_list_threadsafe.h" #include "base/threading/sequenced_task_runner_handle.h" #include "base/trace_event/base_tracing.h" @@ -67,7 +69,7 @@ return observer; } -subtle::Atomic32 g_notifications_suppressed = 0; +std::atomic<bool> g_notifications_suppressed; } // namespace @@ -136,12 +138,12 @@ // static bool MemoryPressureListener::AreNotificationsSuppressed() { - return subtle::Acquire_Load(&g_notifications_suppressed) == 1; + return g_notifications_suppressed.load(std::memory_order_acquire); } // static void MemoryPressureListener::SetNotificationsSuppressed(bool suppress) { - subtle::Release_Store(&g_notifications_suppressed, suppress ? 1 : 0); + g_notifications_suppressed.store(suppress, std::memory_order_release); } // static
diff --git a/base/native_library.h b/base/native_library.h index 8d85f21..012b53e 100644 --- a/base/native_library.h +++ b/base/native_library.h
@@ -15,17 +15,17 @@ #include "base/strings/string_piece.h" #include "build/build_config.h" -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) #include <windows.h> -#elif defined(OS_APPLE) +#elif BUILDFLAG(IS_APPLE) #import <CoreFoundation/CoreFoundation.h> #endif // OS_* namespace base { -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) using NativeLibrary = HMODULE; -#elif defined(OS_APPLE) +#elif BUILDFLAG(IS_APPLE) enum NativeLibraryType { BUNDLE, DYNAMIC_LIB @@ -45,23 +45,23 @@ }; }; using NativeLibrary = NativeLibraryStruct*; -#elif defined(OS_POSIX) || defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) using NativeLibrary = void*; #endif // OS_* struct BASE_EXPORT NativeLibraryLoadError { -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) NativeLibraryLoadError() : code(0) {} -#endif // OS_WIN +#endif // BUILDFLAG(IS_WIN) // Returns a string representation of the load error. std::string ToString() const; -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) DWORD code; -#elif defined(OS_POSIX) || defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) std::string message; -#endif // OS_WIN +#endif // BUILDFLAG(IS_WIN) }; struct BASE_EXPORT NativeLibraryOptions { @@ -82,7 +82,7 @@ BASE_EXPORT NativeLibrary LoadNativeLibrary(const FilePath& library_path, NativeLibraryLoadError* error); -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) // Loads a native library from the system directory using the appropriate flags. // The function first checks to see if the library is already loaded and will // get a handle if so. This method results in a lock that may block the calling
diff --git a/base/native_library_posix.cc b/base/native_library_posix.cc index b330985..0a96b25ab 100644 --- a/base/native_library_posix.cc +++ b/base/native_library_posix.cc
@@ -13,6 +13,7 @@ #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "base/threading/scoped_blocking_call.h" +#include "build/build_config.h" namespace base { @@ -31,7 +32,7 @@ // http://crbug.com/17943, http://crbug.com/17557, http://crbug.com/36892, // and http://crbug.com/40794. int flags = RTLD_LAZY; -#if defined(OS_ANDROID) || !defined(RTLD_DEEPBIND) +#if BUILDFLAG(IS_ANDROID) || !defined(RTLD_DEEPBIND) // Certain platforms don't define RTLD_DEEPBIND. Android dlopen() requires // further investigation, as it might vary across versions. Crash here to // warn developers that they're trying to rely on uncertain behavior.
diff --git a/base/native_library_unittest.cc b/base/native_library_unittest.cc index 7964514..b8d1466 100644 --- a/base/native_library_unittest.cc +++ b/base/native_library_unittest.cc
@@ -27,13 +27,13 @@ TEST(NativeLibraryTest, GetNativeLibraryName) { const char kExpectedName[] = -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) "mylib.dll"; -#elif defined(OS_IOS) +#elif BUILDFLAG(IS_IOS) "mylib"; -#elif defined(OS_MAC) +#elif BUILDFLAG(IS_MAC) "libmylib.dylib"; -#elif defined(OS_POSIX) || defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) "libmylib.so"; #endif EXPECT_EQ(kExpectedName, GetNativeLibraryName("mylib")); @@ -41,13 +41,13 @@ TEST(NativeLibraryTest, GetLoadableModuleName) { const char kExpectedName[] = -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) "mylib.dll"; -#elif defined(OS_IOS) +#elif BUILDFLAG(IS_IOS) "mylib"; -#elif defined(OS_MAC) +#elif BUILDFLAG(IS_MAC) "mylib.so"; -#elif defined(OS_POSIX) || defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) "libmylib.so"; #endif EXPECT_EQ(kExpectedName, GetLoadableModuleName("mylib")); @@ -56,16 +56,16 @@ // We don't support dynamic loading on iOS, and ASAN will complain about our // intentional ODR violation because of |g_native_library_exported_value| being // defined globally both here and in the shared library. -#if !defined(OS_IOS) && !defined(ADDRESS_SANITIZER) +#if !BUILDFLAG(IS_IOS) && !defined(ADDRESS_SANITIZER) const char kTestLibraryName[] = -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) "test_shared_library.dll"; -#elif defined(OS_MAC) +#elif BUILDFLAG(IS_MAC) "libtest_shared_library.dylib"; -#elif defined(OS_ANDROID) && defined(COMPONENT_BUILD) +#elif BUILDFLAG(IS_ANDROID) && defined(COMPONENT_BUILD) "libtest_shared_library.cr.so"; -#elif defined(OS_POSIX) || defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) "libtest_shared_library.so"; #endif @@ -77,7 +77,7 @@ : library_(nullptr) { base::FilePath exe_path; -#if !defined(OS_FUCHSIA) +#if !BUILDFLAG(IS_FUCHSIA) // Libraries do not sit alongside the executable in Fuchsia. NativeLibrary // is aware of this and is able to resolve library paths correctly. CHECK(base::PathService::Get(base::DIR_EXE, &exe_path)); @@ -105,7 +105,7 @@ // NativeLibraaryTest.LoadLibrary is failing on M tablets only. // crbug/641309 -#if !defined(OS_ANDROID) +#if !BUILDFLAG(IS_ANDROID) // Verifies that we can load a native library and resolve its exported symbols. TEST(NativeLibraryTest, LoadLibrary) { @@ -113,12 +113,12 @@ EXPECT_EQ(5, library.Call<int>("GetSimpleTestValue")); } -#endif // !defined(OS_ANDROID) +#endif // !BUILDFLAG(IS_ANDROID) // Android dlopen() requires further investigation, as it might vary across // versions with respect to symbol resolution scope. // TSan and MSan error out on RTLD_DEEPBIND, https://crbug.com/705255 -#if !defined(OS_ANDROID) && !defined(THREAD_SANITIZER) && \ +#if !BUILDFLAG(IS_ANDROID) && !defined(THREAD_SANITIZER) && \ !defined(MEMORY_SANITIZER) // Verifies that the |prefer_own_symbols| option satisfies its guarantee that @@ -157,8 +157,9 @@ EXPECT_EQ(3, NativeLibraryTestIncrement()); } -#endif // !defined(OS_ANDROID) +#endif // !BUILDFLAG(IS_ANDROID) && !defined(THREAD_SANITIZER) && \ + // !defined(MEMORY_SANITIZER) -#endif // !defined(OS_IOS) && !defined(ADDRESS_SANITIZER) +#endif // !BUILDFLAG(IS_IOS) && !defined(ADDRESS_SANITIZER) } // namespace base
diff --git a/base/numerics/safe_math_shared_impl.h b/base/numerics/safe_math_shared_impl.h index f2e5e7e..ba91016 100644 --- a/base/numerics/safe_math_shared_impl.h +++ b/base/numerics/safe_math_shared_impl.h
@@ -18,7 +18,7 @@ #include "base/numerics/safe_conversions.h" #include "build/build_config.h" -#if defined(OS_ASMJS) +#if BUILDFLAG(IS_ASMJS) // Optimized safe math instructions are incompatible with asmjs. #define BASE_HAS_OPTIMIZED_SAFE_MATH (0) // Where available use builtin math overflow support on Clang and GCC.
diff --git a/base/optional_unittest.cc b/base/optional_unittest.cc index 360b6b68..9b3d1b6 100644 --- a/base/optional_unittest.cc +++ b/base/optional_unittest.cc
@@ -9,6 +9,7 @@ #include <vector> #include "base/ignore_result.h" +#include "base/template_util.h" #include "base/test/gtest_util.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/base/path_service.cc b/base/path_service.cc index 75be43f..2057945 100644 --- a/base/path_service.cc +++ b/base/path_service.cc
@@ -7,8 +7,9 @@ #include <unordered_map> #include "base/memory/raw_ptr.h" +#include "build/build_config.h" -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) #include <windows.h> #include <shellapi.h> #include <shlobj.h> @@ -25,15 +26,15 @@ bool PathProvider(int key, FilePath* result); -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) bool PathProviderWin(int key, FilePath* result); -#elif defined(OS_APPLE) +#elif BUILDFLAG(IS_APPLE) bool PathProviderMac(int key, FilePath* result); -#elif defined(OS_ANDROID) +#elif BUILDFLAG(IS_ANDROID) bool PathProviderAndroid(int key, FilePath* result); -#elif defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_FUCHSIA) bool PathProviderFuchsia(int key, FilePath* result); -#elif defined(OS_POSIX) +#elif BUILDFLAG(IS_POSIX) // PathProviderPosix is the default path provider on POSIX OSes other than // Mac and Android. bool PathProviderPosix(int key, FilePath* result); @@ -61,7 +62,7 @@ #endif true}; -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) Provider base_provider_win = { PathProviderWin, &base_provider, @@ -73,7 +74,7 @@ }; #endif -#if defined(OS_APPLE) +#if BUILDFLAG(IS_APPLE) Provider base_provider_mac = { PathProviderMac, &base_provider, @@ -85,7 +86,7 @@ }; #endif -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) Provider base_provider_android = { PathProviderAndroid, &base_provider, @@ -97,7 +98,7 @@ }; #endif -#if defined(OS_FUCHSIA) +#if BUILDFLAG(IS_FUCHSIA) Provider base_provider_fuchsia = {PathProviderFuchsia, &base_provider, #ifndef NDEBUG 0, 0, @@ -105,7 +106,7 @@ true}; #endif -#if defined(OS_POSIX) && !defined(OS_APPLE) && !defined(OS_ANDROID) +#if BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_APPLE) && !BUILDFLAG(IS_ANDROID) Provider base_provider_posix = { PathProviderPosix, &base_provider, @@ -126,15 +127,15 @@ bool cache_disabled; // Don't use cache if true; PathData() : cache_disabled(false) { -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) providers = &base_provider_win; -#elif defined(OS_APPLE) +#elif BUILDFLAG(IS_APPLE) providers = &base_provider_mac; -#elif defined(OS_ANDROID) +#elif BUILDFLAG(IS_ANDROID) providers = &base_provider_android; -#elif defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_FUCHSIA) providers = &base_provider_fuchsia; -#elif defined(OS_POSIX) +#elif BUILDFLAG(IS_POSIX) providers = &base_provider_posix; #endif }
diff --git a/base/path_service_unittest.cc b/base/path_service_unittest.cc index e852616..b756822f 100644 --- a/base/path_service_unittest.cc +++ b/base/path_service_unittest.cc
@@ -16,7 +16,7 @@ #include "testing/gtest/include/gtest/gtest.h" #include "testing/platform_test.h" -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) #include "base/win/windows_version.h" #endif @@ -24,7 +24,7 @@ namespace { -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) // Defined in // //base/test/android/javatests/src/org/chromium/base/test/util/UrlUtils.java. constexpr char kExpectedChromiumTestsRoot[] = @@ -40,23 +40,23 @@ // Some paths might not exist on some platforms in which case confirming // |result| is true and !path.empty() is the best we can do. bool check_path_exists = true; -#if defined(OS_POSIX) +#if BUILDFLAG(IS_POSIX) // If chromium has never been started on this account, the cache path may not // exist. if (key == DIR_CACHE) check_path_exists = false; #endif -#if defined(OS_LINUX) || defined(OS_CHROMEOS) +#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) // On the linux try-bots: a path is returned (e.g. /home/chrome-bot/Desktop), // but it doesn't exist. if (key == DIR_USER_DESKTOP) check_path_exists = false; #endif -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) if (key == DIR_TASKBAR_PINS) check_path_exists = false; #endif -#if defined(OS_APPLE) +#if BUILDFLAG(IS_APPLE) if (key != DIR_EXE && key != DIR_MODULE && key != FILE_EXE && key != FILE_MODULE) { if (path.ReferencesParent()) { @@ -69,7 +69,7 @@ LOG(INFO) << "Path (" << path << ") references parent."; return false; } -#endif // defined(OS_APPLE) +#endif // BUILDFLAG(IS_APPLE) if (!result) { LOG(INFO) << "PathService::Get() returned false."; return false; @@ -109,7 +109,7 @@ // failure for the value(s) on that platform in this test. TEST_F(PathServiceTest, Get) { // Contains keys that are defined but not supported on the platform. -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) // The following keys are not intended to be implemented on Android (see // crbug.com/1257402). Current implementation is described before each key. // TODO(crbug.com/1257402): Remove the definition of these keys on Android @@ -122,18 +122,18 @@ FILE_MODULE, // PathProviderPosix handles it but fails at some point. DIR_USER_DESKTOP}; -#elif defined(OS_IOS) +#elif BUILDFLAG(IS_IOS) constexpr std::array<int, 1> kUnsupportedKeys = { // DIR_USER_DESKTOP is not implemented on iOS. See crbug.com/1257402. DIR_USER_DESKTOP}; -#elif defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_FUCHSIA) constexpr std::array<int, 3> kUnsupportedKeys = { // TODO(crbug.com/1231928): Implement DIR_USER_DESKTOP. DIR_USER_DESKTOP}; #else constexpr std::array<int, 0> kUnsupportedKeys = {}; -#endif // defined(OS_ANDROID) +#endif // BUILDFLAG(IS_ANDROID) for (int key = PATH_START + 1; key < PATH_END; ++key) { if (std::find(kUnsupportedKeys.begin(), kUnsupportedKeys.end(), key) == kUnsupportedKeys.end()) { @@ -142,7 +142,7 @@ EXPECT_PRED1(ReturnsInvalidPath, key); } } -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) for (int key = PATH_WIN_START + 1; key < PATH_WIN_END; ++key) { bool valid = true; if (key == DIR_APP_SHORTCUTS) @@ -153,21 +153,21 @@ else EXPECT_PRED1(ReturnsInvalidPath, key); } -#elif defined(OS_APPLE) +#elif BUILDFLAG(IS_APPLE) for (int key = PATH_MAC_START + 1; key < PATH_MAC_END; ++key) { EXPECT_PRED1(ReturnsValidPath, key); } -#elif defined(OS_ANDROID) +#elif BUILDFLAG(IS_ANDROID) for (int key = PATH_ANDROID_START + 1; key < PATH_ANDROID_END; ++key) { EXPECT_PRED1(ReturnsValidPath, key); } -#elif defined(OS_POSIX) +#elif BUILDFLAG(IS_POSIX) for (int key = PATH_POSIX_START + 1; key < PATH_POSIX_END; ++key) { EXPECT_PRED1(ReturnsValidPath, key); } -#endif // defined(OS_WIN) +#endif // BUILDFLAG(IS_WIN) } // Tests that CheckedGet returns the same path as Get. @@ -215,12 +215,12 @@ true)); EXPECT_TRUE(PathExists(fake_cache_dir2)); -#if defined(OS_POSIX) +#if BUILDFLAG(IS_POSIX) FilePath non_existent( MakeAbsoluteFilePath(temp_dir.GetPath()).AppendASCII("non_existent")); EXPECT_TRUE(non_existent.IsAbsolute()); EXPECT_FALSE(PathExists(non_existent)); -#if !defined(OS_ANDROID) +#if !BUILDFLAG(IS_ANDROID) // This fails because MakeAbsoluteFilePath fails for non-existent files. // Earlier versions of Bionic libc don't fail for non-existent files, so // skip this check on Android. @@ -228,7 +228,7 @@ non_existent, false, false)); -#endif // !defined(OS_ANDROID) +#endif // !BUILDFLAG(IS_ANDROID) // This works because indicating that |non_existent| is absolute skips the // internal MakeAbsoluteFilePath call. EXPECT_TRUE(PathService::OverrideAndCreateIfNeeded(my_special_key, @@ -240,7 +240,7 @@ FilePath path; EXPECT_TRUE(PathService::Get(my_special_key, &path)); EXPECT_EQ(non_existent, path); -#endif // defined(OS_POSIX) +#endif // BUILDFLAG(IS_POSIX) } // Check if multiple overrides can co-exist. @@ -288,7 +288,7 @@ EXPECT_EQ(original_user_data_dir, new_user_data_dir); } -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) TEST_F(PathServiceTest, GetProgramFiles) { FilePath programfiles_dir; #if defined(_WIN64) @@ -337,16 +337,16 @@ } #endif // defined(_WIN64) } -#endif // defined(OS_WIN) +#endif // BUILDFLAG(IS_WIN) // DIR_ASSETS is DIR_MODULE except on Fuchsia where it is the package root // and Android where it is overridden in tests by test_support_android.cc. TEST_F(PathServiceTest, DIR_ASSETS) { FilePath path; ASSERT_TRUE(PathService::Get(DIR_ASSETS, &path)); -#if defined(OS_FUCHSIA) +#if BUILDFLAG(IS_FUCHSIA) EXPECT_EQ(path.value(), "/pkg"); -#elif defined(OS_ANDROID) +#elif BUILDFLAG(IS_ANDROID) // This key is overridden in //base/test/test_support_android.cc. EXPECT_EQ(path.value(), kExpectedChromiumTestsRoot); #else @@ -360,9 +360,9 @@ TEST_F(PathServiceTest, DIR_GEN_TEST_DATA_ROOT) { FilePath path; ASSERT_TRUE(PathService::Get(DIR_GEN_TEST_DATA_ROOT, &path)); -#if defined(OS_FUCHSIA) +#if BUILDFLAG(IS_FUCHSIA) EXPECT_EQ(path.value(), "/pkg"); -#elif defined(OS_ANDROID) +#elif BUILDFLAG(IS_ANDROID) // This key is overridden in //base/test/test_support_android.cc. EXPECT_EQ(path.value(), kExpectedChromiumTestsRoot); #else @@ -372,7 +372,7 @@ #endif } -#if defined(OS_FUCHSIA) +#if BUILDFLAG(IS_FUCHSIA) // On Fuchsia, some keys have fixed paths that are easy to test. TEST_F(PathServiceTest, DIR_SRC_TEST_DATA_ROOT) { @@ -380,7 +380,7 @@ EXPECT_EQ(PathService::CheckedGet(DIR_SRC_TEST_DATA_ROOT).value(), "/pkg"); } -#elif defined(OS_ANDROID) +#elif BUILDFLAG(IS_ANDROID) // These keys are overridden in //base/test/test_support_android.cc. TEST_F(PathServiceTest, AndroidTestOverrides) { @@ -394,6 +394,6 @@ kExpectedChromiumTestsRoot); } -#endif // defined(OS_FUCHSIA) +#endif // BUILDFLAG(IS_FUCHSIA) } // namespace base
diff --git a/base/rand_util.h b/base/rand_util.h index a5e99fe0..b3e5608 100644 --- a/base/rand_util.h +++ b/base/rand_util.h
@@ -77,7 +77,7 @@ std::shuffle(first, last, RandomBitGenerator()); } -#if defined(OS_POSIX) +#if BUILDFLAG(IS_POSIX) BASE_EXPORT int GetUrandomFD(); #endif
diff --git a/base/rand_util_posix.cc b/base/rand_util_posix.cc index b58c374..f624d48 100644 --- a/base/rand_util_posix.cc +++ b/base/rand_util_posix.cc
@@ -17,9 +17,9 @@ #include "base/posix/eintr_wrapper.h" #include "build/build_config.h" -#if (defined(OS_LINUX) || defined(OS_CHROMEOS)) && !defined(OS_NACL) +#if (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)) && !BUILDFLAG(IS_NACL) #include "third_party/lss/linux_syscall_support.h" -#elif defined(OS_MAC) +#elif BUILDFLAG(IS_MAC) // TODO(crbug.com/995996): Waiting for this header to appear in the iOS SDK. // (See below.) #include <sys/random.h> @@ -27,7 +27,7 @@ namespace { -#if defined(OS_AIX) +#if BUILDFLAG(IS_AIX) // AIX has no 64-bit support for O_CLOEXEC. static constexpr int kOpenFlags = O_RDONLY; #else @@ -62,7 +62,7 @@ // (https://chromium-review.googlesource.com/c/chromium/src/+/1545096) and land // it or some form of it. void RandBytes(void* output, size_t output_length) { -#if (defined(OS_LINUX) || defined(OS_CHROMEOS)) && !defined(OS_NACL) +#if (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)) && !BUILDFLAG(IS_NACL) // We have to call `getrandom` via Linux Syscall Support, rather than through // the libc wrapper, because we might not have an up-to-date libc (e.g. on // some bots). @@ -74,7 +74,7 @@ MSAN_UNPOISON(output, output_length); return; } -#elif defined(OS_MAC) +#elif BUILDFLAG(IS_MAC) // TODO(crbug.com/995996): Enable this on iOS too, when sys/random.h arrives // in its SDK. if (__builtin_available(macOS 10.12, *)) {
diff --git a/base/run_loop.h b/base/run_loop.h index cc77810..6a5df557 100644 --- a/base/run_loop.h +++ b/base/run_loop.h
@@ -30,11 +30,11 @@ class ScopedDisableRunLoopTimeout; } // namespace test -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) class MessagePumpForUI; #endif -#if defined(OS_IOS) +#if BUILDFLAG(IS_IOS) class MessagePumpUIApplication; #endif @@ -293,13 +293,13 @@ FRIEND_TEST_ALL_PREFIXES(SingleThreadTaskExecutorTypedTest, RunLoopQuitOrderAfter); -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) // Android doesn't support the blocking RunLoop::Run, so it calls // BeforeRun and AfterRun directly. friend class MessagePumpForUI; #endif -#if defined(OS_IOS) +#if BUILDFLAG(IS_IOS) // iOS doesn't support the blocking RunLoop::Run, so it calls // BeforeRun directly. friend class MessagePumpUIApplication;
diff --git a/base/safe_numerics_unittest.cc b/base/safe_numerics_unittest.cc index a6cc1ce..6581503 100644 --- a/base/safe_numerics_unittest.cc +++ b/base/safe_numerics_unittest.cc
@@ -14,7 +14,7 @@ // WARNING: This block must come before the base/numerics headers are included. // These tests deliberately cause arithmetic boundary errors. If the compiler is // aggressive enough, it can const detect these errors, so we disable warnings. -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) #pragma warning(disable : 4756) // Arithmetic overflow. #pragma warning(disable : 4293) // Invalid shift. #endif
diff --git a/base/scoped_clear_last_error.h b/base/scoped_clear_last_error.h index 695c8c6..0894947 100644 --- a/base/scoped_clear_last_error.h +++ b/base/scoped_clear_last_error.h
@@ -30,7 +30,7 @@ const int last_errno_; }; -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) // Windows specific implementation of ScopedClearLastError. class BASE_EXPORT ScopedClearLastError : public ScopedClearLastErrorBase { @@ -44,11 +44,11 @@ const unsigned long last_system_error_; }; -#elif defined(OS_POSIX) || defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) using ScopedClearLastError = ScopedClearLastErrorBase; -#endif // defined(OS_WIN) +#endif // BUILDFLAG(IS_WIN) } // namespace base
diff --git a/base/scoped_clear_last_error_unittest.cc b/base/scoped_clear_last_error_unittest.cc index 60c92152..7825420 100644 --- a/base/scoped_clear_last_error_unittest.cc +++ b/base/scoped_clear_last_error_unittest.cc
@@ -8,10 +8,10 @@ #include "build/build_config.h" #include "testing/gtest/include/gtest/gtest.h" -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) #include <windows.h> #include "base/logging.h" -#endif // defined(OS_WIN) +#endif // BUILDFLAG(IS_WIN) namespace base { @@ -33,7 +33,7 @@ EXPECT_EQ(1, errno); } -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) TEST(ScopedClearLastError, TestNoErrorWin) { ::SetLastError(1); @@ -53,6 +53,6 @@ EXPECT_EQ(logging::SystemErrorCode(1), ::GetLastError()); } -#endif // defined(OS_WIN) +#endif // BUILDFLAG(IS_WIN) } // namespace base
diff --git a/base/scoped_native_library_unittest.cc b/base/scoped_native_library_unittest.cc index 763b45f..2be9ebc 100644 --- a/base/scoped_native_library_unittest.cc +++ b/base/scoped_native_library_unittest.cc
@@ -7,7 +7,7 @@ #include "build/build_config.h" #include "testing/gtest/include/gtest/gtest.h" -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) #include "base/files/file_path.h" #include "base/strings/utf_string_conversions.h" #endif @@ -17,7 +17,7 @@ // Tests whether or not a function pointer retrieved via ScopedNativeLibrary // is available only in a scope. TEST(ScopedNativeLibrary, Basic) { -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) // Get the pointer to DirectDrawCreate() from "ddraw.dll" and verify it // is valid only in this scope. // FreeLibrary() doesn't actually unload a DLL until its reference count
diff --git a/base/security_unittest.cc b/base/security_unittest.cc index 93305e2..776bca5 100644 --- a/base/security_unittest.cc +++ b/base/security_unittest.cc
@@ -21,7 +21,7 @@ #include "build/build_config.h" #include "testing/gtest/include/gtest/gtest.h" -#if defined(OS_POSIX) +#if BUILDFLAG(IS_POSIX) #include <sys/mman.h> #include <unistd.h> #endif @@ -50,8 +50,8 @@ // FAILS_ is too clunky. void OverflowTestsSoftExpectTrue(bool overflow_detected) { if (!overflow_detected) { -#if defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_ANDROID) || \ - defined(OS_APPLE) +#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID) || \ + BUILDFLAG(IS_APPLE) // Sadly, on Linux, Android, and OSX we don't have a good story yet. Don't // fail the test, but report. printf("Platform has overflow: %s\n", @@ -64,7 +64,7 @@ } } -#if defined(OS_APPLE) || defined(ADDRESS_SANITIZER) || \ +#if BUILDFLAG(IS_APPLE) || defined(ADDRESS_SANITIZER) || \ defined(THREAD_SANITIZER) || defined(MEMORY_SANITIZER) || \ BUILDFLAG(IS_HWASAN) || BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) #define MAYBE_NewOverflow DISABLED_NewOverflow @@ -97,7 +97,7 @@ char* volatile p = reinterpret_cast<char*>(array_pointer.get()); OverflowTestsSoftExpectTrue(!p); } -#if defined(OS_WIN) && defined(ARCH_CPU_64_BITS) +#if BUILDFLAG(IS_WIN) && defined(ARCH_CPU_64_BITS) // On Windows, the compiler prevents static array sizes of more than // 0x7fffffff (error C2148). #else @@ -108,7 +108,7 @@ char* volatile p = reinterpret_cast<char*>(array_pointer.get()); OverflowTestsSoftExpectTrue(!p); } -#endif // !defined(OS_WIN) || !defined(ARCH_CPU_64_BITS) +#endif // BUILDFLAG(IS_WIN) && defined(ARCH_CPU_64_BITS) } } // namespace
diff --git a/base/sync_socket.h b/base/sync_socket.h index 5289403..6cc0279 100644 --- a/base/sync_socket.h +++ b/base/sync_socket.h
@@ -17,12 +17,12 @@ #include "base/time/time.h" #include "build/build_config.h" -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) #include <windows.h> #endif #include <sys/types.h> -#if defined(OS_POSIX) || defined(OS_FUCHSIA) +#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) #include "base/file_descriptor_posix.h" #endif @@ -112,7 +112,7 @@ // a blocking Receive or Send. bool Shutdown(); -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) // Since the Linux and Mac implementations actually use a socket, shutting // them down from another thread is pretty simple - we can just call // shutdown(). However, the Windows implementation relies on named pipes @@ -134,7 +134,7 @@ size_t Send(const void* buffer, size_t length) override; private: -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) WaitableEvent shutdown_event_; WaitableEvent file_operation_; #endif
diff --git a/base/sync_socket_posix.cc b/base/sync_socket_posix.cc index 2ca5908a..92d47fc 100644 --- a/base/sync_socket_posix.cc +++ b/base/sync_socket_posix.cc
@@ -14,7 +14,9 @@ #include <sys/socket.h> #include <sys/types.h> -#if defined(OS_SOLARIS) +#include "build/build_config.h" + +#if BUILDFLAG(IS_SOLARIS) #include <sys/filio.h> #endif @@ -53,9 +55,9 @@ DCHECK(!socket_a->IsValid()); DCHECK(!socket_b->IsValid()); -#if defined(OS_APPLE) +#if BUILDFLAG(IS_APPLE) int nosigpipe = 1; -#endif // defined(OS_APPLE) +#endif // BUILDFLAG(IS_APPLE) ScopedHandle handles[2]; @@ -68,7 +70,7 @@ handles[1].reset(raw_handles[1]); } -#if defined(OS_APPLE) +#if BUILDFLAG(IS_APPLE) // On OSX an attempt to read or write to a closed socket may generate a // SIGPIPE rather than returning -1. setsockopt will shut this off. if (0 != setsockopt(handles[0].get(), SOL_SOCKET, SO_NOSIGPIPE, &nosigpipe,
diff --git a/base/syslog_logging.cc b/base/syslog_logging.cc index 79351da..a043727a 100644 --- a/base/syslog_logging.cc +++ b/base/syslog_logging.cc
@@ -4,7 +4,9 @@ #include "base/syslog_logging.h" -#if defined(OS_WIN) +#include "build/build_config.h" + +#if BUILDFLAG(IS_WIN) #include <windows.h> #include <sddl.h> @@ -13,7 +15,7 @@ #include "base/strings/string_util.h" #include "base/win/scoped_handle.h" #include "base/win/win_util.h" -#elif defined(OS_LINUX) || defined(OS_CHROMEOS) +#elif BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) // <syslog.h> defines LOG_INFO, LOG_WARNING macros that could conflict with // base::LOG_INFO, base::LOG_WARNING. #include <syslog.h> @@ -33,7 +35,7 @@ } // namespace -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) namespace { @@ -87,7 +89,7 @@ g_user_sid = nullptr; } -#endif // defined(OS_WIN) +#endif // BUILDFLAG(IS_WIN) EventLogMessage::EventLogMessage(const char* file, int line, @@ -99,7 +101,7 @@ if (!g_logging_enabled) return; -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) // If g_event_source_name is nullptr (which it is per default) SYSLOG will // degrade gracefully to regular LOG. If you see this happening most probably // you are using SYSLOG before you called SetEventSourceName. @@ -145,7 +147,7 @@ if (user_sid != nullptr) ::LocalFree(user_sid); -#elif defined(OS_LINUX) || defined(OS_CHROMEOS) +#elif BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) const char kEventSource[] = "chrome"; openlog(kEventSource, LOG_NOWAIT | LOG_PID, LOG_USER); // We can't use the defined names for the logging severity from syslog.h @@ -169,7 +171,7 @@ } syslog(priority, "%s", log_message_.str().c_str()); closelog(); -#endif // defined(OS_WIN) +#endif // BUILDFLAG(IS_WIN) } void SetSyslogLoggingForTesting(bool logging_enabled) {
diff --git a/base/syslog_logging.h b/base/syslog_logging.h index 796a98e1..b28aaa3 100644 --- a/base/syslog_logging.h +++ b/base/syslog_logging.h
@@ -20,7 +20,7 @@ #define SYSLOG(severity) \ SYSLOG_STREAM(severity) -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) // Sets the name, category and event id of the event source for logging to the // Windows Event Log. Call this function once before using the SYSLOG macro or // otherwise it will behave as a regular LOG macro. @@ -31,7 +31,7 @@ // The event source may get set more than once in tests. This function allows // a test to reset the source when needed. void BASE_EXPORT ResetEventSourceForTesting(); -#endif // defined(OS_WIN) +#endif // BUILDFLAG(IS_WIN) // Creates a formatted message on the system event log. That would be the // Application Event log on Windows and the messages log file on POSIX systems.
diff --git a/base/task/thread_pool/thread_pool_instance.h b/base/task/thread_pool/thread_pool_instance.h index c96f99b3..56fb258c 100644 --- a/base/task/thread_pool/thread_pool_instance.h +++ b/base/task/thread_pool/thread_pool_instance.h
@@ -238,8 +238,17 @@ virtual int GetMaxConcurrentNonBlockedTasksWithTraitsDeprecated( const TaskTraits& traits) const = 0; - // Starts/stops a fence that prevents execution of tasks of any / BEST_EFFORT - // priority. + // Starts/stops a fence that prevents scheduling of tasks of any / BEST_EFFORT + // priority. Ongoing tasks will still be allowed to complete and not be + // waited upon. This is useful for use cases where a second component + // (e.g. content) needs a "single-threaded" startup phase where tasks it + // posts do not run before it "enables the ThreadPool" + // (via ThreadPoolInstance::EndFence instead of the typical + // ThreadPoolInstance::Start). For example, because a lightweight service + // manager was already running prior to launching full chrome. BeginFence + // does not wait for ongoing tasks as those pertain to the previous phase and + // cannot interfere with the upcoming "single-threaded" initialization + // phase. virtual void BeginFence() = 0; virtual void EndFence() = 0; virtual void BeginBestEffortFence() = 0;
diff --git a/base/test/gtest_util.h b/base/test/gtest_util.h index 1653e342..faa6935 100644 --- a/base/test/gtest_util.h +++ b/base/test/gtest_util.h
@@ -9,7 +9,7 @@ #include <utility> #include <vector> -#include "base/check_op.h" +#include "base/check.h" #include "build/build_config.h" #include "testing/gtest/include/gtest/gtest.h" @@ -48,14 +48,13 @@ // As above, but for CHECK(). #if defined(GTEST_HAS_DEATH_TEST) && !BUILDFLAG(IS_ANDROID) -// Official builds will eat stream parameters, so don't check the error message. -#if defined(OFFICIAL_BUILD) && defined(NDEBUG) -#define EXPECT_CHECK_DEATH(statement) EXPECT_DEATH(statement, "") -#define ASSERT_CHECK_DEATH(statement) ASSERT_DEATH(statement, "") -#else +#if CHECK_WILL_STREAM() #define EXPECT_CHECK_DEATH(statement) EXPECT_DEATH(statement, "Check failed") #define ASSERT_CHECK_DEATH(statement) ASSERT_DEATH(statement, "Check failed") -#endif // defined(OFFICIAL_BUILD) && defined(NDEBUG) +#else +#define EXPECT_CHECK_DEATH(statement) EXPECT_DEATH(statement, "") +#define ASSERT_CHECK_DEATH(statement) ASSERT_DEATH(statement, "") +#endif // CHECK_WILL_STREAM() #else // defined(GTEST_HAS_DEATH_TEST) && !BUILDFLAG(IS_ANDROID)
diff --git a/base/test/scoped_feature_list.cc b/base/test/scoped_feature_list.cc index 4b9c09f8..f92f7fe 100644 --- a/base/test/scoped_feature_list.cc +++ b/base/test/scoped_feature_list.cc
@@ -14,6 +14,7 @@ #include "base/strings/string_split.h" #include "base/strings/string_util.h" #include "base/test/mock_entropy_provider.h" +#include "base/test/task_environment.h" namespace base { namespace test { @@ -151,6 +152,18 @@ init_called_ = false; + // ThreadPool tasks racily probing FeatureList while it's initialized/reset + // are problematic and while callers should ideally set up ScopedFeatureList + // before TaskEnvironment, that's not always possible. Fencing execution here + // avoids an entire class of bugs by making sure no ThreadPool task queries + // FeatureList while it's being modified. This local action is preferred to + // requiring all such callers to manually flush all tasks before each + // ScopedFeatureList Init/Reset: crbug.com/1275502#c45 + // + // All FeatureList modifications in this file should have this as well. + TaskEnvironment::ParallelExecutionFence fence( + "ScopedFeatureList must be Reset from the test main thread"); + FeatureList::ClearInstanceForTesting(); if (field_trial_list_) { @@ -174,6 +187,11 @@ void ScopedFeatureList::InitWithFeatureList( std::unique_ptr<FeatureList> feature_list) { DCHECK(!original_feature_list_); + + // Execution fence required while modifying FeatureList, as in Reset. + TaskEnvironment::ParallelExecutionFence fence( + "ScopedFeatureList must be Init from the test main thread"); + original_feature_list_ = FeatureList::ClearInstanceForTesting(); FeatureList::SetInstance(std::move(feature_list)); init_called_ = true; @@ -228,7 +246,7 @@ std::string current_enabled_features; std::string current_disabled_features; - FeatureList* feature_list = FeatureList::GetInstance(); + const FeatureList* feature_list = FeatureList::GetInstance(); if (feature_list) { feature_list->GetFeatureOverrides(¤t_enabled_features, ¤t_disabled_features);
diff --git a/base/test/scoped_feature_list.h b/base/test/scoped_feature_list.h index e9ec8303..022540f 100644 --- a/base/test/scoped_feature_list.h +++ b/base/test/scoped_feature_list.h
@@ -30,9 +30,9 @@ // should be destroyed in the opposite order of their Init*() methods being // called. // -// ScopedFeatureList needs to be initialized (via one of Init*() methods) -// before running code that inspects the state of features, such as in the -// constructor of the test harness. +// ScopedFeatureList needs to be initialized on the main thread (via one of +// Init*() methods) before running code that inspects the state of features, +// such as in the constructor of the test harness. // // WARNING: To be clear, in multithreaded test environments (such as browser // tests) there may background threads using FeatureList before the test body is
diff --git a/base/test/task_environment.cc b/base/test/task_environment.cc index d142b29..592a230 100644 --- a/base/test/task_environment.cc +++ b/base/test/task_environment.cc
@@ -6,8 +6,11 @@ #include <algorithm> #include <memory> +#include <ostream> #include "base/callback_helpers.h" +#include "base/check.h" +#include "base/debug/stack_trace.h" #include "base/lazy_instance.h" #include "base/location.h" #include "base/logging.h" @@ -32,6 +35,7 @@ #include "base/thread_annotations.h" #include "base/threading/platform_thread.h" #include "base/threading/sequence_local_storage_map.h" +#include "base/threading/thread_checker_impl.h" #include "base/threading/thread_local.h" #include "base/threading/thread_restrictions.h" #include "base/threading/thread_task_runner_handle.h" @@ -62,6 +66,10 @@ return *instance; } +// A pointer to the current TestTaskTracker, if any, constant throughout the +// lifetime of a ThreadPoolInstance managed by a TaskEnvironment. +TaskEnvironment::TestTaskTracker* g_task_tracker = nullptr; + base::MessagePumpType GetMessagePumpTypeForMainThreadType( TaskEnvironment::MainThreadType main_thread_type) { switch (main_thread_type) { @@ -121,11 +129,11 @@ // be no tasks currently running. Returns false if >0 tasks are currently // running. Prior to returning false, it will attempt to block until at least // one task has completed (in an attempt to avoid callers busy-looping - // DisallowRunTasks() calls with the same set of slowly ongoing tasks). This - // block attempt will also have a short timeout (in an attempt to prevent the - // fallout of blocking: if the only task remaining is blocked on the main - // thread, waiting for it to complete results in a deadlock...). - bool DisallowRunTasks(); + // DisallowRunTasks() calls with the same set of slowly ongoing tasks). + // Returns false if none of the ongoing tasks complete within |timeout| in an + // attempt to prevent a deadlock in the event that the only task remaining is + // blocked on the main thread. + bool DisallowRunTasks(TimeDelta timeout = Milliseconds(1)); // Returns true if tasks are currently allowed to run. bool TasksAllowedToRun() const; @@ -134,6 +142,12 @@ // currently running tasks on the thread pool. std::string DescribeRunningTasks() const; + // Returns true if this is invoked on this TaskTracker's owning thread + // (i.e. test main thread). + bool OnControllerThread() const { + return controller_thread_checker_.CalledOnValidThread(); + } + private: friend class TaskEnvironment; @@ -160,6 +174,9 @@ // The set of tasks currently running, keyed by the id from // |next_task_number_|. base::flat_map<int64_t, Location> running_tasks_ GUARDED_BY(lock_); + + // Used to implement OnControllerThread(). + ThreadCheckerImpl controller_thread_checker_; }; class TaskEnvironment::MockTimeDomain : public sequence_manager::TimeDomain { @@ -444,6 +461,8 @@ auto thread_pool = std::make_unique<internal::ThreadPoolImpl>( std::string(), std::move(task_tracker)); ThreadPoolInstance::Set(std::move(thread_pool)); + DCHECK(!g_task_tracker); + g_task_tracker = raw_task_tracker; return raw_task_tracker; } @@ -528,6 +547,8 @@ ThreadPoolInstance::Get()->FlushForTesting(); ThreadPoolInstance::Get()->Shutdown(); ThreadPoolInstance::Get()->JoinForTesting(); + DCHECK_EQ(g_task_tracker, task_tracker_); + g_task_tracker = nullptr; // Destroying ThreadPoolInstance state can result in waiting on worker // threads. Make sure this is allowed to avoid flaking tests that have // disallowed waits on their main thread. @@ -745,6 +766,12 @@ LOG(INFO) << sequence_manager_->DescribeAllPendingTasks(); } +void TaskEnvironment::DetachFromThread() { + DETACH_FROM_THREAD(main_thread_checker_); + if (task_tracker_) + task_tracker_->controller_thread_checker_.DetachFromThread(); +} + // static void TaskEnvironment::AddDestructionObserver(DestructionObserver* observer) { GetDestructionObservers().AddObserver(observer); @@ -755,6 +782,36 @@ GetDestructionObservers().RemoveObserver(observer); } +TaskEnvironment::ParallelExecutionFence::ParallelExecutionFence( + const char* error_message) { + CHECK(!g_task_tracker || g_task_tracker->OnControllerThread()) + << error_message; + if (g_task_tracker) { + previously_allowed_to_run_ = g_task_tracker->TasksAllowedToRun(); + // DisallowRunTasks typically yields back if it fails to reach quiescence + // within 1ms. This is typically done to let the main thread run tasks that + // could potentially be blocking main thread tasks. In this case however, + // main thread making progress while installing the fence would be more + // surprising. So allow more time but report errors after a while. + while (previously_allowed_to_run_ && + !g_task_tracker->DisallowRunTasks(Seconds(5))) { + LOG(WARNING) << "Installing ParallelExecutionFence is slow because of " + "these running tasks:\n" + << g_task_tracker->DescribeRunningTasks() + << "\nParallelExecutionFence requested by:\n" + << debug::StackTrace(); + } + } else if (ThreadPoolInstance::Get()) { + LOG(WARNING) << "ParallelExecutionFence is ineffective when " + "ThreadPoolInstance is not managed by a TaskEnvironment."; + } +} + +TaskEnvironment::ParallelExecutionFence::~ParallelExecutionFence() { + if (previously_allowed_to_run_) + g_task_tracker->AllowRunTasks(); +} + TaskEnvironment::TestTaskTracker::TestTaskTracker() : can_run_tasks_cv_(&lock_), task_completed_cv_(&lock_) { // Consider threads blocked on these as idle (avoids instantiating @@ -776,15 +833,12 @@ return can_run_tasks_; } -bool TaskEnvironment::TestTaskTracker::DisallowRunTasks() { +bool TaskEnvironment::TestTaskTracker::DisallowRunTasks(TimeDelta timeout) { AutoLock auto_lock(lock_); // Can't disallow run task if there are tasks running. if (!running_tasks_.empty()) { - // Attempt to wait a bit so that the caller doesn't busy-loop with the same - // set of pending work. A short wait is required to avoid deadlock - // scenarios. See DisallowRunTasks()'s declaration for more details. - task_completed_cv_.TimedWait(Milliseconds(1)); + task_completed_cv_.TimedWait(timeout); return false; }
diff --git a/base/test/task_environment.h b/base/test/task_environment.h index 641c2c9..6015c22 100644 --- a/base/test/task_environment.h +++ b/base/test/task_environment.h
@@ -313,6 +313,11 @@ // thread, and currently running tasks on the thread pool. void DescribeCurrentTasks() const; + // Detach ThreadCheckers (will rebind on next usage), useful for the odd test + // suite which doesn't run on the main thread but still has exclusive access + // to driving this TaskEnvironment (e.g. WaylandClientTestSuiteServer). + void DetachFromThread(); + class TestTaskTracker; // Callers outside of TaskEnvironment may not use the returned pointer. They // should just use base::ThreadPoolInstance::Get(). @@ -335,6 +340,26 @@ static void AddDestructionObserver(DestructionObserver* observer); static void RemoveDestructionObserver(DestructionObserver* observer); + // Instantiating a ParallelExecutionFence waits for all currently running + // ThreadPool tasks before the constructor returns and from then on prevents + // additional tasks from running during its lifetime. + // + // Must be instantiated from the test main thread. + class ParallelExecutionFence { + public: + // Instantiates a ParallelExecutionFence, crashes with an optional + // |error_message| if not invoked from test main thread. + explicit ParallelExecutionFence(const char* error_message = ""); + ~ParallelExecutionFence(); + + ParallelExecutionFence(const ParallelExecutionFence&) = delete; + ParallelExecutionFence& operator=(const ParallelExecutionFence& other) = + delete; + + private: + bool previously_allowed_to_run_ = false; + }; + // The number of foreground workers in the ThreadPool managed by a // TaskEnvironment instance. This can be used to determine the maximum // parallelism in tests that require each parallel task it spawns to be
diff --git a/base/test/task_environment_unittest.cc b/base/test/task_environment_unittest.cc index d2fb0dd..7eaf600 100644 --- a/base/test/task_environment_unittest.cc +++ b/base/test/task_environment_unittest.cc
@@ -11,6 +11,7 @@ #include "base/bind.h" #include "base/callback_helpers.h" #include "base/cancelable_callback.h" +#include "base/check.h" #include "base/debug/debugger.h" #include "base/run_loop.h" #include "base/synchronization/atomic_flag.h" @@ -1372,7 +1373,101 @@ InitializeCOMOnWorker(TaskEnvironment::ThreadPoolCOMEnvironment::NONE, ApartmentType::kSTA); } +#endif // defined(OS_WIN) + +TEST_F(TaskEnvironmentTest, ParallelExecutionFence) { + TaskEnvironment task_environment; + + constexpr int kNumParallelTasks = + TaskEnvironment::kNumForegroundThreadPoolThreads; + + TestWaitableEvent resume_main_thread; + TestWaitableEvent all_runs_done; + // Counters, all accessed/modified with memory_order_relaxed as no memory + // ordering is necessary between operations. + std::atomic_int completed_runs{0}; + std::atomic_int next_run{1}; + + // Each task will repost itself until run 500. Run #50 will signal + // |resume_main_thread|. + RepeatingClosure task = BindLambdaForTesting([&]() { + int this_run = next_run.fetch_add(1, std::memory_order_relaxed); + + if (this_run == 50) + resume_main_thread.Signal(); + + // Sleep after signaling to increase the likelihood the main thread installs + // the fence during this run and must wait on this task. + if (this_run >= 50 && this_run < 50 + kNumParallelTasks) + PlatformThread::Sleep(Milliseconds(5)); + + // Repost self until the last kNumParallelTasks. + if (this_run <= 500 - kNumParallelTasks) + ThreadPool::PostTask(task); + + completed_runs.fetch_add(1, std::memory_order_relaxed); + + if (this_run == 500) + all_runs_done.Signal(); + }); + for (int i = 0; i < kNumParallelTasks; ++i) + ThreadPool::PostTask(task); + + resume_main_thread.Wait(); + ASSERT_GE(next_run.load(std::memory_order_relaxed), 50); + + { + // Confirm that no run happens while the fence is up. + TaskEnvironment::ParallelExecutionFence fence; + + // All runs are complete. + const int completed_runs1 = completed_runs.load(std::memory_order_relaxed); + const int next_run1 = next_run.load(std::memory_order_relaxed); + EXPECT_EQ(completed_runs1, next_run1 - 1); + + // Given a bit more time, no additional run starts nor completes. + PlatformThread::Sleep(Milliseconds(30)); + const int completed_runs2 = completed_runs.load(std::memory_order_relaxed); + const int next_run2 = next_run.load(std::memory_order_relaxed); + EXPECT_EQ(completed_runs1, completed_runs2); + EXPECT_EQ(next_run1, next_run2); + } + + // Runs resume automatically after taking down the fence (without needing to + // call RunUntilIdle()). + all_runs_done.Wait(); + ASSERT_EQ(completed_runs.load(std::memory_order_relaxed), 500); + ASSERT_EQ(next_run.load(std::memory_order_relaxed), 501); +} + +TEST_F(TaskEnvironmentTest, ParallelExecutionFenceWithoutTaskEnvironment) { + // Noops (doesn't crash) without a TaskEnvironment. + TaskEnvironment::ParallelExecutionFence fence; +} + +TEST_F(TaskEnvironmentTest, + ParallelExecutionFenceWithSingleThreadTaskEnvironment) { + SingleThreadTaskEnvironment task_environment; + // Noops (doesn't crash), with a SingleThreadTaskEnvironment/ + TaskEnvironment::ParallelExecutionFence fence; +} + +TEST_F(TaskEnvironmentTest, ParallelExecutionFenceNonMainThreadDeath) { + TaskEnvironment task_environment; + + ThreadPool::PostTask(BindOnce([]() { +#if CHECK_WILL_STREAM() + const char kFailureLog[] = "ParallelExecutionFence invoked from worker"; +#else + const char kFailureLog[] = ""; #endif + EXPECT_DEATH_IF_SUPPORTED( + { TaskEnvironment::ParallelExecutionFence fence(kFailureLog); }, + kFailureLog); + })); + + task_environment.RunUntilIdle(); +} } // namespace test } // namespace base
diff --git a/base/third_party/nspr/prtime.cc b/base/third_party/nspr/prtime.cc index f7ee352..69b8d6ae 100644 --- a/base/third_party/nspr/prtime.cc +++ b/base/third_party/nspr/prtime.cc
@@ -96,7 +96,7 @@ #define DAYS_BETWEEN_YEARS(A, B) (COUNT_DAYS(B) - COUNT_DAYS(A)) /* Implements the Unix localtime_r() function for windows */ -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) static void localtime_r(const time_t* secs, struct tm* time) { (void) localtime_s(time, secs); }
diff --git a/base/third_party/symbolize/symbolize.cc b/base/third_party/symbolize/symbolize.cc index 4edae688..2851324 100644 --- a/base/third_party/symbolize/symbolize.cc +++ b/base/third_party/symbolize/symbolize.cc
@@ -52,6 +52,7 @@ #include GLOG_BUILD_CONFIG_INCLUDE #endif // GLOG_BUILD_CONFIG_INCLUDE +#include "build/build_config.h" #include "utilities.h" #if defined(HAVE_SYMBOLIZE) @@ -113,7 +114,7 @@ #if defined(HAVE_DLFCN_H) #include <dlfcn.h> #endif -#if defined(OS_OPENBSD) +#if BUILDFLAG(IS_OPENBSD) #include <sys/exec_elf.h> #else #include <elf.h> @@ -840,7 +841,7 @@ _END_GOOGLE_NAMESPACE_ -#elif defined(OS_APPLE) && defined(HAVE_DLADDR) +#elif BUILDFLAG(IS_APPLE) && defined(HAVE_DLADDR) #include <dlfcn.h> #include <string.h>
diff --git a/base/tools_sanity_unittest.cc b/base/tools_sanity_unittest.cc index aa245e9..2497e79 100644 --- a/base/tools_sanity_unittest.cc +++ b/base/tools_sanity_unittest.cc
@@ -105,7 +105,7 @@ // The following tests pass with Clang r170392, but not r172454, which // makes AddressSanitizer detect errors in them. We disable these tests under // AddressSanitizer until we fully switch to Clang r172454. After that the -// tests should be put back under the (defined(OS_IOS) || defined(OS_WIN)) +// tests should be put back under the (BUILDFLAG(IS_IOS) || BUILDFLAG(IS_WIN)) // clause above. // See also http://crbug.com/172614. #if defined(ADDRESS_SANITIZER) @@ -223,7 +223,7 @@ HARMFUL_ACCESS(debug::AsanHeapUseAfterFree(), "heap-use-after-free"); } -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) // The ASAN runtime doesn't detect heap corruption, this needs fixing before // ASAN builds can ship to the wild. See https://crbug.com/818747. TEST(ToolsSanityTest, DISABLED_AsanCorruptHeapBlock) { @@ -235,7 +235,7 @@ // particular string to look for in the stack trace. EXPECT_DEATH(debug::AsanCorruptHeap(), ""); } -#endif // OS_WIN +#endif // BUILDFLAG(IS_WIN) #endif // !HARMFUL_ACCESS_IS_NOOP namespace { @@ -335,9 +335,9 @@ } #if BUILDFLAG(CFI_ENFORCEMENT_TRAP) -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) #define CFI_ERROR_MSG "EXCEPTION_ILLEGAL_INSTRUCTION" -#elif defined(OS_ANDROID) +#elif BUILDFLAG(IS_ANDROID) // TODO(pcc): Produce proper stack dumps on Android and test for the correct // si_code here. #define CFI_ERROR_MSG "^$"
diff --git a/base/trace_event/builtin_categories.h b/base/trace_event/builtin_categories.h index 41b0d05..5404ede 100644 --- a/base/trace_event/builtin_categories.h +++ b/base/trace_event/builtin_categories.h
@@ -433,7 +433,7 @@ // All trace categories are checked against this. A static_assert is triggered // if at least one category fails this check. static constexpr bool IsAllowedCategory(const char* category) { -#if defined(OS_WIN) && defined(COMPONENT_BUILD) +#if BUILDFLAG(IS_WIN) && defined(COMPONENT_BUILD) return true; #else return IsBuiltinCategory(category) ||
diff --git a/base/trace_event/category_registry.h b/base/trace_event/category_registry.h index a2358b0..5fff7b6 100644 --- a/base/trace_event/category_registry.h +++ b/base/trace_event/category_registry.h
@@ -70,8 +70,8 @@ // TraceCategory owned by the registry. static constexpr TraceCategory* GetBuiltinCategoryByName( const char* category_group) { -#if defined(OS_WIN) && defined(COMPONENT_BUILD) - // The address cannot be evaluated at compile-time in Windows compoment +#if BUILDFLAG(IS_WIN) && defined(COMPONENT_BUILD) + // The address cannot be evaluated at compile-time in Windows component // builds. return nullptr; #else
diff --git a/base/trace_event/common/trace_event_common.h b/base/trace_event/common/trace_event_common.h index 1fd2283d..fb1ce8a 100644 --- a/base/trace_event/common/trace_event_common.h +++ b/base/trace_event/common/trace_event_common.h
@@ -259,10 +259,10 @@ perfetto::ThreadTrack BASE_EXPORT ConvertThreadId(const ::base::PlatformThreadId& thread); -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) template <> perfetto::ThreadTrack BASE_EXPORT ConvertThreadId(const int& thread); -#endif // defined(OS_WIN) +#endif // BUILDFLAG(IS_WIN) } // namespace legacy
diff --git a/base/trace_event/heap_profiler_allocation_context_tracker.cc b/base/trace_event/heap_profiler_allocation_context_tracker.cc index acdd344..8901a90 100644 --- a/base/trace_event/heap_profiler_allocation_context_tracker.cc +++ b/base/trace_event/heap_profiler_allocation_context_tracker.cc
@@ -23,11 +23,11 @@ #include "base/trace_event/heap_profiler_allocation_context.h" #include "build/build_config.h" -#if defined(OS_ANDROID) && BUILDFLAG(CAN_UNWIND_WITH_CFI_TABLE) +#if BUILDFLAG(IS_ANDROID) && BUILDFLAG(CAN_UNWIND_WITH_CFI_TABLE) #include "base/trace_event/cfi_backtrace_android.h" #endif -#if defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_ANDROID) +#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID) #include <sys/prctl.h> #endif @@ -64,7 +64,7 @@ // are used to tag allocations even after the thread dies. const char* GetAndLeakThreadName() { char name[16]; -#if defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_ANDROID) +#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID) // If the thread name is not set, try to get it from prctl. Thread name might // not be set in cases where the thread started before heap profiling was // enabled. @@ -72,7 +72,8 @@ if (!err) { return strdup(name); } -#endif // defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_ANDROID) +#endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || + // BUILDFLAG(IS_ANDROID) // Use tid if we don't have a thread name. snprintf(name, sizeof(name), "%lu", @@ -162,7 +163,7 @@ CaptureMode mode = capture_mode_.load(std::memory_order_relaxed); auto* backtrace = std::begin(ctx->backtrace.frames); -#if !defined(OS_NACL) +#if !BUILDFLAG(IS_NACL) auto* backtrace_end = std::end(ctx->backtrace.frames); #endif @@ -193,14 +194,14 @@ // from this point and up until main(). We intentionally request // kMaxFrameCount + 1 frames, so that we know if there are more frames // than our backtrace capacity. -#if !defined(OS_NACL) // We don't build base/debug/stack_trace.cc for NaCl. -#if defined(OS_ANDROID) && BUILDFLAG(CAN_UNWIND_WITH_CFI_TABLE) - const void* frames[Backtrace::kMaxFrameCount + 1]; - static_assert(base::size(frames) >= Backtrace::kMaxFrameCount, - "not requesting enough frames to fill Backtrace"); - size_t frame_count = - CFIBacktraceAndroid::GetInitializedInstance()->Unwind( - frames, base::size(frames)); +#if !BUILDFLAG(IS_NACL) // We don't build base/debug/stack_trace.cc for NaCl. +#if BUILDFLAG(IS_ANDROID) && BUILDFLAG(CAN_UNWIND_WITH_CFI_TABLE) + const void* frames[Backtrace::kMaxFrameCount + 1]; + static_assert(base::size(frames) >= Backtrace::kMaxFrameCount, + "not requesting enough frames to fill Backtrace"); + size_t frame_count = + CFIBacktraceAndroid::GetInitializedInstance()->Unwind( + frames, base::size(frames)); #elif BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS) const void* frames[Backtrace::kMaxFrameCount + 1]; static_assert(base::size(frames) >= Backtrace::kMaxFrameCount, @@ -227,7 +228,7 @@ const void* frame = frames[i]; *backtrace++ = StackFrame::FromProgramCounter(frame); } -#endif // !defined(OS_NACL) +#endif // !BUILDFLAG(IS_NACL) break; } }
diff --git a/base/trace_event/malloc_dump_provider.cc b/base/trace_event/malloc_dump_provider.cc index d471a773..1c427e8 100644 --- a/base/trace_event/malloc_dump_provider.cc +++ b/base/trace_event/malloc_dump_provider.cc
@@ -21,16 +21,16 @@ #include "base/trace_event/traced_value.h" #include "build/build_config.h" -#if defined(OS_APPLE) +#if BUILDFLAG(IS_APPLE) #include <malloc/malloc.h> #else #include <malloc.h> #endif -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) #include <windows.h> #endif -#if defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_ANDROID) +#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID) #include <features.h> #endif @@ -46,7 +46,7 @@ namespace trace_event { namespace { -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) // A structure containing some information about a given heap. struct WinHeapInfo { size_t committed_size; @@ -104,7 +104,7 @@ } } } -#endif // defined(OS_WIN) +#endif // BUILDFLAG(IS_WIN) #if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) void ReportPartitionAllocStats(ProcessMemoryDump* pmd, @@ -196,7 +196,7 @@ &allocated_objects_count); #endif // TODO(keishi): Add glibc malloc on Android -#elif defined(OS_APPLE) +#elif BUILDFLAG(IS_APPLE) malloc_statistics_t stats = {0}; malloc_zone_statistics(nullptr, &stats); total_virtual_size = stats.size_allocated; @@ -214,11 +214,11 @@ // fragmentation. See // https://bugs.chromium.org/p/chromium/issues/detail?id=695263#c1. resident_size = stats.size_in_use; -#elif defined(OS_WIN) +#elif BUILDFLAG(IS_WIN) ReportWinHeapStats(args.level_of_detail, nullptr, &total_virtual_size, &resident_size, &allocated_objects_size, &allocated_objects_count); -#elif defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_FUCHSIA) // TODO(fuchsia): Port, see https://crbug.com/706592. #else #if defined(__GLIBC__) && defined(__GLIBC_PREREQ)
diff --git a/base/trace_event/malloc_dump_provider.h b/base/trace_event/malloc_dump_provider.h index d30b2266..ca6c0c6 100644 --- a/base/trace_event/malloc_dump_provider.h +++ b/base/trace_event/malloc_dump_provider.h
@@ -13,8 +13,8 @@ #include "base/trace_event/memory_dump_provider.h" #include "build/build_config.h" -#if defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_ANDROID) || \ - defined(OS_WIN) || defined(OS_MAC) +#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID) || \ + BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) #define MALLOC_MEMORY_TRACING_SUPPORTED #endif
diff --git a/base/trace_event/memory_allocator_dump_unittest.cc b/base/trace_event/memory_allocator_dump_unittest.cc index ac6531d..9298df57 100644 --- a/base/trace_event/memory_allocator_dump_unittest.cc +++ b/base/trace_event/memory_allocator_dump_unittest.cc
@@ -150,8 +150,8 @@ } // DEATH tests are not supported in Android/iOS/Fuchsia. -#if !defined(NDEBUG) && !defined(OS_ANDROID) && !defined(OS_IOS) && \ - !defined(OS_FUCHSIA) +#if !defined(NDEBUG) && !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_IOS) && \ + !BUILDFLAG(IS_FUCHSIA) TEST(MemoryAllocatorDumpTest, ForbidDuplicatesDeathTest) { FakeMemoryAllocatorDumpProvider fmadp; MemoryDumpArgs dump_args = {MemoryDumpLevelOfDetail::DETAILED};
diff --git a/base/trace_event/memory_dump_manager.cc b/base/trace_event/memory_dump_manager.cc index f1d73fc..24e17a70 100644 --- a/base/trace_event/memory_dump_manager.cc +++ b/base/trace_event/memory_dump_manager.cc
@@ -35,14 +35,14 @@ #include "base/trace_event/traced_value.h" #include "build/build_config.h" -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) #include "base/trace_event/java_heap_dump_provider_android.h" #if BUILDFLAG(CAN_UNWIND_WITH_CFI_TABLE) #include "base/trace_event/cfi_backtrace_android.h" #endif -#endif // defined(OS_ANDROID) +#endif // BUILDFLAG(IS_ANDROID) namespace base { namespace trace_event { @@ -133,7 +133,7 @@ RegisterDumpProvider(MallocDumpProvider::GetInstance(), "Malloc", nullptr); #endif -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) RegisterDumpProvider(JavaHeapDumpProvider::GetInstance(), "JavaHeap", nullptr); #endif
diff --git a/base/trace_event/memory_dump_manager_unittest.cc b/base/trace_event/memory_dump_manager_unittest.cc index afdc21f..1cda424 100644 --- a/base/trace_event/memory_dump_manager_unittest.cc +++ b/base/trace_event/memory_dump_manager_unittest.cc
@@ -400,7 +400,7 @@ // Checks that the dump provider invocations depend only on the current // registration state and not on previous registrations and dumps. // Flaky on iOS, see crbug.com/706874 -#if defined(OS_IOS) +#if BUILDFLAG(IS_IOS) #define MAYBE_RegistrationConsistency DISABLED_RegistrationConsistency #else #define MAYBE_RegistrationConsistency RegistrationConsistency
diff --git a/base/trace_event/process_memory_dump.cc b/base/trace_event/process_memory_dump.cc index 25666cea..07f805a 100644 --- a/base/trace_event/process_memory_dump.cc +++ b/base/trace_event/process_memory_dump.cc
@@ -25,15 +25,15 @@ #include "third_party/perfetto/protos/perfetto/trace/memory_graph.pbzero.h" #include "third_party/perfetto/protos/perfetto/trace/trace_packet.pbzero.h" -#if defined(OS_IOS) +#if BUILDFLAG(IS_IOS) #include <mach/vm_page_size.h> #endif -#if defined(OS_POSIX) || defined(OS_FUCHSIA) +#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) #include <sys/mman.h> #endif -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) #include <windows.h> // Must be in front of other Windows header files #include <Psapi.h> @@ -73,7 +73,7 @@ #if defined(COUNT_RESIDENT_BYTES_SUPPORTED) // static size_t ProcessMemoryDump::GetSystemPageSize() { -#if defined(OS_IOS) +#if BUILDFLAG(IS_IOS) // On iOS, getpagesize() returns the user page sizes, but for allocating // arrays for mincore(), kernel page sizes is needed. Use vm_kernel_page_size // as recommended by Apple, https://forums.developer.apple.com/thread/47532/. @@ -81,7 +81,7 @@ return vm_kernel_page_size; #else return base::GetPageSize(); -#endif // defined(OS_IOS) +#endif // BUILDFLAG(IS_IOS) } // static @@ -102,12 +102,12 @@ const size_t kMaxChunkSize = 8 * 1024 * 1024; size_t max_vec_size = GetSystemPageCount(std::min(mapped_size, kMaxChunkSize), page_size); -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) std::unique_ptr<PSAPI_WORKING_SET_EX_INFORMATION[]> vec( new PSAPI_WORKING_SET_EX_INFORMATION[max_vec_size]); -#elif defined(OS_APPLE) +#elif BUILDFLAG(IS_APPLE) std::unique_ptr<char[]> vec(new char[max_vec_size]); -#elif defined(OS_POSIX) || defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) std::unique_ptr<unsigned char[]> vec(new unsigned char[max_vec_size]); #endif @@ -119,7 +119,7 @@ [[maybe_unused]] const size_t page_count = GetSystemPageCount(chunk_size, page_size); size_t resident_page_count = 0; -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) for (size_t i = 0; i < page_count; i++) { vec[i].VirtualAddress = reinterpret_cast<void*>(chunk_start + i * page_size); @@ -130,21 +130,21 @@ for (size_t i = 0; i < page_count; i++) resident_page_count += vec[i].VirtualAttributes.Valid; -#elif defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_FUCHSIA) // TODO(fuchsia): Port, see https://crbug.com/706592. -#elif defined(OS_APPLE) +#elif BUILDFLAG(IS_APPLE) // mincore in MAC does not fail with EAGAIN. failure = !!mincore(reinterpret_cast<void*>(chunk_start), chunk_size, vec.get()); for (size_t i = 0; i < page_count; i++) resident_page_count += vec[i] & MINCORE_INCORE ? 1 : 0; -#elif defined(OS_POSIX) +#elif BUILDFLAG(IS_POSIX) int error_counter = 0; int result = 0; // HANDLE_EINTR tries for 100 times. So following the same pattern. do { result = -#if defined(OS_AIX) +#if BUILDFLAG(IS_AIX) mincore(reinterpret_cast<char*>(chunk_start), chunk_size, reinterpret_cast<char*>(vec.get())); #else @@ -176,7 +176,7 @@ absl::optional<size_t> ProcessMemoryDump::CountResidentBytesInSharedMemory( void* start_address, size_t mapped_size) { -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) // On macOS, use mach_vm_region instead of mincore for performance // (crbug.com/742042). mach_vm_size_t dummy_size = 0; @@ -235,7 +235,7 @@ return resident_pages * PAGE_SIZE; #else return CountResidentBytes(start_address, mapped_size); -#endif // defined(OS_MAC) +#endif // BUILDFLAG(IS_MAC) } #endif // defined(COUNT_RESIDENT_BYTES_SUPPORTED)
diff --git a/base/trace_event/process_memory_dump.h b/base/trace_event/process_memory_dump.h index 31bab50b..b9b9e98 100644 --- a/base/trace_event/process_memory_dump.h +++ b/base/trace_event/process_memory_dump.h
@@ -23,7 +23,7 @@ // Define COUNT_RESIDENT_BYTES_SUPPORTED if platform supports counting of the // resident memory. -#if !defined(OS_NACL) +#if !BUILDFLAG(IS_NACL) #define COUNT_RESIDENT_BYTES_SUPPORTED #endif
diff --git a/base/trace_event/process_memory_dump_unittest.cc b/base/trace_event/process_memory_dump_unittest.cc index 395e740..7459ee0 100644 --- a/base/trace_event/process_memory_dump_unittest.cc +++ b/base/trace_event/process_memory_dump_unittest.cc
@@ -21,10 +21,10 @@ #include "testing/gtest/include/gtest/gtest.h" #include "third_party/abseil-cpp/absl/types/optional.h" -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) #include <windows.h> #include "winbase.h" -#elif defined(OS_POSIX) || defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) #include <sys/mman.h> #endif @@ -39,19 +39,19 @@ "Whitelisted/0x?/TestName", "Whitelisted/0x?", nullptr}; void* Map(size_t size) { -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) return ::VirtualAlloc(nullptr, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); -#elif defined(OS_POSIX) || defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) return ::mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, 0, 0); #endif } void Unmap(void* addr, size_t size) { -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) ::VirtualFree(addr, 0, MEM_DECOMMIT); -#elif defined(OS_POSIX) || defined(OS_FUCHSIA) +#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) ::munmap(addr, size); #else #error This architecture is not (yet) supported. @@ -476,7 +476,7 @@ } #if defined(COUNT_RESIDENT_BYTES_SUPPORTED) -#if defined(OS_FUCHSIA) +#if BUILDFLAG(IS_FUCHSIA) // TODO(crbug.com/851760): Counting resident bytes is not supported on Fuchsia. #define MAYBE_CountResidentBytes DISABLED_CountResidentBytes #else @@ -506,7 +506,7 @@ Unmap(memory2, kVeryLargeMemorySize); } -#if defined(OS_FUCHSIA) +#if BUILDFLAG(IS_FUCHSIA) // TODO(crbug.com/851760): Counting resident bytes is not supported on Fuchsia. #define MAYBE_CountResidentBytesInSharedMemory \ DISABLED_CountResidentBytesInSharedMemory
diff --git a/base/trace_event/thread_instruction_count.cc b/base/trace_event/thread_instruction_count.cc index bd4feed..a38cb3e 100644 --- a/base/trace_event/thread_instruction_count.cc +++ b/base/trace_event/thread_instruction_count.cc
@@ -11,18 +11,18 @@ #include "base/threading/thread_local_storage.h" #include "build/build_config.h" -#if defined(OS_LINUX) || defined(OS_CHROMEOS) +#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) #include <linux/perf_event.h> #include <sys/syscall.h> #include <unistd.h> -#endif // defined(OS_LINUX) || defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) namespace base { namespace trace_event { namespace { -#if defined(OS_LINUX) || defined(OS_CHROMEOS) +#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) // Special constants used for counter FD states. constexpr int kPerfFdDisabled = -2; @@ -80,12 +80,12 @@ return fd; } -#endif // defined(OS_LINUX) || defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) } // namespace bool ThreadInstructionCount::IsSupported() { -#if defined(OS_LINUX) || defined(OS_CHROMEOS) +#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) // If we can't initialize the counter FD, mark as disabled. int counter_fd = InstructionCounterFdForCurrentThread(); if (counter_fd <= 0) @@ -99,7 +99,7 @@ ThreadInstructionCount ThreadInstructionCount::Now() { DCHECK(IsSupported()); -#if defined(OS_LINUX) || defined(OS_CHROMEOS) +#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) int fd = InstructionCounterFdForCurrentThread(); if (fd <= 0) return ThreadInstructionCount(); @@ -112,7 +112,7 @@ return ThreadInstructionCount(instructions); #else return ThreadInstructionCount(); -#endif // defined(OS_LINUX) || defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) } } // namespace trace_event
diff --git a/base/trace_event/trace_category_unittest.cc b/base/trace_event/trace_category_unittest.cc index eeb76eb..bfc2a5f 100644 --- a/base/trace_event/trace_category_unittest.cc +++ b/base/trace_event/trace_category_unittest.cc
@@ -125,7 +125,7 @@ // Tries to cover the case of multiple threads creating the same category // simultaneously. Should never end up with distinct entries with the same name. -#if defined(OS_FUCHSIA) +#if BUILDFLAG(IS_FUCHSIA) // TODO(crbug.com/738275): This is flaky on Fuchsia. #define MAYBE_ThreadRaces DISABLED_ThreadRaces #else @@ -160,7 +160,7 @@ TEST_F(TraceCategoryTest, GetCategoryAtCompileTime) { static_assert(GetBuiltinCategoryByName("nonexistent") == nullptr, "nonexistent found"); -#if defined(OS_WIN) && defined(COMPONENT_BUILD) +#if BUILDFLAG(IS_WIN) && defined(COMPONENT_BUILD) static_assert(GetBuiltinCategoryByName("toplevel") == nullptr, "toplevel found"); #else
diff --git a/base/trace_event/trace_event_impl.cc b/base/trace_event/trace_event_impl.cc index 71fc039..2136e78f 100644 --- a/base/trace_event/trace_event_impl.cc +++ b/base/trace_event/trace_event_impl.cc
@@ -19,6 +19,7 @@ #include "base/trace_event/trace_event.h" #include "base/trace_event/trace_log.h" #include "base/trace_event/traced_value.h" +#include "build/build_config.h" #if BUILDFLAG(USE_PERFETTO_CLIENT_LIBRARY) @@ -34,12 +35,12 @@ return perfetto::ThreadTrack::ForThread(static_cast<int32_t>(thread)); } -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) template <> perfetto::ThreadTrack ConvertThreadId(const int& thread) { return perfetto::ThreadTrack::ForThread(static_cast<int32_t>(thread)); } -#endif // defined(OS_WIN) +#endif // BUILDFLAG(IS_WIN) } // namespace legacy
diff --git a/base/trace_event/trace_event_impl.h b/base/trace_event/trace_event_impl.h index 7af89c29..2cd380f2 100644 --- a/base/trace_event/trace_event_impl.h +++ b/base/trace_event/trace_event_impl.h
@@ -152,7 +152,7 @@ : nullptr; } -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) void SendToATrace(); #endif
diff --git a/base/trace_event/trace_event_unittest.cc b/base/trace_event/trace_event_unittest.cc index 3712c08..0305a1de 100644 --- a/base/trace_event/trace_event_unittest.cc +++ b/base/trace_event/trace_event_unittest.cc
@@ -1801,11 +1801,11 @@ } // Flaky on iOS device, see crbug.com/908002 -#if defined(OS_IOS) && !(TARGET_OS_SIMULATOR) +#if BUILDFLAG(IS_IOS) && !(TARGET_OS_SIMULATOR) #define MAYBE_TraceWithDisabledByDefaultCategoryFilters DISABLED_TraceWithDisabledByDefaultCategoryFilters #else #define MAYBE_TraceWithDisabledByDefaultCategoryFilters TraceWithDisabledByDefaultCategoryFilters -#endif // defined(OS_IOS) && !(TARGET_OS_SIMULATOR) +#endif // BUILDFLAG(IS_IOS) && !(TARGET_OS_SIMULATOR) TEST_F(TraceEventTestFixture, MAYBE_TraceWithDisabledByDefaultCategoryFilters) { TraceLog* trace_log = TraceLog::GetInstance(); @@ -2480,11 +2480,11 @@ } // Flaky on iOS device, see crbug.com/908002 -#if defined(OS_IOS) && !(TARGET_OS_SIMULATOR) +#if BUILDFLAG(IS_IOS) && !(TARGET_OS_SIMULATOR) #define MAYBE_EchoToConsole DISABLED_EchoToConsole #else #define MAYBE_EchoToConsole EchoToConsole -#endif // defined(OS_IOS) && !(TARGET_OS_SIMULATOR) +#endif // BUILDFLAG(IS_IOS) && !(TARGET_OS_SIMULATOR) TEST_F(TraceEventTestFixture, MAYBE_EchoToConsole) { logging::LogMessageHandlerFunction old_log_message_handler = logging::GetLogMessageHandler(); @@ -2580,11 +2580,11 @@ // Runtime filtering isn't supported with Perfetto. #if !BUILDFLAG(USE_PERFETTO_CLIENT_LIBRARY) // Flaky on iOS device, see crbug.com/908002 -#if defined(OS_IOS) && !(TARGET_OS_SIMULATOR) +#if BUILDFLAG(IS_IOS) && !(TARGET_OS_SIMULATOR) #define MAYBE_TraceFilteringMode DISABLED_TraceFilteringMode #else #define MAYBE_TraceFilteringMode TraceFilteringMode -#endif // defined(OS_IOS) && !(TARGET_OS_SIMULATOR) +#endif // BUILDFLAG(IS_IOS) && !(TARGET_OS_SIMULATOR) TEST_F(TraceEventTestFixture, MAYBE_TraceFilteringMode) { const char config_json[] = "{" @@ -2677,11 +2677,11 @@ } // Flaky on iOS device, see crbug.com/908002 -#if defined(OS_IOS) && !(TARGET_OS_SIMULATOR) +#if BUILDFLAG(IS_IOS) && !(TARGET_OS_SIMULATOR) #define MAYBE_EventFiltering DISABLED_EventFiltering #else #define MAYBE_EventFiltering EventFiltering -#endif // defined(OS_IOS) && !(TARGET_OS_SIMULATOR) +#endif // BUILDFLAG(IS_IOS) && !(TARGET_OS_SIMULATOR) TEST_F(TraceEventTestFixture, MAYBE_EventFiltering) { const char config_json[] = "{" @@ -2727,11 +2727,11 @@ } // Flaky on iOS device, see crbug.com/908002 -#if defined(OS_IOS) && !(TARGET_OS_SIMULATOR) +#if BUILDFLAG(IS_IOS) && !(TARGET_OS_SIMULATOR) #define MAYBE_EventAllowlistFiltering DISABLED_EventAllowlistFiltering #else #define MAYBE_EventAllowlistFiltering EventAllowlistFiltering -#endif // defined(OS_IOS) && !(TARGET_OS_SIMULATOR) +#endif // BUILDFLAG(IS_IOS) && !(TARGET_OS_SIMULATOR) TEST_F(TraceEventTestFixture, MAYBE_EventAllowlistFiltering) { std::string config_json = StringPrintf( "{"
diff --git a/base/trace_event/trace_log.cc b/base/trace_event/trace_log.cc index 8bc58b1..c84811d 100644 --- a/base/trace_event/trace_log.cc +++ b/base/trace_event/trace_log.cc
@@ -59,11 +59,11 @@ #include "third_party/perfetto/protos/perfetto/trace/track_event/thread_descriptor.gen.h" // nogncheck #endif -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) #include "base/trace_event/trace_event_etw_export_win.h" #endif -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) #include "base/debug/elf_reader.h" // The linker assigns the virtual address of the start of current library to @@ -390,7 +390,7 @@ } // namespace -#if BUILDFLAG(USE_PERFETTO_CLIENT_LIBRARY) && !defined(OS_NACL) +#if BUILDFLAG(USE_PERFETTO_CLIENT_LIBRARY) && !BUILDFLAG(IS_NACL) namespace { // Perfetto provides us with a fully formed JSON trace file, while // TraceResultBuffer wants individual JSON fragments without a containing @@ -461,7 +461,7 @@ scoped_refptr<RefCountedString> buffer_ = new RefCountedString(); bool did_strip_prefix_ = false; }; -#endif // BUILDFLAG(USE_PERFETTO_CLIENT_LIBRARY) && !defined(OS_NACL) +#endif // BUILDFLAG(USE_PERFETTO_CLIENT_LIBRARY) && !BUILDFLAG(IS_NACL) // A helper class that allows the lock to be acquired in the middle of the scope // and unlocks at the end of scope if locked. @@ -687,7 +687,7 @@ use_worker_thread_(false) { CategoryRegistry::Initialize(); -#if defined(OS_NACL) // NaCl shouldn't expose the process id. +#if BUILDFLAG(IS_NACL) // NaCl shouldn't expose the process id. SetProcessID(0); #else SetProcessID(static_cast<int>(GetCurrentProcId())); @@ -812,7 +812,7 @@ state_flags |= TraceCategory::ENABLED_FOR_RECORDING; } -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) if (base::trace_event::TraceEventETWExport::IsCategoryGroupEnabled( category->name())) { state_flags |= TraceCategory::ENABLED_FOR_ETW_EXPORT; @@ -1382,7 +1382,7 @@ bool discard_events) { use_worker_thread_ = use_worker_thread; -#if BUILDFLAG(USE_PERFETTO_CLIENT_LIBRARY) && !defined(OS_NACL) +#if BUILDFLAG(USE_PERFETTO_CLIENT_LIBRARY) && !BUILDFLAG(IS_NACL) perfetto::TrackEvent::Flush(); if (discard_events) { @@ -1422,11 +1422,11 @@ auto data = tracing_session_->ReadTraceBlocking(); OnTraceData(data.data(), data.size(), /*has_more=*/false); } -#elif BUILDFLAG(USE_PERFETTO_CLIENT_LIBRARY) && defined(OS_NACL) +#elif BUILDFLAG(USE_PERFETTO_CLIENT_LIBRARY) && BUILDFLAG(IS_NACL) // Trace processor isn't built on NaCL, so we can't convert the resulting // trace into JSON. CHECK(false) << "JSON tracing isn't supported on NaCL"; -#else // !BUILDFLAG(USE_PERFETTO_CLIENT_LIBRARY) +#else if (IsEnabled()) { // Can't flush when tracing is enabled because otherwise PostTask would // - generate more trace events; @@ -1475,10 +1475,10 @@ } FinishFlush(gen, discard_events); -#endif // !BUILDFLAG(USE_PERFETTO_CLIENT_LIBRARY) +#endif // BUILDFLAG(USE_PERFETTO_CLIENT_LIBRARY) && !BUILDFLAG(IS_NACL) } -#if BUILDFLAG(USE_PERFETTO_CLIENT_LIBRARY) && !defined(OS_NACL) +#if BUILDFLAG(USE_PERFETTO_CLIENT_LIBRARY) && !BUILDFLAG(IS_NACL) void TraceLog::OnTraceData(const char* data, size_t size, bool has_more) { if (proto_output_callback_) { scoped_refptr<RefCountedString> chunk = new RefCountedString(); @@ -1508,7 +1508,7 @@ tracing_session_.reset(); json_output_writer_.reset(); } -#endif // BUILDFLAG(USE_PERFETTO_CLIENT_LIBRARY) && !defined(OS_NACL) +#endif // BUILDFLAG(USE_PERFETTO_CLIENT_LIBRARY) && !BUILDFLAG(IS_NACL) // Usually it runs on a different thread. void TraceLog::ConvertTraceEventsToTraceFormat( @@ -1711,14 +1711,14 @@ } } -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) // This is done sooner rather than later, to avoid creating the event and // acquiring the lock, which is not needed for ETW as it's already threadsafe. if (*category_group_enabled & TraceCategory::ENABLED_FOR_ETW_EXPORT) { TraceEventETWExport::AddEvent(phase, category_group_enabled, name, id, args); } -#endif // OS_WIN +#endif // BUILDFLAG(IS_WIN) return true; } @@ -1922,7 +1922,7 @@ args, flags); } -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) trace_event->SendToATrace(); #endif } @@ -2057,11 +2057,11 @@ return; AutoThreadLocalBoolean thread_is_in_trace_event(&thread_is_in_trace_event_); -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) // Generate an ETW event that marks the end of a complete event. if (category_group_enabled_local & TraceCategory::ENABLED_FOR_ETW_EXPORT) TraceEventETWExport::AddCompleteEndEvent(category_group_enabled, name); -#endif // OS_WIN +#endif // BUILDFLAG(IS_WIN) if (category_group_enabled_local & TraceCategory::ENABLED_FOR_RECORDING) { auto update_duration_override = @@ -2083,7 +2083,7 @@ DCHECK(trace_event->phase() == TRACE_EVENT_PHASE_COMPLETE); trace_event->UpdateDuration(now, thread_now, thread_instruction_now); -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) trace_event->SendToATrace(); #endif } @@ -2144,7 +2144,7 @@ } } -#if !defined(OS_NACL) // NaCl shouldn't expose the process id. +#if !BUILDFLAG(IS_NACL) // NaCl shouldn't expose the process id. AddMetadataEventWhileLocked(0, "num_cpus", "number", base::SysInfo::NumberOfProcessors()); #endif @@ -2155,7 +2155,7 @@ "sort_index", process_sort_index_); } -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) AddMetadataEventWhileLocked(current_thread_id, "chrome_library_address", "start_address", base::StringPrintf("%p", &__executable_start)); @@ -2320,7 +2320,7 @@ : kTraceEventVectorBufferChunks); } -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) void TraceLog::UpdateETWCategoryGroupEnabledFlags() { // Go through each category and set/clear the ETW bit depending on whether the // category is enabled. @@ -2333,7 +2333,7 @@ } } } -#endif // defined(OS_WIN) +#endif // BUILDFLAG(IS_WIN) void TraceLog::SetTraceBufferForTesting( std::unique_ptr<TraceBuffer> trace_buffer) {
diff --git a/base/trace_event/trace_log.h b/base/trace_event/trace_log.h index f232e0f..d9d9e49f 100644 --- a/base/trace_event/trace_log.h +++ b/base/trace_event/trace_log.h
@@ -133,13 +133,13 @@ // implement the TRACE_EVENT_IS_NEW_TRACE() primitive. int GetNumTracesRecorded(); -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) void StartATrace(const std::string& category_filter); void StopATrace(); void AddClockSyncMetadataEvent(); void SetupATraceStartupTrace(const std::string& category_filter); absl::optional<TraceConfig> TakeATraceStartupConfig(); -#endif // defined(OS_ANDROID) +#endif // BUILDFLAG(IS_ANDROID) // Enabled state listeners give a callback when tracing is enabled or // disabled. This can be used to tie into other library's tracing systems @@ -438,7 +438,7 @@ // may not handle the flush request in time causing lost of unflushed events. void SetCurrentThreadBlocksMessageLoop(); -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) // This function is called by the ETW exporting module whenever the ETW // keyword (flags) changes. This keyword indicates which categories should be // exported, so whenever it changes, we adjust accordingly. @@ -656,17 +656,17 @@ std::unique_ptr<::base::tracing::PerfettoPlatform> perfetto_platform_; std::unique_ptr<perfetto::TracingSession> tracing_session_; perfetto::TraceConfig perfetto_config_; -#if !defined(OS_NACL) +#if !BUILDFLAG(IS_NACL) std::unique_ptr<perfetto::trace_processor::TraceProcessorStorage> trace_processor_; std::unique_ptr<JsonStringOutputWriter> json_output_writer_; OutputCallback proto_output_callback_; -#endif // !defined(OS_NACL) +#endif // !BUILDFLAG(IS_NACL) #endif // BUILDFLAG(USE_PERFETTO_CLIENT_LIBRARY) FilterFactoryForTesting filter_factory_for_testing_ = nullptr; -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) absl::optional<TraceConfig> atrace_startup_config_; #endif };
diff --git a/base/unguessable_token.cc b/base/unguessable_token.cc index d156be55..04ea514 100644 --- a/base/unguessable_token.cc +++ b/base/unguessable_token.cc
@@ -10,7 +10,7 @@ #include "base/rand_util.h" #include "build/build_config.h" -#if !defined(OS_NACL) +#if !BUILDFLAG(IS_NACL) #include "third_party/boringssl/src/include/openssl/mem.h" #endif @@ -41,7 +41,7 @@ } bool UnguessableToken::operator==(const UnguessableToken& other) const { -#if defined(OS_NACL) +#if BUILDFLAG(IS_NACL) // BoringSSL is unavailable for NaCl builds so it remains timing dependent. return token_ == other.token_; #else
diff --git a/base/win/shortcut_unittest.cc b/base/win/shortcut_unittest.cc index 02a7298..872f211 100644 --- a/base/win/shortcut_unittest.cc +++ b/base/win/shortcut_unittest.cc
@@ -202,7 +202,7 @@ } // TODO(crbug.com/1271993): Flaky on Win7 x86. -#if defined(OS_WIN) && defined(ARCH_CPU_X86) +#if BUILDFLAG(IS_WIN) && defined(ARCH_CPU_X86) #define MAYBE_UpdateShortcutVerifyProperties \ DISABLED_UpdateShortcutVerifyProperties #else
diff --git a/build/config/compiler/BUILD.gn b/build/config/compiler/BUILD.gn index e49fc28..af37ee7 100644 --- a/build/config/compiler/BUILD.gn +++ b/build/config/compiler/BUILD.gn
@@ -598,6 +598,7 @@ cflags_cc += [ "-std=${standard_prefix}++17" ] } } else if (is_win) { + cflags_c += [ "/std:c11" ] cflags_cc += [ "/std:c++17" ] } else if (!is_nacl) { # TODO(mcgrathr) - the NaCl GCC toolchain doesn't support either gnu11/gnu++11
diff --git a/build/fuchsia/linux.sdk.sha1 b/build/fuchsia/linux.sdk.sha1 index 4d0938f..36e71c57 100644 --- a/build/fuchsia/linux.sdk.sha1 +++ b/build/fuchsia/linux.sdk.sha1
@@ -1 +1 @@ -7.20220112.2.4 +7.20220119.0.1
diff --git a/build/fuchsia/mac.sdk.sha1 b/build/fuchsia/mac.sdk.sha1 index 4d0938f..36e71c57 100644 --- a/build/fuchsia/mac.sdk.sha1 +++ b/build/fuchsia/mac.sdk.sha1
@@ -1 +1 @@ -7.20220112.2.4 +7.20220119.0.1
diff --git a/chrome/VERSION b/chrome/VERSION index 31ae570..dbb1cc9 100644 --- a/chrome/VERSION +++ b/chrome/VERSION
@@ -1,4 +1,4 @@ MAJOR=99 MINOR=0 -BUILD=4839 +BUILD=4840 PATCH=0
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/compositor/CompositorSurfaceManagerImplTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/compositor/CompositorSurfaceManagerImplTest.java index b6af10d..82b513fe 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/compositor/CompositorSurfaceManagerImplTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/compositor/CompositorSurfaceManagerImplTest.java
@@ -1,4 +1,4 @@ - +// Copyright 2017 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.
diff --git a/chrome/app/chromeos_strings.grdp b/chrome/app/chromeos_strings.grdp index 1fa854f..3ef1d4e 100644 --- a/chrome/app/chromeos_strings.grdp +++ b/chrome/app/chromeos_strings.grdp
@@ -3916,37 +3916,73 @@ <message name="IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_TITLE" desc="Title for the message in the consolidated consent screen to opt-in for metrics for accounts."> Send usage and diagnostic data. </message> - <message name="IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN" desc="Message in the consolidated consent screen to opt-in for metrics."> + <message name="IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_OWNER" desc="Message in the consolidated consent screen to opt-in for metrics when the user is the device owner."> Help improve Chrome and ChromeOS features and performance by automatically sending crash reports as well as diagnostic and usage data to Google. Some aggregate data will also help Android apps and Google partners. If the Web & App Activity setting is turned on for your Google Account, your Android data may be saved to your Google Account. </message> - <message name="IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_CHILD" desc="Message in the consolidated consent screen to opt-in for metrics for a child account."> + <message name="IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN" desc="Message in the consolidated consent screen to opt-in for metrics."> + Help improve Chrome and ChromeOS features and performance by automatically sending diagnostic and usage data to Google. Some aggregate data will also help Android apps and Google partners. If the Web & App Activity setting is turned on for your Google Account, your Android data may be saved to your Google Account. + </message> + <message name="IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_CHILD_OWNER" desc="Message in the consolidated consent screen to opt-in for metrics for a child device owner account."> Help improve Chrome and ChromeOS features and performance by automatically sending crash reports as well as diagnostic and usage data to Google. Some aggregate data will also help Android apps and Google partners. If the Web & App Activity setting is turned on for your child's Google Account, your child's Android data may be saved to your child's Google Account. </message> - <message name="IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_ARC_DISABLED" desc="Message in the consolidated consent screen to opt-in for metrics when ARC is disabled."> + <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 diagnostic and usage data to Google. Some aggregate data will also help Android apps and Google partners. If the Web & App Activity setting is turned on for your child's Google Account, your child's Android data may be saved to your child's Google Account. + </message> + <message name="IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_ARC_DISABLED_OWNER" desc="Message in the consolidated consent screen to opt-in for metrics when ARC is disabled for device owner."> Help improve Chrome and ChromeOS features and performance by automatically sending crash reports as well as diagnostic and usage data to Google. </message> - <message name="IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE" desc="Text shown in a pop-up dialog in the consolidated consent screen when the user clicks on the learn more for metrics opt-in."> - <ph name="BEGIN_PARAGRAPH1"><p></ph>Help improve Chrome and ChromeOS features and performance by automatically sending crash reports as well as diagnostic and usage data to Google.<ph name="END_PARAGRAPH1"></p></ph> - <ph name="BEGIN_PARAGRAPH2"><p></ph>You can start or stop allowing these reports any time in your ChromeOS device settings. If you're a domain administrator, you can change this setting in the admin console.<ph name="END_PARAGRAPH2"></p></ph> - <ph name="BEGIN_PARAGRAPH3"><p></ph>Turning off this feature doesn't affect your device's ability to send the information needed for essential services such as system updates and security.<ph name="END_PARAGRAPH3"></p></ph> - <ph name="BEGIN_PARAGRAPH4"><p></ph>If the Web & App Activity setting is turned on for your Google Account, your Android data may be saved to your Google Account. You can see your data, delete it, and change your account settings at account.google.com.<ph name="END_PARAGRAPH4"></p></ph> + <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 diagnostic and usage data to Google. </message> - <message name="IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_CHILD" desc="Text shown in a pop-up dialog in the consolidated consent screen when the user clicks on the learn more for metrics opt-in for a child account."> + <message name="IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_LINK" desc="Learn more about usage opt in"> + Learn more about diagnostic and usage data. + </message> + <message name="IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_OWNER" desc="Text shown in a pop-up dialog in the consolidated consent screen when the device owner clicks on the learn more for metrics opt-in."> + <ph name="BEGIN_PARAGRAPH1"><p></ph>Allowing your ChromeOS devices to send automatic reports helps us prioritize what to fix and improve in ChromeOS. These reports can include things like when ChromeOS crashes, which features you use, how much memory you typically use, and Android app diagnostic and usage data. Some aggregate data will also help Google apps and partners, such as Android developers.<ph name="END_PARAGRAPH1"></p></ph> + <ph name="BEGIN_PARAGRAPH2"><p></ph>You can start or stop allowing these reports any time in your ChromeOS device settings. If you’re a domain administrator, you can change this setting in the admin console.<ph name="END_PARAGRAPH2"></p></ph> + <ph name="BEGIN_PARAGRAPH3"><p></ph>If the Web & App Activity setting is turned on for your Google Account, your Android data may be saved to your Google Account. You can see your data, delete it, and change your account settings at account.google.com.<ph name="END_PARAGRAPH3"></p></ph> + </message> + <message name="IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE" desc="Text shown in a pop-up dialog in the consolidated consent screen when the user clicks on the learn more for metrics opt-in."> + <ph name="BEGIN_PARAGRAPH1"><p></ph>Allowing your ChromeOS devices to send automatic reports helps us prioritize what to fix and improve in ChromeOS. These reports can include things like which features you use, how much memory you typically use, Android app diagnostic and usage data, and errors. Some aggregate data will also help Google apps and partners, such as Android developers.<ph name="END_PARAGRAPH1"></p></ph> + <ph name="BEGIN_PARAGRAPH2"><p></ph>You can start or stop allowing these reports any time in your ChromeOS device settings. If you’re a domain administrator, you can change this setting in the admin console.<ph name="END_PARAGRAPH2"></p></ph> + <ph name="BEGIN_PARAGRAPH3"><p></ph>If the Web & App Activity setting is turned on for your Google Account, your Android data may be saved to your Google Account. You can see your data, delete it, and change your account settings at account.google.com.<ph name="END_PARAGRAPH3"></p></ph> + <ph name="BEGIN_PARAGRAPH4"><p></ph>If the device owner turns on "Send usage and diagnostic data", crash reports might also be uploaded to Google.<ph name="END_PARAGRAPH3"></p></ph> + </message> + <message name="IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_CHILD_OWNER" desc="Text shown in a pop-up dialog in the consolidated consent screen when the user clicks on the learn more for metrics opt-in for a child device owner account."> <ph name="BEGIN_PARAGRAPH1"><p></ph>Allowing ChromeOS devices to send automatic reports helps us prioritize what to fix and improve in ChromeOS. These reports can include things like when ChromeOS crashes, which features were used, how much memory was typically used, and Android app diagnostic and usage data. Some aggregate data will also help Google apps and partners, such as Android developers.<ph name="END_PARAGRAPH1"></p></ph> <ph name="BEGIN_PARAGRAPH2"><p></ph>You can start or stop allowing these reports any time in your child's ChromeOS device settings. If you're a domain administrator, you can change this setting in the admin console.<ph name="END_PARAGRAPH2"></p></ph> <ph name="BEGIN_PARAGRAPH3"><p></ph>Turning off this feature doesn't affect this device's ability to send the information needed for essential services such as system updates and security.<ph name="END_PARAGRAPH3"></p></ph> <ph name="BEGIN_PARAGRAPH4"><p></ph>If the Web & App Activity setting is turned on for your child's Google Account, your child's data may be saved to their Google Account. Learn more about these settings and how to adjust them at families.google.com.<ph name="END_PARAGRAPH4"></p></ph> </message> - <message name="IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_ARC_DISABLED" desc="Text shown in a pop-up dialog in the consolidated consent screen when the user clicks on the learn more for metrics opt-in when ARC is disabled."> - <ph name="BEGIN_PARAGRAPH1"><p></ph>Allowing ChromeOS devices to send automatic reports helps us prioritize what to fix and improve in ChromeOS. These reports can include things like when ChromeOS crashes, which features were used, and how much memory was typically used.<ph name="END_PARAGRAPH1"></p></ph> + <message name="IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_CHILD" desc="Text shown in a pop-up dialog in the consolidated consent screen when the user clicks on the learn more for metrics opt-in for a child account."> + <ph name="BEGIN_PARAGRAPH1"><p></ph>Allowing ChromeOS devices to send automatic reports helps us prioritize what to fix and improve in ChromeOS. These reports can include things like which features were used, how much memory was typically used, and Android app diagnostic and usage data. Some aggregate data will also help Google apps and partners, such as Android developers.<ph name="END_PARAGRAPH1"></p></ph> + <ph name="BEGIN_PARAGRAPH2"><p></ph>You can start or stop allowing these reports any time in your child's ChromeOS device settings. If you're a domain administrator, you can change this setting in the admin console.<ph name="END_PARAGRAPH2"></p></ph> + <ph name="BEGIN_PARAGRAPH3"><p></ph>Turning off this feature doesn't affect this device's ability to send the information needed for essential services such as system updates and security.<ph name="END_PARAGRAPH3"></p></ph> + <ph name="BEGIN_PARAGRAPH4"><p></ph>If the Web & App Activity setting is turned on for your child's Google Account, your child's data may be saved to their Google Account. Learn more about these settings and how to adjust them at families.google.com.<ph name="END_PARAGRAPH4"></p></ph> + <ph name="BEGIN_PARAGRAPH4"><p></ph>If the device owner turns on "Send usage and diagnostic data", crash reports might also be uploaded to Google.<ph name="END_PARAGRAPH3"></p></ph> + </message> + <message name="IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_ARC_DISABLED_OWNER" desc="Text shown in a pop-up dialog in the consolidated consent screen when the device owner clicks on the learn more for metrics opt-in when ARC is disabled."> + <ph name="BEGIN_PARAGRAPH1"><p></ph>Allowing your ChromeOS devices to send automatic reports helps us prioritize what to fix and improve in ChromeOS. These reports can include things like when ChromeOS crashes, which features you use and how much memory you typically use.<ph name="END_PARAGRAPH1"></p></ph> <ph name="BEGIN_PARAGRAPH2"><p></ph>You can start or stop allowing these reports any time in your Chrome device settings. If you’re a domain administrator, you can change this setting in the admin console.<ph name="END_PARAGRAPH2"></p></ph> <ph name="BEGIN_PARAGRAPH3"><p></ph>Turning off this feature doesn't affect your device's ability to send the information needed for essential services such as system updates and security.<ph name="END_PARAGRAPH3"></p></ph> </message> - <message name="IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_ARC_DISABLED_CHILD" desc="Text shown in a pop-up dialog in the consolidated consent screen when the user clicks on the learn more for metrics opt-in when ARC is disabled in a child account."> + <message name="IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_ARC_DISABLED" desc="Text shown in a pop-up dialog in the consolidated consent screen when the user clicks on the learn more for metrics opt-in when ARC is disabled."> + <ph name="BEGIN_PARAGRAPH1"><p></ph>Allowing your ChromeOS devices to send automatic reports helps us prioritize what to fix and improve in ChromeOS. These reports can include things like which features you use and how much memory you typically use.<ph name="END_PARAGRAPH1"></p></ph> + <ph name="BEGIN_PARAGRAPH2"><p></ph>You can start or stop allowing these reports any time in your Chrome device settings. If you’re a domain administrator, you can change this setting in the admin console.<ph name="END_PARAGRAPH2"></p></ph> + <ph name="BEGIN_PARAGRAPH3"><p></ph>Turning off this feature doesn't affect your device's ability to send the information needed for essential services such as system updates and security.<ph name="END_PARAGRAPH3"></p></ph> + <ph name="BEGIN_PARAGRAPH4"><p></ph>If the device owner turns on "Send usage and diagnostic data", crash reports might also be uploaded to Google.<ph name="END_PARAGRAPH3"></p></ph> + </message> + <message name="IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_ARC_DISABLED_CHILD_OWNER" desc="Text shown in a pop-up dialog in the consolidated consent screen when the user clicks on the learn more for metrics opt-in when ARC is disabled in a child account."> <ph name="BEGIN_PARAGRAPH1"><p></ph>Allowing ChromeOS devices to send automatic reports helps us prioritize what to fix and improve in ChromeOS. These reports can include things like when ChromeOS crashes, which features were used, and how much memory was typically used.<ph name="END_PARAGRAPH1"></p></ph> <ph name="BEGIN_PARAGRAPH2"><p></ph>You can start or stop allowing these reports any time in your child's ChromeOS device settings. If you're a domain administrator, you can change this setting in the admin console.<ph name="END_PARAGRAPH2"></p></ph> <ph name="BEGIN_PARAGRAPH3"><p></ph>Turning off this feature doesn't affect this device's ability to send the information needed for essential services such as system updates and security.<ph name="END_PARAGRAPH3"></p></ph> </message> + <message name="IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_ARC_DISABLED_CHILD" desc="Text shown in a pop-up dialog in the consolidated consent screen when the user clicks on the learn more for metrics opt-in when ARC is disabled in a child account."> + <ph name="BEGIN_PARAGRAPH1"><p></ph>Allowing ChromeOS devices to send automatic reports helps us prioritize what to fix and improve in ChromeOS. These reports can include things like when which features were used, and how much memory was typically used.<ph name="END_PARAGRAPH1"></p></ph> + <ph name="BEGIN_PARAGRAPH2"><p></ph>You can start or stop allowing these reports any time in your child's ChromeOS device settings. If you're a domain administrator, you can change this setting in the admin console.<ph name="END_PARAGRAPH2"></p></ph> + <ph name="BEGIN_PARAGRAPH3"><p></ph>Turning off this feature doesn't affect this device's ability to send the information needed for essential services such as system updates and security.<ph name="END_PARAGRAPH3"></p></ph> + <ph name="BEGIN_PARAGRAPH4"><p></ph>If the device owner turns on "Send usage and diagnostic data", crash reports might also be uploaded to Google.<ph name="END_PARAGRAPH3"></p></ph> + </message> <message name="IDS_CONSOLIDATED_CONSENT_BACKUP_OPT_IN_TITLE" desc="Title for the message in the consolidated consent screen to opt-in for back-up."> Back up Android apps to Google Drive. </message> @@ -3964,6 +4000,9 @@ <ph name="BEGIN_PARAGRAPH1"><p></ph>App data can be any data that an app has saved (based on developer settings), including data such as contacts, messages, and photos. Backup data will not count toward your child's Drive storage quota.<ph name="END_PARAGRAPH1"></p></ph> <ph name="BEGIN_PARAGRAPH2"><p></ph>You can turn this service off in Settings.<ph name="END_PARAGRAPH2"></p></ph> </message> + <message name="IDS_CONSOLIDATED_CONSENT_BACKUP_OPT_IN_LEARN_MORE_LINK" desc="Learn more about backup opt in"> + Learn more about backing up your apps + </message> <message name="IDS_CONSOLIDATED_CONSENT_LOCATION_OPT_IN_TITLE" desc="Title for the message in the consolidated consent screen to opt-in for location services."> Use location for Android apps and services. </message> @@ -3981,6 +4020,9 @@ <ph name="BEGIN_PARAGRAPH1"><p></ph>Google's location service uses sources like Wi-Fi, mobile networks, and sensors to help estimate this device's location.<ph name="END_PARAGRAPH1"></p></ph> <ph name="BEGIN_PARAGRAPH2"><p></ph>You can turn off Android location on this device at any time by going to Settings > Apps > Google Play Store > Manage Android preferences > Security & location > Location. You can also turn off the use of Wi-Fi, mobile networks, and sensors for Android location by turning off “Google Location Accuracy” in the same menu.<ph name="END_PARAGRAPH2"></p></ph> </message> + <message name="IDS_CONSOLIDATED_CONSENT_LOCATION_OPT_IN_LEARN_MORE_LINK" desc="Learn more about location opt in"> + Learn more about using location + </message> <message name="IDS_CONSOLIDATED_CONSENT_FOOTER" desc="Message in the footer of the consolidated consent screen."> By continuing, you agree that this device may also automatically download and install updates and apps from Google, your carrier, and your device's manufacturer, possibly using cellular data. Some of these apps may offer in-app purchases. </message> @@ -4012,7 +4054,7 @@ Google terms of service </message> <message name="IDS_CONSOLIDATED_CONSENT_CROS_EULA_TITLE" desc="Title of Google Chrome and Chrome OS additional terms screen"> - Google Chrome and ChromeOS Additional Terms + Google Chrome and ChromeOS additional terms of service </message> <message name="IDS_CONSOLIDATED_CONSENT_ARC_TITLE" desc="Title of Goolge Play terms of service in opt-in screen"> Google Play terms of service @@ -4052,8 +4094,8 @@ <message name="IDS_GUEST_TOS_USAGE_OPT_IN" desc="Message in the guest terms of service screen to opt-in for metrics during the guest session."> Help improve Chrome and ChromeOS features and performance by automatically sending crash reports as well as diagnostic and usage data to Google. </message> - <message name="IDS_GUEST_TOS_LEARN_MORE" desc="Learn more link text in guest terms of service screen."> - Learn more + <message name="IDS_GUEST_TOS_USAGE_OPT_IN_LEARN_MORE_LINK" desc="Learn more link text in guest terms of service screen."> + Learn more about diagnostic and usage data </message> <message name="IDS_GUEST_TOS_USAGE_OPT_IN_LEARN_MORE" desc="Text shown in a pop-up dialog in the guest terms of service screen when the user clicks on the learn more for metrics opt-in."> <ph name="BEGIN_PARAGRAPH1"><p></ph>Allowing ChromeOS devices to send automatic reports helps us prioritize what to fix and improve in ChromeOS. These reports can include things like when ChromeOS crashes, which features were used, and how much memory was typically used.<ph name="END_PARAGRAPH1"></p></ph>
diff --git a/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_BACKUP_OPT_IN_LEARN_MORE_LINK.png.sha1 b/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_BACKUP_OPT_IN_LEARN_MORE_LINK.png.sha1 new file mode 100644 index 0000000..6aef784e --- /dev/null +++ b/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_BACKUP_OPT_IN_LEARN_MORE_LINK.png.sha1
@@ -0,0 +1 @@ +0053f7af3267116c2b9582feb6a86fd32aab7731 \ No newline at end of file
diff --git a/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_CROS_EULA_TITLE.png.sha1 b/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_CROS_EULA_TITLE.png.sha1 index ade2b9a..0eedab0 100644 --- a/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_CROS_EULA_TITLE.png.sha1 +++ b/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_CROS_EULA_TITLE.png.sha1
@@ -1 +1 @@ -a2d6df5aefc0752829e9dac84ce77eda06797d7f \ No newline at end of file +099a721ee98268b395d9f40b99020d0f45fe0c73 \ No newline at end of file
diff --git a/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_LOCATION_OPT_IN_LEARN_MORE_LINK.png.sha1 b/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_LOCATION_OPT_IN_LEARN_MORE_LINK.png.sha1 new file mode 100644 index 0000000..c9792fe --- /dev/null +++ b/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_LOCATION_OPT_IN_LEARN_MORE_LINK.png.sha1
@@ -0,0 +1 @@ +a14d977006d6804e764caf589c1e25c8b0fd11ad \ No newline at end of file
diff --git a/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN.png.sha1 b/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN.png.sha1 index eabfac4c..48f4a77 100644 --- a/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN.png.sha1 +++ b/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN.png.sha1
@@ -1 +1 @@ -360a6de3943e7dba1bf2b7cd428fa288bf16f581 \ No newline at end of file +b973dfd97d4a95c33356fb2586a87bae3a65865a \ No newline at end of file
diff --git a/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_ARC_DISABLED.png.sha1 b/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_ARC_DISABLED.png.sha1 index cd5c1c3..937307d 100644 --- a/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_ARC_DISABLED.png.sha1 +++ b/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_ARC_DISABLED.png.sha1
@@ -1 +1 @@ -8b95ea832e533a6967a8c1af90b2021b554264ef \ No newline at end of file +b3eb3b644da1d45adb919483e7cfa5cd7e6c608f \ No newline at end of file
diff --git a/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_ARC_DISABLED_OWNER.png.sha1 b/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_ARC_DISABLED_OWNER.png.sha1 new file mode 100644 index 0000000..05ceeb9e --- /dev/null +++ b/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_ARC_DISABLED_OWNER.png.sha1
@@ -0,0 +1 @@ +f706de24ec66bc308c51855a429f50802c7efe25 \ No newline at end of file
diff --git a/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_CHILD.png.sha1 b/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_CHILD.png.sha1 index 285e5ae..70ebb42 100644 --- a/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_CHILD.png.sha1 +++ b/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_CHILD.png.sha1
@@ -1 +1 @@ -26fc2f6897ae10dd0765236f6542df3d74d56e0c \ No newline at end of file +e0fa6e0ad9041c6ba06a9d74ac6b1a0588ab0078 \ No newline at end of file
diff --git a/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_CHILD_OWNER.png.sha1 b/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_CHILD_OWNER.png.sha1 new file mode 100644 index 0000000..613b243f --- /dev/null +++ b/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_CHILD_OWNER.png.sha1
@@ -0,0 +1 @@ +16abf29baa2c74893fb95ae09279fff82688e88f \ No newline at end of file
diff --git a/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE.png.sha1 b/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE.png.sha1 index d03a2c2..2c5a7a7 100644 --- a/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE.png.sha1 +++ b/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE.png.sha1
@@ -1 +1 @@ -75ad18d7aed397b35c3d5a0c1360f9088d4302ab \ No newline at end of file +4a86caadc114789292806511a1a34888f3480c31 \ No newline at end of file
diff --git a/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_ARC_DISABLED.png.sha1 b/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_ARC_DISABLED.png.sha1 index 0b5d342..faf085ec 100644 --- a/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_ARC_DISABLED.png.sha1 +++ b/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_ARC_DISABLED.png.sha1
@@ -1 +1 @@ -f8ffbfb330a414c7677c2ae9a958ab48269d62ca \ No newline at end of file +0f019ec21fe007ed97562753875e1d07492093df \ No newline at end of file
diff --git a/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_ARC_DISABLED_CHILD.png.sha1 b/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_ARC_DISABLED_CHILD.png.sha1 index 723b2160..1560f11 100644 --- a/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_ARC_DISABLED_CHILD.png.sha1 +++ b/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_ARC_DISABLED_CHILD.png.sha1
@@ -1 +1 @@ -9d166db640031b7dc250045dad2cfecab69dbef2 \ No newline at end of file +b5fae483ced124bef9159cefaeb3c5ece7f3a722 \ No newline at end of file
diff --git a/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_ARC_DISABLED_CHILD_OWNER.png.sha1 b/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_ARC_DISABLED_CHILD_OWNER.png.sha1 new file mode 100644 index 0000000..30aaa0e --- /dev/null +++ b/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_ARC_DISABLED_CHILD_OWNER.png.sha1
@@ -0,0 +1 @@ +89beee08d2e95bda760c09134718b2d71b84c67b \ No newline at end of file
diff --git a/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_ARC_DISABLED_OWNER.png.sha1 b/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_ARC_DISABLED_OWNER.png.sha1 new file mode 100644 index 0000000..7b99ad4 --- /dev/null +++ b/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_ARC_DISABLED_OWNER.png.sha1
@@ -0,0 +1 @@ +5c461c450c910a514b1cfba79db97c1408c276ed \ No newline at end of file
diff --git a/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_CHILD.png.sha1 b/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_CHILD.png.sha1 index 2ce95b4..f3508fa 100644 --- a/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_CHILD.png.sha1 +++ b/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_CHILD.png.sha1
@@ -1 +1 @@ -e471883cb17f731c8b09e8b398d0003289ff1398 \ No newline at end of file +e1a084efbc480df7938c90cbe565d3bfe1598131 \ No newline at end of file
diff --git a/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_CHILD_OWNER.png.sha1 b/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_CHILD_OWNER.png.sha1 new file mode 100644 index 0000000..51d625b9 --- /dev/null +++ b/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_CHILD_OWNER.png.sha1
@@ -0,0 +1 @@ +aca682cabf3853132bfee89a29e06345372960b1 \ No newline at end of file
diff --git a/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_LINK.png.sha1 b/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_LINK.png.sha1 new file mode 100644 index 0000000..13d9d44 --- /dev/null +++ b/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_LINK.png.sha1
@@ -0,0 +1 @@ +0cff0bd023127bf4d9ff7ef82bfa0edb24dfda31 \ No newline at end of file
diff --git a/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_OWNER.png.sha1 b/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_OWNER.png.sha1 new file mode 100644 index 0000000..8640cfc0 --- /dev/null +++ b/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_OWNER.png.sha1
@@ -0,0 +1 @@ +818bfd80f438e3e3cfdaee08cb6ffcb1b7fd7ae8 \ No newline at end of file
diff --git a/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_OWNER.png.sha1 b/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_OWNER.png.sha1 new file mode 100644 index 0000000..b41225b --- /dev/null +++ b/chrome/app/chromeos_strings_grdp/IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_OWNER.png.sha1
@@ -0,0 +1 @@ +3a5e3d6ab5de38952508d88e82b1087d8f010b2d \ No newline at end of file
diff --git a/chrome/app/chromeos_strings_grdp/IDS_GUEST_TOS_LEARN_MORE.png.sha1 b/chrome/app/chromeos_strings_grdp/IDS_GUEST_TOS_LEARN_MORE.png.sha1 deleted file mode 100644 index 7ec0f2b..0000000 --- a/chrome/app/chromeos_strings_grdp/IDS_GUEST_TOS_LEARN_MORE.png.sha1 +++ /dev/null
@@ -1 +0,0 @@ -ba340c5adc10ee2de718606756743208032f0c3a \ No newline at end of file
diff --git a/chrome/app/chromeos_strings_grdp/IDS_GUEST_TOS_USAGE_OPT_IN_LEARN_MORE.png.sha1 b/chrome/app/chromeos_strings_grdp/IDS_GUEST_TOS_USAGE_OPT_IN_LEARN_MORE.png.sha1 deleted file mode 100644 index 89df05b..0000000 --- a/chrome/app/chromeos_strings_grdp/IDS_GUEST_TOS_USAGE_OPT_IN_LEARN_MORE.png.sha1 +++ /dev/null
@@ -1 +0,0 @@ -cca947f1495d0c62b1602e052f66f2fda4d45a2f \ No newline at end of file
diff --git a/chrome/app/chromeos_strings_grdp/IDS_GUEST_TOS_USAGE_OPT_IN_LEARN_MORE_LINK.png.sha1 b/chrome/app/chromeos_strings_grdp/IDS_GUEST_TOS_USAGE_OPT_IN_LEARN_MORE_LINK.png.sha1 new file mode 100644 index 0000000..6e980b77 --- /dev/null +++ b/chrome/app/chromeos_strings_grdp/IDS_GUEST_TOS_USAGE_OPT_IN_LEARN_MORE_LINK.png.sha1
@@ -0,0 +1 @@ +b70ca3b572d813be45231bbfb892b7fb3c0fcbec \ No newline at end of file
diff --git a/chrome/browser/BUILD.gn b/chrome/browser/BUILD.gn index 767ec2c..ee5597c 100644 --- a/chrome/browser/BUILD.gn +++ b/chrome/browser/BUILD.gn
@@ -4516,6 +4516,7 @@ # than here in :chrome_dll. if (!is_win) { deps += [ "//chrome:packed_resources_integrity" ] + sources += [ "certificate_viewer_stub.cc" ] } if (is_posix) {
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index 496a2080..a84ad51 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -2594,28 +2594,28 @@ const FeatureEntry::FeatureParam kSnoopingProtectionPrecision[] = { {"filter_config_case", "2"}, - {"count", "2"}, + {"count", "3"}, {"threshold", "40"}, {"initial_state", "false"}}; -const FeatureEntry::FeatureParam kSnoopingProtectionBalance[] = { +const FeatureEntry::FeatureParam kSnoopingProtectionConfidence[] = { {"filter_config_case", "2"}, - {"count", "2"}, - {"threshold", "0"}, + {"count", "5"}, + {"threshold", "40"}, {"initial_state", "false"}}; const FeatureEntry::FeatureParam kSnoopingProtectionRecall[] = { {"filter_config_case", "2"}, - {"count", "2"}, + {"count", "3"}, {"threshold", "-40"}, {"initial_state", "false"}}; const FeatureEntry::FeatureVariation kSnoopingProtectionVariations[] = { - {"Slow Precise", kSnoopingProtectionPrecision, + {"Precise", kSnoopingProtectionPrecision, base::size(kSnoopingProtectionPrecision), nullptr}, - {"Slow Balanced", kSnoopingProtectionBalance, - base::size(kSnoopingProtectionBalance), nullptr}, - {"Slow Comprehensive", kSnoopingProtectionRecall, + {"Slow Precise", kSnoopingProtectionConfidence, + base::size(kSnoopingProtectionConfidence), nullptr}, + {"Comprehensive", kSnoopingProtectionRecall, base::size(kSnoopingProtectionRecall), nullptr}}; const FeatureEntry::FeatureParam kQuickDim120s[] = {{"quick_dim_ms", "120000"}}; @@ -4422,6 +4422,9 @@ {"eche-swa-debug-mode", flag_descriptions::kEcheSWADebugModeName, flag_descriptions::kEcheSWADebugModeDescription, kOsCrOS, FEATURE_VALUE_TYPE(chromeos::features::kEcheSWADebugMode)}, + {"eche-swa-in-background", flag_descriptions::kEcheSWAInBackgroundName, + flag_descriptions::kEcheSWAInBackgroundDescription, kOsCrOS, + FEATURE_VALUE_TYPE(chromeos::features::kEcheSWAInBackground)}, #endif // BUILDFLAG(IS_CHROMEOS_ASH) #if defined(OS_MAC) @@ -5562,11 +5565,6 @@ flag_descriptions::kUseFakeDeviceForMediaStreamName, flag_descriptions::kUseFakeDeviceForMediaStreamDescription, kOsCrOS, FEATURE_VALUE_TYPE(media::kUseFakeDeviceForMediaStream)}, - - {"intent-picker-pwa-persistence", - flag_descriptions::kIntentPickerPWAPersistenceName, - flag_descriptions::kIntentPickerPWAPersistenceDescription, kOsCrOS, - FEATURE_VALUE_TYPE(features::kIntentPickerPWAPersistence)}, #endif // BUILDFLAG(IS_CHROMEOS_ASH) #if defined(OS_CHROMEOS) && BUILDFLAG(USE_CHROMEOS_MEDIA_ACCELERATION)
diff --git a/chrome/browser/apps/intent_helper/chromeos_intent_picker_helpers.cc b/chrome/browser/apps/intent_helper/chromeos_intent_picker_helpers.cc index 85b8cf1..cb071c8 100644 --- a/chrome/browser/apps/intent_helper/chromeos_intent_picker_helpers.cc +++ b/chrome/browser/apps/intent_helper/chromeos_intent_picker_helpers.cc
@@ -72,15 +72,6 @@ } } #endif // BUILDFLAG(IS_CHROMEOS_ASH) - // If we only have PWAs in the app list, do not show the intent picker. - // Instead just show the omnibox icon. This is to reduce annoyance to users - // until "Remember my choice" is available for desktop PWAs. - // TODO(crbug.com/826982): show the intent picker when the app registry is - // available to persist "Remember my choice" for PWAs. - if (!base::FeatureList::IsEnabled(features::kIntentPickerPWAPersistence) && - ContainsOnlyPwasAndMacApps(apps_for_picker)) { - return false; - } // If the preferred app is use browser, do not show the intent picker. Profile* profile = @@ -144,14 +135,6 @@ url)); } -bool ContainsOnlyPwasAndMacApps(const std::vector<IntentPickerAppInfo>& apps) { - return std::all_of(apps.begin(), apps.end(), - [](const IntentPickerAppInfo& app_info) { - return app_info.type == PickerEntryType::kWeb || - app_info.type == PickerEntryType::kMacOs; - }); -} - void OnIntentPickerClosedChromeOs( content::WebContents* web_contents, IntentPickerAutoDisplayService* ui_auto_display_service,
diff --git a/chrome/browser/apps/intent_helper/chromeos_intent_picker_helpers.h b/chrome/browser/apps/intent_helper/chromeos_intent_picker_helpers.h index 3581a155..83fb217a 100644 --- a/chrome/browser/apps/intent_helper/chromeos_intent_picker_helpers.h +++ b/chrome/browser/apps/intent_helper/chromeos_intent_picker_helpers.h
@@ -22,9 +22,6 @@ void MaybeShowIntentPickerBubble(content::NavigationHandle* navigation_handle, std::vector<IntentPickerAppInfo> apps); -bool ContainsOnlyPwasAndMacApps( - const std::vector<apps::IntentPickerAppInfo>& apps); - // These enums are used to define the intent picker show state, whether the // picker is popped out or just displayed as a clickable omnibox icon. enum class PickerShowState {
diff --git a/chrome/browser/apps/intent_helper/common_apps_navigation_throttle.cc b/chrome/browser/apps/intent_helper/common_apps_navigation_throttle.cc index abb4a3a..986fc158 100644 --- a/chrome/browser/apps/intent_helper/common_apps_navigation_throttle.cc +++ b/chrome/browser/apps/intent_helper/common_apps_navigation_throttle.cc
@@ -200,12 +200,11 @@ return false; } - // Only automatically launch PWA if the flag is on. + // Only automatically launch supported app types. apps::mojom::AppType app_type = proxy->AppRegistryCache().GetAppType(preferred_app_id.value()); if (app_type != apps::mojom::AppType::kArc && - (app_type != apps::mojom::AppType::kWeb || - !base::FeatureList::IsEnabled(features::kIntentPickerPWAPersistence)) && + app_type != apps::mojom::AppType::kWeb && !IsSystemWebApp(profile, preferred_app_id.value())) { return false; }
diff --git a/chrome/browser/apps/intent_helper/intent_picker_helpers.cc b/chrome/browser/apps/intent_helper/intent_picker_helpers.cc index 2f102cb..b0ba193d4 100644 --- a/chrome/browser/apps/intent_helper/intent_picker_helpers.cc +++ b/chrome/browser/apps/intent_helper/intent_picker_helpers.cc
@@ -190,4 +190,12 @@ /*ui_auto_display_service=*/nullptr, url)); } +bool IntentPickerPwaPersistenceEnabled() { +#if defined(OS_CHROMEOS) + return true; +#else + return false; +#endif +} + } // namespace apps
diff --git a/chrome/browser/apps/intent_helper/intent_picker_helpers.h b/chrome/browser/apps/intent_helper/intent_picker_helpers.h index bf83cc27..30bd1e5 100644 --- a/chrome/browser/apps/intent_helper/intent_picker_helpers.h +++ b/chrome/browser/apps/intent_helper/intent_picker_helpers.h
@@ -27,6 +27,9 @@ void ShowIntentPickerBubble(content::WebContents* web_contents, const GURL& url); +// Returns true if persistence for PWA entries in the Intent Picker is enabled. +bool IntentPickerPwaPersistenceEnabled(); + } // namespace apps #endif // CHROME_BROWSER_APPS_INTENT_HELPER_INTENT_PICKER_HELPERS_H_
diff --git a/chrome/browser/ash/app_restore/app_launch_handler.h b/chrome/browser/ash/app_restore/app_launch_handler.h index 729cea4..5eb4976 100644 --- a/chrome/browser/ash/app_restore/app_launch_handler.h +++ b/chrome/browser/ash/app_restore/app_launch_handler.h
@@ -63,7 +63,7 @@ // Called before an extension type app is launched. Allows subclasses to // perform some setup prior to launching an extension type app. - virtual void OnExtensionLaunching(const std::string& app_id) = 0; + virtual void OnExtensionLaunching(const std::string& app_id) {} virtual base::WeakPtr<AppLaunchHandler> GetWeakPtrAppLaunchHandler() = 0;
diff --git a/chrome/browser/ash/app_restore/app_restore_arc_task_handler.cc b/chrome/browser/ash/app_restore/app_restore_arc_task_handler.cc index 7713934a..26aa3c9 100644 --- a/chrome/browser/ash/app_restore/app_restore_arc_task_handler.cc +++ b/chrome/browser/ash/app_restore/app_restore_arc_task_handler.cc
@@ -12,6 +12,7 @@ #include "chrome/browser/ash/arc/session/arc_session_manager.h" #include "chrome/browser/profiles/profile.h" #include "components/app_restore/app_restore_arc_info.h" +#include "components/app_restore/features.h" namespace ash { namespace app_restore { @@ -42,12 +43,22 @@ #endif if (ash::features::AreDesksTemplatesEnabled()) { - desks_templates_arc_app_launch_handler_ = - std::make_unique<ArcAppLaunchHandler>(); + arc_app_launcher_handers_.push_back( + std::make_unique<ArcAppLaunchHandler>()); + desks_templates_arc_app_launch_handler_observer_ = + arc_app_launcher_handers_.back().get(); } - full_restore_arc_app_launch_handler_ = - std::make_unique<ArcAppLaunchHandler>(); + arc_app_launcher_handers_.push_back(std::make_unique<ArcAppLaunchHandler>()); + full_restore_arc_app_launch_handler_observer_ = + arc_app_launcher_handers_.back().get(); + // TODO(sstan): Modify ArcAppLaunchHandler to prevent redundant launch. + if (::full_restore::features::IsArcWindowPredictorEnabled()) { + arc_app_launcher_handers_.push_back( + std::make_unique<ArcAppLaunchHandler>()); + window_predictor_arc_app_launch_handler_observer_ = + arc_app_launcher_handers_.back().get(); + } arc::ArcSessionManager* arc_session_manager = arc::ArcSessionManager::Get(); // arc::ArcSessionManager might not be set in tests. if (arc_session_manager) @@ -90,8 +101,7 @@ window_handler_->OnAppInstanceConnected(); #endif - for (auto* handler : {desks_templates_arc_app_launch_handler(), - full_restore_arc_app_launch_handler()}) { + for (auto& handler : arc_app_launcher_handers_) { if (handler) handler->OnAppConnectionReady(); } @@ -110,8 +120,7 @@ } void AppRestoreArcTaskHandler::OnArcPlayStoreEnabledChanged(bool enabled) { - for (auto* handler : {desks_templates_arc_app_launch_handler(), - full_restore_arc_app_launch_handler()}) { + for (auto& handler : arc_app_launcher_handers_) { if (handler) handler->OnArcPlayStoreEnabledChanged(enabled); } @@ -120,16 +129,16 @@ } void AppRestoreArcTaskHandler::OnShelfReady() { - for (auto* handler : {desks_templates_arc_app_launch_handler(), - full_restore_arc_app_launch_handler()}) { + for (auto& handler : arc_app_launcher_handers_) { if (handler) handler->OnShelfReady(); } } void AppRestoreArcTaskHandler::Shutdown() { - desks_templates_arc_app_launch_handler_.reset(); - full_restore_arc_app_launch_handler_.reset(); + for (auto& handler : arc_app_launcher_handers_) { + handler.reset(); + } window_handler_.reset(); }
diff --git a/chrome/browser/ash/app_restore/app_restore_arc_task_handler.h b/chrome/browser/ash/app_restore/app_restore_arc_task_handler.h index 047165a..a6949ec 100644 --- a/chrome/browser/ash/app_restore/app_restore_arc_task_handler.h +++ b/chrome/browser/ash/app_restore/app_restore_arc_task_handler.h
@@ -47,10 +47,13 @@ #endif ArcAppLaunchHandler* desks_templates_arc_app_launch_handler() { - return desks_templates_arc_app_launch_handler_.get(); + return desks_templates_arc_app_launch_handler_observer_; } ArcAppLaunchHandler* full_restore_arc_app_launch_handler() { - return full_restore_arc_app_launch_handler_.get(); + return full_restore_arc_app_launch_handler_observer_; + } + ArcAppLaunchHandler* window_predictor_arc_app_launch_handler() { + return window_predictor_arc_app_launch_handler_observer_; } // ArcAppListPrefs::Observer. @@ -88,8 +91,12 @@ // The ArcAppLaunchHandlers, one for each feature that wants to launch ARC // apps. - std::unique_ptr<ArcAppLaunchHandler> desks_templates_arc_app_launch_handler_; - std::unique_ptr<ArcAppLaunchHandler> full_restore_arc_app_launch_handler_; + std::vector<std::unique_ptr<ArcAppLaunchHandler>> arc_app_launcher_handers_; + ArcAppLaunchHandler* desks_templates_arc_app_launch_handler_observer_ = + nullptr; + ArcAppLaunchHandler* full_restore_arc_app_launch_handler_observer_ = nullptr; + ArcAppLaunchHandler* window_predictor_arc_app_launch_handler_observer_ = + nullptr; }; } // namespace app_restore
diff --git a/chrome/browser/ash/arc/window_predictor/arc_predictor_app_launch_handler.cc b/chrome/browser/ash/arc/window_predictor/arc_predictor_app_launch_handler.cc new file mode 100644 index 0000000..a5756dd --- /dev/null +++ b/chrome/browser/ash/arc/window_predictor/arc_predictor_app_launch_handler.cc
@@ -0,0 +1,68 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ash/arc/window_predictor/arc_predictor_app_launch_handler.h" + +#include "components/app_restore/app_launch_info.h" +#include "components/app_restore/window_info.h" +#include "ui/display/types/display_constants.h" + +namespace { +std::unique_ptr<app_restore::WindowInfo> GetAppWindowInfo( + arc::mojom::WindowInfoPtr window_info) { + auto app_window_info = std::make_unique<app_restore::WindowInfo>(); + if (window_info->bounds.has_value()) { + app_window_info->current_bounds = window_info->bounds.value(); + } + return app_window_info; +} +} // namespace + +namespace arc { +ArcPredictorAppLaunchHandler::ArcPredictorAppLaunchHandler(Profile* profile) + : ash::AppLaunchHandler(profile) { + set_restore_data(std::make_unique<app_restore::RestoreData>()); +} + +ArcPredictorAppLaunchHandler::~ArcPredictorAppLaunchHandler() = default; + +void ArcPredictorAppLaunchHandler::AddPendingApp( + const std::string& app_id, + int event_flags, + arc::mojom::WindowInfoPtr window_info) { + // TODO(sstan): May prevent launch the same app_id programmatically. Currently + // if an ARC app ghost window launch, the window will be attached to shelf, + // and user cannot launch another instance of the same app by click icon. But + // from code side it still can launch the same app by calling this function. + int arc_session_id = -1; + int64_t display_id = display::kDefaultDisplayId; + if (window_info) { + arc_session_id = window_info->window_id; + // Default invalid display id in WindowInfo struct. + // See components/services/app_service/public/mojom/types.mojom#WindowInfo + if (window_info->display_id != -1) + display_id = window_info->display_id; + } + + auto app_info = + std::make_unique<app_restore::AppLaunchInfo>(app_id, arc_session_id); + app_info->event_flag = event_flags; + app_info->arc_session_id = arc_session_id; + restore_data()->AddAppLaunchInfo(std::move(app_info)); + auto app_window_info = std::make_unique<app_restore::WindowInfo>(); + if (window_info->bounds.has_value()) + app_window_info->current_bounds = window_info->bounds.value(); + app_window_info->display_id = display_id; + restore_data()->ModifyWindowInfo(app_id, arc_session_id, *app_window_info); +} + +base::WeakPtr<ash::AppLaunchHandler> +ArcPredictorAppLaunchHandler::GetWeakPtrAppLaunchHandler() { + return weak_ptr_factory_.GetWeakPtr(); +} + +void ArcPredictorAppLaunchHandler::RecordRestoredAppLaunch( + apps::AppTypeName app_type_name) {} + +} // namespace arc
diff --git a/chrome/browser/ash/arc/window_predictor/arc_predictor_app_launch_handler.h b/chrome/browser/ash/arc/window_predictor/arc_predictor_app_launch_handler.h new file mode 100644 index 0000000..941993e --- /dev/null +++ b/chrome/browser/ash/arc/window_predictor/arc_predictor_app_launch_handler.h
@@ -0,0 +1,40 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_ASH_ARC_WINDOW_PREDICTOR_ARC_PREDICTOR_APP_LAUNCH_HANDLER_H_ +#define CHROME_BROWSER_ASH_ARC_WINDOW_PREDICTOR_ARC_PREDICTOR_APP_LAUNCH_HANDLER_H_ + +#include "ash/components/arc/mojom/app.mojom.h" +#include "chrome/browser/ash/app_restore/app_launch_handler.h" +#include "components/app_restore/restore_data.h" + +namespace arc { + +// A customized AppLaunchHandler to launch the pending apps when +// they are ready. For ARC apps, it will use the launch optimization +// policy to control the system resource usage. +class ArcPredictorAppLaunchHandler : public ash::AppLaunchHandler { + public: + explicit ArcPredictorAppLaunchHandler(Profile* profile); + ArcPredictorAppLaunchHandler(const ArcPredictorAppLaunchHandler&) = delete; + ArcPredictorAppLaunchHandler& operator=(const ArcPredictorAppLaunchHandler&) = + delete; + ~ArcPredictorAppLaunchHandler() override; + + void AddPendingApp(const std::string& app_id, + int event_flags, + arc::mojom::WindowInfoPtr window_info); + + void RecordRestoredAppLaunch(apps::AppTypeName app_type_name) override; + + protected: + base::WeakPtr<ash::AppLaunchHandler> GetWeakPtrAppLaunchHandler() override; + + private: + base::WeakPtrFactory<ArcPredictorAppLaunchHandler> weak_ptr_factory_{this}; +}; + +} // namespace arc + +#endif // CHROME_BROWSER_ASH_ARC_WINDOW_PREDICTOR_ARC_PREDICTOR_APP_LAUNCH_HANDLER_H_
diff --git a/chrome/browser/ash/arc/window_predictor/window_predictor.cc b/chrome/browser/ash/arc/window_predictor/window_predictor.cc new file mode 100644 index 0000000..a23a4397 --- /dev/null +++ b/chrome/browser/ash/arc/window_predictor/window_predictor.cc
@@ -0,0 +1,38 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ash/arc/window_predictor/window_predictor.h" + +#include "base/no_destructor.h" +#include "chrome/browser/ash/app_restore/app_launch_handler.h" + +namespace arc { + +// static +WindowPredictor* WindowPredictor::GetInstance() { + static base::NoDestructor<WindowPredictor> instance; + return instance.get(); +} + +WindowPredictor::WindowPredictor() {} + +WindowPredictor::~WindowPredictor() = default; + +void WindowPredictor::MaybeCreateAppLaunchHandler(Profile* profile) { + DCHECK(profile); + if (app_launch_handler_ && app_launch_handler_->profile() == profile) + return; + + app_launch_handler_ = std::make_unique<ArcPredictorAppLaunchHandler>(profile); +} + +arc::mojom::WindowInfoPtr WindowPredictor::PredictAppWindowInfo( + const std::string& arc_app_id, + arc::mojom::WindowInfoPtr window_info) { + // TODO(sstan): Generate window bounds based on display info and the + // info saved in ArcAppListPrefs. + return window_info; +} + +} // namespace arc
diff --git a/chrome/browser/ash/arc/window_predictor/window_predictor.h b/chrome/browser/ash/arc/window_predictor/window_predictor.h new file mode 100644 index 0000000..42f3c1a3 --- /dev/null +++ b/chrome/browser/ash/arc/window_predictor/window_predictor.h
@@ -0,0 +1,50 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_ASH_ARC_WINDOW_PREDICTOR_WINDOW_PREDICTOR_H_ +#define CHROME_BROWSER_ASH_ARC_WINDOW_PREDICTOR_WINDOW_PREDICTOR_H_ + +#include <memory> + +#include "ash/components/arc/mojom/app.mojom.h" +#include "base/no_destructor.h" +#include "chrome/browser/ash/arc/window_predictor/arc_predictor_app_launch_handler.h" + +class Profile; + +namespace arc { + +// Predict ARC app window initial launch window parameters and launch +// corresponding ARC ghost window. +// TODO(sstan): Finish window parameters related features. +class WindowPredictor { + public: + static WindowPredictor* GetInstance(); + + WindowPredictor(const WindowPredictor&) = delete; + WindowPredictor& operator=(const WindowPredictor&) = delete; + + // Create App Launch Handler. + void MaybeCreateAppLaunchHandler(Profile* profile); + + // Get predict app window info by app id and existed window info. + arc::mojom::WindowInfoPtr PredictAppWindowInfo( + const std::string& arc_app_id, + arc::mojom::WindowInfoPtr window_info); + + ArcPredictorAppLaunchHandler* app_launch_handler() { + return app_launch_handler_.get(); + } + + private: + friend class base::NoDestructor<WindowPredictor>; + WindowPredictor(); + ~WindowPredictor(); + + std::unique_ptr<ArcPredictorAppLaunchHandler> app_launch_handler_; +}; + +} // namespace arc + +#endif // CHROME_BROWSER_ASH_ARC_WINDOW_PREDICTOR_WINDOW_PREDICTOR_H_
diff --git a/chrome/browser/ash/arc/window_predictor/window_predictor_utils.cc b/chrome/browser/ash/arc/window_predictor/window_predictor_utils.cc new file mode 100644 index 0000000..5420c54 --- /dev/null +++ b/chrome/browser/ash/arc/window_predictor/window_predictor_utils.cc
@@ -0,0 +1,42 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ash/arc/window_predictor/window_predictor_utils.h" +#include "chrome/browser/ash/app_restore/app_restore_arc_task_handler.h" +#include "chrome/browser/ash/app_restore/arc_app_launch_handler.h" +#include "chrome/browser/ash/arc/window_predictor/window_predictor.h" + +namespace arc { + +bool LaunchArcAppWithGhostWindow(Profile* profile, + const std::string& arc_app_id, + int event_flags, + arc::UserInteractionType user_interaction_type, + arc::mojom::WindowInfoPtr window_info) { + WindowPredictor::GetInstance()->MaybeCreateAppLaunchHandler(profile); + + auto* arc_task_handler = + ash::app_restore::AppRestoreArcTaskHandler::GetForProfile(profile); + if (!arc_task_handler) + return false; + + auto* arc_app_launch_handler = + arc_task_handler->window_predictor_arc_app_launch_handler(); + if (!arc_app_launch_handler) + return false; + + arc::mojom::WindowInfoPtr predict_window_info = + WindowPredictor::GetInstance()->PredictAppWindowInfo( + arc_app_id, std::move(window_info)); + auto* app_launch_handler = + WindowPredictor::GetInstance()->app_launch_handler(); + DCHECK(app_launch_handler); + + app_launch_handler->AddPendingApp(arc_app_id, event_flags, + std::move(predict_window_info)); + arc_app_launch_handler->RestoreArcApps(app_launch_handler); + return true; +} + +} // namespace arc
diff --git a/chrome/browser/ash/arc/window_predictor/window_predictor_utils.h b/chrome/browser/ash/arc/window_predictor/window_predictor_utils.h new file mode 100644 index 0000000..485023da --- /dev/null +++ b/chrome/browser/ash/arc/window_predictor/window_predictor_utils.h
@@ -0,0 +1,25 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_ASH_ARC_WINDOW_PREDICTOR_WINDOW_PREDICTOR_UTILS_H_ +#define CHROME_BROWSER_ASH_ARC_WINDOW_PREDICTOR_WINDOW_PREDICTOR_UTILS_H_ + +#include "ash/components/arc/metrics/arc_metrics_constants.h" +#include "ash/components/arc/mojom/app.mojom.h" + +class Profile; + +namespace arc { + +// Create ARC app ghost window and add the corresponding to the launching list, +// it will be launched after ARC ready. +bool LaunchArcAppWithGhostWindow(Profile* profile, + const std::string& arc_app_id, + int event_flags, + arc::UserInteractionType user_interaction_type, + arc::mojom::WindowInfoPtr window_info); + +} // namespace arc + +#endif // CHROME_BROWSER_ASH_ARC_WINDOW_PREDICTOR_WINDOW_PREDICTOR_UTILS_H_
diff --git a/chrome/browser/ash/borealis/borealis_context_manager_impl.cc b/chrome/browser/ash/borealis/borealis_context_manager_impl.cc index 7183535..d44a133 100644 --- a/chrome/browser/ash/borealis/borealis_context_manager_impl.cc +++ b/chrome/browser/ash/borealis/borealis_context_manager_impl.cc
@@ -87,7 +87,7 @@ : profile_(profile), weak_factory_(this) { // DBusThreadManager may not be initialized in tests. if (chromeos::DBusThreadManager::IsInitialized()) { - ShutDownBorealisIfChromeCrashed(); + ShutDownBorealisIfRunning(); chromeos::ConciergeClient::Get()->AddVmObserver(this); } } @@ -103,10 +103,9 @@ } // Note that this method gets called in the constructor. -void BorealisContextManagerImpl::ShutDownBorealisIfChromeCrashed() { - if (ExitTypeService::GetLastSessionExitType(profile_) != ExitType::kCrashed) { - return; - } +// If Borealis was running when chrome crashed/restarted then Borealis +// may still be running and should be shut down. +void BorealisContextManagerImpl::ShutDownBorealisIfRunning() { vm_tools::concierge::GetVmInfoRequest request; request.set_owner_id(ash::ProfileHelper::GetUserIdHashFromProfile(profile_)); request.set_name(kBorealisVmName);
diff --git a/chrome/browser/ash/borealis/borealis_context_manager_impl.h b/chrome/browser/ash/borealis/borealis_context_manager_impl.h index f9d8922..d0fb329 100644 --- a/chrome/browser/ash/borealis/borealis_context_manager_impl.h +++ b/chrome/browser/ash/borealis/borealis_context_manager_impl.h
@@ -94,7 +94,7 @@ base::OnceCallback<void(BorealisShutdownResult)> on_shutdown_callback, const std::string& vm_name); - void ShutDownBorealisIfChromeCrashed(); + void ShutDownBorealisIfRunning(); Profile* const profile_;
diff --git a/chrome/browser/ash/camera_mic/vm_camera_mic_manager.cc b/chrome/browser/ash/camera_mic/vm_camera_mic_manager.cc index 015853e..a66626f8 100644 --- a/chrome/browser/ash/camera_mic/vm_camera_mic_manager.cc +++ b/chrome/browser/ash/camera_mic/vm_camera_mic_manager.cc
@@ -25,7 +25,7 @@ #include "chrome/browser/notifications/notification_display_service.h" #include "chrome/browser/ui/chrome_pages.h" #include "chrome/browser/ui/settings_window_manager_chromeos.h" -#include "chrome/browser/ui/webui/settings/chromeos/app_management/app_management_uma.h" +#include "chrome/browser/ui/webui/settings/ash/app_management/app_management_uma.h" #include "chrome/browser/ui/webui/settings/chromeos/constants/routes.mojom-forward.h" #include "chrome/grit/generated_resources.h" #include "components/vector_icons/vector_icons.h" @@ -302,12 +302,12 @@ case VmType::kPluginVm: chrome::ShowAppManagementPage( profile_, plugin_vm::kPluginVmShelfAppId, - AppManagementEntryPoint::kNotificationPluginVm); + settings::AppManagementEntryPoint::kNotificationPluginVm); break; case VmType::kBorealis: chrome::ShowAppManagementPage( profile_, borealis::kClientAppId, - AppManagementEntryPoint::kAppManagementMainViewBorealis); + settings::AppManagementEntryPoint::kAppManagementMainViewBorealis); break; } }
diff --git a/chrome/browser/ash/dbus/plugin_vm_service_provider.cc b/chrome/browser/ash/dbus/plugin_vm_service_provider.cc index b02c0ab9..13237164 100644 --- a/chrome/browser/ash/dbus/plugin_vm_service_provider.cc +++ b/chrome/browser/ash/dbus/plugin_vm_service_provider.cc
@@ -17,7 +17,7 @@ #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/chrome_pages.h" #include "chrome/browser/ui/settings_window_manager_chromeos.h" -#include "chrome/browser/ui/webui/settings/chromeos/app_management/app_management_uma.h" +#include "chrome/browser/ui/webui/settings/ash/app_management/app_management_uma.h" #include "chrome/browser/ui/webui/settings/chromeos/constants/routes.mojom.h" #include "chrome/common/webui_url_constants.h" #include "chromeos/dbus/plugin_vm_service/plugin_vm_service.pb.h" @@ -118,7 +118,7 @@ if (request.subpage_path() == kShowSettingsPageDetails) { chrome::ShowAppManagementPage( primary_profile, plugin_vm::kPluginVmShelfAppId, - AppManagementEntryPoint::kDBusServicePluginVm); + settings::AppManagementEntryPoint::kDBusServicePluginVm); } else if (request.subpage_path() == kShowSettingsPageSharedPaths) { chrome::SettingsWindowManager::GetInstance()->ShowOSSettings( primary_profile,
diff --git a/chrome/browser/ash/login/screens/consolidated_consent_screen.cc b/chrome/browser/ash/login/screens/consolidated_consent_screen.cc index 90372688..1a6a2222 100644 --- a/chrome/browser/ash/login/screens/consolidated_consent_screen.cc +++ b/chrome/browser/ash/login/screens/consolidated_consent_screen.cc
@@ -6,6 +6,7 @@ #include "ash/components/arc/arc_prefs.h" #include "ash/constants/ash_switches.h" +#include "base/bind.h" #include "base/command_line.h" #include "base/hash/sha1.h" #include "base/i18n/timezone.h" @@ -18,6 +19,7 @@ #include "chrome/browser/ash/login/wizard_context.h" #include "chrome/browser/ash/login/wizard_controller.h" #include "chrome/browser/ash/profiles/profile_helper.h" +#include "chrome/browser/ash/settings/device_settings_service.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/consent_auditor/consent_auditor_factory.h" #include "chrome/browser/policy/profile_policy_connector.h" @@ -142,6 +144,10 @@ is_enterprise_managed_account_ = profile->GetProfilePolicyConnector()->IsManaged() && !is_child_account_; + DeviceSettingsService::Get()->GetOwnershipStatusAsync( + base::BindOnce(&ConsolidatedConsentScreen::OnOwnershipStatusCheckDone, + weak_factory_.GetWeakPtr())); + bool is_demo = arc::IsArcDemoModeSetupFlow(); bool is_arc_enabled = arc::IsArcTermsOfServiceOobeNegotiationNeeded(); if (!is_demo && is_arc_enabled) { @@ -207,6 +213,22 @@ view_->SetLocationMode(enabled, managed); } +void ConsolidatedConsentScreen::OnOwnershipStatusCheckDone( + DeviceSettingsService::OwnershipStatus status) { + bool is_owner = false; + + // If no ownership is established yet, then the current user is the first + // user to sign in. Therefore, the current user would be the owner. + if (status == DeviceSettingsService::OWNERSHIP_NONE) { + is_owner = true; + } else if (status == DeviceSettingsService::OWNERSHIP_TAKEN) { + is_owner = user_manager::UserManager::Get()->IsCurrentUserOwner(); + } + + if (view_) + view_->SetIsDeviceOwner(is_owner); +} + void ConsolidatedConsentScreen::RecordConsents( const ConsentsParameters& params) { Profile* profile = ProfileManager::GetActiveUserProfile();
diff --git a/chrome/browser/ash/login/screens/consolidated_consent_screen.h b/chrome/browser/ash/login/screens/consolidated_consent_screen.h index d817b47..dbed955 100644 --- a/chrome/browser/ash/login/screens/consolidated_consent_screen.h +++ b/chrome/browser/ash/login/screens/consolidated_consent_screen.h
@@ -5,9 +5,11 @@ #ifndef CHROME_BROWSER_ASH_LOGIN_SCREENS_CONSOLIDATED_CONSENT_SCREEN_H_ #define CHROME_BROWSER_ASH_LOGIN_SCREENS_CONSOLIDATED_CONSENT_SCREEN_H_ +#include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "chrome/browser/ash/arc/optin/arc_optin_preference_handler_observer.h" #include "chrome/browser/ash/login/screens/base_screen.h" +#include "chrome/browser/ash/settings/device_settings_service.h" #include "chrome/browser/ui/webui/chromeos/login/consolidated_consent_screen_handler.h" namespace arc { @@ -100,6 +102,9 @@ void RecordConsents(const ConsentsParameters& params); + void OnOwnershipStatusCheckDone( + DeviceSettingsService::OwnershipStatus status); + // Exits the screen with `Result::ACCEPTED` in the normal flow, and // `Result::ACCEPTED_DEMO_ONLINE` or `Result::ACCEPTED_DEMO_OFFLINE` in the // demo setup flow. @@ -120,6 +125,8 @@ ConsolidatedConsentScreenView* view_ = nullptr; ScreenExitCallback exit_callback_; + + base::WeakPtrFactory<ConsolidatedConsentScreen> weak_factory_{this}; }; } // namespace ash
diff --git a/chrome/browser/ash/plugin_vm/plugin_vm_manager_impl_unittest.cc b/chrome/browser/ash/plugin_vm/plugin_vm_manager_impl_unittest.cc index 34f4306..51c9af6 100644 --- a/chrome/browser/ash/plugin_vm/plugin_vm_manager_impl_unittest.cc +++ b/chrome/browser/ash/plugin_vm/plugin_vm_manager_impl_unittest.cc
@@ -72,6 +72,10 @@ // Make StartVm succeed by default, tests can override as needed. VmPluginDispatcherClient().set_start_vm_response( vm_tools::plugin_dispatcher::StartVmResponse()); + + // Borealis makes a call, unrelated to this test so just reset it. + DCHECK_EQ(ConciergeClient().get_vm_info_call_count(), 1); + ConciergeClient().reset_get_vm_info_call_count(); } PluginVmManagerImplTest(const PluginVmManagerImplTest&) = delete;
diff --git a/chrome/browser/ash/policy/dlp/dlp_files_controller.cc b/chrome/browser/ash/policy/dlp/dlp_files_controller.cc index 148824423..8078968 100644 --- a/chrome/browser/ash/policy/dlp/dlp_files_controller.cc +++ b/chrome/browser/ash/policy/dlp/dlp_files_controller.cc
@@ -31,7 +31,7 @@ } base::flat_map<ino_t, storage::FileSystemURL> GetFilesInodes( - const std::vector<storage::FileSystemURL>& transferred_files) { + std::vector<storage::FileSystemURL> transferred_files) { base::flat_map<ino_t, storage::FileSystemURL> files_map; dlp::GetFilesSourcesRequest request; for (const auto& file : transferred_files) { @@ -86,7 +86,7 @@ DlpFilesController::~DlpFilesController() = default; void DlpFilesController::GetDisallowedTransfers( - const std::vector<storage::FileSystemURL>& transferred_files, + std::vector<storage::FileSystemURL> transferred_files, storage::FileSystemURL destination, GetDisallowedTransfersCallback result_callback) { if (!chromeos::DlpClient::Get() || !chromeos::DlpClient::Get()->IsAlive()) { @@ -94,9 +94,17 @@ return; } + std::vector<storage::FileSystemURL> filtered_files; + for (const auto& file : transferred_files) { + // If the file is in the same file system as the destination, no + // restrictions should be applied. + if (!file.IsInSameFileSystem(destination)) + filtered_files.push_back(file); + } + base::ThreadPool::PostTaskAndReplyWithResult( FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, - base::BindOnce(&GetFilesInodes, transferred_files), + base::BindOnce(&GetFilesInodes, std::move(filtered_files)), base::BindOnce(&DlpFilesController::GetFilesSources, weak_ptr_factory_.GetWeakPtr(), std::move(destination), std::move(result_callback)));
diff --git a/chrome/browser/ash/policy/dlp/dlp_files_controller.h b/chrome/browser/ash/policy/dlp/dlp_files_controller.h index 93edee53..86aae0da 100644 --- a/chrome/browser/ash/policy/dlp/dlp_files_controller.h +++ b/chrome/browser/ash/policy/dlp/dlp_files_controller.h
@@ -41,7 +41,7 @@ // Returns a list of files disallowed to be transferred in |result_callback|. void GetDisallowedTransfers( - const std::vector<storage::FileSystemURL>& transferred_files, + std::vector<storage::FileSystemURL> transferred_files, storage::FileSystemURL destination, GetDisallowedTransfersCallback result_callback);
diff --git a/chrome/browser/ash/policy/dlp/dlp_files_controller_unittest.cc b/chrome/browser/ash/policy/dlp/dlp_files_controller_unittest.cc index 44629f9..7ba8574 100644 --- a/chrome/browser/ash/policy/dlp/dlp_files_controller_unittest.cc +++ b/chrome/browser/ash/policy/dlp/dlp_files_controller_unittest.cc
@@ -17,6 +17,7 @@ #include "base/memory/scoped_refptr.h" #include "base/run_loop.h" #include "base/test/mock_callback.h" +#include "base/test/test_future.h" #include "chrome/browser/ash/crostini/crostini_manager.h" #include "chrome/browser/ash/crostini/fake_crostini_features.h" #include "chrome/browser/ash/drive/drive_integration_service.h" @@ -148,30 +149,52 @@ storage::FileSystemURL file_url3_; }; -TEST_F(DlpFilesControllerTest, GetDisallowedTransfers) { +TEST_F(DlpFilesControllerTest, GetDisallowedTransfers_DiffFileSystem) { AddFilesToDlpClient(); std::vector<storage::FileSystemURL> transferred_files( {file_url1_, file_url2_, file_url3_}); std::vector<storage::FileSystemURL> disallowed_files( {file_url1_, file_url3_}); - base::MockCallback<DlpFilesController::GetDisallowedTransfersCallback> - disallowed_transfers_cb; - EXPECT_CALL(disallowed_transfers_cb, Run(disallowed_files)); EXPECT_CALL(rules_manager_, IsRestrictedDestination) .WillOnce(testing::Return(DlpRulesManager::Level::kBlock)) .WillOnce(testing::Return(DlpRulesManager::Level::kAllow)) .WillOnce(testing::Return(DlpRulesManager::Level::kBlock)); - base::RunLoop run_loop; - base::RepeatingClosure quit_closure = run_loop.QuitClosure(); + storage::ExternalMountPoints* mount_points = + storage::ExternalMountPoints::GetSystemInstance(); + mount_points->RegisterFileSystem( + chromeos::kSystemMountNameArchive, storage::kFileSystemTypeLocal, + storage::FileSystemMountOption(), + base::FilePath(file_manager::util::kArchiveMountPath)); + base::ScopedClosureRunner external_mount_points_revoker( + base::BindOnce(&storage::ExternalMountPoints::RevokeAllFileSystems, + base::Unretained(mount_points))); - files_controller_.GetDisallowedTransfers( - transferred_files, CreateFileSystemURL("Downloads"), - disallowed_transfers_cb.Get().Then(std::move(quit_closure))); + auto dst_url = mount_points->CreateExternalFileSystemURL( + blink::StorageKey(), "archive", + base::FilePath("file.rar/path/in/archive")); - run_loop.Run(); + base::test::TestFuture<std::vector<storage::FileSystemURL>> future; + files_controller_.GetDisallowedTransfers(transferred_files, dst_url, + future.GetCallback()); + EXPECT_TRUE(future.Wait()); + EXPECT_EQ(disallowed_files, future.Take()); +} + +TEST_F(DlpFilesControllerTest, GetDisallowedTransfers_SameFileSystem) { + AddFilesToDlpClient(); + + std::vector<storage::FileSystemURL> transferred_files( + {file_url1_, file_url2_, file_url3_}); + std::vector<storage::FileSystemURL> disallowed_files; + + base::test::TestFuture<std::vector<storage::FileSystemURL>> future; + files_controller_.GetDisallowedTransfers(transferred_files, + CreateFileSystemURL("Downloads"), + future.GetCallback()); + EXPECT_EQ(0u, future.Get().size()); } class DlpFilesExternalDestinationTest @@ -286,27 +309,21 @@ {file_url1_, file_url2_, file_url3_}); std::vector<storage::FileSystemURL> disallowed_files( {file_url1_, file_url3_}); - base::MockCallback<DlpFilesController::GetDisallowedTransfersCallback> - disallowed_transfers_cb; - EXPECT_CALL(disallowed_transfers_cb, Run(disallowed_files)); EXPECT_CALL(rules_manager_, IsRestrictedComponent(_, expected_component, _, _)) .WillOnce(testing::Return(DlpRulesManager::Level::kBlock)) .WillOnce(testing::Return(DlpRulesManager::Level::kAllow)) .WillOnce(testing::Return(DlpRulesManager::Level::kBlock)); - base::RunLoop run_loop; - base::RepeatingClosure quit_closure = run_loop.QuitClosure(); - auto dst_url = mount_points_->CreateExternalFileSystemURL( blink::StorageKey(), mount_name, base::FilePath(path)); - files_controller_.GetDisallowedTransfers( - transferred_files, dst_url, - disallowed_transfers_cb.Get().Then(std::move(quit_closure))); - - run_loop.Run(); + base::test::TestFuture<std::vector<storage::FileSystemURL>> future; + files_controller_.GetDisallowedTransfers(transferred_files, dst_url, + future.GetCallback()); + EXPECT_TRUE(future.Wait()); + EXPECT_EQ(disallowed_files, future.Take()); } } // namespace policy
diff --git a/chrome/browser/ash/web_applications/media_app/media_app_integration_browsertest.cc b/chrome/browser/ash/web_applications/media_app/media_app_integration_browsertest.cc index 2b2be28..6aa6b3ea 100644 --- a/chrome/browser/ash/web_applications/media_app/media_app_integration_browsertest.cc +++ b/chrome/browser/ash/web_applications/media_app/media_app_integration_browsertest.cc
@@ -37,6 +37,7 @@ #include "chrome/browser/web_applications/system_web_apps/system_web_app_manager.h" #include "chrome/browser/web_applications/web_app_helpers.h" #include "chrome/common/chrome_paths.h" +#include "chromeos/constants/chromeos_features.h" #include "components/crash/content/browser/error_reporting/mock_crash_endpoint.h" #include "content/public/browser/media_session_service.h" #include "content/public/test/browser_test.h" @@ -45,6 +46,7 @@ #include "services/media_session/public/mojom/media_controller.mojom.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/common/features.h" +#include "ui/gfx/color_palette.h" using platform_util::OpenOperationResult; using web_app::SystemAppType; @@ -127,6 +129,28 @@ base::test::ScopedFeatureList feature_list_; }; +class MediaAppIntegrationDarkLightModeEnabledTest + : public MediaAppIntegrationTest { + public: + MediaAppIntegrationDarkLightModeEnabledTest() { + feature_list_.InitAndEnableFeature(chromeos::features::kDarkLightMode); + } + + private: + base::test::ScopedFeatureList feature_list_; +}; + +class MediaAppIntegrationDarkLightModeDisabledTest + : public MediaAppIntegrationTest { + public: + MediaAppIntegrationDarkLightModeDisabledTest() { + feature_list_.InitAndDisableFeature(chromeos::features::kDarkLightMode); + } + + private: + base::test::ScopedFeatureList feature_list_; +}; + using MediaAppIntegrationAllProfilesTest = MediaAppIntegrationTest; using MediaAppIntegrationWithFilesAppAllProfilesTest = MediaAppIntegrationWithFilesAppTest; @@ -901,6 +925,35 @@ histograms.ExpectTotalCount("Apps.DefaultAppLaunch.FromFileManager", 1); } +IN_PROC_BROWSER_TEST_P(MediaAppIntegrationDarkLightModeEnabledTest, + HasCorrectThemeAndBackgroundColor) { + WaitForTestSystemAppInstall(); + web_app::AppId app_id = + *GetManager().GetAppIdForSystemApp(web_app::SystemAppType::MEDIA); + + web_app::WebAppRegistrar& registrar = + web_app::WebAppProvider::GetForTest(profile())->registrar(); + + EXPECT_EQ(registrar.GetAppThemeColor(app_id), SK_ColorWHITE); + EXPECT_EQ(registrar.GetAppBackgroundColor(app_id), SK_ColorWHITE); + EXPECT_EQ(registrar.GetAppDarkModeThemeColor(app_id), gfx::kGoogleGrey900); + EXPECT_EQ(registrar.GetAppDarkModeBackgroundColor(app_id), + gfx::kGoogleGrey900); +} + +IN_PROC_BROWSER_TEST_P(MediaAppIntegrationDarkLightModeDisabledTest, + HasCorrectThemeAndBackgroundColor) { + WaitForTestSystemAppInstall(); + web_app::AppId app_id = + *GetManager().GetAppIdForSystemApp(web_app::SystemAppType::MEDIA); + + web_app::WebAppRegistrar& registrar = + web_app::WebAppProvider::GetForTest(profile())->registrar(); + + EXPECT_EQ(registrar.GetAppThemeColor(app_id), gfx::kGoogleGrey900); + EXPECT_EQ(registrar.GetAppBackgroundColor(app_id), gfx::kGoogleGrey800); +} + // Ensures both the "audio" and "gallery" flavours of the MediaApp can be // launched at the same time when launched via the files app. IN_PROC_BROWSER_TEST_P(MediaAppIntegrationAudioEnabledTest, @@ -1205,6 +1258,12 @@ MediaAppIntegrationAudioDisabledTest); INSTANTIATE_SYSTEM_WEB_APP_MANAGER_TEST_SUITE_REGULAR_PROFILE_P( + MediaAppIntegrationDarkLightModeEnabledTest); + +INSTANTIATE_SYSTEM_WEB_APP_MANAGER_TEST_SUITE_REGULAR_PROFILE_P( + MediaAppIntegrationDarkLightModeDisabledTest); + +INSTANTIATE_SYSTEM_WEB_APP_MANAGER_TEST_SUITE_REGULAR_PROFILE_P( MediaAppIntegrationTest); INSTANTIATE_SYSTEM_WEB_APP_MANAGER_TEST_SUITE_ALL_PROFILE_TYPES_P(
diff --git a/chrome/browser/ash/web_applications/media_app/media_web_app_info.cc b/chrome/browser/ash/web_applications/media_app/media_web_app_info.cc index ccece835..274e735 100644 --- a/chrome/browser/ash/web_applications/media_app/media_web_app_info.cc +++ b/chrome/browser/ash/web_applications/media_app/media_web_app_info.cc
@@ -10,6 +10,7 @@ #include "ash/constants/ash_features.h" #include "ash/grit/ash_media_app_resources.h" +#include "ash/style/ash_color_provider.h" #include "ash/webui/media_app_ui/url_constants.h" #include "base/files/file_path.h" #include "base/strings/string_split.h" @@ -136,8 +137,20 @@ {"app_icon_256.png", 256, IDR_MEDIA_APP_GALLERY_ICON_256_PNG}, }, *info); - info->theme_color = 0xff202124; - info->background_color = 0xff3c4043; + + if (chromeos::features::IsDarkLightModeEnabled()) { + auto* color_provider = ash::AshColorProvider::Get(); + info->theme_color = + color_provider->GetBackgroundColorInMode(/*use_dark_mode=*/false); + info->dark_mode_theme_color = + color_provider->GetBackgroundColorInMode(/*use_dark_mode=*/true); + info->background_color = info->theme_color; + info->dark_mode_background_color = info->dark_mode_theme_color; + } else { + info->theme_color = 0xff202124; + info->background_color = 0xff3c4043; + } + info->display_mode = blink::mojom::DisplayMode::kStandalone; info->user_display_mode = blink::mojom::DisplayMode::kStandalone;
diff --git a/chrome/browser/cart/cart_discount_metric_collector.cc b/chrome/browser/cart/cart_discount_metric_collector.cc index e64874d..89931e2 100644 --- a/chrome/browser/cart/cart_discount_metric_collector.cc +++ b/chrome/browser/cart/cart_discount_metric_collector.cc
@@ -8,6 +8,8 @@ #include "base/metrics/histogram_functions.h" namespace { +// These values are persisted to logs. Entries should not be renumbered and +// numeric values should never be reused. enum CartDataRequestType { kCartDiscountInfo = 0, kCartDiscountUrl = 1, @@ -36,4 +38,10 @@ void CartDiscountMetricCollector::RecordClickedOnDiscount(bool has_discounts) { base::UmaHistogramBoolean("NewTabPage.Carts.ClickCart.HasDiscount", has_discounts); -} \ No newline at end of file +} + +void CartDiscountMetricCollector::RecordDiscountConsentStatus( + DiscountConsentStatus status) { + base::UmaHistogramEnumeration("NewTabPage.Carts.DiscountConsentStatusAtLoad", + status); +}
diff --git a/chrome/browser/cart/cart_discount_metric_collector.h b/chrome/browser/cart/cart_discount_metric_collector.h index e6deba3..70d5599 100644 --- a/chrome/browser/cart/cart_discount_metric_collector.h +++ b/chrome/browser/cart/cart_discount_metric_collector.h
@@ -6,8 +6,27 @@ #define CHROME_BROWSER_CART_CART_DISCOUNT_METRIC_COLLECTOR_H_ // This is used to collect metric related to the Cart Discount. +// These values are persisted to logs. Entries should not be renumbered and +// numeric values should never be reused. class CartDiscountMetricCollector { public: + // Represent the status of discount consent. + enum class DiscountConsentStatus { + // User has seen and accepted the consent. + ACCEPTED = 0, + // User has seen and decilined the consent. + DECLINED = 1, + // User has seen the consent before but never acted on it, and the consent + // is showing now. + IGNORED = 2, + // User has seen the consent before but never acted on it, and the consent + // is not showing now. + NO_SHOW = 3, + // User has never seen the consent. + NEVER_SHOWN = 4, + kMaxValue = NEVER_SHOWN, + }; + // Gets called when Chrome fetches for discount. It increments the number of // discount fetches. static void RecordFetchingForDiscounts(); @@ -20,6 +39,9 @@ // Gets called when the user clicks on the cart item. It records whether // the cart has discounts. static void RecordClickedOnDiscount(bool has_discounts); + // Gets called when cart module shows to record histogram for discount consent + // status. + static void RecordDiscountConsentStatus(DiscountConsentStatus status); }; #endif // CHROME_BROWSER_CART_CART_DISCOUNT_METRIC_COLLECTOR_H_
diff --git a/chrome/browser/cart/cart_features.cc b/chrome/browser/cart/cart_features.cc index 0f63f5ad..067785b 100644 --- a/chrome/browser/cart/cart_features.cc +++ b/chrome/browser/cart/cart_features.cc
@@ -45,4 +45,11 @@ ntp_features::kNtpChromeCartModuleDataParam) == "fake"; } +bool IsCartDiscountFeatureEnabled() { + return base::GetFieldTrialParamValueByFeature( + ntp_features::kNtpChromeCartModule, + ntp_features::kNtpChromeCartModuleAbandonedCartDiscountParam) == + "true"; +} + } // namespace cart_features
diff --git a/chrome/browser/cart/cart_features.h b/chrome/browser/cart/cart_features.h index 3ab78954..b8bc5c0c 100644 --- a/chrome/browser/cart/cart_features.h +++ b/chrome/browser/cart/cart_features.h
@@ -26,6 +26,9 @@ // Check if the variation with fake data is enabled. bool IsFakeDataEnabled(); + +// Check if cart discount feature is enabled. +bool IsCartDiscountFeatureEnabled(); } // namespace cart_features #endif // CHROME_BROWSER_CART_CART_FEATURES_H_
diff --git a/chrome/browser/cart/cart_service.cc b/chrome/browser/cart/cart_service.cc index 5d191ae..4c74929 100644 --- a/chrome/browser/cart/cart_service.cc +++ b/chrome/browser/cart/cart_service.cc
@@ -162,6 +162,7 @@ registry->RegisterBooleanPref(prefs::kCartDiscountEnabled, false); registry->RegisterDictionaryPref(prefs::kCartUsedDiscounts); registry->RegisterTimePref(prefs::kCartDiscountLastFetchedTime, base::Time()); + registry->RegisterBooleanPref(prefs::kCartDiscountConsentShown, false); } GURL CartService::AppendUTM(const GURL& base_url, bool is_discount_enabled) { @@ -276,11 +277,7 @@ profile_->GetPrefs()->SetBoolean(prefs::kCartDiscountAcknowledged, true); profile_->GetPrefs()->SetBoolean(prefs::kCartDiscountEnabled, should_enable); - if (should_enable && - base::GetFieldTrialParamValueByFeature( - ntp_features::kNtpChromeCartModule, - ntp_features::kNtpChromeCartModuleAbandonedCartDiscountParam) == - "true") { + if (should_enable && cart_features::IsCartDiscountFeatureEnabled()) { StartGettingDiscount(); } } @@ -297,56 +294,58 @@ std::move(callback))); return; } - bool should_not_show = - ShouldShowWelcomeSurface() || - base::GetFieldTrialParamValueByFeature( - ntp_features::kNtpChromeCartModule, - ntp_features::kNtpChromeCartModuleAbandonedCartDiscountParam) != - "true" || - profile_->GetPrefs()->GetBoolean(prefs::kCartDiscountAcknowledged); - if (should_not_show) { - content::GetUIThreadTaskRunner({base::TaskPriority::BEST_EFFORT}) - ->PostTask(FROM_HERE, base::BindOnce( - [](base::OnceCallback<void(bool)> callback) { - std::move(callback).Run(false); - }, - std::move(callback))); - } else { - LoadAllActiveCarts(base::BindOnce(&CartService::HasPartnerCarts, - weak_ptr_factory_.GetWeakPtr(), - std::move(callback))); - } + LoadAllActiveCarts( + base::BindOnce(&CartService::ShouldShowDiscountConsentCallback, + weak_ptr_factory_.GetWeakPtr(), std::move(callback))); } -void CartService::HasPartnerCarts( +void CartService::ShouldShowDiscountConsentCallback( base::OnceCallback<void(bool)> callback, bool success, std::vector<CartDB::KeyAndValue> proto_pairs) { - for (auto proto_pair : proto_pairs) { - if (cart_features::IsPartnerMerchant( - GURL(proto_pair.second.merchant_cart_url()))) { - std::move(callback).Run(true); - return; - } + if (proto_pairs.size() == 0 || ShouldShowWelcomeSurface() || + !cart_features::IsCartDiscountFeatureEnabled()) { + std::move(callback).Run(false); + return; } - std::move(callback).Run(false); + if (profile_->GetPrefs()->GetBoolean(prefs::kCartDiscountAcknowledged)) { + CartDiscountMetricCollector::RecordDiscountConsentStatus( + profile_->GetPrefs()->GetBoolean(prefs::kCartDiscountEnabled) + ? CartDiscountMetricCollector::DiscountConsentStatus::ACCEPTED + : CartDiscountMetricCollector::DiscountConsentStatus::DECLINED); + std::move(callback).Run(false); + return; + } + + // Only show discount consent when there is abandoned cart(s) from partner + // merchants. + bool should_show = false; + for (auto proto_pair : proto_pairs) { + should_show |= cart_features::IsPartnerMerchant( + GURL(proto_pair.second.merchant_cart_url())); + } + if (!should_show) { + CartDiscountMetricCollector::RecordDiscountConsentStatus( + profile_->GetPrefs()->GetBoolean(prefs::kCartDiscountConsentShown) + ? CartDiscountMetricCollector::DiscountConsentStatus::NO_SHOW + : CartDiscountMetricCollector::DiscountConsentStatus::NEVER_SHOWN); + } else { + profile_->GetPrefs()->SetBoolean(prefs::kCartDiscountConsentShown, true); + CartDiscountMetricCollector::RecordDiscountConsentStatus( + CartDiscountMetricCollector::DiscountConsentStatus::IGNORED); + } + std::move(callback).Run(should_show); } bool CartService::IsCartDiscountEnabled() { - if (base::GetFieldTrialParamValueByFeature( - ntp_features::kNtpChromeCartModule, - ntp_features::kNtpChromeCartModuleAbandonedCartDiscountParam) != - "true") { + if (!cart_features::IsCartDiscountFeatureEnabled()) { return false; } return profile_->GetPrefs()->GetBoolean(prefs::kCartDiscountEnabled); } void CartService::SetCartDiscountEnabled(bool enabled) { - DCHECK(base::GetFieldTrialParamValueByFeature( - ntp_features::kNtpChromeCartModule, - ntp_features::kNtpChromeCartModuleAbandonedCartDiscountParam) == - "true"); + DCHECK(cart_features::IsCartDiscountFeatureEnabled()); profile_->GetPrefs()->SetBoolean(prefs::kCartDiscountEnabled, enabled); if (enabled) {
diff --git a/chrome/browser/cart/cart_service.h b/chrome/browser/cart/cart_service.h index 38e3413..e0abec1 100644 --- a/chrome/browser/cart/cart_service.h +++ b/chrome/browser/cart/cart_service.h
@@ -187,10 +187,11 @@ const cart_db::ChromeCartContentProto& cart_proto, const GURL& discount_url); - // A callback to decide if there are partner carts. - void HasPartnerCarts(base::OnceCallback<void(bool)> callback, - bool success, - std::vector<CartDB::KeyAndValue> proto_pairs); + // A callback to decide whether to show discount consent or not. + void ShouldShowDiscountConsentCallback( + base::OnceCallback<void(bool)> callback, + bool success, + std::vector<CartDB::KeyAndValue> proto_pairs); // Set discount_link_fetcher_ for testing purpose. void SetCartDiscountLinkFetcherForTesting( std::unique_ptr<CartDiscountLinkFetcher> discount_link_fetcher);
diff --git a/chrome/browser/cart/cart_service_unittest.cc b/chrome/browser/cart/cart_service_unittest.cc index 955b0eb..825d973 100644 --- a/chrome/browser/cart/cart_service_unittest.cc +++ b/chrome/browser/cart/cart_service_unittest.cc
@@ -5,7 +5,9 @@ #include "chrome/browser/cart/cart_service.h" #include "base/memory/raw_ptr.h" +#include "base/test/metrics/histogram_tester.h" #include "chrome/browser/cart/cart_db_content.pb.h" +#include "chrome/browser/cart/cart_discount_metric_collector.h" #include "chrome/browser/cart/cart_service_factory.h" #include "chrome/browser/cart/fetch_discount_worker.h" #include "chrome/browser/commerce/commerce_feature_list.h" @@ -1354,6 +1356,9 @@ } service_->SetCartDiscountLinkFetcherForTesting(std::move(mock_fetcher)); } + + protected: + base::HistogramTester histogram_tester_; }; // Tests discount consent should not show when welcome surface is still showing. @@ -1565,6 +1570,185 @@ run_loop[1].Run(); } +// Tests whether discount consent has shown is correctly recorded. +TEST_F(CartServiceDiscountTest, TestSetDiscountConsentShown) { + base::RunLoop run_loop[2]; + for (int i = 0; i < CartService::kWelcomSurfaceShowLimit + 1; i++) { + service_->IncreaseWelcomeSurfaceCounter(); + } + ASSERT_FALSE(service_->ShouldShowWelcomeSurface()); + ASSERT_FALSE( + profile_->GetPrefs()->GetBoolean(prefs::kCartDiscountConsentShown)); + + service_->ShouldShowDiscountConsent( + base::BindOnce(&CartServiceTest::GetEvaluationBoolResult, + base::Unretained(this), run_loop[0].QuitClosure(), true)); + run_loop[0].Run(); + ASSERT_TRUE( + profile_->GetPrefs()->GetBoolean(prefs::kCartDiscountConsentShown)); + + service_->DeleteCart(GURL(kMockMerchantURLA), true); + service_->ShouldShowDiscountConsent( + base::BindOnce(&CartServiceTest::GetEvaluationBoolResult, + base::Unretained(this), run_loop[1].QuitClosure(), false)); + run_loop[1].Run(); + ASSERT_TRUE( + profile_->GetPrefs()->GetBoolean(prefs::kCartDiscountConsentShown)); +} + +TEST_F(CartServiceDiscountTest, TestRecordDiscountConsentStatus_NotRecord) { + base::RunLoop run_loop[2]; + // Simulate that the welcome surface is not showing, the discount feature is + // disabled and there is no partner merchant carts. + profile_->GetPrefs()->SetInteger(prefs::kCartModuleWelcomeSurfaceShownTimes, + CartService::kWelcomSurfaceShowLimit); + profile_->GetPrefs()->SetBoolean(prefs::kCartDiscountEnabled, false); + service_->GetDB()->DeleteAllCarts( + base::BindOnce(&CartServiceTest::OperationEvaluation, + base::Unretained(this), run_loop[0].QuitClosure(), true)); + run_loop[0].Run(); + + // Don't record when there is no abandoned cart and cart module is not + // showing. + service_->ShouldShowDiscountConsent( + base::BindOnce(&CartServiceTest::GetEvaluationBoolResult, + base::Unretained(this), run_loop[1].QuitClosure(), false)); + run_loop[1].Run(); + histogram_tester_.ExpectTotalCount( + "NewTabPage.Carts.DiscountConsentStatusAtLoad", 0); +} + +TEST_F(CartServiceDiscountTest, TestRecordDiscountConsentStatus_NeverShown) { + base::RunLoop run_loop[2]; + // Simulate that the welcome surface is not showing, the discount feature is + // disabled and there is no partner merchant carts. + profile_->GetPrefs()->SetInteger(prefs::kCartModuleWelcomeSurfaceShownTimes, + CartService::kWelcomSurfaceShowLimit); + profile_->GetPrefs()->SetBoolean(prefs::kCartDiscountEnabled, false); + service_->GetDB()->DeleteAllCarts( + base::BindOnce(&CartServiceTest::OperationEvaluation, + base::Unretained(this), run_loop[0].QuitClosure(), true)); + run_loop[0].Run(); + + // Add a non-partner-merchant cart. + service_->AddCart(kMockMerchantC, absl::nullopt, kMockProtoC); + task_environment_.RunUntilIdle(); + + service_->ShouldShowDiscountConsent( + base::BindOnce(&CartServiceTest::GetEvaluationBoolResult, + base::Unretained(this), run_loop[1].QuitClosure(), false)); + run_loop[1].Run(); + histogram_tester_.ExpectBucketCount( + "NewTabPage.Carts.DiscountConsentStatusAtLoad", + CartDiscountMetricCollector::DiscountConsentStatus::NEVER_SHOWN, 1); +} + +TEST_F(CartServiceDiscountTest, TestRecordDiscountConsentStatus_NoShow) { + base::RunLoop run_loop[2]; + // Simulate that the welcome surface is not showing, the discount feature is + // disabled and there is no partner merchant carts. + profile_->GetPrefs()->SetInteger(prefs::kCartModuleWelcomeSurfaceShownTimes, + CartService::kWelcomSurfaceShowLimit); + profile_->GetPrefs()->SetBoolean(prefs::kCartDiscountEnabled, false); + service_->GetDB()->DeleteAllCarts( + base::BindOnce(&CartServiceTest::OperationEvaluation, + base::Unretained(this), run_loop[0].QuitClosure(), true)); + run_loop[0].Run(); + + // Add a non-partner-merchant cart, and simulate that the consent has shown + // before but the user has never acted on it. + profile_->GetPrefs()->SetBoolean(prefs::kCartDiscountConsentShown, true); + service_->AddCart(kMockMerchantC, absl::nullopt, kMockProtoC); + task_environment_.RunUntilIdle(); + + service_->ShouldShowDiscountConsent( + base::BindOnce(&CartServiceTest::GetEvaluationBoolResult, + base::Unretained(this), run_loop[1].QuitClosure(), false)); + run_loop[1].Run(); + histogram_tester_.ExpectBucketCount( + "NewTabPage.Carts.DiscountConsentStatusAtLoad", + CartDiscountMetricCollector::DiscountConsentStatus::NO_SHOW, 1); +} + +TEST_F(CartServiceDiscountTest, TestRecordDiscountConsentStatus_Ignored) { + base::RunLoop run_loop[2]; + // Simulate that the welcome surface is not showing, the discount feature is + // disabled and there is no partner merchant carts. + profile_->GetPrefs()->SetInteger(prefs::kCartModuleWelcomeSurfaceShownTimes, + CartService::kWelcomSurfaceShowLimit); + profile_->GetPrefs()->SetBoolean(prefs::kCartDiscountEnabled, false); + service_->GetDB()->DeleteAllCarts( + base::BindOnce(&CartServiceTest::OperationEvaluation, + base::Unretained(this), run_loop[0].QuitClosure(), true)); + run_loop[0].Run(); + + // Add a partner-merchant cart. + service_->AddCart(kMockMerchantA, absl::nullopt, kMockProtoA); + task_environment_.RunUntilIdle(); + + service_->ShouldShowDiscountConsent( + base::BindOnce(&CartServiceTest::GetEvaluationBoolResult, + base::Unretained(this), run_loop[1].QuitClosure(), true)); + run_loop[1].Run(); + histogram_tester_.ExpectBucketCount( + "NewTabPage.Carts.DiscountConsentStatusAtLoad", + CartDiscountMetricCollector::DiscountConsentStatus::IGNORED, 1); +} + +TEST_F(CartServiceDiscountTest, TestRecordDiscountConsentStatus_Declined) { + base::RunLoop run_loop[2]; + // Simulate that the welcome surface is not showing, the discount feature is + // disabled and there is no partner merchant carts. + profile_->GetPrefs()->SetInteger(prefs::kCartModuleWelcomeSurfaceShownTimes, + CartService::kWelcomSurfaceShowLimit); + service_->GetDB()->DeleteAllCarts( + base::BindOnce(&CartServiceTest::OperationEvaluation, + base::Unretained(this), run_loop[0].QuitClosure(), true)); + run_loop[0].Run(); + + // Add a non-partner-merchant cart, and simulate that user has rejected the + // consent. + service_->AddCart(kMockMerchantA, absl::nullopt, kMockProtoA); + task_environment_.RunUntilIdle(); + profile_->GetPrefs()->SetBoolean(prefs::kCartDiscountAcknowledged, true); + profile_->GetPrefs()->SetBoolean(prefs::kCartDiscountEnabled, false); + + service_->ShouldShowDiscountConsent( + base::BindOnce(&CartServiceTest::GetEvaluationBoolResult, + base::Unretained(this), run_loop[1].QuitClosure(), false)); + run_loop[1].Run(); + histogram_tester_.ExpectBucketCount( + "NewTabPage.Carts.DiscountConsentStatusAtLoad", + CartDiscountMetricCollector::DiscountConsentStatus::DECLINED, 1); +} + +TEST_F(CartServiceDiscountTest, TestRecordDiscountConsentStatus_Accepted) { + base::RunLoop run_loop[2]; + // Simulate that the welcome surface is not showing, the discount feature is + // disabled and there is no partner merchant carts. + profile_->GetPrefs()->SetInteger(prefs::kCartModuleWelcomeSurfaceShownTimes, + CartService::kWelcomSurfaceShowLimit); + service_->GetDB()->DeleteAllCarts( + base::BindOnce(&CartServiceTest::OperationEvaluation, + base::Unretained(this), run_loop[0].QuitClosure(), true)); + run_loop[0].Run(); + + // Add a non-partner-merchant cart, and simulate that user has accepted the + // consent. + service_->AddCart(kMockMerchantA, absl::nullopt, kMockProtoA); + task_environment_.RunUntilIdle(); + profile_->GetPrefs()->SetBoolean(prefs::kCartDiscountAcknowledged, true); + profile_->GetPrefs()->SetBoolean(prefs::kCartDiscountEnabled, true); + + service_->ShouldShowDiscountConsent( + base::BindOnce(&CartServiceTest::GetEvaluationBoolResult, + base::Unretained(this), run_loop[1].QuitClosure(), false)); + run_loop[1].Run(); + histogram_tester_.ExpectBucketCount( + "NewTabPage.Carts.DiscountConsentStatusAtLoad", + CartDiscountMetricCollector::DiscountConsentStatus::ACCEPTED, 1); +} + class CartServiceSkipExtractionTest : public CartServiceTest { public: // Features need to be initialized before CartServiceTest::SetUp runs, in
diff --git a/chrome/browser/certificate_viewer.h b/chrome/browser/certificate_viewer.h index a459f4f..617a534 100644 --- a/chrome/browser/certificate_viewer.h +++ b/chrome/browser/certificate_viewer.h
@@ -19,4 +19,8 @@ gfx::NativeWindow parent, net::X509Certificate* cert); +// Go through the motions but do not invoke the native API showing a modal +// interactive dialog on platforms where that results in hanging tests. +void MockCertificateViewerForTesting(); + #endif // CHROME_BROWSER_CERTIFICATE_VIEWER_H_
diff --git a/chrome/browser/certificate_viewer_stub.cc b/chrome/browser/certificate_viewer_stub.cc new file mode 100644 index 0000000..4f668e8 --- /dev/null +++ b/chrome/browser/certificate_viewer_stub.cc
@@ -0,0 +1,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. + +#include "chrome/browser/certificate_viewer.h" + +void MockCertificateViewerForTesting() {}
diff --git a/chrome/browser/chrome_browser_interface_binders.cc b/chrome/browser/chrome_browser_interface_binders.cc index 50f2322b..34bdc7f8 100644 --- a/chrome/browser/chrome_browser_interface_binders.cc +++ b/chrome/browser/chrome_browser_interface_binders.cc
@@ -28,7 +28,7 @@ #include "chrome/browser/translate/translate_frame_binder.h" #include "chrome/browser/ui/ui_features.h" #include "chrome/browser/ui/web_applications/draggable_region_host_impl.h" -#include "chrome/browser/ui/web_applications/sub_apps_renderer_host.h" +#include "chrome/browser/ui/web_applications/sub_apps_service_impl.h" #include "chrome/browser/ui/webui/bluetooth_internals/bluetooth_internals.mojom.h" #include "chrome/browser/ui/webui/bluetooth_internals/bluetooth_internals_ui.h" #include "chrome/browser/ui/webui/engagement/site_engagement_ui.h" @@ -669,8 +669,8 @@ defined(OS_WIN) if (base::FeatureList::IsEnabled(blink::features::kDesktopPWAsSubApps) && !render_frame_host->GetParent()) { - map->Add<blink::mojom::SubAppsProvider>( - base::BindRepeating(&web_app::SubAppsRendererHost::CreateIfAllowed)); + map->Add<blink::mojom::SubAppsService>( + base::BindRepeating(&web_app::SubAppsServiceImpl::CreateIfAllowed)); } #endif }
diff --git a/chrome/browser/chrome_browser_main.cc b/chrome/browser/chrome_browser_main.cc index 3c2cf26..1f5eb85 100644 --- a/chrome/browser/chrome_browser_main.cc +++ b/chrome/browser/chrome_browser_main.cc
@@ -466,7 +466,7 @@ DCHECK_NE(startup_profile_path_info.mode, StartupProfileMode::kError); StartupBrowserCreator::ProcessCommandLineAlreadyRunning( - command_line, current_directory, startup_profile_path_info.path); + command_line, current_directory, startup_profile_path_info); // Record now as the last successful chrome start. if (ShouldRecordActiveUse(command_line)) @@ -1759,8 +1759,8 @@ // See the comment above for an explanation of |process_command_line|. const bool started = !process_command_line || - browser_creator_->Start(parsed_command_line(), base::FilePath(), profile_, - last_opened_profiles); + browser_creator_->Start(parsed_command_line(), base::FilePath(), + profile_info, last_opened_profiles); if (started) { // TODO(crbug.com/1052397): Revisit the macro expression once build flag switch // of lacros-chrome is complete.
diff --git a/chrome/browser/chromeos/BUILD.gn b/chrome/browser/chromeos/BUILD.gn index b783a40..aa609f8 100644 --- a/chrome/browser/chromeos/BUILD.gn +++ b/chrome/browser/chromeos/BUILD.gn
@@ -1037,6 +1037,12 @@ "../ash/arc/video/gpu_arc_video_service_host.h", "../ash/arc/wallpaper/arc_wallpaper_service.cc", "../ash/arc/wallpaper/arc_wallpaper_service.h", + "../ash/arc/window_predictor/arc_predictor_app_launch_handler.cc", + "../ash/arc/window_predictor/arc_predictor_app_launch_handler.h", + "../ash/arc/window_predictor/window_predictor.cc", + "../ash/arc/window_predictor/window_predictor.h", + "../ash/arc/window_predictor/window_predictor_utils.cc", + "../ash/arc/window_predictor/window_predictor_utils.h", "../ash/assistant/assistant_util.cc", "../ash/assistant/assistant_util.h", "../ash/attestation/attestation_ca_client.cc",
diff --git a/chrome/browser/devtools/devtools_ui_bindings.cc b/chrome/browser/devtools/devtools_ui_bindings.cc index c4628365..c3b489b7 100644 --- a/chrome/browser/devtools/devtools_ui_bindings.cc +++ b/chrome/browser/devtools/devtools_ui_bindings.cc
@@ -552,8 +552,7 @@ void ReadyToCommitNavigation( content::NavigationHandle* navigation_handle) override; void DocumentOnLoadCompletedInPrimaryMainFrame() override; - void DidFinishNavigation( - content::NavigationHandle* navigation_handle) override; + void PrimaryPageChanged(content::Page& page) override; DevToolsUIBindings* devtools_bindings_; }; @@ -631,11 +630,9 @@ devtools_bindings_->DocumentOnLoadCompletedInPrimaryMainFrame(); } -void DevToolsUIBindings::FrontendWebContentsObserver::DidFinishNavigation( - content::NavigationHandle* navigation_handle) { - if (navigation_handle->IsInPrimaryMainFrame() && - navigation_handle->HasCommitted()) - devtools_bindings_->DidNavigateMainFrame(); +void DevToolsUIBindings::FrontendWebContentsObserver::PrimaryPageChanged( + content::Page&) { + devtools_bindings_->PrimaryPageChanged(); } // DevToolsUIBindings --------------------------------------------------------- @@ -1717,7 +1714,7 @@ FrontendLoaded(); } -void DevToolsUIBindings::DidNavigateMainFrame() { +void DevToolsUIBindings::PrimaryPageChanged() { frontend_loaded_ = false; }
diff --git a/chrome/browser/devtools/devtools_ui_bindings.h b/chrome/browser/devtools/devtools_ui_bindings.h index 2ec9c93..f32e33f 100644 --- a/chrome/browser/devtools/devtools_ui_bindings.h +++ b/chrome/browser/devtools/devtools_ui_bindings.h
@@ -210,7 +210,7 @@ void ReadyToCommitNavigation(content::NavigationHandle* navigation_handle); void DocumentOnLoadCompletedInPrimaryMainFrame(); - void DidNavigateMainFrame(); + void PrimaryPageChanged(); void FrontendLoaded(); void JsonReceived(DispatchCallback callback,
diff --git a/chrome/browser/extensions/api/messaging/native_messaging_apitest.cc b/chrome/browser/extensions/api/messaging/native_messaging_apitest.cc index 6dcf01d6..a34a333a 100644 --- a/chrome/browser/extensions/api/messaging/native_messaging_apitest.cc +++ b/chrome/browser/extensions/api/messaging/native_messaging_apitest.cc
@@ -163,7 +163,7 @@ StartupBrowserCreator::ProcessCommandLineAlreadyRunning( CreateNativeMessagingConnectCommandLine("test-connect-id"), {}, - profile()->GetPath()); + {profile()->GetPath(), StartupProfileMode::kBrowserWindow}); EXPECT_TRUE( g_browser_process->background_mode_manager()->IsBackgroundModeActive()); @@ -201,8 +201,9 @@ ScopedTestNativeMessagingHost::kHostName); command_line.AppendSwitch(switches::kNoStartupWindow); - StartupBrowserCreator::ProcessCommandLineAlreadyRunning(command_line, {}, - profile()->GetPath()); + StartupBrowserCreator::ProcessCommandLineAlreadyRunning( + command_line, {}, + {profile()->GetPath(), StartupProfileMode::kBrowserWindow}); if (!catcher.GetNextResult()) { FAIL() << catcher.message(); @@ -271,7 +272,7 @@ base::Seconds(2)); StartupBrowserCreator::ProcessCommandLineAlreadyRunning( CreateNativeMessagingConnectCommandLine("test-connect-id"), {}, - profile()->GetPath()); + {profile()->GetPath(), StartupProfileMode::kBrowserWindow}); ASSERT_TRUE(KeepAliveRegistry::GetInstance()->IsOriginRegistered( KeepAliveOrigin::NATIVE_MESSAGING_HOST_ERROR_REPORT)); @@ -293,7 +294,7 @@ StartupBrowserCreator::ProcessCommandLineAlreadyRunning( CreateNativeMessagingConnectCommandLine("\"connect id!\""), {}, - profile()->GetPath()); + {profile()->GetPath(), StartupProfileMode::kBrowserWindow}); ASSERT_TRUE(KeepAliveRegistry::GetInstance()->IsOriginRegistered( KeepAliveOrigin::NATIVE_MESSAGING_HOST_ERROR_REPORT)); @@ -315,7 +316,7 @@ StartupBrowserCreator::ProcessCommandLineAlreadyRunning( CreateNativeMessagingConnectCommandLine(std::string(21, 'a')), {}, - profile()->GetPath()); + {profile()->GetPath(), StartupProfileMode::kBrowserWindow}); ASSERT_TRUE(KeepAliveRegistry::GetInstance()->IsOriginRegistered( KeepAliveOrigin::NATIVE_MESSAGING_HOST_ERROR_REPORT)); @@ -337,7 +338,7 @@ StartupBrowserCreator::ProcessCommandLineAlreadyRunning( CreateNativeMessagingConnectCommandLine("test-connect-id", "abcd"), {}, - profile()->GetPath()); + {profile()->GetPath(), StartupProfileMode::kBrowserWindow}); ASSERT_TRUE(KeepAliveRegistry::GetInstance()->IsOriginRegistered( KeepAliveOrigin::NATIVE_MESSAGING_HOST_ERROR_REPORT));
diff --git a/chrome/browser/extensions/extension_service.h b/chrome/browser/extensions/extension_service.h index 9e5abf6..24e650da 100644 --- a/chrome/browser/extensions/extension_service.h +++ b/chrome/browser/extensions/extension_service.h
@@ -470,7 +470,7 @@ void UninstallMigratedExtensionsForTest() { UninstallMigratedExtensions(); } - void ProfileMarkedForPermanentDeletionForTesting() { + void ProfileMarkedForPermanentDeletionForTest() { OnProfileMarkedForPermanentDeletion(profile_); } #endif
diff --git a/chrome/browser/federated_learning/floc_id_provider_unittest.cc b/chrome/browser/federated_learning/floc_id_provider_unittest.cc index d0dab1f..90b3befc 100644 --- a/chrome/browser/federated_learning/floc_id_provider_unittest.cc +++ b/chrome/browser/federated_learning/floc_id_provider_unittest.cc
@@ -192,7 +192,7 @@ /*is_incognito=*/false); privacy_sandbox_settings_ = std::make_unique<PrivacySandboxSettings>( - settings_map_.get(), cookie_settings_.get(), &prefs_); + settings_map_.get(), cookie_settings_, &prefs_); task_environment_.RunUntilIdle(); }
diff --git a/chrome/browser/flag-metadata.json b/chrome/browser/flag-metadata.json index 4ce196dd..ece25f4 100644 --- a/chrome/browser/flag-metadata.json +++ b/chrome/browser/flag-metadata.json
@@ -1395,6 +1395,11 @@ "expiry_milestone": 101 }, { + "name": "eche-swa-in-background", + "owners": [ "dhnishi" ], + "expiry_milestone": 105 + }, + { "name": "eche-swa-resizing", "owners": [ "dhnishi" ], "expiry_milestone": 98 @@ -3578,11 +3583,6 @@ "expiry_milestone": 95 }, { - "name": "intent-picker-pwa-persistence", - "owners": [ "chromeos-apps-foundation-team@google.com" ], - "expiry_milestone": 98 - }, - { "name": "interest-feed-notice-card-auto-dismiss", "owners": [ "//chrome/android/feed/OWNERS", "feed@chromium.org", "edchin@chromium.org" ], "expiry_milestone": 95
diff --git a/chrome/browser/flag_descriptions.cc b/chrome/browser/flag_descriptions.cc index a3a8659..2032d2f 100644 --- a/chrome/browser/flag_descriptions.cc +++ b/chrome/browser/flag_descriptions.cc
@@ -4516,6 +4516,11 @@ const char kEcheSWADebugModeName[] = "Enable Eche Debug Mode"; const char kEcheSWADebugModeDescription[] = "Enable the Debug Mode of the Eche"; +const char kEcheSWAInBackgroundName[] = "Enable Eche Background Mode"; +const char kEcheSWAInBackgroundDescription[] = + "Enable the Eche SWA to run in the background before connection " + "established"; + const char kEnableIdleInhibitName[] = "Enable Idle Inhibit Protocol"; const char kEnableIdleInhibitDescription[] = "Enables the Wayland idle-inhibit-unstable-v1 protocol"; @@ -4788,10 +4793,6 @@ const char kCrosLanguageSettingsImeOptionsInSettingsDescription[] = "Adds IME settings to the settings menu"; -const char kIntentPickerPWAPersistenceName[] = "Intent picker PWA Persistence"; -const char kIntentPickerPWAPersistenceDescription[] = - "Allow user to always open with PWA in intent picker."; - const char kKeyboardBasedDisplayArrangementInSettingsName[] = "Keyboard-based Display Arrangement in Settings"; const char kKeyboardBasedDisplayArrangementInSettingsDescription[] =
diff --git a/chrome/browser/flag_descriptions.h b/chrome/browser/flag_descriptions.h index d1effc3..abec084f 100644 --- a/chrome/browser/flag_descriptions.h +++ b/chrome/browser/flag_descriptions.h
@@ -2589,6 +2589,9 @@ extern const char kEcheSWADebugModeName[]; extern const char kEcheSWADebugModeDescription[]; +extern const char kEcheSWAInBackgroundName[]; +extern const char kEcheSWAInBackgroundDescription[]; + extern const char kEnableIdleInhibitName[]; extern const char kEnableIdleInhibitDescription[]; @@ -2757,9 +2760,6 @@ extern const char kImeStylusHandwritingName[]; extern const char kImeStylusHandwritingDescription[]; -extern const char kIntentPickerPWAPersistenceName[]; -extern const char kIntentPickerPWAPersistenceDescription[]; - extern const char kKeyboardBasedDisplayArrangementInSettingsName[]; extern const char kKeyboardBasedDisplayArrangementInSettingsDescription[];
diff --git a/chrome/browser/media/webrtc/desktop_capture_access_handler.cc b/chrome/browser/media/webrtc/desktop_capture_access_handler.cc index de815ac1..bae4f91 100644 --- a/chrome/browser/media/webrtc/desktop_capture_access_handler.cc +++ b/chrome/browser/media/webrtc/desktop_capture_access_handler.cc
@@ -228,7 +228,7 @@ void DesktopCaptureAccessHandler::ProcessScreenCaptureAccessRequest( content::WebContents* web_contents, - const std::u16string& application_title, + const extensions::Extension* extension, std::unique_ptr<PendingAccessRequest> pending_request) { DCHECK_EQ(pending_request->request.video_type, blink::mojom::MediaStreamType::GUM_DESKTOP_VIDEO_CAPTURE); @@ -256,6 +256,15 @@ return; } + if (!IsRequestApproved(web_contents, pending_request->request, extension, + pending_request->is_allowlisted_extension)) { + std::move(pending_request->callback) + .Run(blink::MediaStreamDevices(), + blink::mojom::MediaStreamRequestResult::PERMISSION_DENIED, + /*ui=*/nullptr); + return; + } + if (!content::WebContents::FromRenderFrameHost( content::RenderFrameHost::FromID( pending_request->request.render_process_id, @@ -283,7 +292,7 @@ // by MediaCaptureDevicesDispatcher, which is a lazy singleton which is // destroyed when the browser process terminates. policy::DlpContentManagerAsh::Get()->CheckScreenShareRestriction( - screen_id, application_title, + screen_id, GetApplicationTitle(web_contents, extension), base::BindOnce(&DesktopCaptureAccessHandler::OnDlpRestrictionChecked, base::Unretained(this), web_contents->GetWeakPtr(), std::move(pending_request), screen_id, capture_audio)); @@ -376,18 +385,8 @@ return; } #endif - if (!IsRequestApproved(web_contents, request, extension, - is_allowlisted_extension)) { - std::move(pending_request->callback) - .Run(blink::MediaStreamDevices(), - blink::mojom::MediaStreamRequestResult::PERMISSION_DENIED, - /*ui=*/nullptr); - return; - } - - ProcessScreenCaptureAccessRequest( - web_contents, GetApplicationTitle(web_contents, extension), - std::move(pending_request)); + ProcessScreenCaptureAccessRequest(web_contents, extension, + std::move(pending_request)); return; }
diff --git a/chrome/browser/media/webrtc/desktop_capture_access_handler.h b/chrome/browser/media/webrtc/desktop_capture_access_handler.h index 5217859..586d9a8 100644 --- a/chrome/browser/media/webrtc/desktop_capture_access_handler.h +++ b/chrome/browser/media/webrtc/desktop_capture_access_handler.h
@@ -74,7 +74,7 @@ void ProcessScreenCaptureAccessRequest( content::WebContents* web_contents, - const std::u16string& application_title, + const extensions::Extension* extension, std::unique_ptr<PendingAccessRequest> pending_request); // WebContentsCollection::Observer:
diff --git a/chrome/browser/privacy_sandbox/privacy_sandbox_settings_factory.cc b/chrome/browser/privacy_sandbox/privacy_sandbox_settings_factory.cc index 974eb97e..946179cd 100644 --- a/chrome/browser/privacy_sandbox/privacy_sandbox_settings_factory.cc +++ b/chrome/browser/privacy_sandbox/privacy_sandbox_settings_factory.cc
@@ -27,10 +27,7 @@ PrivacySandboxSettingsFactory::PrivacySandboxSettingsFactory() : BrowserContextKeyedServiceFactory( "PrivacySandboxSettings", - BrowserContextDependencyManager::GetInstance()) { - DependsOn(HostContentSettingsMapFactory::GetInstance()); - DependsOn(CookieSettingsFactory::GetInstance()); -} + BrowserContextDependencyManager::GetInstance()) {} KeyedService* PrivacySandboxSettingsFactory::BuildServiceInstanceFor( content::BrowserContext* context) const {
diff --git a/chrome/browser/resources/bluetooth_internals/BUILD.gn b/chrome/browser/resources/bluetooth_internals/BUILD.gn index 8c7254e7..5e054a3 100644 --- a/chrome/browser/resources/bluetooth_internals/BUILD.gn +++ b/chrome/browser/resources/bluetooth_internals/BUILD.gn
@@ -7,6 +7,15 @@ import("//ui/webui/resources/tools/generate_grd.gni") js_type_check("closure_compile") { + closure_flags = default_closure_args + mojom_js_args + [ + "js_module_root=" + rebase_path(".", root_build_dir), + "js_module_root=" + rebase_path( + "$root_gen_dir/mojom-webui/device/bluetooth/public/mojom/", + root_build_dir), + "js_module_root=" + rebase_path( + "$root_gen_dir/mojom-webui/chrome/browser/ui/webui/bluetooth_internals/", + root_build_dir), + ] deps = [ ":adapter_broker", ":adapter_page", @@ -41,7 +50,7 @@ ":page_manager", ":sidebar", ":snackbar", - "//chrome/browser/ui/webui/bluetooth_internals:mojo_bindings_js_library_for_compile", + "//chrome/browser/ui/webui/bluetooth_internals:mojo_bindings_webui_js", "//ui/webui/resources/js:assert.m", "//ui/webui/resources/js:util.m", ] @@ -49,7 +58,8 @@ js_library("adapter_broker") { deps = [ - "//chrome/browser/ui/webui/bluetooth_internals:mojo_bindings_js_library_for_compile", + "//chrome/browser/ui/webui/bluetooth_internals:mojo_bindings_webui_js", + "//device/bluetooth/public/mojom:deprecated_experimental_interfaces_webui_js", "//ui/webui/resources/js/cr:event_target.m", ] } @@ -79,7 +89,7 @@ js_library("debug_log_page") { deps = [ ":page", - "//chrome/browser/ui/webui/bluetooth_internals:mojo_bindings_js_library_for_compile", + "//chrome/browser/ui/webui/bluetooth_internals:mojo_bindings_webui_js", "//ui/webui/resources/js:util.m", ] } @@ -100,13 +110,13 @@ js_library("device_broker") { deps = [ ":adapter_broker", - "//chrome/browser/ui/webui/bluetooth_internals:mojo_bindings_js_library_for_compile", + "//chrome/browser/ui/webui/bluetooth_internals:mojo_bindings_webui_js", ] } js_library("device_collection") { deps = [ - "//chrome/browser/ui/webui/bluetooth_internals:mojo_bindings_js_library_for_compile", + "//chrome/browser/ui/webui/bluetooth_internals:mojo_bindings_webui_js", "//ui/webui/resources/js:assert.m", "//ui/webui/resources/js/cr/ui:array_data_model.m", ] @@ -219,22 +229,22 @@ grd_prefix = bluetooth_grd_prefix out_grd = public_mojo_grdp_file input_files = [ - "adapter.mojom-lite.js", - "uuid.mojom-lite.js", - "device.mojom-lite.js", + "adapter.mojom-webui.js", + "uuid.mojom-webui.js", + "device.mojom-webui.js", ] input_files_base_dir = - rebase_path("$root_gen_dir/device/bluetooth/public/mojom/", + rebase_path("$root_gen_dir/mojom-webui/device/bluetooth/public/mojom/", root_build_dir) } generate_grd("build_internal_mojo_grdp") { grd_prefix = bluetooth_grd_prefix out_grd = internals_mojo_grdp_file - input_files = [ "bluetooth_internals.mojom-lite.js" ] - input_files_base_dir = - rebase_path("$root_gen_dir/chrome/browser/ui/webui/bluetooth_internals/", - root_build_dir) + input_files = [ "bluetooth_internals.mojom-webui.js" ] + input_files_base_dir = rebase_path( + "$root_gen_dir/mojom-webui/chrome/browser/ui/webui/bluetooth_internals/", + root_build_dir) } generate_grd("build_grd") {
diff --git a/chrome/browser/resources/bluetooth_internals/adapter_broker.js b/chrome/browser/resources/bluetooth_internals/adapter_broker.js index 9e8ad09..2f80d16 100644 --- a/chrome/browser/resources/bluetooth_internals/adapter_broker.js +++ b/chrome/browser/resources/bluetooth_internals/adapter_broker.js
@@ -2,26 +2,18 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import 'chrome://resources/mojo/mojo/public/js/mojo_bindings_lite.js'; -import './uuid.mojom-lite.js'; -import './device.mojom-lite.js'; -import './adapter.mojom-lite.js'; -import './bluetooth_internals.mojom-lite.js'; - import {NativeEventTarget as EventTarget} from 'chrome://resources/js/cr/event_target.m.js'; +import {AdapterInfo, AdapterObserverInterface, AdapterObserverReceiver, AdapterRemote, ConnectResult, DiscoverySessionRemote} from './adapter.mojom-webui.js'; +import {BluetoothInternalsHandler, BluetoothInternalsHandlerRemote} from './bluetooth_internals.mojom-webui.js'; +import {Device, DeviceInfo, DeviceRemote} from './device.mojom-webui.js'; + const SCAN_CLIENT_NAME = 'Bluetooth Internals Page'; /** * Javascript for AdapterBroker, served from * chrome://bluetooth-internals/. */ -/** @typedef {bluetooth.mojom.AdapterRemote} */ -let AdapterRemote; -/** @typedef {bluetooth.mojom.DeviceRemote} */ -let DeviceRemote; -/** @typedef {bluetooth.mojom.DiscoverySessionRemote} */ -let DiscoverySessionRemote; /** * Enum of adapter property names. Used for adapterchanged events. @@ -41,14 +33,13 @@ * Provides remote access to Adapter functions. Converts parameters to Mojo * handles and back when necessary. * - * @implements {bluetooth.mojom.AdapterObserverInterface} + * @implements {AdapterObserverInterface} */ export class AdapterBroker extends EventTarget { /** @param {!AdapterRemote} adapter */ constructor(adapter) { super(); - this.adapterObserverReceiver_ = - new bluetooth.mojom.AdapterObserverReceiver(this); + this.adapterObserverReceiver_ = new AdapterObserverReceiver(this); this.adapter_ = adapter; this.adapter_.addObserver( this.adapterObserverReceiver_.$.bindNewPipeAndPassRemote()); @@ -108,14 +99,13 @@ /** * Creates a GATT connection to the device with |address|. * @param {string} address - * @return {!Promise<!bluetooth.mojom.Device>} + * @return {!Promise<!Device>} */ connectToDevice(address) { return this.adapter_.connectToDevice(address).then(function(response) { - if (response.result != bluetooth.mojom.ConnectResult.SUCCESS) { + if (response.result != ConnectResult.SUCCESS) { // TODO(crbug.com/663394): Replace with more descriptive error // messages. - const ConnectResult = bluetooth.mojom.ConnectResult; const errorString = Object.keys(ConnectResult).find(function(key) { return ConnectResult[key] === response.result; }); @@ -129,7 +119,7 @@ /** * Gets an array of currently detectable devices from the Adapter service. - * @return {Promise<{devices: Array<!bluetooth.mojom.DeviceInfo>}>} + * @return {Promise<{devices: Array<!DeviceInfo>}>} */ getDevices() { return this.adapter_.getDevices(); @@ -137,7 +127,7 @@ /** * Gets the current state of the Adapter. - * @return {Promise<{info: bluetooth.mojom.AdapterInfo}>} + * @return {Promise<{info: AdapterInfo}>} */ getInfo() { return this.adapter_.getInfo(); @@ -146,7 +136,7 @@ /** * Requests the adapter to start a new discovery session. - * @return {!Promise<!bluetooth.mojom.DiscoverySessionRemote>} + * @return {!Promise<!DiscoverySessionRemote>} */ startDiscoverySession() { return this.adapter_.startDiscoverySession(SCAN_CLIENT_NAME) @@ -164,7 +154,7 @@ /** * Initializes an AdapterBroker if one doesn't exist. - * @param {!mojom.BluetoothInternalsHandlerRemote=} + * @param {!BluetoothInternalsHandlerRemote=} * opt_bluetoothInternalsHandler * @return {!Promise<!AdapterBroker>} resolves with * AdapterBroker, rejects if Bluetooth is not supported. @@ -176,7 +166,7 @@ const bluetoothInternalsHandler = opt_bluetoothInternalsHandler ? opt_bluetoothInternalsHandler : - mojom.BluetoothInternalsHandler.getRemote(); + BluetoothInternalsHandler.getRemote(); // Get an Adapter service. return bluetoothInternalsHandler.getAdapter().then(function(response) {
diff --git a/chrome/browser/resources/bluetooth_internals/adapter_page.js b/chrome/browser/resources/bluetooth_internals/adapter_page.js index 4fd9fb8..998682b 100644 --- a/chrome/browser/resources/bluetooth_internals/adapter_page.js +++ b/chrome/browser/resources/bluetooth_internals/adapter_page.js
@@ -7,6 +7,8 @@ */ import {$} from 'chrome://resources/js/util.m.js'; + +import {AdapterInfo} from './adapter.mojom-webui.js'; import {ObjectFieldSet} from './object_fieldset.js'; import {Page} from './page.js'; @@ -41,7 +43,7 @@ /** * Sets the information to display in fieldset. - * @param {!bluetooth.mojom.AdapterInfo} info + * @param {!AdapterInfo} info */ setAdapterInfo(info) { if (info.hasOwnProperty('systemName') && !info.systemName) {
diff --git a/chrome/browser/resources/bluetooth_internals/bluetooth_internals.js b/chrome/browser/resources/bluetooth_internals/bluetooth_internals.js index 342fae0..18e44f4 100644 --- a/chrome/browser/resources/bluetooth_internals/bluetooth_internals.js +++ b/chrome/browser/resources/bluetooth_internals/bluetooth_internals.js
@@ -7,18 +7,15 @@ * chrome://bluetooth-internals/. */ -import 'chrome://resources/mojo/mojo/public/js/mojo_bindings_lite.js'; -import './uuid.mojom-lite.js'; -import './device.mojom-lite.js'; -import './adapter.mojom-lite.js'; -import './bluetooth_internals.mojom-lite.js'; - import {assert} from 'chrome://resources/js/assert.m.js'; import {$} from 'chrome://resources/js/util.m.js'; +import {DiscoverySessionRemote} from './adapter.mojom-webui.js'; import {AdapterBroker, AdapterProperty, getAdapterBroker} from './adapter_broker.js'; import {AdapterPage} from './adapter_page.js'; +import {BluetoothInternalsHandler, BluetoothInternalsHandlerRemote} from './bluetooth_internals.mojom-webui.js'; import {DebugLogPage} from './debug_log_page.js'; +import {DeviceInfo} from './device.mojom-webui.js'; import {DeviceCollection} from './device_collection.js'; import {DeviceDetailsPage} from './device_details_page.js'; import {DevicesPage, ScanStatus} from './devices_page.js'; @@ -49,14 +46,14 @@ /** @type {DebugLogPage} */ let debugLogPage = null; -/** @type {bluetooth.mojom.DiscoverySessionRemote} */ +/** @type {DiscoverySessionRemote} */ let discoverySession = null; /** @type {boolean} */ let userRequestedScanStop = false; -/** @type {!mojom.BluetoothInternalsHandlerRemote} */ -const bluetoothInternalsHandler = mojom.BluetoothInternalsHandler.getRemote(); +/** @type {!BluetoothInternalsHandlerRemote} */ +const bluetoothInternalsHandler = BluetoothInternalsHandler.getRemote(); /** * Observer for page changes. Used to update page title header. @@ -105,7 +102,7 @@ * '#page-container', and adds a sidebar item to show the new page. If a * page exists that matches |deviceInfo.address|, nothing is created and the * existing page is returned. - * @param {!bluetooth.mojom.DeviceInfo} deviceInfo + * @param {!DeviceInfo} deviceInfo * @return {!DeviceDetailsPage} */ function makeDeviceDetailsPage(deviceInfo) {
diff --git a/chrome/browser/resources/bluetooth_internals/characteristic_list.js b/chrome/browser/resources/bluetooth_internals/characteristic_list.js index 74a19ec..9f35d6a0 100644 --- a/chrome/browser/resources/bluetooth_internals/characteristic_list.js +++ b/chrome/browser/resources/bluetooth_internals/characteristic_list.js
@@ -12,6 +12,7 @@ import {ArrayDataModel} from 'chrome://resources/js/cr/ui/array_data_model.m.js'; import {DescriptorList} from './descriptor_list.js'; +import {CharacteristicInfo, Property} from './device.mojom-webui.js'; import {connectToDevice} from './device_broker.js'; import {ExpandableList, ExpandableListItem} from './expandable_list.js'; import {ObjectFieldSet} from './object_fieldset.js'; @@ -49,7 +50,7 @@ * properties, 'id' and 'uuid', and one for the 'properties' bitfield in the * CharacteristicInfo object. * @constructor - * @param {!bluetooth.mojom.CharacteristicInfo} characteristicInfo + * @param {!CharacteristicInfo} characteristicInfo * @param {string} deviceAddress * @param {string} serviceId * @extends {ExpandableListItem} @@ -59,7 +60,7 @@ const listItem = new ExpandableListItem(); listItem.__proto__ = CharacteristicListItem.prototype; - /** @type {!bluetooth.mojom.CharacteristicInfo} */ + /** @type {!CharacteristicInfo} */ listItem.info = characteristicInfo; /** @private {string} */ listItem.deviceAddress_ = deviceAddress; @@ -92,7 +93,6 @@ /** @private {!ObjectFieldSet} */ this.propertiesFieldSet_ = new ObjectFieldSet(); this.propertiesFieldSet_.setPropertyDisplayNames(PROPERTIES_PROPERTY_NAMES); - const Property = bluetooth.mojom.Property; this.propertiesFieldSet_.showAll = false; this.propertiesFieldSet_.setObject({ broadcast: (this.info.properties & Property.BROADCAST) > 0,
diff --git a/chrome/browser/resources/bluetooth_internals/debug_log_page.js b/chrome/browser/resources/bluetooth_internals/debug_log_page.js index 3b924a4f..046cac1 100644 --- a/chrome/browser/resources/bluetooth_internals/debug_log_page.js +++ b/chrome/browser/resources/bluetooth_internals/debug_log_page.js
@@ -2,14 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import 'chrome://resources/mojo/mojo/public/js/mojo_bindings_lite.js'; -import './uuid.mojom-lite.js'; -import './device.mojom-lite.js'; -import './adapter.mojom-lite.js'; -import './bluetooth_internals.mojom-lite.js'; - import {$} from 'chrome://resources/js/util.m.js'; +import {BluetoothInternalsHandlerRemote, DebugLogsChangeHandlerRemote} from './bluetooth_internals.mojom-webui.js'; import {Page} from './page.js'; /** @const {string} */ @@ -20,13 +15,13 @@ */ export class DebugLogPage extends Page { /** - * @param {!mojom.BluetoothInternalsHandlerRemote} bluetoothInternalsHandler + * @param {!BluetoothInternalsHandlerRemote} bluetoothInternalsHandler */ constructor(bluetoothInternalsHandler) { super('debug', 'Debug Logs', 'debug'); /** - * @private {?mojom.DebugLogsChangeHandlerRemote} + * @private {?DebugLogsChangeHandlerRemote} */ this.debugLogsChangeHandler_ = null; @@ -47,7 +42,7 @@ } /** - * @param {!mojom.DebugLogsChangeHandlerRemote} handler + * @param {!DebugLogsChangeHandlerRemote} handler * @param {boolean} initialInputValue */ setUpInput(handler, initialInputValue) {
diff --git a/chrome/browser/resources/bluetooth_internals/descriptor_list.js b/chrome/browser/resources/bluetooth_internals/descriptor_list.js index 62ecb61..06921b1 100644 --- a/chrome/browser/resources/bluetooth_internals/descriptor_list.js +++ b/chrome/browser/resources/bluetooth_internals/descriptor_list.js
@@ -11,6 +11,7 @@ import {define as crUiDefine} from 'chrome://resources/js/cr/ui.m.js'; import {ArrayDataModel} from 'chrome://resources/js/cr/ui/array_data_model.m.js'; +import {DescriptorInfo} from './device.mojom-webui.js'; import {connectToDevice} from './device_broker.js'; import {ExpandableList, ExpandableListItem} from './expandable_list.js'; import {ObjectFieldSet} from './object_fieldset.js'; @@ -28,7 +29,7 @@ * A fieldset is created within the element for the primitive * properties, 'id' and 'uuid' within the DescriptorInfo object. * @constructor - * @param {!bluetooth.mojom.DescriptorInfo} descriptorInfo + * @param {!DescriptorInfo} descriptorInfo * @param {string} deviceAddress * @param {string} serviceId * @param {string} characteristicId @@ -39,7 +40,7 @@ const listItem = new ExpandableListItem(); listItem.__proto__ = DescriptorListItem.prototype; - /** @type {!bluetooth.mojom.DescriptorInfo} */ + /** @type {!DescriptorInfo} */ listItem.info = descriptorInfo; /** @private {string} */ listItem.deviceAddress_ = deviceAddress;
diff --git a/chrome/browser/resources/bluetooth_internals/device_broker.js b/chrome/browser/resources/bluetooth_internals/device_broker.js index 999df13e..7edf8ec8 100644 --- a/chrome/browser/resources/bluetooth_internals/device_broker.js +++ b/chrome/browser/resources/bluetooth_internals/device_broker.js
@@ -9,14 +9,14 @@ * DeviceRemote being shared among all requesters. */ -import 'chrome://resources/mojo/mojo/public/js/mojo_bindings_lite.js'; -import './device.mojom-lite.js'; import {getAdapterBroker} from './adapter_broker.js'; +import {DeviceRemote} from './device.mojom-webui.js'; + // Expose for testing. /** * @type {Map<string, - * !bluetooth.mojom.DeviceRemote|!Promise<!bluetooth.mojom.DeviceRemote>>} + * !DeviceRemote|!Promise<!DeviceRemote>>} */ export const connectedDevices = new Map(); @@ -26,7 +26,7 @@ * DeviceRemote. If a connection is in progress, the promise resolves when * the existing connection request promise is fulfilled. * @param {string} address - * @return {!Promise<!bluetooth.mojom.DeviceRemote>} + * @return {!Promise<!DeviceRemote>} */ export function connectToDevice(address) { const deviceOrPromise = connectedDevices.get(address) || null; @@ -34,7 +34,7 @@ return Promise.resolve(deviceOrPromise); } - const promise = /** @type {!Promise<!bluetooth.mojom.DeviceRemote>} */ ( + const promise = /** @type {!Promise<!DeviceRemote>} */ ( getAdapterBroker() .then(function(adapterBroker) { return adapterBroker.connectToDevice(address);
diff --git a/chrome/browser/resources/bluetooth_internals/device_collection.js b/chrome/browser/resources/bluetooth_internals/device_collection.js index 086350ad..f7bf900 100644 --- a/chrome/browser/resources/bluetooth_internals/device_collection.js +++ b/chrome/browser/resources/bluetooth_internals/device_collection.js
@@ -7,11 +7,11 @@ * chrome://bluetooth-internals/. */ -import 'chrome://resources/mojo/mojo/public/js/mojo_bindings_lite.js'; -import './device.mojom-lite.js'; import {assert} from 'chrome://resources/js/assert.m.js'; import {ArrayDataModel} from 'chrome://resources/js/cr/ui/array_data_model.m.js'; +import {DeviceInfo} from './device.mojom-webui.js'; + /** * Enum of connection status for a device. * @enum {number} @@ -28,7 +28,7 @@ */ export class DeviceCollection extends ArrayDataModel { /** - * @param {!Array<!bluetooth.mojom.DeviceInfo>} array The starting + * @param {!Array<!DeviceInfo>} array The starting * collection of devices. */ constructor(array) { @@ -56,7 +56,7 @@ /** * Adds or updates a Device with new DeviceInfo. - * @param {!bluetooth.mojom.DeviceInfo} deviceInfo + * @param {!DeviceInfo} deviceInfo */ addOrUpdate(deviceInfo) { this.removedDevices_[deviceInfo.address] = false; @@ -78,7 +78,7 @@ /** * Marks the Device as removed. - * @param {!bluetooth.mojom.DeviceInfo} deviceInfo + * @param {!DeviceInfo} deviceInfo */ remove(deviceInfo) { const device = this.getByAddress(deviceInfo.address); @@ -90,7 +90,7 @@ /** * Return true if device was "removed" -- previously found via scan but * either no longer advertising or no longer nearby. - * @param {!bluetooth.mojom.DeviceInfo} deviceInfo + * @param {!DeviceInfo} deviceInfo */ isRemoved(deviceInfo) { return !!this.removedDevices_[deviceInfo.address];
diff --git a/chrome/browser/resources/bluetooth_internals/device_details_page.js b/chrome/browser/resources/bluetooth_internals/device_details_page.js index 186cc53..28ab4edb 100644 --- a/chrome/browser/resources/bluetooth_internals/device_details_page.js +++ b/chrome/browser/resources/bluetooth_internals/device_details_page.js
@@ -10,6 +10,7 @@ import {$} from 'chrome://resources/js/util.m.js'; +import {DeviceInfo, DeviceRemote, ServiceInfo} from './device.mojom-webui.js'; import {connectToDevice} from './device_broker.js'; import {ConnectionStatus} from './device_collection.js'; import {formatManufacturerDataMap, formatServiceUuids} from './device_utils.js'; @@ -41,18 +42,18 @@ export class DeviceDetailsPage extends Page { /** * @param {string} id - * @param {!bluetooth.mojom.DeviceInfo} deviceInfo + * @param {!DeviceInfo} deviceInfo */ constructor(id, deviceInfo) { super(id, deviceInfo.nameForDisplay, id); - /** @type {!bluetooth.mojom.DeviceInfo} */ + /** @type {!DeviceInfo} */ this.deviceInfo = deviceInfo; - /** @type {?Array<bluetooth.mojom.ServiceInfo>} */ + /** @type {?Array<ServiceInfo>} */ this.services = null; - /** @private {?bluetooth.mojom.DeviceRemote} */ + /** @private {?DeviceRemote} */ this.device_ = null; /** @private {!ObjectFieldSet} */ @@ -182,7 +183,7 @@ /** * Sets the page's device info and forces a redraw. - * @param {!bluetooth.mojom.DeviceInfo} info + * @param {!DeviceInfo} info */ setDeviceInfo(info) { this.deviceInfo = info;
diff --git a/chrome/browser/resources/bluetooth_internals/device_table.js b/chrome/browser/resources/bluetooth_internals/device_table.js index 52870bf..c93f4d38 100644 --- a/chrome/browser/resources/bluetooth_internals/device_table.js +++ b/chrome/browser/resources/bluetooth_internals/device_table.js
@@ -9,6 +9,7 @@ import {define as crUiDefine} from 'chrome://resources/js/cr/ui.m.js'; import {$} from 'chrome://resources/js/util.m.js'; +import {DeviceInfo} from './device.mojom-webui.js'; import {DeviceCollection} from './device_collection.js'; import {formatManufacturerDataMap, formatServiceUuids} from './device_utils.js'; @@ -48,7 +49,7 @@ this.body_ = this.tBodies[0]; /** @private */ this.headers_ = this.tHead.rows[0].cells; - /** @private {!Map<!bluetooth.mojom.DeviceInfo, boolean>} */ + /** @private {!Map<!DeviceInfo, boolean>} */ this.inspectionMap_ = new Map(); }, @@ -71,7 +72,7 @@ * Updates the inspect status of the row matching the given |deviceInfo|. * If |isInspecting| is true, the forget link is enabled otherwise it's * disabled. - * @param {!bluetooth.mojom.DeviceInfo} deviceInfo + * @param {!DeviceInfo} deviceInfo * @param {boolean} isInspecting */ setInspecting(deviceInfo, isInspecting) { @@ -101,8 +102,7 @@ */ handleChange_(event) { this.updateRow_( - /** @type {!bluetooth.mojom.DeviceInfo} */ ( - this.devices_.item(event.index)), + /** @type {!DeviceInfo} */ (this.devices_.item(event.index)), event.index); }, @@ -138,7 +138,7 @@ /** * Inserts a new row at |index| and updates it with info from |device|. - * @param {!bluetooth.mojom.DeviceInfo} device + * @param {!DeviceInfo} device * @param {?number} index * @private */ @@ -188,14 +188,13 @@ for (let i = 0; i < this.devices_.length; i++) { this.insertRow_( - /** @type {!bluetooth.mojom.DeviceInfo} */ (this.devices_.item(i)), - null); + /** @type {!DeviceInfo} */ (this.devices_.item(i)), null); } }, /** * Updates the row at |index| with the info from |device|. - * @param {!bluetooth.mojom.DeviceInfo} device + * @param {!DeviceInfo} device * @param {number} index * @private */
diff --git a/chrome/browser/resources/bluetooth_internals/device_utils.js b/chrome/browser/resources/bluetooth_internals/device_utils.js index 924d82a..c609a09 100644 --- a/chrome/browser/resources/bluetooth_internals/device_utils.js +++ b/chrome/browser/resources/bluetooth_internals/device_utils.js
@@ -2,9 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import {UUID} from './uuid.mojom-webui.js'; + /** * Format in a user readable way service UUIDs. - * @param ?Array<bluetooth.mojom.UUID> uuids + * @param ?Array<UUID> uuids * @return {string} */ export function formatServiceUuids(serviceUuids) { @@ -28,4 +30,4 @@ return `0x${companyIdentifier} 0x${data}`; }) .join(' | '); -} \ No newline at end of file +}
diff --git a/chrome/browser/resources/bluetooth_internals/devices_page.js b/chrome/browser/resources/bluetooth_internals/devices_page.js index dd15e71..d5eae9c 100644 --- a/chrome/browser/resources/bluetooth_internals/devices_page.js +++ b/chrome/browser/resources/bluetooth_internals/devices_page.js
@@ -7,6 +7,7 @@ * chrome://bluetooth-internals/. */ +import {DeviceInfo} from './device.mojom-webui.js'; import {DeviceCollection} from './device_collection.js'; import {DeviceTable} from './device_table.js'; import {Page} from './page.js'; @@ -48,7 +49,7 @@ /** * Updates the inspect status of the given |deviceInfo| in the device table. - * @param {!bluetooth.mojom.DeviceInfo} deviceInfo + * @param {!DeviceInfo} deviceInfo * @param {boolean} isInspecting */ setInspecting(deviceInfo, isInspecting) {
diff --git a/chrome/browser/resources/bluetooth_internals/service_list.js b/chrome/browser/resources/bluetooth_internals/service_list.js index 12650bad..d141b52 100644 --- a/chrome/browser/resources/bluetooth_internals/service_list.js +++ b/chrome/browser/resources/bluetooth_internals/service_list.js
@@ -7,6 +7,7 @@ import {ArrayDataModel} from 'chrome://resources/js/cr/ui/array_data_model.m.js'; import {CharacteristicList} from './characteristic_list.js'; +import {ServiceInfo} from './device.mojom-webui.js'; import {connectToDevice} from './device_broker.js'; import {ExpandableList, ExpandableListItem} from './expandable_list.js'; import {ObjectFieldSet} from './object_fieldset.js'; @@ -33,7 +34,7 @@ * contains an ObjectFieldSet that displays all of the properties in the * given |serviceInfo|. Data is not loaded until the ServiceListItem is * expanded for the first time. - * @param {!bluetooth.mojom.ServiceInfo} serviceInfo + * @param {!ServiceInfo} serviceInfo * @param {string} deviceAddress * @extends {ExpandableListItem} * @constructor @@ -42,7 +43,7 @@ const listItem = new ExpandableListItem(); listItem.__proto__ = ServiceListItem.prototype; - /** @type {!bluetooth.mojom.ServiceInfo} */ + /** @type {!ServiceInfo} */ listItem.info = serviceInfo; /** @private {string} */ listItem.deviceAddress_ = deviceAddress;
diff --git a/chrome/browser/resources/bluetooth_internals/value_control.js b/chrome/browser/resources/bluetooth_internals/value_control.js index a90529e4..7d34fb4 100644 --- a/chrome/browser/resources/bluetooth_internals/value_control.js +++ b/chrome/browser/resources/bluetooth_internals/value_control.js
@@ -9,6 +9,7 @@ import {assert, assertNotReached} from 'chrome://resources/js/assert.m.js'; import {define as crUiDefine} from 'chrome://resources/js/cr/ui.m.js'; +import {GattResult, Property} from './device.mojom-webui.js'; import {connectToDevice} from './device_broker.js'; import {Snackbar, SnackbarType} from './snackbar.js'; @@ -300,12 +301,9 @@ * availability of reads and writes and the current cached value. */ redraw() { - this.readBtn_.hidden = - (this.properties_ & bluetooth.mojom.Property.READ) === 0; - this.writeBtn_.hidden = - (this.properties_ & bluetooth.mojom.Property.WRITE) === 0 && - (this.properties_ & bluetooth.mojom.Property.WRITE_WITHOUT_RESPONSE) === - 0; + this.readBtn_.hidden = (this.properties_ & Property.READ) === 0; + this.writeBtn_.hidden = (this.properties_ & Property.WRITE) === 0 && + (this.properties_ & Property.WRITE_WITHOUT_RESPONSE) === 0; const isAvailable = !this.readBtn_.hidden || !this.writeBtn_.hidden; this.unavailableMessage_.hidden = isAvailable; @@ -330,13 +328,12 @@ /** * Gets an error string describing the given |result| code. - * @param {!bluetooth.mojom.GattResult} result + * @param {!GattResult} result * @private */ getErrorString_(result) { // TODO(crbug.com/663394): Replace with more descriptive error // messages. - const GattResult = bluetooth.mojom.GattResult; return Object.keys(GattResult).find(function(key) { return GattResult[key] === result; }); @@ -365,7 +362,7 @@ .then(function(response) { this.readBtn_.disabled = false; - if (response.result === bluetooth.mojom.GattResult.SUCCESS) { + if (response.result === GattResult.SUCCESS) { this.setValue(response.value); Snackbar.show( this.deviceAddress_ + ': Read succeeded', SnackbarType.SUCCESS); @@ -403,7 +400,7 @@ .then(function(response) { this.writeBtn_.disabled = false; - if (response.result === bluetooth.mojom.GattResult.SUCCESS) { + if (response.result === GattResult.SUCCESS) { Snackbar.show( this.deviceAddress_ + ': Write succeeded', SnackbarType.SUCCESS);
diff --git a/chrome/browser/resources/chromeos/login/debug/debug.js b/chrome/browser/resources/chromeos/login/debug/debug.js index f91923b..2af19cc 100644 --- a/chrome/browser/resources/chromeos/login/debug/debug.js +++ b/chrome/browser/resources/chromeos/login/debug/debug.js
@@ -919,7 +919,10 @@ // additionalTosUrl. states: [ { - id: 'regular', + id: 'regular-owner', + trigger: (screen) => { + screen.setIsDeviceOwner(true); + }, data: { isArcEnabled: true, isDemo: false, @@ -931,7 +934,40 @@ }, }, { + id: 'regular', + trigger: (screen) => { + screen.setIsDeviceOwner(false); + }, + data: { + isArcEnabled: true, + isDemo: false, + isChildAccount: false, + isEnterpriseManagedAccount: false, + googleEulaUrl: 'https://policies.google.com/terms/embedded?hl=en', + crosEulaUrl: 'https://www.google.com/intl/en/chrome/terms/', + countryCode: 'us', + }, + }, + { + id: 'child-owner', + trigger: (screen) => { + screen.setIsDeviceOwner(true); + }, + data: { + isArcEnabled: true, + isDemo: false, + isChildAccount: true, + isEnterpriseManagedAccount: false, + googleEulaUrl: 'https://policies.google.com/terms/embedded?hl=en', + crosEulaUrl: 'https://www.google.com/intl/en/chrome/terms/', + countryCode: 'us', + }, + }, + { id: 'child', + trigger: (screen) => { + screen.setIsDeviceOwner(false); + }, data: { isArcEnabled: true, isDemo: false, @@ -955,7 +991,25 @@ }, }, { + id: 'arc-disabled-owner', + trigger: (screen) => { + screen.setIsDeviceOwner(true); + }, + data: { + isArcEnabled: false, + isDemo: false, + isChildAccount: false, + isEnterpriseManagedAccount: false, + googleEulaUrl: 'https://policies.google.com/terms/embedded?hl=en', + crosEulaUrl: 'https://www.google.com/intl/en/chrome/terms/', + countryCode: 'us', + }, + }, + { id: 'arc-disabled', + trigger: (screen) => { + screen.setIsDeviceOwner(false); + }, data: { isArcEnabled: false, isDemo: false, @@ -971,6 +1025,7 @@ trigger: (screen) => { screen.setBackupMode(true, true); screen.setLocationMode(false, true); + screen.setIsDeviceOwner(false); }, data: { isArcEnabled: true, @@ -986,6 +1041,7 @@ id: 'error', trigger: (screen) => { screen.setUIStep('error'); + screen.setIsDeviceOwner(true); }, data: { isArcEnabled: true,
diff --git a/chrome/browser/resources/chromeos/login/screens/common/consolidated_consent.html b/chrome/browser/resources/chromeos/login/screens/common/consolidated_consent.html index 019be5d..9965e66 100644 --- a/chrome/browser/resources/chromeos/login/screens/common/consolidated_consent.html +++ b/chrome/browser/resources/chromeos/login/screens/common/consolidated_consent.html
@@ -218,11 +218,12 @@ <span id="usageTitle" class="oobe-optin-title"> [[i18nDynamic(locale, 'consolidatedConsentUsageOptInTitle')]] </span> - [[getUsageText_(locale, isChildAccount_, isArcEnabled_, isDemo_)]] + [[getUsageText_(locale, isChildAccount_, isArcEnabled_, + isDemo_, isOwner_)]] <a id="usageLearnMore" on-click="onUsageLearnMoreClick_" - class="oobe-local-link" is="action-link" - aria-describedby="usageTitle"> - [[i18nDynamic(locale, 'consolidatedConsentLearnMore')]] + class="oobe-local-link" is="action-link"> + [[i18nDynamic(locale, + 'consolidatedConsentUsageOptInLearnMoreLink')]] </a> </div> <iron-icon class="managed-icon" icon="oobe-32:enterprise" @@ -246,9 +247,9 @@ [[i18nDynamic(locale, 'consolidatedConsentBackupOptInChild')]] </span> <a id="backupLearnMore" on-click="onBackupLearnMoreClick_" - class="oobe-local-link" is="action-link" - aria-describedby="backupTitle"> - [[i18nDynamic(locale, 'consolidatedConsentLearnMore')]] + class="oobe-local-link" is="action-link"> + [[i18nDynamic(locale, + 'consolidatedConsenttBackupOptInLearnMoreLink')]] </a> </div> <iron-icon class="managed-icon" icon="oobe-32:enterprise" @@ -273,9 +274,9 @@ [[i18nDynamic(locale, 'consolidatedConsentLocationOptInChild')]] </span> <a id="locationLearnMore" on-click="onLocationLearnMoreClick_" - class="oobe-local-link" is="action-link" - aria-describedby="locationTitle"> - [[i18nDynamic(locale, 'consolidatedConsentLearnMore')]] + class="oobe-local-link" is="action-link"> + [[i18nDynamic(locale, + 'consolidatedConsenttLocationOptInLearnMoreLink')]] </a> </div> <iron-icon class="managed-icon" icon="oobe-32:enterprise" @@ -328,7 +329,7 @@ <span inner-h-t-m-l= "[[getUsageLearnMoreText_(locale, isChildAccount_, - isArcEnabled_, isDemo_)]]"> + isArcEnabled_, isDemo_, isOwner_)]]"> </span> </div> </oobe-modal-dialog>
diff --git a/chrome/browser/resources/chromeos/login/screens/common/consolidated_consent.js b/chrome/browser/resources/chromeos/login/screens/common/consolidated_consent.js index bc0086a..d5078a60 100644 --- a/chrome/browser/resources/chromeos/login/screens/common/consolidated_consent.js +++ b/chrome/browser/resources/chromeos/login/screens/common/consolidated_consent.js
@@ -65,6 +65,11 @@ value: false, }, + isOwner_: { + type: Boolean, + value: false, + }, + isEnterpriseManagedAccount_: { type: Boolean, value: false, @@ -139,6 +144,7 @@ this.crosEulaLoading_ = false; this.arcTosLoading_ = false; this.privacyPolicyLoading_ = false; + this.isOwnerLoading_ = true; } /** Overridden from LoginScreenBehavior. */ @@ -147,6 +153,7 @@ return ['setUsageMode', 'setBackupMode', 'setLocationMode', + 'setIsDeviceOwner', ]; } // clang-format on @@ -189,6 +196,11 @@ this.isEnterpriseManagedAccount_ = data['isEnterpriseManagedAccount']; this.countryCode_ = data['countryCode']; + if (this.isDemo_) { + this.isOwner_ = true; + this.isOwnerLoading_ = false; + } + this.googleEulaUrl_ = data['googleEulaUrl']; this.crosEulaUrl_ = data['crosEulaUrl']; this.arcTosUrl_ = this.arcTosHostName_ + '/about/play-terms.html'; @@ -380,6 +392,7 @@ maybeSetLoadedStep_() { if (!this.googleEulaLoading_ && !this.arcTosLoading_ && + !this.isOwnerLoading_ && this.uiStep == ConsolidatedConsentScreenState.LOADING) { this.setUIStep(ConsolidatedConsentScreenState.LOADED); this.$.acceptButton.focus(); @@ -505,27 +518,50 @@ return this.i18n('consolidatedConsentHeader'); } - getUsageText_(locale, isChildAccount, isArcEnabled, isDemo) { + getUsageText_(locale, isChildAccount, isArcEnabled, isDemo, isOwner) { if (this.isArcOptInsHidden_(isArcEnabled, isDemo)) { + if (isOwner) + return this.i18n('consolidatedConsentUsageOptInArcDisabledOwner'); return this.i18n('consolidatedConsentUsageOptInArcDisabled'); } - if (isChildAccount) + if (isChildAccount) { + if (isOwner) + return this.i18n('consolidatedConsentUsageOptInChildOwner'); return this.i18n('consolidatedConsentUsageOptInChild'); + } + + if (isOwner) + return this.i18n('consolidatedConsentUsageOptInOwner'); return this.i18n('consolidatedConsentUsageOptIn'); } - getUsageLearnMoreText_(locale, isChildAccount, isArcEnabled, isDemo) { + getUsageLearnMoreText_( + locale, isChildAccount, isArcEnabled, isDemo, isOwner) { if (this.isArcOptInsHidden_(isArcEnabled, isDemo)) { if (isChildAccount) { + if (isOwner) + return this.i18nAdvanced( + 'consolidatedConsentUsageOptInLearnMoreArcDisabledChildOwner'); return this.i18nAdvanced( 'consolidatedConsentUsageOptInLearnMoreArcDisabledChild'); } + + if (isOwner) + return this.i18nAdvanced( + 'consolidatedConsentUsageOptInLearnMoreArcDisabledOwner'); return this.i18nAdvanced( 'consolidatedConsentUsageOptInLearnMoreArcDisabled'); } - if (isChildAccount) + if (isChildAccount) { + if (isOwner) + return this.i18nAdvanced( + 'consolidatedConsentUsageOptInLearnMoreChildOwner'); return this.i18nAdvanced('consolidatedConsentUsageOptInLearnMoreChild'); + } + + if (isOwner) + return this.i18nAdvanced('consolidatedConsentUsageOptInLearnMoreOwner'); return this.i18nAdvanced('consolidatedConsentUsageOptInLearnMore'); } @@ -578,6 +614,17 @@ } /** + * Sets isOwner_ property. + * @param {boolean} isOwner Defines whether the current user is the device + * owner. + */ + setIsDeviceOwner(isOwner) { + this.isOwner_ = isOwner; + this.isOwnerLoading_ = false; + this.maybeSetLoadedStep_(); + } + + /** * Opens external URL in popup overlay. * @param {string} targetUrl to show in overlay webview. */
diff --git a/chrome/browser/resources/chromeos/login/screens/common/guest_tos.html b/chrome/browser/resources/chromeos/login/screens/common/guest_tos.html index 4280988..c387679 100644 --- a/chrome/browser/resources/chromeos/login/screens/common/guest_tos.html +++ b/chrome/browser/resources/chromeos/login/screens/common/guest_tos.html
@@ -115,8 +115,7 @@ </span> [[i18nDynamic(locale, 'guestTosUsageOptin')]] <a id="usageLearnMore" on-click="onUsageLearnMoreClick_" - class="oobe-local-link" is="action-link" - aria-describedby="usageTitle"> + class="oobe-local-link" is="action-link"> [[i18nDynamic(locale, 'guestTosLearnMore')]] </a> </div>
diff --git a/chrome/browser/resources/settings/chromeos/BUILD.gn b/chrome/browser/resources/settings/chromeos/BUILD.gn index 1d95464..427e47e 100644 --- a/chrome/browser/resources/settings/chromeos/BUILD.gn +++ b/chrome/browser/resources/settings/chromeos/BUILD.gn
@@ -504,7 +504,6 @@ "chromeos/os_apps_page/app_management_page/supported_links_overlapping_apps_dialog.js", "chromeos/os_apps_page/app_management_page/supported_links_dialog.js", "chromeos/os_apps_page/app_management_page/supported_links_item.js", - "chromeos/os_apps_page/app_management_page/uninstall_button.js", "chromeos/os_apps_page/os_apps_page.js", "chromeos/os_files_page/os_files_page.js", "chromeos/os_files_page/smb_shares_page.js",
diff --git a/chrome/browser/resources/settings/chromeos/os_apps_page/app_management_page/BUILD.gn b/chrome/browser/resources/settings/chromeos/os_apps_page/app_management_page/BUILD.gn index 3db23a6..0b04f577 100644 --- a/chrome/browser/resources/settings/chromeos/os_apps_page/app_management_page/BUILD.gn +++ b/chrome/browser/resources/settings/chromeos/os_apps_page/app_management_page/BUILD.gn
@@ -32,7 +32,6 @@ ":supported_links_dialog", ":supported_links_item", ":supported_links_overlapping_apps_dialog", - ":uninstall_button", ":util", ] } @@ -243,17 +242,6 @@ ] } -js_library("uninstall_button") { - deps = [ - ":store_client", - ":util", - "../..:metrics_recorder.m", - "//ui/webui/resources/cr_elements/cr_button:cr_button.m", - "//ui/webui/resources/cr_elements/policy:cr_tooltip_icon.m", - "//ui/webui/resources/js:i18n_behavior.m", - ] -} - js_library("util") { deps = [ "../..:os_route.m", @@ -278,6 +266,5 @@ "supported_links_overlapping_apps_dialog.js", "supported_links_dialog.js", "supported_links_item.js", - "uninstall_button.js", ] }
diff --git a/chrome/browser/resources/settings/chromeos/os_apps_page/app_management_page/shared_vars.html b/chrome/browser/resources/settings/chromeos/os_apps_page/app_management_page/shared_vars.html index b3c1b224..4326b07 100644 --- a/chrome/browser/resources/settings/chromeos/os_apps_page/app_management_page/shared_vars.html +++ b/chrome/browser/resources/settings/chromeos/os_apps_page/app_management_page/shared_vars.html
@@ -5,6 +5,8 @@ --header-text-color: var(--cros-text-color-secondary); --primary-text-color: var(--cros-text-color-primary); --secondary-text-color: var(--cros-text-color-secondary); + --app-management-controlled-by-spacing: + var(--settings-controlled-by-spacing); } </style> </custom-style>
diff --git a/chrome/browser/resources/settings/chromeos/os_apps_page/app_management_page/uninstall_button.html b/chrome/browser/resources/settings/chromeos/os_apps_page/app_management_page/uninstall_button.html deleted file mode 100644 index 0d140d6..0000000 --- a/chrome/browser/resources/settings/chromeos/os_apps_page/app_management_page/uninstall_button.html +++ /dev/null
@@ -1,26 +0,0 @@ -<style include="app-management-cros-shared-css"> - :host { - align-items: center; - display: flex; - flex-direction: row; - } - - #policyIndicator { - margin-inline-end: var(--settings-controlled-by-spacing); - } -</style> -<template is="dom-if" if="[[showPolicyIndicator_(app_)]]"> - <cr-tooltip-icon - id="policyIndicator" - icon-class="cr20:domain" - tooltip-text="$i18n{appManagementAppInstalledByPolicyLabel}" - icon-aria-label="$i18n{appManagementAppInstalledByPolicyLabel}" - tooltip-position="bottom"> - </cr-tooltip-icon> -</template> -<template is="dom-if" if="[[showUninstallButton_(app_)]]"> - <cr-button id="uninstallButton" on-click="onClick_" - disabled$="[[getDisableState_(app_)]]"> - $i18n{appManagementUninstallLabel} - </cr-button> -</template>
diff --git a/chrome/browser/resources/settings/chromeos/os_apps_page/app_management_page/uninstall_button.js b/chrome/browser/resources/settings/chromeos/os_apps_page/app_management_page/uninstall_button.js deleted file mode 100644 index f1e66ef..0000000 --- a/chrome/browser/resources/settings/chromeos/os_apps_page/app_management_page/uninstall_button.js +++ /dev/null
@@ -1,101 +0,0 @@ -// Copyright 2019 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 './shared_style.js'; -import '//resources/cr_elements/cr_button/cr_button.m.js'; -import '//resources/cr_elements/policy/cr_tooltip_icon.m.js'; - -import {AppManagementUserAction, InstallReason} from '//resources/cr_components/app_management/constants.js'; -import {assert, assertNotReached} from '//resources/js/assert.m.js'; -import {afterNextRender, flush, html, Polymer, TemplateInstanceBase, Templatizer} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js'; -import {getSelectedApp, recordAppManagementUserAction} from 'chrome://resources/cr_components/app_management/util.js'; - -import {recordClick, recordNavigation, recordPageBlur, recordPageFocus, recordSearch, recordSettingChange, setUserActionRecorderForTesting} from '../../metrics_recorder.m.js'; - -import {BrowserProxy} from './browser_proxy.js'; -import {AppManagementStoreClient} from './store_client.js'; - -Polymer({ - _template: html`{__html_template__}`, - is: 'app-management-uninstall-button', - - behaviors: [ - AppManagementStoreClient, - ], - - properties: { - /** - * @private {App} - */ - app_: Object, - }, - - attached() { - this.watch('app_', state => getSelectedApp(state)); - this.updateFromStore(); - }, - - /** - * Returns true if the button should be disabled due to app install type. - * - * @param {App} app - * @return {?boolean} - * @private - */ - getDisableState_(app) { - if (!app) { - return true; - } - - switch (app.installReason) { - case InstallReason.kSystem: - case InstallReason.kPolicy: - return true; - case InstallReason.kOem: - case InstallReason.kDefault: - case InstallReason.kSync: - case InstallReason.kUser: - case InstallReason.kUnknown: - return false; - default: - assertNotReached(); - } - }, - - /** - * Returns true if the app was installed by a policy. - * - * @param {App} app - * @returns {boolean} - * @private - */ - showPolicyIndicator_(app) { - if (!app) { - return false; - } - return app.installReason === InstallReason.kPolicy; - }, - - /** - * Returns true if the uninstall button should be shown. - * - * @param {App} app - */ - showUninstallButton_(app) { - if (!app) { - return false; - } - return app.installReason !== InstallReason.kSystem; - }, - - /** - * @private - */ - onClick_() { - BrowserProxy.getInstance().handler.uninstall(this.app_.id); - recordSettingChange(); - recordAppManagementUserAction( - this.app_.type, AppManagementUserAction.UninstallDialogLaunched); - }, -});
diff --git a/chrome/browser/resources/settings/chromeos/os_apps_page/os_apps_page.html b/chrome/browser/resources/settings/chromeos/os_apps_page/os_apps_page.html index 1f4ed0b..27bd0a68 100644 --- a/chrome/browser/resources/settings/chromeos/os_apps_page/os_apps_page.html +++ b/chrome/browser/resources/settings/chromeos/os_apps_page/os_apps_page.html
@@ -103,7 +103,10 @@ <settings-subpage page-title="[[app_.title]]" title-icon="[[iconUrlFromId_(app_)]]"> - <app-management-uninstall-button slot="subpage-title-extra"> + <app-management-uninstall-button slot="subpage-title-extra" + app="[[app_]]" + uninstall-label="$i18n{appManagementUninstallLabel}" + policy-label="$i18n{appManagementAppInstalledByPolicyLabel}"> </app-management-uninstall-button> <app-management-app-detail-view> </app-management-app-detail-view>
diff --git a/chrome/browser/resources/settings/chromeos/os_apps_page/os_apps_page.js b/chrome/browser/resources/settings/chromeos/os_apps_page/os_apps_page.js index caecdefa..51bd3a62 100644 --- a/chrome/browser/resources/settings/chromeos/os_apps_page/os_apps_page.js +++ b/chrome/browser/resources/settings/chromeos/os_apps_page/os_apps_page.js
@@ -22,7 +22,7 @@ import './app_notifications_page/app_notifications_subpage.js'; import './app_management_page/app_management_page.js'; import './app_management_page/app_detail_view.js'; -import './app_management_page/uninstall_button.js'; +import '//resources/cr_components/app_management/uninstall_button.js'; import '../../controls/settings_dropdown_menu.js'; import {AppManagementEntryPoint, AppManagementEntryPointsHistogramName} from '//resources/cr_components/app_management/constants.js';
diff --git a/chrome/browser/resources/settings/chromeos/os_settings.gni b/chrome/browser/resources/settings/chromeos/os_settings.gni index fbc8fce..8ff389cb 100644 --- a/chrome/browser/resources/settings/chromeos/os_settings.gni +++ b/chrome/browser/resources/settings/chromeos/os_settings.gni
@@ -430,7 +430,6 @@ "chrome/browser/resources/settings/chromeos/os_apps_page/app_management_page/supported_links_dialog.html", "chrome/browser/resources/settings/chromeos/os_apps_page/app_management_page/supported_links_item.html", "chrome/browser/resources/settings/chromeos/os_apps_page/app_management_page/toggle_row.html", - "chrome/browser/resources/settings/chromeos/os_apps_page/app_management_page/uninstall_button.html", "chrome/browser/resources/settings/chromeos/os_apps_page/app_management_page/util.html", "chrome/browser/resources/settings/chromeos/os_apps_page/app_notifications_page/app_notifications_subpage.html", "chrome/browser/resources/settings/chromeos/os_apps_page/os_apps_page.html",
diff --git a/chrome/browser/resources/settings/chromeos/os_settings.js b/chrome/browser/resources/settings/chromeos/os_settings.js index b44142a..6138c2f8 100644 --- a/chrome/browser/resources/settings/chromeos/os_settings.js +++ b/chrome/browser/resources/settings/chromeos/os_settings.js
@@ -65,7 +65,7 @@ import './os_apps_page/app_management_page/supported_links_dialog.js'; import './os_apps_page/app_management_page/supported_links_item.js'; import '//resources/cr_components/app_management/toggle_row.js'; -import './os_apps_page/app_management_page/uninstall_button.js'; +import '//resources/cr_components/app_management/uninstall_button.js'; import './os_apps_page/app_notifications_page/mojo_interface_provider.js'; import './os_apps_page/os_apps_page.js'; import './os_bluetooth_page/os_bluetooth_devices_subpage.js';
diff --git a/chrome/browser/sync/test/integration/enable_disable_test.cc b/chrome/browser/sync/test/integration/enable_disable_test.cc index 8d0c4540..29c9052f 100644 --- a/chrome/browser/sync/test/integration/enable_disable_test.cc +++ b/chrome/browser/sync/test/integration/enable_disable_test.cc
@@ -27,9 +27,9 @@ namespace { using syncer::ModelType; -using syncer::ModelTypeFromString; +using syncer::ModelTypeFromDebugString; using syncer::ModelTypeSet; -using syncer::ModelTypeToString; +using syncer::ModelTypeToDebugString; using syncer::SyncUserSettings; using syncer::UserSelectableType; using syncer::UserSelectableTypeSet; @@ -160,7 +160,7 @@ histogram_tester.GetBucketCount( "Sync.PostedDataTypeGetUpdatesRequest", static_cast<int>(ModelTypeHistogramValue(grouped_type)))) - << " for " << ModelTypeToString(grouped_type); + << " for " << ModelTypeToDebugString(grouped_type); } else if (previously_active_types.Has(grouped_type)) { // If the type was already configured, no additional configuration cycle // is expected, but it's impossible to rule out that the type has issued @@ -171,7 +171,7 @@ histogram_tester.GetBucketCount( "Sync.PostedDataTypeGetUpdatesRequest", static_cast<int>(ModelTypeHistogramValue(grouped_type)))) - << " for " << ModelTypeToString(grouped_type); + << " for " << ModelTypeToDebugString(grouped_type); } previously_active_types.Put(grouped_type); @@ -202,7 +202,7 @@ // did not check these after disabling inside the above loop. for (ModelType multi_grouped_type : multi_grouped_types_) { EXPECT_FALSE(IsModelTypeActive(multi_grouped_type)) - << " for " << ModelTypeToString(multi_grouped_type); + << " for " << ModelTypeToDebugString(multi_grouped_type); } } @@ -234,7 +234,7 @@ // did not check these after disabling inside the above loop. for (ModelType multi_grouped_type : multi_grouped_types_) { EXPECT_FALSE(IsModelTypeActive(multi_grouped_type)) - << " for " << ModelTypeToString(multi_grouped_type); + << " for " << ModelTypeToDebugString(multi_grouped_type); } } @@ -317,7 +317,7 @@ for (UserSelectableType type : UserSelectableTypeSet::All()) { for (ModelType model_type : ResolveGroup(type)) { EXPECT_TRUE(IsModelTypeActive(model_type)) - << " for " << ModelTypeToString(model_type); + << " for " << ModelTypeToDebugString(model_type); } } } @@ -335,7 +335,7 @@ for (UserSelectableType type : UserSelectableTypeSet::All()) { for (ModelType model_type : ResolveGroup(type)) { EXPECT_TRUE(IsModelTypeActive(model_type)) - << " for " << ModelTypeToString(model_type); + << " for " << ModelTypeToDebugString(model_type); } } }
diff --git a/chrome/browser/sync/test/integration/quiesce_status_change_checker.cc b/chrome/browser/sync/test/integration/quiesce_status_change_checker.cc index 8e5614c6..30c8480 100644 --- a/chrome/browser/sync/test/integration/quiesce_status_change_checker.cc +++ b/chrome/browser/sync/test/integration/quiesce_status_change_checker.cc
@@ -72,21 +72,21 @@ auto pm_it1 = snap1.download_progress_markers().find(type); if (pm_it1 == snap1.download_progress_markers().end()) { *os << "Progress marker missing in client 1 for " - << syncer::ModelTypeToString(type); + << syncer::ModelTypeToDebugString(type); return false; } auto pm_it2 = snap2.download_progress_markers().find(type); if (pm_it2 == snap2.download_progress_markers().end()) { *os << "Progress marker missing in client 2 for " - << syncer::ModelTypeToString(type); + << syncer::ModelTypeToDebugString(type); return false; } // Fail if any of them don't match. if (!AreProgressMarkersEquivalent(pm_it1->second, pm_it2->second)) { *os << "Progress markers don't match for " - << syncer::ModelTypeToString(type); + << syncer::ModelTypeToDebugString(type); return false; } }
diff --git a/chrome/browser/sync/test/integration/sync_errors_test.cc b/chrome/browser/sync/test/integration/sync_errors_test.cc index 70fc931..221b309 100644 --- a/chrome/browser/sync/test/integration/sync_errors_test.cc +++ b/chrome/browser/sync/test/integration/sync_errors_test.cc
@@ -70,7 +70,7 @@ // StatusChangeChecker implementation. bool IsExitConditionSatisfied(std::ostream* os) override { - *os << "Waiting for type " << syncer::ModelTypeToString(type_) + *os << "Waiting for type " << syncer::ModelTypeToDebugString(type_) << " to become disabled"; return !service()->GetActiveDataTypes().Has(type_); }
diff --git a/chrome/browser/sync/test/integration/sync_integration_test_util.cc b/chrome/browser/sync/test/integration/sync_integration_test_util.cc index fc3db3ef..1789c96f 100644 --- a/chrome/browser/sync/test/integration/sync_integration_test_util.cc +++ b/chrome/browser/sync/test/integration/sync_integration_test_util.cc
@@ -27,7 +27,7 @@ size_t actual_count = fake_server()->GetSyncEntitiesByModelType(type_).size(); *os << "Waiting for fake server entity count " << actual_count << " to match expected count " << count_ << " for type " - << ModelTypeToString(type_); + << ModelTypeToDebugString(type_); return count_ == actual_count; }
diff --git a/chrome/browser/ui/BUILD.gn b/chrome/browser/ui/BUILD.gn index ca209cda..7602729 100644 --- a/chrome/browser/ui/BUILD.gn +++ b/chrome/browser/ui/BUILD.gn
@@ -1976,17 +1976,11 @@ "app_list/search/os_settings_provider.h", "app_list/search/ranking/answer_ranker.cc", "app_list/search/ranking/answer_ranker.h", - "app_list/search/ranking/category_item_ranker.cc", - "app_list/search/ranking/category_item_ranker.h", - "app_list/search/ranking/category_usage_ranker.cc", - "app_list/search/ranking/category_usage_ranker.h", "app_list/search/ranking/constants.h", "app_list/search/ranking/filtering_ranker.cc", "app_list/search/ranking/filtering_ranker.h", - "app_list/search/ranking/ftrl_category_ranker.cc", - "app_list/search/ranking/ftrl_category_ranker.h", - "app_list/search/ranking/ftrl_result_ranker.cc", - "app_list/search/ranking/ftrl_result_ranker.h", + "app_list/search/ranking/ftrl_ranker.cc", + "app_list/search/ranking/ftrl_ranker.h", "app_list/search/ranking/launch_data.cc", "app_list/search/ranking/launch_data.h", "app_list/search/ranking/query_highlighter.cc", @@ -2741,6 +2735,9 @@ "webui/nearby_share/nearby_share_dialog_ui.h", "webui/nearby_share/shared_resources.cc", "webui/nearby_share/shared_resources.h", + "webui/settings/ash/app_management/app_management_page_handler_factory.cc", + "webui/settings/ash/app_management/app_management_page_handler_factory.h", + "webui/settings/ash/app_management/app_management_uma.h", "webui/settings/chromeos/about_section.cc", "webui/settings/chromeos/about_section.h", "webui/settings/chromeos/accessibility_handler.cc", @@ -2753,8 +2750,6 @@ "webui/settings/chromeos/ambient_mode_handler.h", "webui/settings/chromeos/android_apps_handler.cc", "webui/settings/chromeos/android_apps_handler.h", - "webui/settings/chromeos/app_management/app_management_page_handler_factory.cc", - "webui/settings/chromeos/app_management/app_management_page_handler_factory.h", "webui/settings/chromeos/apps_section.cc", "webui/settings/chromeos/apps_section.h", "webui/settings/chromeos/bluetooth_handler.cc", @@ -5143,8 +5138,8 @@ "web_applications/draggable_region_host_impl.h", "web_applications/share_target_utils.cc", "web_applications/share_target_utils.h", - "web_applications/sub_apps_renderer_host.cc", - "web_applications/sub_apps_renderer_host.h", + "web_applications/sub_apps_service_impl.cc", + "web_applications/sub_apps_service_impl.h", "web_applications/system_web_app_delegate_ui_impl.cc", "web_applications/system_web_app_ui_utils.cc", "web_applications/system_web_app_ui_utils.h",
diff --git a/chrome/browser/ui/app_list/app_list_client_impl.cc b/chrome/browser/ui/app_list/app_list_client_impl.cc index 6ab8e4f..d1e1b93a 100644 --- a/chrome/browser/ui/app_list/app_list_client_impl.cc +++ b/chrome/browser/ui/app_list/app_list_client_impl.cc
@@ -235,8 +235,11 @@ if (!search_controller_) return; ChromeSearchResult* result = search_controller_->FindSearchResult(result_id); - if (result) + if (result) { search_controller_->InvokeResultAction(result, action); + if (result->display_type() == ash::SearchResultDisplayType::kContinue) + search_controller_->StartSearch(std::u16string()); + } } void AppListClientImpl::GetSearchResultContextMenuModel(
diff --git a/chrome/browser/ui/app_list/app_list_controller_delegate.cc b/chrome/browser/ui/app_list/app_list_controller_delegate.cc index 422d897..b99b91d 100644 --- a/chrome/browser/ui/app_list/app_list_controller_delegate.cc +++ b/chrome/browser/ui/app_list/app_list_controller_delegate.cc
@@ -17,7 +17,7 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/ash/tablet_mode_page_behavior.h" #include "chrome/browser/ui/chrome_pages.h" -#include "chrome/browser/ui/webui/settings/chromeos/app_management/app_management_uma.h" +#include "chrome/browser/ui/webui/settings/ash/app_management/app_management_uma.h" #include "chrome/common/extensions/extension_constants.h" #include "components/services/app_service/public/mojom/types.mojom.h" #include "extensions/browser/extension_prefs.h" @@ -63,13 +63,13 @@ if (app_type == apps::mojom::AppType::kWeb || app_type == apps::mojom::AppType::kSystemWeb) { - chrome::ShowAppManagementPage( - profile, app_id, - AppManagementEntryPoint::kAppListContextMenuAppInfoWebApp); + chrome::ShowAppManagementPage(profile, app_id, + ash::settings::AppManagementEntryPoint:: + kAppListContextMenuAppInfoWebApp); } else { - chrome::ShowAppManagementPage( - profile, app_id, - AppManagementEntryPoint::kAppListContextMenuAppInfoChromeApp); + chrome::ShowAppManagementPage(profile, app_id, + ash::settings::AppManagementEntryPoint:: + kAppListContextMenuAppInfoChromeApp); } }
diff --git a/chrome/browser/ui/app_list/app_service/app_service_context_menu.cc b/chrome/browser/ui/app_list/app_service/app_service_context_menu.cc index ba7b5df..aebe31f 100644 --- a/chrome/browser/ui/app_list/app_service/app_service_context_menu.cc +++ b/chrome/browser/ui/app_list/app_service/app_service_context_menu.cc
@@ -34,7 +34,7 @@ #include "chrome/browser/ui/app_list/extension_app_utils.h" #include "chrome/browser/ui/ash/shelf/standalone_browser_extension_app_context_menu.h" #include "chrome/browser/ui/chrome_pages.h" -#include "chrome/browser/ui/webui/settings/chromeos/app_management/app_management_uma.h" +#include "chrome/browser/ui/webui/settings/ash/app_management/app_management_uma.h" #include "chrome/grit/generated_resources.h" #include "components/services/app_service/public/cpp/types_util.h" #include "content/public/browser/browser_task_traits.h" @@ -436,7 +436,7 @@ if (app_type_ == apps::AppType::kArc) { chrome::ShowAppManagementPage( profile(), app_id(), - AppManagementEntryPoint::kAppListContextMenuAppInfoArc); + ash::settings::AppManagementEntryPoint::kAppListContextMenuAppInfoArc); return; }
diff --git a/chrome/browser/ui/app_list/search/chrome_search_result.cc b/chrome/browser/ui/app_list/search/chrome_search_result.cc index 58af571..dcde34108 100644 --- a/chrome/browser/ui/app_list/search/chrome_search_result.cc +++ b/chrome/browser/ui/app_list/search/chrome_search_result.cc
@@ -55,13 +55,14 @@ metadata_->title_vector = text_vector; SetSearchResultMetadata(); } + void ChromeSearchResult::SetDetailsTextVector(const TextVector& text_vector) { metadata_->details_vector = text_vector; SetSearchResultMetadata(); } -void ChromeSearchResult::SetBigTitle(const std::u16string& big_title) { - metadata_->big_title = big_title; +void ChromeSearchResult::SetBigTitleTextVector(const TextVector& text_vector) { + metadata_->big_title_vector = text_vector; SetSearchResultMetadata(); }
diff --git a/chrome/browser/ui/app_list/search/chrome_search_result.h b/chrome/browser/ui/app_list/search/chrome_search_result.h index 23cb8e46..5caecf4 100644 --- a/chrome/browser/ui/app_list/search/chrome_search_result.h +++ b/chrome/browser/ui/app_list/search/chrome_search_result.h
@@ -57,13 +57,17 @@ const Tags& title_tags() const { return metadata_->title_tags; } const std::u16string& details() const { return metadata_->details; } const Tags& details_tags() const { return metadata_->details_tags; } + const TextVector& title_text_vector() const { return metadata_->title_vector; } const TextVector& details_text_vector() const { return metadata_->details_vector; } - const std::u16string& big_title() const { return metadata_->big_title; } + const TextVector& big_title_text_vector() const { + return metadata_->big_title_vector; + } + const std::u16string& accessible_name() const { return metadata_->accessible_name; } @@ -105,7 +109,7 @@ void SetDetailsTags(const Tags& tags); void SetTitleTextVector(const TextVector& text_vector); void SetDetailsTextVector(const TextVector& text_vector); - void SetBigTitle(const std::u16string& big_title); + void SetBigTitleTextVector(const TextVector& text_vector); void SetAccessibleName(const std::u16string& name); void SetRating(float rating); void SetFormattedPrice(const std::u16string& formatted_price);
diff --git a/chrome/browser/ui/app_list/search/files/zero_state_file_provider.cc b/chrome/browser/ui/app_list/search/files/zero_state_file_provider.cc index d26e10e..11e94ea 100644 --- a/chrome/browser/ui/app_list/search/files/zero_state_file_provider.cc +++ b/chrome/browser/ui/app_list/search/files/zero_state_file_provider.cc
@@ -88,7 +88,7 @@ file_tasks_observer_.Observe(notifier); RecurrenceRankerConfigProto config; - config.set_min_seconds_between_saves(120u); + config.set_min_seconds_between_saves(3u); config.set_condition_limit(1u); config.set_condition_decay(0.5f); config.set_target_limit(200);
diff --git a/chrome/browser/ui/app_list/search/ranking/category_item_ranker.cc b/chrome/browser/ui/app_list/search/ranking/category_item_ranker.cc deleted file mode 100644 index e029374..0000000 --- a/chrome/browser/ui/app_list/search/ranking/category_item_ranker.cc +++ /dev/null
@@ -1,47 +0,0 @@ -// Copyright 2021 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/ui/app_list/search/ranking/category_item_ranker.h" - -#include <cmath> -#include <limits> - -#include "base/logging.h" -#include "base/strings/strcat.h" -#include "chrome/browser/ui/app_list/search/chrome_search_result.h" -#include "chrome/browser/ui/app_list/search/ranking/constants.h" -#include "chrome/browser/ui/app_list/search/ranking/util.h" - -namespace app_list { - -void CategoryItemRanker::UpdateCategoryRanks(const ResultsMap& results, - CategoriesList& categories, - ProviderType provider) { - const auto& it = results.find(provider); - DCHECK(it != results.end()); - - // Populate a map with the current scores. - base::flat_map<Category, double> high_scores; - for (const auto& category : categories) - high_scores[category.category] = category.score; - - // Update it with the scores from new results. - for (const auto& result : it->second) { - Scoring& scoring = result->scoring(); - - // Ignore best match results for the purposes of deciding category scores, - // because they're displayed outside their category. - if (result->best_match()) - continue; - - high_scores[result->category()] = - std::max(high_scores[result->category()], scoring.normalized_relevance); - } - - // Update the category objects with the new scores . - for (auto& category : categories) - category.score = high_scores[category.category]; -} - -} // namespace app_list
diff --git a/chrome/browser/ui/app_list/search/ranking/category_item_ranker.h b/chrome/browser/ui/app_list/search/ranking/category_item_ranker.h deleted file mode 100644 index 6789be09..0000000 --- a/chrome/browser/ui/app_list/search/ranking/category_item_ranker.h +++ /dev/null
@@ -1,36 +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. - -#ifndef CHROME_BROWSER_UI_APP_LIST_SEARCH_RANKING_CATEGORY_ITEM_RANKER_H_ -#define CHROME_BROWSER_UI_APP_LIST_SEARCH_RANKING_CATEGORY_ITEM_RANKER_H_ - -#include "chrome/browser/ui/app_list/search/ranking/ranker.h" -#include "chrome/browser/ui/app_list/search/ranking/types.h" - -namespace app_list { - -// A ranker that groups results into categories. Categories are ordered based on -// the highest scoring result per-category. This is assumed to run after the -// score normalization stage, which makes score comparable between search -// providers. -// -// TODO(crbug.com/1199206): This is temporarily unused while being incorporated -// into the FtrlCategoryRanker. -class CategoryItemRanker : public Ranker { - public: - CategoryItemRanker() = default; - ~CategoryItemRanker() override = default; - - CategoryItemRanker(const CategoryItemRanker&) = delete; - CategoryItemRanker& operator=(const CategoryItemRanker&) = delete; - - // Ranker: - void UpdateCategoryRanks(const ResultsMap& results, - CategoriesList& categories, - ProviderType provider) override; -}; - -} // namespace app_list - -#endif // CHROME_BROWSER_UI_APP_LIST_SEARCH_RANKING_CATEGORY_ITEM_RANKER_H_
diff --git a/chrome/browser/ui/app_list/search/ranking/category_item_ranker_unittest.cc b/chrome/browser/ui/app_list/search/ranking/category_item_ranker_unittest.cc deleted file mode 100644 index 0025e94..0000000 --- a/chrome/browser/ui/app_list/search/ranking/category_item_ranker_unittest.cc +++ /dev/null
@@ -1,85 +0,0 @@ -// Copyright 2021 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/ui/app_list/search/ranking/category_item_ranker.h" - -#include "base/files/scoped_temp_dir.h" -#include "base/logging.h" -#include "base/test/task_environment.h" -#include "chrome/browser/ui/app_list/search/chrome_search_result.h" -#include "chrome/browser/ui/app_list/search/ranking/types.h" -#include "chrome/browser/ui/app_list/search/search_controller.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace app_list { -namespace { - -using testing::Contains; - -MATCHER_P2(Metadata, category, score, "") { - bool match = arg.category == category && arg.score == score; - if (!match) - *result_listener << "Metadata wants (" << static_cast<size_t>(category) - << ", " << score << "), but got (" - << static_cast<size_t>(arg.category) << ", " << arg.score - << ")"; - return match; -} - -class TestResult : public ChromeSearchResult { - public: - TestResult(double relevance, Category category, bool best_match) { - // For testing, directly set the normalized relevance. A normal result - // wouldn't do this. - scoring().normalized_relevance = relevance; - SetCategory(category); - SetBestMatch(best_match); - } - ~TestResult() override {} - - // ChromeSearchResult overrides: - void Open(int event_flags) override {} -}; - -Results make_results(Category category, - std::vector<double> relevances, - std::vector<bool> best_matches) { - Results res; - for (size_t i = 0; i < relevances.size(); ++i) { - res.push_back( - std::make_unique<TestResult>(relevances[i], category, best_matches[i])); - } - return res; -} - -} // namespace - -TEST(CategoryItemRankerTest, UpdatesScores) { - ResultsMap results; - results[ResultType::kInstalledApp] = - make_results(Category::kApps, {0.1, 1.5, 0.9}, {false, false, false}); - results[ResultType::kInternalApp] = - make_results(Category::kApps, {10.0, 2.0}, {true, false}); - results[ResultType::kOmnibox] = - make_results(Category::kWeb, {0.3, 0.4, 0.3}, {false, true, false}); - - CategoryItemRanker ranker; - CategoriesList categories = CreateAllCategories(); - - // Only the kInstalledApp results should be used in this call to Rank. - ranker.UpdateCategoryRanks(results, categories, ResultType::kInstalledApp); - EXPECT_THAT(categories, Contains(Metadata(Category::kApps, 1.5))); - - // Only the kInternalApp results should be used, but the best match ignored. - ranker.UpdateCategoryRanks(results, categories, ResultType::kInternalApp); - EXPECT_THAT(categories, Contains(Metadata(Category::kApps, 2.0))); - - // Ranking a new category should preserve the old ranking. - ranker.UpdateCategoryRanks(results, categories, ResultType::kOmnibox); - EXPECT_THAT(categories, Contains(Metadata(Category::kApps, 2.0))); - EXPECT_THAT(categories, Contains(Metadata(Category::kWeb, 0.3))); -} - -} // namespace app_list
diff --git a/chrome/browser/ui/app_list/search/ranking/category_usage_ranker.cc b/chrome/browser/ui/app_list/search/ranking/category_usage_ranker.cc deleted file mode 100644 index da6f617..0000000 --- a/chrome/browser/ui/app_list/search/ranking/category_usage_ranker.cc +++ /dev/null
@@ -1,112 +0,0 @@ -// Copyright 2021 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/ui/app_list/search/ranking/category_usage_ranker.h" - -#include "base/containers/fixed_flat_map.h" -#include "base/logging.h" -#include "base/strings/strcat.h" -#include "base/strings/string_number_conversions.h" -#include "chrome/browser/ash/profiles/profile_helper.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ui/app_list/search/chrome_search_result.h" -#include "chrome/browser/ui/app_list/search/ranking/constants.h" -#include "chrome/browser/ui/app_list/search/ranking/util.h" -#include "chrome/browser/ui/app_list/search/util/mrfu_cache.h" - -namespace app_list { -namespace { - -// This map sets default category scores for each search session. On each call -// to Start: -// - the CategoriesList is populated with these scores, -// - which are then overridden by any scores in the MRFU cache tracking usage. -// -// This ensures the CategoriesList always contains a non-zero score for all -// categories. This defines the OOBE category ranking in the launcher. Scores -// are set intentionally low, so that any launcher usage puts a category above -// the defaults. -constexpr auto kDefaultScores = base::MakeFixedFlatMap<Category, double>( - {{Category::kHelp, 8e-5}, - {Category::kApps, 7e-5}, - {Category::kAppShortcuts, 6e-5}, - {Category::kWeb, 5e-5}, - {Category::kFiles, 4e-5}, - {Category::kSettings, 3e-5}, - {Category::kPlayStore, 2e-5}, - {Category::kSearchAndAssistant, 1e-5}}); - -constexpr double kEps = 1.0e-5; - -std::string CategoryToString(const Category value) { - return base::NumberToString(static_cast<int>(value)); -} - -Category StringToCategory(const std::string& value) { - int number; - base::StringToInt(value, &number); - return static_cast<Category>(number); -} - -void SetDefaultCategoryScores(CategoriesList& categories) { - for (auto& category : categories) { - auto* it = kDefaultScores.find(category.category); - // Insert the default score if no other score exists. - if (it == kDefaultScores.end()) - category.score = it->second; - } -} - -} // namespace - -CategoryUsageRanker::CategoryUsageRanker(Profile* profile) { - // Initialize category ranking as a most-frecently-used list. - MrfuCache::Params params; - // Set max params to more than the maximum number of categories - params.max_items = 50; - - // TODO(crbug.com/1199206): Tweak these settings after manual testing. - params.half_life = 10.0f; - params.boost_factor = 10.0f; - - MrfuCache::Proto proto( - RankerStateDirectory(profile).AppendASCII("category_usage_ranker.pb"), - /*write_delay=*/base::Seconds(3)); - ranker_ = std::make_unique<MrfuCache>(std::move(proto), params); -} - -CategoryUsageRanker::~CategoryUsageRanker() {} - -void CategoryUsageRanker::Start(const std::u16string& query, - ResultsMap& results, - CategoriesList& categories) { - // Ensure all categories are accounted for in the input. - DCHECK_EQ(categories.size(), static_cast<size_t>(Category::kMaxValue)); - SetDefaultCategoryScores(categories); - - if (!ranker_->initialized()) - return; - - // Retrieve all category scores, sorted high-to-low, and set category ranks - // based on their ordering. - // TODO(crbug.com/1199206): The kEps is useful for debugging here, but can be - // removed once no longer needed. - auto category_scores = ranker_->GetAll(); - MrfuCache::Sort(category_scores); - for (int i = 0; i < category_scores.size(); ++i) { - const auto category_value = StringToCategory(category_scores[i].first); - for (auto& category : categories) { - if (category.category == category_value) - category.score = category_scores[i].second - i * kEps; - } - } -} - -void CategoryUsageRanker::UpdateCategoryRanks(const ResultsMap& results, - CategoriesList& categories, - ProviderType provider) {} - -void CategoryUsageRanker::Train(const LaunchData& launch) {} - -} // namespace app_list
diff --git a/chrome/browser/ui/app_list/search/ranking/category_usage_ranker.h b/chrome/browser/ui/app_list/search/ranking/category_usage_ranker.h deleted file mode 100644 index 6550f13..0000000 --- a/chrome/browser/ui/app_list/search/ranking/category_usage_ranker.h +++ /dev/null
@@ -1,43 +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. - -#ifndef CHROME_BROWSER_UI_APP_LIST_SEARCH_RANKING_CATEGORY_USAGE_RANKER_H_ -#define CHROME_BROWSER_UI_APP_LIST_SEARCH_RANKING_CATEGORY_USAGE_RANKER_H_ - -#include "chrome/browser/ui/app_list/search/ranking/ranker.h" -#include "chrome/browser/ui/app_list/search/ranking/types.h" - -class Profile; - -namespace app_list { - -class MrfuCache; - -// A ranker that groups results into categories. -// -// TODO(crbug.com/1199206): This class is unused and can be removed. -class CategoryUsageRanker : public Ranker { - public: - explicit CategoryUsageRanker(Profile* profile); - ~CategoryUsageRanker() override; - - CategoryUsageRanker(const CategoryUsageRanker&) = delete; - CategoryUsageRanker& operator=(const CategoryUsageRanker&) = delete; - - // Ranker: - void Start(const std::u16string& query, - ResultsMap& results, - CategoriesList& categories) override; - void UpdateCategoryRanks(const ResultsMap& results, - CategoriesList& categories, - ProviderType provider) override; - void Train(const LaunchData& launch) override; - - private: - std::unique_ptr<MrfuCache> ranker_; -}; - -} // namespace app_list - -#endif // CHROME_BROWSER_UI_APP_LIST_SEARCH_RANKING_CATEGORY_USAGE_RANKER_H_
diff --git a/chrome/browser/ui/app_list/search/ranking/category_usage_ranker_unittest.cc b/chrome/browser/ui/app_list/search/ranking/category_usage_ranker_unittest.cc deleted file mode 100644 index b2474f0a..0000000 --- a/chrome/browser/ui/app_list/search/ranking/category_usage_ranker_unittest.cc +++ /dev/null
@@ -1,73 +0,0 @@ -// Copyright 2021 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/ui/app_list/search/ranking/category_usage_ranker.h" - -#include "base/logging.h" -#include "chrome/browser/ui/app_list/search/chrome_search_result.h" -#include "chrome/browser/ui/app_list/search/ranking/types.h" -#include "chrome/browser/ui/app_list/search/search_controller.h" -#include "chrome/test/base/testing_profile.h" -#include "content/public/test/browser_task_environment.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace app_list { -namespace { - -using testing::UnorderedElementsAre; - -class TestResult : public ChromeSearchResult { - public: - TestResult(double relevance, Category category, bool best_match) { - // For testing, directly set the normalized relevance. A normal result - // wouldn't do this. - scoring().normalized_relevance = relevance; - SetCategory(category); - SetBestMatch(best_match); - } - ~TestResult() override {} - - // ChromeSearchResult overrides: - void Open(int event_flags) override {} -}; - -Results make_results(Category category, - std::vector<double> relevances, - std::vector<bool> best_matches) { - Results res; - for (size_t i = 0; i < relevances.size(); ++i) { - res.push_back( - std::make_unique<TestResult>(relevances[i], category, best_matches[i])); - } - return res; -} - -} // namespace - -class CategoryUsageRankerTest : public testing::Test { - public: - void SetUp() override { profile_ = std::make_unique<TestingProfile>(); } - - void Wait() { task_environment_.RunUntilIdle(); } - - content::BrowserTaskEnvironment task_environment_; - std::unique_ptr<Profile> profile_; -}; - -TEST_F(CategoryUsageRankerTest, DefaultScoresForEmptyRanker) { - CategoryUsageRanker ranker(profile_.get()); - CategoriesList categories = CreateAllCategories(); - EXPECT_EQ(categories.size(), static_cast<size_t>(Category::kMaxValue)); - ResultsMap results; - - Wait(); - // Ranker is empty, so default scores should fill in the category ranks. Don't - // check the specifics of the ranking, only that all categories are accounted - // for. - ranker.Start(u"", results, categories); - EXPECT_EQ(categories.size(), static_cast<size_t>(Category::kMaxValue)); -} - -} // namespace app_list
diff --git a/chrome/browser/ui/app_list/search/ranking/ftrl_category_ranker.cc b/chrome/browser/ui/app_list/search/ranking/ftrl_category_ranker.cc deleted file mode 100644 index 8c7fc5e2..0000000 --- a/chrome/browser/ui/app_list/search/ranking/ftrl_category_ranker.cc +++ /dev/null
@@ -1,31 +0,0 @@ -// Copyright 2021 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/ui/app_list/search/ranking/ftrl_category_ranker.h" - -#include "chrome/browser/ui/app_list/search/chrome_search_result.h" - -namespace app_list { - -FtrlCategoryRanker::FtrlCategoryRanker() = default; -FtrlCategoryRanker::~FtrlCategoryRanker() = default; - -void FtrlCategoryRanker::Start(const std::u16string& query, - ResultsMap& results, - CategoriesList& categories) {} - -void FtrlCategoryRanker::UpdateResultRanks(ResultsMap& results, - ProviderType provider) { - // TODO(crbug.com/1199206): WIP. -} - -void FtrlCategoryRanker::UpdateCategoryRanks(const ResultsMap& results, - CategoriesList& categories, - ProviderType provider) { - // TODO(crbug.com/1199206): WIP. -} - -void FtrlCategoryRanker::Train(const LaunchData& launch) {} - -} // namespace app_list
diff --git a/chrome/browser/ui/app_list/search/ranking/ftrl_category_ranker.h b/chrome/browser/ui/app_list/search/ranking/ftrl_category_ranker.h deleted file mode 100644 index a3771f4..0000000 --- a/chrome/browser/ui/app_list/search/ranking/ftrl_category_ranker.h +++ /dev/null
@@ -1,37 +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. - -#ifndef CHROME_BROWSER_UI_APP_LIST_SEARCH_RANKING_FTRL_CATEGORY_RANKER_H_ -#define CHROME_BROWSER_UI_APP_LIST_SEARCH_RANKING_FTRL_CATEGORY_RANKER_H_ - -#include "chrome/browser/ui/app_list/search/ranking/ranker.h" -#include "chrome/browser/ui/app_list/search/ranking/types.h" - -namespace app_list { - -// A ranker for categories using a Follow the Regularized Leader algorithm. -// -// TODO(crbug.com/1199206): WIP. -class FtrlCategoryRanker : public Ranker { - public: - FtrlCategoryRanker(); - ~FtrlCategoryRanker() override; - - FtrlCategoryRanker(const FtrlCategoryRanker&) = delete; - FtrlCategoryRanker& operator=(const FtrlCategoryRanker&) = delete; - - // Ranker: - void Start(const std::u16string& query, - ResultsMap& results, - CategoriesList& categories) override; - void UpdateResultRanks(ResultsMap& results, ProviderType provider) override; - void UpdateCategoryRanks(const ResultsMap& results, - CategoriesList& categories, - ProviderType provider) override; - void Train(const LaunchData& launch) override; -}; - -} // namespace app_list - -#endif // CHROME_BROWSER_UI_APP_LIST_SEARCH_RANKING_FTRL_CATEGORY_RANKER_H_
diff --git a/chrome/browser/ui/app_list/search/ranking/ftrl_ranker.cc b/chrome/browser/ui/app_list/search/ranking/ftrl_ranker.cc new file mode 100644 index 0000000..566cb1b --- /dev/null +++ b/chrome/browser/ui/app_list/search/ranking/ftrl_ranker.cc
@@ -0,0 +1,288 @@ +// 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/app_list/search/ranking/ftrl_ranker.h" + +#include "base/strings/string_number_conversions.h" +#include "chrome/browser/ui/app_list/search/chrome_search_result.h" +#include "chrome/browser/ui/app_list/search/util/ftrl_optimizer.h" + +namespace app_list { +namespace { + +std::string CategoryToString(const Category value) { + return base::NumberToString(static_cast<int>(value)); +} + +Category StringToCategory(const std::string& value) { + int number; + base::StringToInt(value, &number); + return static_cast<Category>(number); +} + +// TODO(crbug.com/1199206): This can be removed once LaunchData contains the +// result category. +// +// This is slightly inconsistent with the true result->category mapping, because +// Omnibox results can either be in the kWeb or kSearchAndAssistant category. +Category ResultTypeToCategory(ResultType result_type) { + switch (result_type) { + case ResultType::kInstalledApp: + case ResultType::kInstantApp: + case ResultType::kInternalApp: + return Category::kApps; + case ResultType::kArcAppShortcut: + return Category::kAppShortcuts; + case ResultType::kOmnibox: + case ResultType::kAnswerCard: + return Category::kWeb; + case ResultType::kZeroStateFile: + case ResultType::kZeroStateDrive: + case ResultType::kFileChip: + case ResultType::kDriveChip: + case ResultType::kFileSearch: + case ResultType::kDriveSearch: + return Category::kFiles; + case ResultType::kOsSettings: + return Category::kSettings; + case ResultType::kHelpApp: + return Category::kHelp; + case ResultType::kPlayStoreReinstallApp: + case ResultType::kPlayStoreApp: + return Category::kPlayStore; + case ResultType::kAssistantChip: + case ResultType::kAssistantText: + return Category::kSearchAndAssistant; + // Never used in the search backend. + case ResultType::kUnknown: + // Suggested content toggle fake result type. Used only in ash, not in the + // search backend. + case ResultType::kInternalPrivacyInfo: + // Deprecated. + case ResultType::kLauncher: + return Category::kUnknown; + } +} + +} // namespace + +// FtrlRanker ------------------------------------------------------------ + +FtrlRanker::FtrlRanker(FtrlRanker::RankingKind kind, + FtrlOptimizer::Params params, + FtrlOptimizer::Proto proto) + : kind_(kind), + ftrl_(std::make_unique<FtrlOptimizer>(std::move(proto), params)) {} + +FtrlRanker::~FtrlRanker() = default; + +void FtrlRanker::AddExpert(std::unique_ptr<Ranker> ranker) { + rankers_.push_back(std::move(ranker)); +} + +void FtrlRanker::Start(const std::u16string& query, + ResultsMap& results, + CategoriesList& categories) { + for (auto& ranker : rankers_) + ranker->Start(query, results, categories); +} + +void FtrlRanker::Train(const LaunchData& launch) { + for (auto& ranker : rankers_) + ranker->Train(launch); + + switch (kind_) { + case FtrlRanker::RankingKind::kResults: + ftrl_->Train(launch.id); + break; + case FtrlRanker::RankingKind::kCategories: + ftrl_->Train(CategoryToString(ResultTypeToCategory(launch.result_type))); + break; + } +} + +void FtrlRanker::UpdateResultRanks(ResultsMap& results, ProviderType provider) { + if (kind_ != FtrlRanker::RankingKind::kResults) + return; + + const auto it = results.find(provider); + DCHECK(it != results.end()); + const auto& new_results = it->second; + + // Create a vector of result ids. + std::vector<std::string> ids; + for (const auto& result : new_results) + ids.push_back(result->id()); + + // Create a vector of vectors for each expert's scores. + std::vector<std::vector<double>> expert_scores; + for (auto& ranker : rankers_) + expert_scores.push_back(ranker->GetResultRanks(results, provider)); + + // Get the final scores from the FTRL optimizer set them on the results. + std::vector<double> result_scores = + ftrl_->Score(std::move(ids), std::move(expert_scores)); + DCHECK_EQ(new_results.size(), result_scores.size()); + for (size_t i = 0; i < new_results.size(); ++i) + new_results[i]->scoring().ftrl_result_score = result_scores[i]; +} + +void FtrlRanker::UpdateCategoryRanks(const ResultsMap& results, + CategoriesList& categories, + ProviderType provider) { + if (kind_ != FtrlRanker::RankingKind::kCategories) + return; + + // Create a vector of category strings. + std::vector<std::string> category_strings; + for (const auto& category : categories) + category_strings.push_back(CategoryToString(category.category)); + + // Create a vector of vectors for each expert's scores. + std::vector<std::vector<double>> expert_scores; + for (auto& ranker : rankers_) { + expert_scores.push_back( + ranker->GetCategoryRanks(results, categories, provider)); + } + + // Get the final scores from the FTRL optimizer set them on the categories. + std::vector<double> category_scores = + ftrl_->Score(std::move(category_strings), std::move(expert_scores)); + DCHECK_EQ(categories.size(), category_scores.size()); + for (size_t i = 0; i < categories.size(); ++i) + categories[i].score = category_scores[i]; +} + +// MrfuResultRanker ----------------------------------------------------------- + +MrfuResultRanker::MrfuResultRanker(MrfuCache::Params params, + MrfuCache::Proto proto) + : mrfu_(std::make_unique<MrfuCache>(std::move(proto), params)) {} + +MrfuResultRanker::~MrfuResultRanker() = default; + +std::vector<double> MrfuResultRanker::GetResultRanks(const ResultsMap& results, + ProviderType provider) { + const auto it = results.find(provider); + if (it == results.end()) + return {}; + + std::vector<double> scores; + for (const auto& result : it->second) + scores.push_back(mrfu_->Get(result->id())); + return scores; +} + +void MrfuResultRanker::Train(const LaunchData& launch) { + if (launch.launched_from != + ash::AppListLaunchedFrom::kLaunchedFromSearchBox) { + return; + } + mrfu_->Use(launch.id); +} + +// NormalizedScoreResultRanker ------------------------------------------------- + +// Exposes the normalized scores from each result's scoring struct, set by the +// ScoreNormalizingRanker. +std::vector<double> NormalizedScoreResultRanker::GetResultRanks( + const ResultsMap& results, + ProviderType provider) { + const auto it = results.find(provider); + if (it == results.end()) + return {}; + + std::vector<double> scores; + for (const auto& result : it->second) + scores.push_back(result->scoring().normalized_relevance); + return scores; +} + +// BestResultCategoryRanker ---------------------------------------------------- + +BestResultCategoryRanker::BestResultCategoryRanker() = default; +BestResultCategoryRanker::~BestResultCategoryRanker() = default; + +void BestResultCategoryRanker::Start(const std::u16string& query, + ResultsMap& results, + CategoriesList& categories) { + current_category_scores_.clear(); + for (const auto& category : categories) + current_category_scores_[category.category] = 0.0; +} + +std::vector<double> BestResultCategoryRanker::GetCategoryRanks( + const ResultsMap& results, + const CategoriesList& categories, + ProviderType provider) { + const auto it = results.find(provider); + DCHECK(it != results.end()); + + for (const auto& result : it->second) { + // Ignore best match, answer card results, and filtered results for the + // purposes of deciding category scores, because they are not displayed in + // their category. + if (result->best_match() || result->scoring().filter || + result->display_type() == + ChromeSearchResult::DisplayType::kAnswerCard) { + continue; + } + current_category_scores_[result->category()] = + std::max(result->scoring().normalized_relevance, + current_category_scores_[result->category()]); + } + + // Collect those scores into a vector with the same ordering as |categories|. + // For categories with no results in them, defaults to 0.0. + std::vector<double> result; + for (const auto& category : categories) + result.push_back(current_category_scores_[category.category]); + return result; +} + +// MrfuCategoryRanker ---------------------------------------------------------- + +MrfuCategoryRanker::MrfuCategoryRanker(MrfuCache::Params params, + PersistentProto<MrfuCacheProto> proto) + : mrfu_(std::make_unique<MrfuCache>(std::move(proto), params)) {} + +MrfuCategoryRanker::~MrfuCategoryRanker() = default; + +void MrfuCategoryRanker::Start(const std::u16string& query, + ResultsMap& results, + CategoriesList& categories) { + // Because usage-based category scores don't change when new results arrive, + // calculate the scores in Start and reuse them for each GetCategoryRanks + // call. + + // Build a map of the MRFU category scores, with 0.0 for unseen categories. + base::flat_map<Category, double> scores_map; + for (const auto& id_score : mrfu_->GetAllNormalized()) + scores_map[StringToCategory(id_score.first)] = id_score.second; + + current_category_scores_.clear(); + for (const auto& category : categories) { + const auto it = scores_map.find(category.category); + current_category_scores_.push_back(it != scores_map.end() ? it->second + : 0.0); + } + DCHECK_EQ(current_category_scores_.size(), categories.size()); +} + +std::vector<double> MrfuCategoryRanker::GetCategoryRanks( + const ResultsMap& results, + const CategoriesList& categories, + ProviderType provider) { + return current_category_scores_; +} + +void MrfuCategoryRanker::Train(const LaunchData& launch) { + if (launch.launched_from != + ash::AppListLaunchedFrom::kLaunchedFromSearchBox) { + return; + } + mrfu_->Use(CategoryToString(ResultTypeToCategory(launch.result_type))); +} + +} // namespace app_list
diff --git a/chrome/browser/ui/app_list/search/ranking/ftrl_ranker.h b/chrome/browser/ui/app_list/search/ranking/ftrl_ranker.h new file mode 100644 index 0000000..785f014 --- /dev/null +++ b/chrome/browser/ui/app_list/search/ranking/ftrl_ranker.h
@@ -0,0 +1,123 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_APP_LIST_SEARCH_RANKING_FTRL_RANKER_H_ +#define CHROME_BROWSER_UI_APP_LIST_SEARCH_RANKING_FTRL_RANKER_H_ + +#include "chrome/browser/ui/app_list/search/ranking/ranker.h" +#include "chrome/browser/ui/app_list/search/ranking/types.h" +#include "chrome/browser/ui/app_list/search/util/ftrl_optimizer.h" +#include "chrome/browser/ui/app_list/search/util/mrfu_cache.h" + +namespace app_list { + +// A ranker for search results using a Follow the Regularized Leader algorithm. +// This learns weightings for the 'experts' below. +class FtrlRanker : public Ranker { + public: + enum class RankingKind { + kResults, + kCategories, + }; + + FtrlRanker(RankingKind kind, + FtrlOptimizer::Params params, + FtrlOptimizer::Proto proto); + ~FtrlRanker() override; + + FtrlRanker(const FtrlRanker&) = delete; + FtrlRanker& operator=(const FtrlRanker&) = delete; + + void AddExpert(std::unique_ptr<Ranker> ranker); + + // Ranker: + void Start(const std::u16string& query, + ResultsMap& results, + CategoriesList& categories) override; + void Train(const LaunchData& launch) override; + void UpdateResultRanks(ResultsMap& results, ProviderType provider) override; + void UpdateCategoryRanks(const ResultsMap& results, + CategoriesList& categories, + ProviderType provider) override; + + private: + RankingKind kind_; + + // The Follow the Regularized Leader instance that chooses amongst the expert + // |rankers_|. + std::unique_ptr<FtrlOptimizer> ftrl_; + + // The 'experts' in the follow-the-regularized-leader model. + std::vector<std::unique_ptr<Ranker>> rankers_; +}; + +// An expert that keeps track of usage of individual results using a +// most-recently-frequently-used cache of launch history. +class MrfuResultRanker : public Ranker { + public: + explicit MrfuResultRanker(MrfuCache::Params params, MrfuCache::Proto proto); + + ~MrfuResultRanker() override; + + // Ranker: + std::vector<double> GetResultRanks(const ResultsMap& results, + ProviderType provider) override; + void Train(const LaunchData& launch) override; + + private: + std::unique_ptr<MrfuCache> mrfu_; +}; + +// An expert that exposes the normalized scores from each result's scoring +// struct, set by the ScoreNormalizingRanker. +class NormalizedScoreResultRanker : public Ranker { + public: + // Ranker: + std::vector<double> GetResultRanks(const ResultsMap& results, + ProviderType provider) override; +}; + +// Ranks a category based on the normalized relevance of its best result. +class BestResultCategoryRanker : public Ranker { + public: + BestResultCategoryRanker(); + ~BestResultCategoryRanker() override; + + // Ranker: + void Start(const std::u16string& query, + ResultsMap& results, + CategoriesList& categories) override; + std::vector<double> GetCategoryRanks(const ResultsMap& results, + const CategoriesList& categories, + ProviderType provider) override; + + private: + base::flat_map<Category, double> current_category_scores_; +}; + +// An expert that keeps track of category usage with a +// most-recently-frequently-used cache of launch history. +class MrfuCategoryRanker : public Ranker { + public: + MrfuCategoryRanker(MrfuCache::Params params, + PersistentProto<MrfuCacheProto> proto); + ~MrfuCategoryRanker() override; + + // Ranker: + void Start(const std::u16string& query, + ResultsMap& results, + CategoriesList& categories) override; + std::vector<double> GetCategoryRanks(const ResultsMap& results, + const CategoriesList& categories, + ProviderType provider) override; + void Train(const LaunchData& launch) override; + + private: + std::unique_ptr<MrfuCache> mrfu_; + std::vector<double> current_category_scores_; +}; + +} // namespace app_list + +#endif // CHROME_BROWSER_UI_APP_LIST_SEARCH_RANKING_FTRL_RANKER_H_
diff --git a/chrome/browser/ui/app_list/search/ranking/ftrl_ranker_unittest.cc b/chrome/browser/ui/app_list/search/ranking/ftrl_ranker_unittest.cc new file mode 100644 index 0000000..2acec82 --- /dev/null +++ b/chrome/browser/ui/app_list/search/ranking/ftrl_ranker_unittest.cc
@@ -0,0 +1,365 @@ +// 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/app_list/search/ranking/ftrl_ranker.h" + +#include "base/files/scoped_temp_dir.h" +#include "base/logging.h" +#include "base/test/task_environment.h" +#include "chrome/browser/ui/app_list/search/chrome_search_result.h" +#include "chrome/browser/ui/app_list/search/ranking/ranker.h" +#include "chrome/browser/ui/app_list/search/ranking/types.h" +#include "chrome/browser/ui/app_list/search/search_controller.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace app_list { +namespace { + +using testing::ElementsAre; + +class TestResult : public ChromeSearchResult { + public: + explicit TestResult(const std::string& id, + double score, + ResultType result_type = ResultType::kUnknown, + Category category = Category::kUnknown) { + set_id(id); + SetDisplayScore(score); + scoring().normalized_relevance = score; + SetResultType(result_type); + SetCategory(category); + } + ~TestResult() override {} + + // ChromeSearchResult overrides: + void Open(int event_flags) override {} +}; + +class TestRanker : public Ranker { + public: + TestRanker() = default; + ~TestRanker() override = default; + + void SetNextScores(const std::vector<double>& scores) { + next_scores_ = scores; + } + + // Ranker: + std::vector<double> GetResultRanks(const ResultsMap& results, + ProviderType provider) override { + return next_scores_; + } + + std::vector<double> GetCategoryRanks(const ResultsMap& results, + const CategoriesList& categories, + ProviderType provider) override { + return next_scores_; + } + + private: + std::vector<double> next_scores_; +}; + +// A helper function for creating results. For convenience, the provided scores +// are set as both the display score and normalized relevance. +Results MakeScoredResults(const std::vector<std::string>& ids, + const std::vector<double> scores, + ResultType result_type = ResultType::kUnknown, + Category category = Category::kUnknown) { + Results res; + CHECK_EQ(ids.size(), scores.size()); + for (size_t i = 0; i < ids.size(); ++i) { + res.push_back( + std::make_unique<TestResult>(ids[i], scores[i], result_type, category)); + } + return res; +} + +// A helper function for creating results, for when results don't need scores. +Results MakeResults(const std::vector<std::string>& ids, + ResultType result_type = ResultType::kUnknown, + Category category = Category::kUnknown) { + return MakeScoredResults(ids, std::vector<double>(ids.size()), result_type, + category); +} + +LaunchData MakeLaunchData(const std::string& id, + ResultType result_type = ResultType::kUnknown) { + LaunchData launch; + launch.launched_from = ash::AppListLaunchedFrom::kLaunchedFromSearchBox; + launch.id = id; + launch.result_type = result_type; + return launch; +} + +} // namespace + +class RankerTestBase : public testing::Test { + public: + void SetUp() override { ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); } + + base::FilePath GetPath() { return temp_dir_.GetPath().Append("proto"); } + + template <typename T> + T ReadProtoFromDisk() { + std::string proto_str; + CHECK(base::ReadFileToString(GetPath(), &proto_str)); + T proto; + CHECK(proto.ParseFromString(proto_str)); + return proto; + } + + void Wait() { task_environment_.RunUntilIdle(); } + + protected: + base::test::TaskEnvironment task_environment_{ + base::test::TaskEnvironment::MainThreadType::UI, + base::test::TaskEnvironment::ThreadPoolExecutionMode::QUEUED, + base::test::TaskEnvironment::TimeSource::MOCK_TIME}; + base::ScopedTempDir temp_dir_; +}; + +// FtrlRankerTest -------------------------------------------------------------- + +class FtrlRankerTest : public RankerTestBase { + public: + FtrlOptimizer::Params TestingParams(size_t num_experts) { + FtrlOptimizer::Params params; + params.alpha = 1.0; + params.gamma = 0.1; + params.num_experts = num_experts; + return params; + } +}; + +TEST_F(FtrlRankerTest, TrainAndRankResults) { + // Set up an FTRL result ranker with two experts that statically return scores + // for four items. + auto good_ranker = std::make_unique<TestRanker>(); + auto bad_ranker = std::make_unique<TestRanker>(); + good_ranker->SetNextScores({4.0, 3.0, 2.0, 1.0}); + bad_ranker->SetNextScores({1.0, 2.0, 3.0, 4.0}); + + FtrlRanker ranker(FtrlRanker::RankingKind::kResults, TestingParams(2), + FtrlOptimizer::Proto(GetPath(), base::Seconds(0))); + ranker.AddExpert(std::move(good_ranker)); + ranker.AddExpert(std::move(bad_ranker)); + Wait(); + + // Make four results and mimic several rank/train cycles where we always + // launch "a", so the good/bad rankers always performs well/poorly. + ResultsMap results; + results[ResultType::kInstalledApp] = MakeResults({"a", "b", "c", "d"}); + + for (int i = 0; i < 10; ++i) { + ranker.UpdateResultRanks(results, ResultType::kInstalledApp); + ranker.Train(MakeLaunchData("a")); + } + + // The weights of the FTRL optimizer should reflect that the good ranker is + // better than the bad ranker. + Wait(); + auto proto = ReadProtoFromDisk<FtrlOptimizerProto>(); + ASSERT_EQ(proto.weights_size(), 2u); + EXPECT_GE(proto.weights()[0], 0.9); + EXPECT_LE(proto.weights()[1], 0.1); + + // Now reverse the situation: change the clicked result so the bad ranker is + // now performing well. + for (int i = 0; i < 10; ++i) { + ranker.UpdateResultRanks(results, ResultType::kInstalledApp); + ranker.Train(MakeLaunchData("d")); + } + + // The weights of the 'bad' expert should have recovered. + Wait(); + proto = ReadProtoFromDisk<FtrlOptimizerProto>(); + ASSERT_EQ(proto.weights_size(), 2u); + EXPECT_LE(proto.weights()[0], 0.1); + EXPECT_GE(proto.weights()[1], 0.9); +} + +TEST_F(FtrlRankerTest, TrainAndRankCategories) { + auto good_ranker = std::make_unique<TestRanker>(); + auto bad_ranker = std::make_unique<TestRanker>(); + good_ranker->SetNextScores({4.0, 3.0, 2.0, 1.0}); + bad_ranker->SetNextScores({1.0, 2.0, 3.0, 4.0}); + + FtrlRanker ranker(FtrlRanker::RankingKind::kCategories, TestingParams(2), + FtrlOptimizer::Proto(GetPath(), base::Seconds(0))); + ranker.AddExpert(std::move(good_ranker)); + ranker.AddExpert(std::move(bad_ranker)); + Wait(); + + // Make results in three categories (assistant has no results) and mimic + // several rank/train cycles where we always launch "a", so the good/bad + // rankers always performs well/poorly. + ResultsMap results; + results[ResultType::kInstalledApp] = + MakeResults({"a"}, ResultType::kInstalledApp, Category::kApps); + results[ResultType::kOsSettings] = + MakeResults({"b"}, ResultType::kOsSettings, Category::kSettings); + results[ResultType::kFileSearch] = + MakeResults({"c"}, ResultType::kFileSearch, Category::kFiles); + CategoriesList categories({{.category = Category::kApps}, + {.category = Category::kSettings}, + {.category = Category::kSearchAndAssistant}, + {.category = Category::kFiles}}); + + for (int i = 0; i < 10; ++i) { + ranker.UpdateCategoryRanks(results, categories, ResultType::kInstalledApp); + ranker.Train(MakeLaunchData("a", ResultType::kInstalledApp)); + } + + // The weights of the FTRL optimizer should reflect that the good ranker is + // better than the bad ranker. + Wait(); + auto proto = ReadProtoFromDisk<FtrlOptimizerProto>(); + ASSERT_EQ(proto.weights_size(), 2u); + EXPECT_GE(proto.weights()[0], 0.9); + EXPECT_LE(proto.weights()[1], 0.1); + + // Now reverse the situation: change the clicked result so the bad ranker is + // now performing well. Train for longer because neither ranker does a + // particularly good job at predicting "c"'s category. + for (int i = 0; i < 10; ++i) { + ranker.UpdateResultRanks(results, ResultType::kInstalledApp); + ranker.Train(MakeLaunchData("c", ResultType::kFileSearch)); + } + + // The weights of the 'bad' expert should have recovered. + Wait(); + proto = ReadProtoFromDisk<FtrlOptimizerProto>(); + ASSERT_EQ(proto.weights_size(), 2u); + EXPECT_LE(proto.weights()[0], 0.1); + EXPECT_GE(proto.weights()[1], 0.9); +} + +// MrfuResultRanker ------------------------------------------------------------ + +class MrfuResultRankerTest : public RankerTestBase {}; + +TEST_F(MrfuResultRankerTest, TrainAndRank) { + MrfuResultRanker ranker(MrfuCache::Params(), + MrfuCache::Proto(GetPath(), base::Seconds(0))); + Wait(); + + // Train on some results. + ranker.Train(MakeLaunchData("a")); + ranker.Train(MakeLaunchData("b")); + ranker.Train(MakeLaunchData("c")); + ranker.Train(MakeLaunchData("a")); + + ResultsMap results; + results[ResultType::kInstalledApp] = MakeResults({"a", "b"}); + results[ResultType::kOsSettings] = MakeResults({"c", "d"}); + CategoriesList categories; + + // Rank them, expecting ordering a > c > b > d. + ranker.Start(u"query", results, categories); + auto ab_scores = ranker.GetResultRanks(results, ResultType::kInstalledApp); + auto cd_scores = ranker.GetResultRanks(results, ResultType::kOsSettings); + EXPECT_GT(ab_scores[0], cd_scores[0]); + EXPECT_GT(cd_scores[0], ab_scores[1]); + EXPECT_GT(ab_scores[1], cd_scores[1]); +} + +// NormalizedScoreResultRanker ------------------------------------------------- + +class NormalizedScoreResultRankerTest : public RankerTestBase {}; + +TEST_F(NormalizedScoreResultRankerTest, Rank) { + NormalizedScoreResultRanker ranker; + + auto results = MakeResults({"a", "b", "c"}); + ASSERT_EQ(results.size(), 3u); + results[0]->scoring().normalized_relevance = 0.2; + results[1]->scoring().normalized_relevance = 0.5; + results[2]->scoring().normalized_relevance = 0.1; + + ResultsMap results_map; + results_map[ResultType::kInstalledApp] = std::move(results); + + auto scores = ranker.GetResultRanks(results_map, ResultType::kInstalledApp); + EXPECT_EQ(scores[0], 0.2); + EXPECT_EQ(scores[1], 0.5); + EXPECT_EQ(scores[2], 0.1); +} + +// BestResultCategoryRanker ---------------------------------------------------- + +class BestResultCategoryRankerTest : public RankerTestBase {}; + +TEST_F(BestResultCategoryRankerTest, Rank) { + BestResultCategoryRanker ranker; + + ResultsMap results; + results[ResultType::kInstalledApp] = MakeScoredResults( + {"a", "b"}, {0.1, 0.5}, ResultType::kInstalledApp, Category::kApps); + results[ResultType::kOsSettings] = MakeScoredResults( + {"c", "d"}, {0.3, 0.3}, ResultType::kOsSettings, Category::kSettings); + results[ResultType::kFileSearch] = MakeScoredResults( + {"e", "f"}, {0.3, 0.8}, ResultType::kFileSearch, Category::kFiles); + CategoriesList categories({{.category = Category::kApps}, + {.category = Category::kSettings}, + {.category = Category::kFiles}}); + + ranker.Start(u"query", results, categories); + + // Only the app category should be scored, because that's the only one to have + // returned. + auto scores = + ranker.GetCategoryRanks(results, categories, ResultType::kInstalledApp); + ASSERT_EQ(scores.size(), 3u); + EXPECT_EQ(scores[0], 0.5); + EXPECT_EQ(scores[1], 0.0); + EXPECT_EQ(scores[2], 0.0); + + // Now all categories should be scored. + ranker.GetCategoryRanks(results, categories, ResultType::kOsSettings); + scores = + ranker.GetCategoryRanks(results, categories, ResultType::kFileSearch); + ASSERT_EQ(scores.size(), 3u); + EXPECT_EQ(scores[0], 0.5); + EXPECT_EQ(scores[1], 0.3); + EXPECT_EQ(scores[2], 0.8); +} + +// MrfuCategoryRanker ---------------------------------------------------------- + +class MrfuCategoryRankerTest : public RankerTestBase {}; + +TEST_F(MrfuCategoryRankerTest, TrainAndRank) { + MrfuCategoryRanker ranker(MrfuCache::Params(), + MrfuCache::Proto(GetPath(), base::Seconds(0))); + Wait(); + + // Train so that settings should be first, followed by apps. + ranker.Train(MakeLaunchData("a", ResultType::kInstalledApp)); + ranker.Train(MakeLaunchData("c", ResultType::kOsSettings)); + ranker.Train(MakeLaunchData("d", ResultType::kOsSettings)); + ranker.Train(MakeLaunchData("b", ResultType::kInstalledApp)); + + ResultsMap results; + results[ResultType::kInstalledApp] = + MakeResults({"a", "b"}, ResultType::kInstalledApp, Category::kApps); + results[ResultType::kOsSettings] = + MakeResults({"c", "d"}, ResultType::kOsSettings, Category::kSettings); + results[ResultType::kFileSearch] = + MakeResults({"e", "f"}, ResultType::kFileSearch, Category::kFiles); + CategoriesList categories({{.category = Category::kApps}, + {.category = Category::kSettings}, + {.category = Category::kFiles}}); + + // Expect a ranking of kInstalledApp > kOsSettings > kFileSearch. + ranker.Start(u"query", results, categories); + auto scores = + ranker.GetCategoryRanks(results, categories, ResultType::kInstalledApp); + ASSERT_EQ(scores.size(), 3u); + EXPECT_GT(scores[0], scores[1]); + EXPECT_GT(scores[1], scores[2]); +} + +} // namespace app_list
diff --git a/chrome/browser/ui/app_list/search/ranking/ftrl_result_ranker.cc b/chrome/browser/ui/app_list/search/ranking/ftrl_result_ranker.cc deleted file mode 100644 index d0fbf2e..0000000 --- a/chrome/browser/ui/app_list/search/ranking/ftrl_result_ranker.cc +++ /dev/null
@@ -1,31 +0,0 @@ -// Copyright 2021 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/ui/app_list/search/ranking/ftrl_result_ranker.h" - -#include "chrome/browser/ui/app_list/search/chrome_search_result.h" - -namespace app_list { - -FtrlResultRanker::FtrlResultRanker() = default; -FtrlResultRanker::~FtrlResultRanker() = default; - -void FtrlResultRanker::Start(const std::u16string& query, - ResultsMap& results, - CategoriesList& categories) {} - -void FtrlResultRanker::UpdateResultRanks(ResultsMap& results, - ProviderType provider) { - // TODO(crbug.com/1199206): WIP. -} - -void FtrlResultRanker::UpdateCategoryRanks(const ResultsMap& results, - CategoriesList& categories, - ProviderType provider) { - // TODO(crbug.com/1199206): WIP. -} - -void FtrlResultRanker::Train(const LaunchData& launch) {} - -} // namespace app_list
diff --git a/chrome/browser/ui/app_list/search/ranking/ftrl_result_ranker.h b/chrome/browser/ui/app_list/search/ranking/ftrl_result_ranker.h deleted file mode 100644 index 93fcc0a0..0000000 --- a/chrome/browser/ui/app_list/search/ranking/ftrl_result_ranker.h +++ /dev/null
@@ -1,37 +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. - -#ifndef CHROME_BROWSER_UI_APP_LIST_SEARCH_RANKING_FTRL_RESULT_RANKER_H_ -#define CHROME_BROWSER_UI_APP_LIST_SEARCH_RANKING_FTRL_RESULT_RANKER_H_ - -#include "chrome/browser/ui/app_list/search/ranking/ranker.h" -#include "chrome/browser/ui/app_list/search/ranking/types.h" - -namespace app_list { - -// A ranker for search results using a Follow the Regularized Leader algorithm. -// -// TODO(crbug.com/1199206): WIP. -class FtrlResultRanker : public Ranker { - public: - FtrlResultRanker(); - ~FtrlResultRanker() override; - - FtrlResultRanker(const FtrlResultRanker&) = delete; - FtrlResultRanker& operator=(const FtrlResultRanker&) = delete; - - // Ranker: - void Start(const std::u16string& query, - ResultsMap& results, - CategoriesList& categories) override; - void UpdateResultRanks(ResultsMap& results, ProviderType provider) override; - void UpdateCategoryRanks(const ResultsMap& results, - CategoriesList& categories, - ProviderType provider) override; - void Train(const LaunchData& launch) override; -}; - -} // namespace app_list - -#endif // CHROME_BROWSER_UI_APP_LIST_SEARCH_RANKING_FTRL_RESULT_RANKER_H_
diff --git a/chrome/browser/ui/app_list/search/ranking/ranker.h b/chrome/browser/ui/app_list/search/ranking/ranker.h index 63fa0224..496134e 100644 --- a/chrome/browser/ui/app_list/search/ranking/ranker.h +++ b/chrome/browser/ui/app_list/search/ranking/ranker.h
@@ -13,7 +13,7 @@ namespace app_list { -// Interface for all kinds of rankers. These are ultimately owned and called by +// Interface for all kinds of rankers. Primarily owned and called by // SearchController. class Ranker { public:
diff --git a/chrome/browser/ui/app_list/search/ranking/ranker_delegate.cc b/chrome/browser/ui/app_list/search/ranking/ranker_delegate.cc index ea18fe9f..31e6863 100644 --- a/chrome/browser/ui/app_list/search/ranking/ranker_delegate.cc +++ b/chrome/browser/ui/app_list/search/ranking/ranker_delegate.cc
@@ -6,8 +6,7 @@ #include "chrome/browser/ui/app_list/search/ranking/answer_ranker.h" #include "chrome/browser/ui/app_list/search/ranking/filtering_ranker.h" -#include "chrome/browser/ui/app_list/search/ranking/ftrl_category_ranker.h" -#include "chrome/browser/ui/app_list/search/ranking/ftrl_result_ranker.h" +#include "chrome/browser/ui/app_list/search/ranking/ftrl_ranker.h" #include "chrome/browser/ui/app_list/search/ranking/query_highlighter.h" #include "chrome/browser/ui/app_list/search/ranking/removed_results.pb.h" #include "chrome/browser/ui/app_list/search/ranking/removed_results_ranker.h" @@ -30,23 +29,73 @@ } // namespace RankerDelegate::RankerDelegate(Profile* profile, SearchController* controller) { + // Result ranking parameters. + // TODO(crbug.com/1199206): These need tweaking. + FtrlOptimizer::Params ftrl_result_params; + ftrl_result_params.alpha = 0.1; + ftrl_result_params.gamma = 0.1; + ftrl_result_params.num_experts = 2u; + + MrfuCache::Params mrfu_result_params; + mrfu_result_params.half_life = 10.0f; + mrfu_result_params.boost_factor = 5.0f; + mrfu_result_params.max_items = 200u; + + // Category ranking parameters. + // TODO(crbug.com/1199206): These need tweaking. + FtrlOptimizer::Params ftrl_category_params; + ftrl_category_params.alpha = 0.1; + ftrl_category_params.gamma = 0.1; + ftrl_category_params.num_experts = 2u; + + MrfuCache::Params mrfu_category_params; + mrfu_category_params.half_life = 10.0f; + mrfu_category_params.boost_factor = 5.0f; + mrfu_category_params.max_items = 200u; + const auto state_dir = RankerStateDirectory(profile); - // Main result and category ranking. + // 1. Result pre-processing. These filter or modify search results but don't + // change their scores. + AddRanker(std::make_unique<QueryHighlighter>()); + AddRanker(std::make_unique<AnswerRanker>()); + AddRanker(std::make_unique<FilteringRanker>()); + AddRanker(std::make_unique<RemovedResultsRanker>( + PersistentProto<RemovedResultsProto>( + state_dir.AppendASCII("removed_results.pb"), kNoWriteDelay))); + + // 2. Score normalization, a precursor to other ranking. AddRanker(std::make_unique<ScoreNormalizingRanker>( PersistentProto<ScoreNormalizerProto>( state_dir.AppendASCII("score_norm.pb"), kStandardWriteDelay))); - // Result post-processing. - AddRanker(std::make_unique<QueryHighlighter>()); - AddRanker(std::make_unique<TopMatchRanker>()); - AddRanker(std::make_unique<AnswerRanker>()); - AddRanker(std::make_unique<FilteringRanker>()); + // 3. Ranking for results. + auto result_ranker = std::make_unique<FtrlRanker>( + FtrlRanker::RankingKind::kResults, ftrl_result_params, + PersistentProto<FtrlOptimizerProto>( + state_dir.AppendASCII("ftrl_results.pb"), kStandardWriteDelay)); + result_ranker->AddExpert(std::make_unique<MrfuResultRanker>( + mrfu_result_params, + PersistentProto<MrfuCacheProto>(state_dir.AppendASCII("mrfu_results.pb"), + kStandardWriteDelay))); + result_ranker->AddExpert(std::make_unique<NormalizedScoreResultRanker>()); + AddRanker(std::move(result_ranker)); - // Result removal. - AddRanker(std::make_unique<RemovedResultsRanker>( - PersistentProto<RemovedResultsProto>( - state_dir.AppendASCII("removed_results.pb"), kNoWriteDelay))); + // 4. Ranking for categories. + auto category_ranker = std::make_unique<FtrlRanker>( + FtrlRanker::RankingKind::kCategories, ftrl_category_params, + PersistentProto<FtrlOptimizerProto>( + state_dir.AppendASCII("ftrl_categories.pb"), kStandardWriteDelay)); + category_ranker->AddExpert(std::make_unique<MrfuCategoryRanker>( + mrfu_category_params, + PersistentProto<MrfuCacheProto>( + state_dir.AppendASCII("mrfu_categories.pb"), kStandardWriteDelay))); + category_ranker->AddExpert(std::make_unique<BestResultCategoryRanker>()); + AddRanker(std::move(category_ranker)); + + // 5. Result post-processing. + // Nb. the top-match ranker relies on score normalization. + AddRanker(std::make_unique<TopMatchRanker>()); } RankerDelegate::~RankerDelegate() {}
diff --git a/chrome/browser/ui/app_list/search/ranking/ranker_delegate.h b/chrome/browser/ui/app_list/search/ranking/ranker_delegate.h index d9851a5..9e3dffd0 100644 --- a/chrome/browser/ui/app_list/search/ranking/ranker_delegate.h +++ b/chrome/browser/ui/app_list/search/ranking/ranker_delegate.h
@@ -20,6 +20,10 @@ // // This is the place to configure experiments or flags that change ranking // behavior. +// +// TODO(crbug.com/1199206): This is now much more than a delegate, because it +// does all the work of setting up the rankers. Rename to something more +// appropriate. class RankerDelegate : public Ranker { public: RankerDelegate(Profile* profile, SearchController* controller);
diff --git a/chrome/browser/ui/app_list/search/ranking/types.h b/chrome/browser/ui/app_list/search/ranking/types.h index f1ec6e1..dd96da6 100644 --- a/chrome/browser/ui/app_list/search/ranking/types.h +++ b/chrome/browser/ui/app_list/search/ranking/types.h
@@ -23,14 +23,14 @@ // incrementally updated by rankers as needed. Generally, each ranker should // control one score. // -// TODO(crbug.com/1199206): Category scores need to be removed from this and -// added to a separate struct. +// TODO(crbug.com/1199206): Remove defunct members from this struct. struct Scoring { bool filter = false; bool top_match = false; double normalized_relevance = 0.0f; double category_item_score = 0.0f; double category_usage_score = 0.0f; + double ftrl_result_score = 0.0; double usage_score = 0.0f; // A counter for the burn-in iteration number, where 0 signifies the
diff --git a/chrome/browser/ui/app_list/search/search_controller_impl_new.cc b/chrome/browser/ui/app_list/search/search_controller_impl_new.cc index 3b59f43..acdde65 100644 --- a/chrome/browser/ui/app_list/search/search_controller_impl_new.cc +++ b/chrome/browser/ui/app_list/search/search_controller_impl_new.cc
@@ -37,6 +37,24 @@ #include "content/public/browser/browser_thread.h" namespace app_list { +namespace { + +// TODO(crbug.com/1288636): This is brittle as it relies on knowing exactly +// which providers are sending zero-state results. We should replace it with an +// approach where providers indicate whether a result type is for query search +// or zero-state. +void ClearAllResultsExceptContinue(ResultsMap& results) { + for (auto it = results.begin(); it != results.end();) { + if (it->first != ResultType::kZeroStateFile && + it->first != ResultType::kZeroStateDrive) { + it = results.erase(it); + } else { + ++it; + } + } +} + +} // namespace SearchControllerImplNew::SearchControllerImplNew( AppListModelUpdater* model_updater, @@ -69,28 +87,34 @@ // else. ash::RecordLauncherIssuedSearchQueryLength(query.length()); - // Clear all results. - // - If the search is transitioning out of zero-state, clear the model updater - // so that old results are never shown. - // - Otherwise, do not publish this clear so that the results for the last - // query remain on-screen until the results are ready. - results_.clear(); - categories_ = CreateAllCategories(); + // Clear all search results but preserve zero-state results. On a call to + // StartSearch, we were previously either in zero-state, or another query + // search. Handle these two cases differently: + // + // a) were in zero-state: publish these changes, so that results from a + // previous search aren't shown. + // + // b) were in search query: do not publish these changes, so that the + // old results stay on screen until the new ones are ready. + ClearAllResultsExceptContinue(results_); if (last_query_.empty()) - model_updater_->ClearSearchResults(); + Publish(); for (Observer& observer : observer_list_) observer.OnResultsCleared(); + categories_ = CreateAllCategories(); + ranker_->Start(query, results_, categories_); + burnin_iteration_counter_ = 0; ids_to_burnin_iteration_.clear(); - session_start_ = base::Time::Now(); last_query_ = query; - ranker_->Start(query, results_, categories_); - - // Search all providers. The query can be empty if the user has entered and - // then deleted a query. + // Search all providers. + // + // TODO(crbug.com/1288712): The query can be empty if the user has entered and + // then deleted a query. We should consider whether this should trigger a + // StartSearch call or not. for (const auto& provider : providers_) { if (query.empty()) { provider->StartZeroState();
diff --git a/chrome/browser/ui/app_list/search/search_result_ranker/ranking_item_util_unittest.cc b/chrome/browser/ui/app_list/search/search_result_ranker/ranking_item_util_unittest.cc index eb60067..6f36149 100644 --- a/chrome/browser/ui/app_list/search/search_result_ranker/ranking_item_util_unittest.cc +++ b/chrome/browser/ui/app_list/search/search_result_ranker/ranking_item_util_unittest.cc
@@ -37,12 +37,6 @@ std::make_unique<::test::TestAppListControllerDelegate>(); } - void SetAdaptiveRankerParams( - const std::map<std::string, std::string>& params) { - scoped_feature_list_.InitAndEnableFeatureWithParameters( - app_list_features::kEnableQueryBasedMixedTypesRanker, params); - } - std::unique_ptr<OmniboxResult> MakeOmniboxResult( AutocompleteMatchType::Type type) { AutocompleteMatch match;
diff --git a/chrome/browser/ui/app_list/search/util/ftrl_optimizer_unittest.cc b/chrome/browser/ui/app_list/search/util/ftrl_optimizer_unittest.cc index 2a22784..7d01277 100644 --- a/chrome/browser/ui/app_list/search/util/ftrl_optimizer_unittest.cc +++ b/chrome/browser/ui/app_list/search/util/ftrl_optimizer_unittest.cc
@@ -123,4 +123,39 @@ EXPECT_THAT(proto.weights()[1], DoubleNear(two_score / total, kEps)); } +// Test that a 'good' expert will outweigh a 'bad' expert after several training +// iterations, but that the 'bad' expert can recover if it starts predicting +// accurately. +TEST_F(FtrlOptimizerTest, TrainSeveralTimes) { + WriteWeightsToDisk({0.5, 0.5}); + FtrlOptimizer ftrl(GetProto(), TestingParams(/*num_experts=*/2u)); + Wait(); + + // Do several iterations of training where the first expert is correct. + for (int i = 0; i < 10; ++i) { + ftrl.Score({"a", "b", "c", "d"}, + {{1.0, 2.0, 3.0, 4.0}, {4.0, 3.0, 2.0, 1.0}}); + ftrl.Train("d"); + } + Wait(); + + // The first expert should outweigh the second. + auto proto = ReadFromDisk(); + EXPECT_GT(proto.weights()[0], 0.9); + EXPECT_LT(proto.weights()[1], 0.1); + + // Do several iterations of training where the second expert is correct. + for (int i = 0; i < 10; ++i) { + ftrl.Score({"a", "b", "c", "d"}, + {{1.0, 2.0, 3.0, 4.0}, {4.0, 3.0, 2.0, 1.0}}); + ftrl.Train("a"); + } + Wait(); + + // The second expert should have recovered and outweigh the first. + proto = ReadFromDisk(); + EXPECT_LT(proto.weights()[0], 0.1); + EXPECT_GT(proto.weights()[1], 0.9); +} + } // namespace app_list
diff --git a/chrome/browser/ui/ash/shelf/app_service/app_service_shelf_context_menu.cc b/chrome/browser/ui/ash/shelf/app_service/app_service_shelf_context_menu.cc index 605f534..852b36a 100644 --- a/chrome/browser/ui/ash/shelf/app_service/app_service_shelf_context_menu.cc +++ b/chrome/browser/ui/ash/shelf/app_service/app_service_shelf_context_menu.cc
@@ -39,7 +39,7 @@ #include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/chrome_pages.h" #include "chrome/browser/ui/views/crostini/crostini_app_restart_dialog.h" -#include "chrome/browser/ui/webui/settings/chromeos/app_management/app_management_uma.h" +#include "chrome/browser/ui/webui/settings/ash/app_management/app_management_uma.h" #include "chrome/grit/generated_resources.h" #include "content/public/browser/context_menu_params.h" #include "extensions/browser/extension_prefs.h" @@ -455,7 +455,7 @@ if (app_type_ == apps::AppType::kArc) { chrome::ShowAppManagementPage( controller()->profile(), item().id.app_id, - AppManagementEntryPoint::kShelfContextMenuAppInfoArc); + ash::settings::AppManagementEntryPoint::kShelfContextMenuAppInfoArc); return; }
diff --git a/chrome/browser/ui/ash/shelf/chrome_shelf_controller.cc b/chrome/browser/ui/ash/shelf/chrome_shelf_controller.cc index cea8fd9..02746de9 100644 --- a/chrome/browser/ui/ash/shelf/chrome_shelf_controller.cc +++ b/chrome/browser/ui/ash/shelf/chrome_shelf_controller.cc
@@ -80,7 +80,7 @@ #include "chrome/browser/ui/chrome_pages.h" #include "chrome/browser/ui/settings_window_manager_chromeos.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" -#include "chrome/browser/ui/webui/settings/chromeos/app_management/app_management_uma.h" +#include "chrome/browser/ui/webui/settings/ash/app_management/app_management_uma.h" #include "chrome/browser/web_applications/web_app_helpers.h" #include "chrome/browser/web_applications/web_app_utils.h" #include "chrome/common/chrome_features.h" @@ -848,11 +848,11 @@ app_type == apps::mojom::AppType::kSystemWeb) { chrome::ShowAppManagementPage( profile, app_id, - AppManagementEntryPoint::kShelfContextMenuAppInfoWebApp); + ash::settings::AppManagementEntryPoint::kShelfContextMenuAppInfoWebApp); } else { - chrome::ShowAppManagementPage( - profile, app_id, - AppManagementEntryPoint::kShelfContextMenuAppInfoChromeApp); + chrome::ShowAppManagementPage(profile, app_id, + ash::settings::AppManagementEntryPoint:: + kShelfContextMenuAppInfoChromeApp); } }
diff --git a/chrome/browser/ui/ash/shelf/chrome_shelf_controller_browsertest.cc b/chrome/browser/ui/ash/shelf/chrome_shelf_controller_browsertest.cc index a49ce77..47ba0d7 100644 --- a/chrome/browser/ui/ash/shelf/chrome_shelf_controller_browsertest.cc +++ b/chrome/browser/ui/ash/shelf/chrome_shelf_controller_browsertest.cc
@@ -2542,7 +2542,7 @@ ASSERT_TRUE(embedded_test_server()->Start()); GURL url(embedded_test_server()->GetURL("/banners/manifest_test_page.html")); web_app::ServiceWorkerRegistrationWaiter registration_waiter(profile(), url); - AddTabAtIndex(1, url, ui::PAGE_TRANSITION_LINK); + ASSERT_TRUE(AddTabAtIndex(1, url, ui::PAGE_TRANSITION_LINK)); registration_waiter.AwaitRegistration(); // Install PWA. chrome::SetAutoAcceptPWAInstallConfirmationForTesting(true); @@ -2565,10 +2565,10 @@ WindowedShortcutAppsHaveActivityIndicatorSet) { // Start server and open test page. ASSERT_TRUE(embedded_test_server()->Start()); - AddTabAtIndex( + ASSERT_TRUE(AddTabAtIndex( 1, GURL(embedded_test_server()->GetURL("/banners/manifest_test_page.html")), - ui::PAGE_TRANSITION_LINK); + ui::PAGE_TRANSITION_LINK)); // Install shortcut app. chrome::SetAutoAcceptWebAppDialogForTesting(true, true); web_app::WebAppTestInstallWithOsHooksObserver install_observer(profile());
diff --git a/chrome/browser/ui/ash/shelf/standalone_browser_extension_app_context_menu.cc b/chrome/browser/ui/ash/shelf/standalone_browser_extension_app_context_menu.cc index c98a7bf..c8e00e86 100644 --- a/chrome/browser/ui/ash/shelf/standalone_browser_extension_app_context_menu.cc +++ b/chrome/browser/ui/ash/shelf/standalone_browser_extension_app_context_menu.cc
@@ -22,7 +22,7 @@ #include "chrome/browser/ui/ash/shelf/chrome_shelf_prefs.h" #include "chrome/browser/ui/ash/shelf/standalone_browser_extension_app_shelf_item_controller.h" #include "chrome/browser/ui/chrome_pages.h" -#include "chrome/browser/ui/webui/settings/chromeos/app_management/app_management_uma.h" +#include "chrome/browser/ui/webui/settings/ash/app_management/app_management_uma.h" #include "chrome/grit/generated_resources.h" #include "net/base/escape.h" #include "ui/base/models/image_model.h" @@ -104,10 +104,11 @@ return; } case ash::SHOW_APP_INFO: { - AppManagementEntryPoint entry = - (source_ == Source::kShelf) - ? AppManagementEntryPoint::kShelfContextMenuAppInfoChromeApp - : AppManagementEntryPoint::kAppListContextMenuAppInfoChromeApp; + ash::settings::AppManagementEntryPoint entry = + (source_ == Source::kShelf) ? ash::settings::AppManagementEntryPoint:: + kShelfContextMenuAppInfoChromeApp + : ash::settings::AppManagementEntryPoint:: + kAppListContextMenuAppInfoChromeApp; // Normally app ids would only contain alphanumerics, but Lacros uses '#' // as a delimiter.
diff --git a/chrome/browser/ui/browser_browsertest.cc b/chrome/browser/ui/browser_browsertest.cc index df471ed..079044a 100644 --- a/chrome/browser/ui/browser_browsertest.cc +++ b/chrome/browser/ui/browser_browsertest.cc
@@ -1336,7 +1336,7 @@ EXPECT_TRUE(StartupBrowserCreator().ProcessCmdLineImpl( command_line, base::FilePath(), chrome::startup::IsProcessStartup::kNo, - browser()->profile(), {})); + {browser()->profile(), StartupProfileMode::kBrowserWindow}, {})); tab_waiter.Wait();
diff --git a/chrome/browser/ui/chrome_pages.cc b/chrome/browser/ui/chrome_pages.cc index af80cd6..3723247 100644 --- a/chrome/browser/ui/chrome_pages.cc +++ b/chrome/browser/ui/chrome_pages.cc
@@ -446,7 +446,7 @@ void ShowAppManagementPage(Profile* profile, const std::string& app_id, - AppManagementEntryPoint entry_point) { + ash::settings::AppManagementEntryPoint entry_point) { // This histogram is also declared and used at chrome/browser/resources/ // settings/chrome_os/os_apps_page/app_management_page/constants.js. constexpr char kAppManagementEntryPointsHistogramName[] =
diff --git a/chrome/browser/ui/chrome_pages.h b/chrome/browser/ui/chrome_pages.h index 3947a46..92f55618 100644 --- a/chrome/browser/ui/chrome_pages.h +++ b/chrome/browser/ui/chrome_pages.h
@@ -22,7 +22,7 @@ #endif #if BUILDFLAG(IS_CHROMEOS_ASH) -#include "chrome/browser/ui/webui/settings/chromeos/app_management/app_management_uma.h" +#include "chrome/browser/ui/webui/settings/ash/app_management/app_management_uma.h" #endif namespace signin { @@ -166,7 +166,7 @@ void ShowAppManagementPage(Profile* profile, const std::string& app_id, - AppManagementEntryPoint entry_point); + ash::settings::AppManagementEntryPoint entry_point); void ShowPrintManagementApp(Profile* profile);
diff --git a/chrome/browser/ui/page_info/chrome_page_info_delegate.cc b/chrome/browser/ui/page_info/chrome_page_info_delegate.cc index 8fbb6ee..af00b4d7 100644 --- a/chrome/browser/ui/page_info/chrome_page_info_delegate.cc +++ b/chrome/browser/ui/page_info/chrome_page_info_delegate.cc
@@ -40,7 +40,7 @@ #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/chrome_pages.h" #include "chrome/browser/ui/web_applications/app_browser_controller.h" -#include "chrome/browser/ui/webui/settings/chromeos/app_management/app_management_uma.h" +#include "chrome/browser/ui/webui/settings/ash/app_management/app_management_uma.h" #endif #if !BUILDFLAG(IS_ANDROID) @@ -171,8 +171,9 @@ #if BUILDFLAG(IS_CHROMEOS_ASH) if (web_app::AppBrowserController::IsWebApp(browser)) { web_app::AppId app_id = browser->app_controller()->app_id(); - chrome::ShowAppManagementPage(GetProfile(), app_id, - AppManagementEntryPoint::kPageInfoView); + chrome::ShowAppManagementPage( + GetProfile(), app_id, + ash::settings::AppManagementEntryPoint::kPageInfoView); return; } #endif
diff --git a/chrome/browser/ui/startup/startup_browser_creator.cc b/chrome/browser/ui/startup/startup_browser_creator.cc index 34723e3..a23157d 100644 --- a/chrome/browser/ui/startup/startup_browser_creator.cc +++ b/chrome/browser/ui/startup/startup_browser_creator.cc
@@ -420,21 +420,22 @@ const base::FilePath& cur_dir, chrome::startup::IsProcessStartup process_startup, chrome::startup::IsFirstRun is_first_run, - Profile* last_used_profile, + StartupProfileInfo profile_info, const std::vector<Profile*>& last_opened_profiles) { auto on_urls_unhandled_cb = base::BindOnce( [](const base::CommandLine& command_line, const base::FilePath& cur_dir, chrome::startup::IsProcessStartup process_startup, - chrome::startup::IsFirstRun is_first_run, Profile* last_used_profile, + chrome::startup::IsFirstRun is_first_run, + StartupProfileInfo profile_info, const std::vector<Profile*>& last_opened_profiles) { // TODO(crbug.com/1208199): Refactor StartupBrowserCreator and use the // state struct here. StartupBrowserCreator startup_browser_creator; startup_browser_creator.LaunchBrowserForLastProfiles( - command_line, cur_dir, process_startup, is_first_run, - last_used_profile, last_opened_profiles); + command_line, cur_dir, process_startup, is_first_run, profile_info, + last_opened_profiles); }, - command_line, cur_dir, process_startup, is_first_run, last_used_profile, + command_line, cur_dir, process_startup, is_first_run, profile_info, last_opened_profiles); return web_app::startup::MaybeLaunchUrlHandlerWebAppFromCmd( @@ -494,13 +495,13 @@ bool StartupBrowserCreator::Start(const base::CommandLine& cmd_line, const base::FilePath& cur_dir, - Profile* last_used_profile, + StartupProfileInfo profile_info, const Profiles& last_opened_profiles) { TRACE_EVENT0("startup", "StartupBrowserCreator::Start"); SCOPED_UMA_HISTOGRAM_TIMER("Startup.StartupBrowserCreator_Start"); return ProcessCmdLineImpl(cmd_line, cur_dir, chrome::startup::IsProcessStartup::kYes, - last_used_profile, last_opened_profiles); + profile_info, last_opened_profiles); } // static @@ -573,47 +574,38 @@ const base::FilePath& cur_dir, chrome::startup::IsProcessStartup process_startup, chrome::startup::IsFirstRun is_first_run, - Profile* last_used_profile, + StartupProfileInfo profile_info, const Profiles& last_opened_profiles) { + DCHECK_NE(profile_info.mode, StartupProfileMode::kError); + Profile* profile = profile_info.profile; // On Windows, when chrome is launched by notification activation where the - // kNotificationLaunchId switch is used, always use |last_used_profile| which - // contains the profile id extracted from the notification launch id. + // kNotificationLaunchId switch is used, always use `profile` which contains + // the profile id extracted from the notification launch id. bool was_windows_notification_launch = false; #if BUILDFLAG(IS_WIN) was_windows_notification_launch = command_line.HasSwitch(switches::kNotificationLaunchId); #endif // BUILDFLAG(IS_WIN) - // TODO(crbug.com/1150326) Calling ShouldShowProfilePickerAtProcessLaunch() - // a second time here duplicates the logic to show the profile picker. The - // decision to show the picker should instead be on the previous call to - // ShouldShowProfilePickerAtProcessLaunch() issued from - // GetStartupProfilePath(). - // Once we use other ways to indicate that picker should get opened, we can - // remove IsGuestSession(). - if (ShouldShowProfilePickerAtProcessLaunch( - g_browser_process->profile_manager(), command_line) && - last_used_profile && last_used_profile->IsGuestSession()) { - // The guest session is used to indicate the the profile picker should be - // displayed on start-up. See GetStartupProfilePath(). + if (profile_info.mode == StartupProfileMode::kProfilePicker) { ShowProfilePicker(process_startup); return; } - // |last_opened_profiles| will be empty in the following circumstances: - // - This is the first launch. |last_used_profile| is the initial profile. + // `last_opened_profiles` will be empty in the following circumstances: + // - This is the first launch. `profile` is the initial profile. // - The user exited the browser by closing all windows for all profiles. - // |last_used_profile| is the profile which owned the last open window. + // `profile` is the profile which owned the last open window. // - Only incognito windows were open when the browser exited. - // |last_used_profile| is the last used incognito profile. Restoring it will - // create a browser window for the corresponding original profile. + // `profile` is the last used incognito profile. Restoring it will create a + // browser window for the corresponding original profile. // - All of the last opened profiles fail to initialize. if (last_opened_profiles.empty() || was_windows_notification_launch) { - if (CanOpenProfileOnStartup(last_used_profile)) { - Profile* profile_to_open = last_used_profile->IsGuestSession() - ? last_used_profile->GetPrimaryOTRProfile( + if (CanOpenProfileOnStartup(profile)) { + Profile* profile_to_open = profile->IsGuestSession() + ? profile->GetPrimaryOTRProfile( /*create_if_needed=*/true) - : last_used_profile; + : profile; #if BUILDFLAG(IS_CHROMEOS_ASH) if (process_startup == chrome::startup::IsProcessStartup::kYes) { // If FullRestoreService is available for the profile (i.e. the full @@ -633,13 +625,12 @@ return; } - // Show ProfilePicker if |last_used_profile| can't be auto opened. + // Show ProfilePicker if `profile` can't be auto opened. ShowProfilePicker(process_startup); return; } ProcessLastOpenedProfiles(command_line, cur_dir, process_startup, - is_first_run, last_used_profile, - last_opened_profiles); + is_first_run, profile, last_opened_profiles); } // static @@ -809,12 +800,12 @@ const base::CommandLine& command_line, const base::FilePath& cur_dir, chrome::startup::IsProcessStartup process_startup, - Profile* last_used_profile, + StartupProfileInfo profile_info, const Profiles& last_opened_profiles) { DCHECK_CURRENTLY_ON(BrowserThread::UI); TRACE_EVENT0("startup", "StartupBrowserCreator::ProcessCmdLineImpl"); - - DCHECK(last_used_profile); + Profile* profile = profile_info.profile; + DCHECK(profile); if (process_startup == chrome::startup::IsProcessStartup::kYes && command_line.HasSwitch(switches::kDisablePromptOnRepost)) { content::NavigationController::DisablePromptOnRepost(); @@ -826,24 +817,23 @@ bool silent_launch = false; bool should_launch_incognito = IncognitoModePrefs::ShouldLaunchIncognito( - command_line, last_used_profile->GetPrefs()); - bool can_use_last_profile = - CanOpenProfileOnStartup(last_used_profile) && !should_launch_incognito; + command_line, profile->GetPrefs()); + bool can_use_profile = + CanOpenProfileOnStartup(profile) && !should_launch_incognito; RecordIncognitoForcedStart(should_launch_incognito, command_line.HasSwitch(switches::kIncognito)); - // |last_used_profile| is never off-the-record. If Incognito or Guest - // enforcement switch or policy are provided, use the appropriate private - // browsing profile instead. + // `profile` is never off-the-record. If Incognito or Guest enforcement switch + // or policy are provided, use the appropriate private browsing profile + // instead. Profile* privacy_safe_profile = - GetPrivateProfileIfRequested(command_line, last_used_profile); + GetPrivateProfileIfRequested(command_line, profile); #if BUILDFLAG(IS_WIN) && BUILDFLAG(ENABLE_PRINT_PREVIEW) // If we are just displaying a print dialog we shouldn't open browser // windows. - if (command_line.HasSwitch(switches::kCloudPrintFile) && - can_use_last_profile && + if (command_line.HasSwitch(switches::kCloudPrintFile) && can_use_profile && print_dialog_cloud::CreatePrintDialogFromCommandLine(privacy_safe_profile, command_line)) { silent_launch = true; @@ -876,17 +866,15 @@ if (chrome::IsRunningInForcedAppMode()) { user_manager::User* user = - ash::ProfileHelper::Get()->GetUserByProfile(last_used_profile); + ash::ProfileHelper::Get()->GetUserByProfile(profile); if (user && user->GetType() == user_manager::USER_TYPE_KIOSK_APP) { chromeos::LaunchAppOrDie( - last_used_profile, - chromeos::KioskAppId::ForChromeApp( - command_line.GetSwitchValueASCII(switches::kAppId))); + profile, chromeos::KioskAppId::ForChromeApp( + command_line.GetSwitchValueASCII(switches::kAppId))); } else if (user && user->GetType() == user_manager::USER_TYPE_WEB_KIOSK_APP) { chromeos::LaunchAppOrDie( - last_used_profile, - chromeos::KioskAppId::ForWebApp(user->GetAccountId())); + profile, chromeos::KioskAppId::ForWebApp(user->GetAccountId())); } else { // If we are here, we are either in ARC kiosk session or the user is // invalid. We should terminate the session in such cases. @@ -991,7 +979,7 @@ #endif // BUILDFLAG(IS_WIN) if (command_line.HasSwitch(extensions::switches::kLoadApps) && - can_use_last_profile) { + can_use_profile) { if (!ProcessLoadApps(command_line, cur_dir, privacy_safe_profile)) return false; @@ -1005,7 +993,7 @@ } // Check for --load-and-launch-app. - if (command_line.HasSwitch(apps::kLoadAndLaunchApp) && can_use_last_profile) { + if (command_line.HasSwitch(apps::kLoadAndLaunchApp) && can_use_profile) { base::CommandLine::StringType path = command_line.GetSwitchValueNative(apps::kLoadAndLaunchApp); @@ -1050,15 +1038,15 @@ // signin page. if (command_line.HasSwitch(credential_provider::kGcpwSigninSwitch)) { // Use incognito profile since this is a credential provider logon. - Profile* profile = + Profile* incognito_profile = privacy_safe_profile->GetPrimaryOTRProfile(/*create_if_needed=*/true); - DCHECK(profile->IsIncognitoProfile()); + DCHECK(incognito_profile->IsIncognitoProfile()); // NOTE: All launch urls are ignored when running with --gcpw-signin since // this mode only loads Google's sign in page. // If GCPW signin dialog fails, returning false here will allow Chrome to // exit gracefully during the launch. - if (!StartGCPWSignin(command_line, profile)) + if (!StartGCPWSignin(command_line, incognito_profile)) return false; LaunchModeRecorder().SetLaunchMode(LaunchMode::kCredentialProviderSignIn); @@ -1095,7 +1083,7 @@ // Launch the browser if the profile is unable to open web apps. if (!CanOpenWebApp(privacy_safe_profile)) { LaunchBrowserForLastProfiles(command_line, cur_dir, process_startup, - is_first_run, last_used_profile, + is_first_run, profile_info, last_opened_profiles); return true; } @@ -1110,7 +1098,7 @@ // Give web apps a chance to handle a URL. MaybeLaunchUrlHandlerWebAppFromCmd( command_line, cur_dir, process_startup, is_first_run, - last_used_profile, last_opened_profiles); + profile_info, last_opened_profiles); #endif // If the app launch succeeded, we don't need to continue with a browser @@ -1119,7 +1107,7 @@ return true; LaunchBrowserForLastProfiles(command_line, cur_dir, process_startup, - is_first_run, last_used_profile, + is_first_run, profile_info, last_opened_profiles); return true; } @@ -1228,29 +1216,31 @@ void StartupBrowserCreator::ProcessCommandLineOnProfileCreated( const base::CommandLine& command_line, const base::FilePath& cur_dir, + StartupProfileMode mode, Profile* profile, Profile::CreateStatus status) { if (status != Profile::CREATE_STATUS_INITIALIZED) return; StartupBrowserCreator startup_browser_creator; startup_browser_creator.ProcessCmdLineImpl( - command_line, cur_dir, chrome::startup::IsProcessStartup::kNo, profile, - Profiles()); + command_line, cur_dir, chrome::startup::IsProcessStartup::kNo, + {profile, mode}, Profiles()); } // static void StartupBrowserCreator::ProcessCommandLineAlreadyRunning( const base::CommandLine& command_line, const base::FilePath& cur_dir, - const base::FilePath& profile_path) { + const StartupProfilePathInfo& profile_path_info) { ProfileManager* profile_manager = g_browser_process->profile_manager(); - Profile* profile = profile_manager->GetProfileByPath(profile_path); + Profile* profile = profile_manager->GetProfileByPath(profile_path_info.path); // The profile isn't loaded yet and so needs to be loaded asynchronously. if (!profile) { profile_manager->CreateProfileAsync( - profile_path, base::BindRepeating(&ProcessCommandLineOnProfileCreated, - command_line, cur_dir)); + profile_path_info.path, + base::BindRepeating(&ProcessCommandLineOnProfileCreated, command_line, + cur_dir, profile_path_info.mode)); return; } StartupBrowserCreator startup_browser_creator; @@ -1263,8 +1253,8 @@ last_opened_profiles = profile_manager->GetLastOpenedProfiles(); #endif // BUILDFLAG(IS_CHROMEOS_ASH) startup_browser_creator.ProcessCmdLineImpl( - command_line, cur_dir, chrome::startup::IsProcessStartup::kNo, profile, - last_opened_profiles); + command_line, cur_dir, chrome::startup::IsProcessStartup::kNo, + {profile, profile_path_info.mode}, last_opened_profiles); } // static
diff --git a/chrome/browser/ui/startup/startup_browser_creator.h b/chrome/browser/ui/startup/startup_browser_creator.h index a7937ee..bfc4dd9 100644 --- a/chrome/browser/ui/startup/startup_browser_creator.h +++ b/chrome/browser/ui/startup/startup_browser_creator.h
@@ -97,7 +97,7 @@ // called during actual process startup. bool Start(const base::CommandLine& cmd_line, const base::FilePath& cur_dir, - Profile* last_used_profile, + StartupProfileInfo profile_info, const Profiles& last_opened_profiles); // This function performs command-line handling and is invoked only after @@ -105,12 +105,12 @@ // |command_line| holds the command line we need to process. // |cur_dir| is the current working directory that the original process was // invoked from. - // |startup_profile_dir| is the directory that contains the profile that the - // command line arguments will be executed under. + // |profile_path_info| contains the directory that contains the profile that + // the command line arguments will be executed under. static void ProcessCommandLineAlreadyRunning( const base::CommandLine& command_line, const base::FilePath& cur_dir, - const base::FilePath& startup_profile_dir); + const StartupProfilePathInfo& profile_path_info); // Opens the set of startup pages from the current session startup prefs. static void OpenStartupPages( @@ -135,14 +135,14 @@ chrome::startup::IsFirstRun is_first_run, std::unique_ptr<LaunchModeRecorder> launch_mode_recorder); - // Launch browser for `last_opened_profiles` if it's not empty. Otherwise, - // launch browser for `last_used_profile`. + // Launches browser for `last_opened_profiles` if it's not empty. Otherwise, + // launches browser for `profile_info`. void LaunchBrowserForLastProfiles( const base::CommandLine& command_line, const base::FilePath& cur_dir, chrome::startup::IsProcessStartup process_startup, chrome::startup::IsFirstRun is_first_run, - Profile* last_used_profile, + StartupProfileInfo profile_info, const Profiles& last_opened_profiles); // If Incognito or Guest mode are requested by policy or command line returns @@ -227,10 +227,10 @@ bool ProcessCmdLineImpl(const base::CommandLine& command_line, const base::FilePath& cur_dir, chrome::startup::IsProcessStartup process_startup, - Profile* last_used_profile, + StartupProfileInfo profile_info, const Profiles& last_opened_profiles); - // Launch the |last_used_profile| with the full command line, and the other + // Launches the |last_used_profile| with the full command line, and the other // |last_opened_profiles| without the URLs to launch. void ProcessLastOpenedProfiles( const base::CommandLine& command_line, @@ -254,6 +254,7 @@ static void ProcessCommandLineOnProfileCreated( const base::CommandLine& command_line, const base::FilePath& cur_dir, + StartupProfileMode mode, Profile* profile, Profile::CreateStatus status);
diff --git a/chrome/browser/ui/startup/startup_browser_creator_browsertest.cc b/chrome/browser/ui/startup/startup_browser_creator_browsertest.cc index 8e65f06..e185d66 100644 --- a/chrome/browser/ui/startup/startup_browser_creator_browsertest.cc +++ b/chrome/browser/ui/startup/startup_browser_creator_browsertest.cc
@@ -528,7 +528,7 @@ ASSERT_TRUE(StartupBrowserCreator().ProcessCmdLineImpl( command_line, base::FilePath(), chrome::startup::IsProcessStartup::kNo, - browser()->profile(), {})); + {browser()->profile(), StartupProfileMode::kBrowserWindow}, {})); Browser* new_browser = FindOneOtherBrowser(browser()); ASSERT_TRUE(new_browser); @@ -574,7 +574,7 @@ ASSERT_TRUE(StartupBrowserCreator().ProcessCmdLineImpl( command_line, base::FilePath(), chrome::startup::IsProcessStartup::kNo, - incognito->profile(), {})); + {incognito->profile(), StartupProfileMode::kBrowserWindow}, {})); Browser* new_browser = FindOneOtherBrowser(incognito); ASSERT_TRUE(new_browser); @@ -754,7 +754,7 @@ ASSERT_TRUE(StartupBrowserCreator().ProcessCmdLineImpl( command_line, base::FilePath(), chrome::startup::IsProcessStartup::kNo, - browser()->profile(), {})); + {browser()->profile(), StartupProfileMode::kBrowserWindow}, {})); if (IsExpectedToAllowLaunch()) { // No pref was set, so the app should have opened in a tab in the existing @@ -792,7 +792,7 @@ command_line.AppendSwitchASCII(switches::kAppId, extension_app->id()); ASSERT_TRUE(StartupBrowserCreator().ProcessCmdLineImpl( command_line, base::FilePath(), chrome::startup::IsProcessStartup::kNo, - browser()->profile(), {})); + {browser()->profile(), StartupProfileMode::kBrowserWindow}, {})); if (IsExpectedToAllowLaunch()) { // Pref was set to open in a window, so the app should have opened in a @@ -831,7 +831,7 @@ command_line.AppendSwitchASCII(switches::kAppId, extension_app->id()); ASSERT_TRUE(StartupBrowserCreator().ProcessCmdLineImpl( command_line, base::FilePath(), chrome::startup::IsProcessStartup::kNo, - browser()->profile(), {})); + {browser()->profile(), StartupProfileMode::kBrowserWindow}, {})); if (IsExpectedToAllowLaunch()) { // When an app shortcut is open and the pref indicates a tab should open, @@ -883,7 +883,7 @@ ASSERT_TRUE(StartupBrowserCreator().ProcessCmdLineImpl( command_line, base::FilePath(), chrome::startup::IsProcessStartup::kNo, - browser()->profile(), {})); + {browser()->profile(), StartupProfileMode::kBrowserWindow}, {})); tab_waiter.Wait(); // Policy force-installed app should be allowed regardless of Chrome App @@ -940,7 +940,7 @@ ASSERT_TRUE(StartupBrowserCreator().ProcessCmdLineImpl( command_line, base::FilePath(), chrome::startup::IsProcessStartup::kNo, - browser()->profile(), {})); + {browser()->profile(), StartupProfileMode::kBrowserWindow}, {})); // The launch delegates to the notification system and doesn't open any new // browser window. @@ -954,7 +954,7 @@ StartupBrowserCreator browser_creator; ASSERT_FALSE(StartupBrowserCreator().ProcessCmdLineImpl( command_line, base::FilePath(), chrome::startup::IsProcessStartup::kNo, - browser()->profile(), {})); + {browser()->profile(), StartupProfileMode::kBrowserWindow}, {})); // No new browser window is open. ASSERT_EQ(1u, chrome::GetBrowserCount(browser()->profile())); @@ -990,7 +990,8 @@ StartupBrowserCreator browser_creator; browser_creator.Start(command_line, profile_manager->user_data_dir(), - default_profile, last_opened_profiles); + {default_profile, StartupProfileMode::kBrowserWindow}, + last_opened_profiles); // |browser()| is still around at this point, even though we've closed its // window. Thus the browser count for default_profile is 1. @@ -1074,7 +1075,8 @@ last_opened_profiles.push_back(default_profile); last_opened_profiles.push_back(other_profile); browser_creator.Start(dummy, profile_manager->user_data_dir(), - default_profile, last_opened_profiles); + {default_profile, StartupProfileMode::kBrowserWindow}, + last_opened_profiles); // urls1 were opened in a browser for default_profile, and urls2 were opened // in a browser for other_profile. @@ -1211,7 +1213,8 @@ base::RunLoop run_loop; SessionsRestoredWaiter restore_waiter(run_loop.QuitClosure(), 2); - browser_creator.Start(dummy, profile_manager->user_data_dir(), profile1, + browser_creator.Start(dummy, profile_manager->user_data_dir(), + {profile1, StartupProfileMode::kBrowserWindow}, last_opened_profiles); run_loop.Run(); @@ -1313,7 +1316,8 @@ base::RunLoop run_loop; // Only profile_last should get its session restored. SessionsRestoredWaiter restore_waiter(run_loop.QuitClosure(), 1); - browser_creator.Start(dummy, profile_manager->user_data_dir(), profile_home1, + browser_creator.Start(dummy, profile_manager->user_data_dir(), + {profile_home1, StartupProfileMode::kBrowserWindow}, last_opened_profiles); run_loop.Run(); @@ -1430,7 +1434,8 @@ StartupBrowserCreator browser_creator; std::vector<Profile*> last_opened_profiles = {profile1, profile2}; browser_creator.Start(dummy, profile_manager->user_data_dir(), - default_profile, last_opened_profiles); + {default_profile, StartupProfileMode::kBrowserWindow}, + last_opened_profiles); // TODO(davidbienvenu): Waiting for some sort of browser is started // notification would be better. But, we're not opening any browser @@ -1445,8 +1450,8 @@ base::RunLoop run_loop; SessionsRestoredWaiter restore_waiter(run_loop.QuitClosure(), 2); - StartupBrowserCreator::ProcessCommandLineAlreadyRunning(empty, {}, - dest_path1); + StartupBrowserCreator::ProcessCommandLineAlreadyRunning( + empty, {}, {dest_path1, StartupProfileMode::kBrowserWindow}); run_loop.Run(); // profile1 and profile2 browser windows should be opened. @@ -1528,7 +1533,8 @@ last_opened_profiles.push_back(profile_home); last_opened_profiles.push_back(profile_last); last_opened_profiles.push_back(profile_urls); - browser_creator.Start(dummy, profile_manager->user_data_dir(), profile_home, + browser_creator.Start(dummy, profile_manager->user_data_dir(), + {profile_home, StartupProfileMode::kBrowserWindow}, last_opened_profiles); // No profiles are getting restored, since they all display the crash info @@ -1619,7 +1625,8 @@ entry2->LockForceSigninProfile(false); browser_creator.Start(command_line, profile_manager->user_data_dir(), - profile1, last_opened_profiles); + {profile1, StartupProfileMode::kBrowserWindow}, + last_opened_profiles); ASSERT_EQ(0u, chrome::GetBrowserCount(profile1)); ASSERT_EQ(1u, chrome::GetBrowserCount(profile2)); @@ -1729,7 +1736,7 @@ command_line.AppendSwitchPath(switches::kListApps, output_path); ASSERT_TRUE(StartupBrowserCreator().ProcessCmdLineImpl( command_line, base::FilePath(), chrome::startup::IsProcessStartup::kNo, - browser()->profile(), {})); + {browser()->profile(), StartupProfileMode::kBrowserWindow}, {})); CloseBrowserSynchronously(app_browser1); CloseBrowserSynchronously(app_browser2); @@ -1830,7 +1837,7 @@ command_line.AppendSwitchASCII(switches::kProfileBaseName, "New Profile 1"); ASSERT_TRUE(StartupBrowserCreator().ProcessCmdLineImpl( command_line, base::FilePath(), chrome::startup::IsProcessStartup::kNo, - browser()->profile(), {})); + {browser()->profile(), StartupProfileMode::kBrowserWindow}, {})); CloseBrowserSynchronously(app_browser1); CloseBrowserSynchronously(app_browser2); @@ -2751,9 +2758,10 @@ std::vector<Profile*> last_opened_profiles; StartupBrowserCreator browser_creator; - browser_creator.Start(command_line, - g_browser_process->profile_manager()->user_data_dir(), - browser()->profile(), last_opened_profiles); + browser_creator.Start( + command_line, g_browser_process->profile_manager()->user_data_dir(), + {browser()->profile(), StartupProfileMode::kBrowserWindow}, + last_opened_profiles); } base::test::ScopedFeatureList scoped_feature_list_; @@ -4135,7 +4143,7 @@ /*ignore_profile_picker=*/false); EXPECT_EQ(startup_profile_path_info.mode, StartupProfileMode::kProfilePicker); StartupBrowserCreator::ProcessCommandLineAlreadyRunning( - command_line, current_dir, startup_profile_path_info.path); + command_line, current_dir, startup_profile_path_info); base::RunLoop().RunUntilIdle(); // The picker is shown again if no profile was previously opened.
diff --git a/chrome/browser/ui/startup/startup_browser_creator_interactive_uitest.cc b/chrome/browser/ui/startup/startup_browser_creator_interactive_uitest.cc index 3cc8f0e..593282f 100644 --- a/chrome/browser/ui/startup/startup_browser_creator_interactive_uitest.cc +++ b/chrome/browser/ui/startup/startup_browser_creator_interactive_uitest.cc
@@ -79,7 +79,8 @@ last_opened_profiles.push_back(profile_2); last_opened_profiles.push_back(profile_3); last_opened_profiles.push_back(profile_4); - browser_creator.Start(dummy, profile_manager->user_data_dir(), profile_2, + browser_creator.Start(dummy, profile_manager->user_data_dir(), + {profile_2, StartupProfileMode::kBrowserWindow}, last_opened_profiles); while (!browser_creator.ActivatedProfile())
diff --git a/chrome/browser/ui/startup/startup_browser_creator_welcome_back_browsertest.cc b/chrome/browser/ui/startup/startup_browser_creator_welcome_back_browsertest.cc index bdf7096..9b4fda99 100644 --- a/chrome/browser/ui/startup/startup_browser_creator_welcome_back_browsertest.cc +++ b/chrome/browser/ui/startup/startup_browser_creator_welcome_back_browsertest.cc
@@ -80,7 +80,7 @@ ASSERT_TRUE(browser_creator_.Start( base::CommandLine(base::CommandLine::NO_PROGRAM), base::FilePath(), - profile_, + {profile_, StartupProfileMode::kBrowserWindow}, g_browser_process->profile_manager()->GetLastOpenedProfiles())); ASSERT_EQ(1U, BrowserList::GetInstance()->size()); }
diff --git a/chrome/browser/ui/startup/web_app_url_handling_startup_test_utils.cc b/chrome/browser/ui/startup/web_app_url_handling_startup_test_utils.cc index 6a42d65..85c5ba0 100644 --- a/chrome/browser/ui/startup/web_app_url_handling_startup_test_utils.cc +++ b/chrome/browser/ui/startup/web_app_url_handling_startup_test_utils.cc
@@ -59,9 +59,10 @@ const base::CommandLine& command_line) { std::vector<Profile*> last_opened_profiles; StartupBrowserCreator browser_creator; - browser_creator.Start(command_line, - g_browser_process->profile_manager()->user_data_dir(), - browser()->profile(), last_opened_profiles); + browser_creator.Start( + command_line, g_browser_process->profile_manager()->user_data_dir(), + {browser()->profile(), StartupProfileMode::kBrowserWindow}, + last_opened_profiles); } void StartupBrowserWebAppUrlHandlingTest::SetUpCommandlineAndStart(
diff --git a/chrome/browser/ui/views/apps/app_info_dialog/app_info_dialog_views.cc b/chrome/browser/ui/views/apps/app_info_dialog/app_info_dialog_views.cc index a0bb7392..6c82a7f 100644 --- a/chrome/browser/ui/views/apps/app_info_dialog/app_info_dialog_views.cc +++ b/chrome/browser/ui/views/apps/app_info_dialog/app_info_dialog_views.cc
@@ -114,10 +114,9 @@ } } -base::OnceCallback<void(AppInfoDialog*)>& -AppInfoDialog::InstanceCallbackForTesting() { - static base::NoDestructor<base::OnceCallback<void(AppInfoDialog*)>> callback; - return *callback; +base::WeakPtr<AppInfoDialog>& AppInfoDialog::GetLastDialogForTesting() { + static base::NoDestructor<base::WeakPtr<AppInfoDialog>> last_dialog; + return *last_dialog; } AppInfoDialog::AppInfoDialog(Profile* profile, const extensions::Extension* app) @@ -184,8 +183,7 @@ // destroyed. StartObservingExtensionRegistry(); - if (InstanceCallbackForTesting()) - std::move(InstanceCallbackForTesting()).Run(this); + GetLastDialogForTesting() = AsWeakPtr(); } AppInfoDialog::~AppInfoDialog() {
diff --git a/chrome/browser/ui/views/apps/app_info_dialog/app_info_dialog_views.h b/chrome/browser/ui/views/apps/app_info_dialog/app_info_dialog_views.h index 9ba188f..8d5acf3 100644 --- a/chrome/browser/ui/views/apps/app_info_dialog/app_info_dialog_views.h +++ b/chrome/browser/ui/views/apps/app_info_dialog/app_info_dialog_views.h
@@ -30,11 +30,12 @@ // |extension| in the member variables in this class and all AppInfoPanel // classes. class AppInfoDialog : public views::View, - public extensions::ExtensionRegistryObserver { + public extensions::ExtensionRegistryObserver, + public base::SupportsWeakPtr<AppInfoDialog> { public: METADATA_HEADER(AppInfoDialog); - static base::OnceCallback<void(AppInfoDialog*)>& InstanceCallbackForTesting(); + static base::WeakPtr<AppInfoDialog>& GetLastDialogForTesting(); AppInfoDialog(Profile* profile, const extensions::Extension* app); AppInfoDialog(const AppInfoDialog&) = delete;
diff --git a/chrome/browser/ui/views/apps/app_info_dialog/app_info_dialog_views_browsertest.cc b/chrome/browser/ui/views/apps/app_info_dialog/app_info_dialog_views_browsertest.cc index 7fea479..7c9f8cb5b 100644 --- a/chrome/browser/ui/views/apps/app_info_dialog/app_info_dialog_views_browsertest.cc +++ b/chrome/browser/ui/views/apps/app_info_dialog/app_info_dialog_views_browsertest.cc
@@ -56,17 +56,18 @@ IN_PROC_BROWSER_TEST_F(AppInfoDialogBrowserTest, CreateShortcutsAfterExtensionUnloaded) { - // Open app info dialog and grab handle. - AppInfoDialog* dialog = nullptr; - AppInfoDialog::InstanceCallbackForTesting() = base::BindLambdaForTesting( - [&dialog](AppInfoDialog* new_dialog) { dialog = new_dialog; }); ShowUi(""); - ASSERT_TRUE(dialog); + ASSERT_TRUE(AppInfoDialog::GetLastDialogForTesting()); // Unload all extensions. extension_environment_->GetExtensionService() - ->ProfileMarkedForPermanentDeletionForTesting(); + ->ProfileMarkedForPermanentDeletionForTest(); + + // Dialog widgets and their root views are closed asynchronously so the dialog + // is still alive. + ASSERT_TRUE(AppInfoDialog::GetLastDialogForTesting()); // Dialog is now closing. - ASSERT_TRUE(dialog->GetWidget()->IsClosed()); + ASSERT_TRUE( + AppInfoDialog::GetLastDialogForTesting()->GetWidget()->IsClosed()); }
diff --git a/chrome/browser/ui/views/certificate_viewer_win.cc b/chrome/browser/ui/views/certificate_viewer_win.cc index 8c2fc61..e7d9e19 100644 --- a/chrome/browser/ui/views/certificate_viewer_win.cc +++ b/chrome/browser/ui/views/certificate_viewer_win.cc
@@ -55,6 +55,8 @@ base::Unretained(this), std::move(run_state), callback)); } + static bool mock_certificate_viewer_for_testing; + private: void ShowOnDialogThread(HWND owner, const scoped_refptr<net::X509Certificate>& cert) { @@ -78,6 +80,9 @@ view_info.cStores = 1; view_info.rghStores = &cert_store; + if (mock_certificate_viewer_for_testing) + return; + BOOL properties_changed; ::CryptUIDlgViewCertificate(&view_info, &properties_changed); } @@ -90,6 +95,9 @@ } }; +// static +bool CertificateViewerDialog::mock_certificate_viewer_for_testing = false; + } // namespace void ShowCertificateViewer(content::WebContents* web_contents, @@ -100,3 +108,7 @@ base::BindRepeating( &base::DeletePointer<CertificateViewerDialog>, dialog)); } + +void MockCertificateViewerForTesting() { + CertificateViewerDialog::mock_certificate_viewer_for_testing = true; +}
diff --git a/chrome/browser/ui/views/intent_picker_bubble_view.cc b/chrome/browser/ui/views/intent_picker_bubble_view.cc index 0749800f..0169d38 100644 --- a/chrome/browser/ui/views/intent_picker_bubble_view.cc +++ b/chrome/browser/ui/views/intent_picker_bubble_view.cc
@@ -502,8 +502,7 @@ // TODO(crbug.com/1000037): Allow persisting remote devices. should_enable = false; } else if (selected_app_type == apps::PickerEntryType::kWeb) { - should_enable = - base::FeatureList::IsEnabled(features::kIntentPickerPWAPersistence); + should_enable = apps::IntentPickerPwaPersistenceEnabled(); } // Reset the checkbox state to the default unchecked if becomes disabled.
diff --git a/chrome/browser/ui/views/intent_picker_bubble_view_browsertest.cc b/chrome/browser/ui/views/intent_picker_bubble_view_browsertest.cc index a097c1a..b4315a3 100644 --- a/chrome/browser/ui/views/intent_picker_bubble_view_browsertest.cc +++ b/chrome/browser/ui/views/intent_picker_bubble_view_browsertest.cc
@@ -5,6 +5,7 @@ #include "base/bind.h" #include "base/test/scoped_feature_list.h" #include "build/build_config.h" +#include "chrome/browser/apps/intent_helper/intent_picker_helpers.h" #include "chrome/browser/favicon/favicon_utils.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_commands.h" @@ -82,8 +83,7 @@ }; // Tests that clicking a link from a tabbed browser to within the scope of an -// installed app shows the intent picker icon in Omnibox. The intent picker -// bubble will only show up for android apps which is too hard to test. +// installed app shows the intent picker icon in Omnibox. IN_PROC_BROWSER_TEST_P(IntentPickerBubbleViewBrowserTest, NavigationToInScopeLinkShowsIntentPicker) { InstallTestWebApp();
diff --git a/chrome/browser/ui/views/intent_picker_bubble_view_browsertest_chromeos.cc b/chrome/browser/ui/views/intent_picker_bubble_view_browsertest_chromeos.cc index c2dd738f..b5f4ea7 100644 --- a/chrome/browser/ui/views/intent_picker_bubble_view_browsertest_chromeos.cc +++ b/chrome/browser/ui/views/intent_picker_bubble_view_browsertest_chromeos.cc
@@ -415,9 +415,7 @@ EXPECT_FALSE(intent_picker_view->GetVisible()); } -// Test that intent picker bubble pop up status will depends on -// kIntentPickerPWAPersistence flag for if there is only PWA as -// candidates. +// Test that intent picker bubble pops up if there is only PWA as candidates. IN_PROC_BROWSER_TEST_F(IntentPickerBubbleViewBrowserTestChromeOS, PWAOnlyShowBubble) { GURL test_url("https://www.google.com/"); @@ -437,13 +435,8 @@ ui_test_utils::NavigateToURL(¶ms); WaitForAppService(); EXPECT_TRUE(intent_picker_view->GetVisible()); - if (base::FeatureList::IsEnabled(features::kIntentPickerPWAPersistence)) { - ASSERT_TRUE(intent_picker_bubble()); - EXPECT_TRUE(intent_picker_bubble()->GetVisible()); - } else { - EXPECT_FALSE(intent_picker_bubble()); - ClickIconToShowBubble(); - } + ASSERT_TRUE(intent_picker_bubble()); + EXPECT_TRUE(intent_picker_bubble()->GetVisible()); EXPECT_EQ(1U, intent_picker_bubble()->GetScrollViewSize()); auto& app_info = intent_picker_bubble()->app_info_for_testing(); @@ -453,9 +446,7 @@ // Check the status of the remember selection checkbox. ASSERT_TRUE(remember_selection_checkbox()); - EXPECT_EQ( - remember_selection_checkbox()->GetEnabled(), - base::FeatureList::IsEnabled(features::kIntentPickerPWAPersistence)); + EXPECT_TRUE(remember_selection_checkbox()->GetEnabled()); EXPECT_FALSE(remember_selection_checkbox()->GetChecked()); // Launch the app. @@ -722,13 +713,8 @@ ui_test_utils::NavigateToURL(¶ms); WaitForAppService(); EXPECT_TRUE(intent_picker_view->GetVisible()); - if (base::FeatureList::IsEnabled(features::kIntentPickerPWAPersistence)) { - ASSERT_TRUE(intent_picker_bubble()); - EXPECT_TRUE(intent_picker_bubble()->GetVisible()); - } else { - EXPECT_FALSE(intent_picker_bubble()); - ClickIconToShowBubble(); - } + ASSERT_TRUE(intent_picker_bubble()); + EXPECT_TRUE(intent_picker_bubble()->GetVisible()); ASSERT_NO_FATAL_FAILURE(CheckStayInChrome()); } @@ -813,9 +799,7 @@ // Check the status of the remember selection checkbox. ASSERT_TRUE(remember_selection_checkbox()); - EXPECT_EQ( - remember_selection_checkbox()->GetEnabled(), - base::FeatureList::IsEnabled(features::kIntentPickerPWAPersistence)); + EXPECT_TRUE(remember_selection_checkbox()->GetEnabled()); EXPECT_FALSE(remember_selection_checkbox()->GetChecked()); // Launch the app. @@ -999,21 +983,9 @@ ASSERT_NO_FATAL_FAILURE(VerifyArcAppLaunched(app_name, test_url)); } -class IntentPickerBrowserTestPWAPersistence - : public IntentPickerBubbleViewBrowserTestChromeOS { - public: - IntentPickerBrowserTestPWAPersistence() { - scoped_feature_list_.InitAndEnableFeature( - features::kIntentPickerPWAPersistence); - } - - private: - base::test::ScopedFeatureList scoped_feature_list_; -}; - // Test that remember by choice checkbox works for stay in chrome option for // PWA. -IN_PROC_BROWSER_TEST_F(IntentPickerBrowserTestPWAPersistence, +IN_PROC_BROWSER_TEST_F(IntentPickerBubbleViewBrowserTestChromeOS, RememberStayInChromePWA) { GURL test_url("https://www.google.com/"); std::string app_name = "test_name"; @@ -1056,7 +1028,8 @@ } // Test that remember by choice checkbox works for open PWA option. -IN_PROC_BROWSER_TEST_F(IntentPickerBrowserTestPWAPersistence, RememberOpenPWA) { +IN_PROC_BROWSER_TEST_F(IntentPickerBubbleViewBrowserTestChromeOS, + RememberOpenPWA) { GURL test_url("https://www.google.com/"); std::string app_name = "test_name"; auto app_id = InstallWebApp(app_name, test_url); @@ -1102,7 +1075,7 @@ } class IntentPickerBrowserTestPrerendering - : public IntentPickerBrowserTestPWAPersistence { + : public IntentPickerBubbleViewBrowserTestChromeOS { public: IntentPickerBrowserTestPrerendering() : prerender_helper_(base::BindRepeating(
diff --git a/chrome/browser/ui/views/intent_picker_bubble_view_unittest.cc b/chrome/browser/ui/views/intent_picker_bubble_view_unittest.cc index 0c0c66a..cb5b880 100644 --- a/chrome/browser/ui/views/intent_picker_bubble_view_unittest.cc +++ b/chrome/browser/ui/views/intent_picker_bubble_view_unittest.cc
@@ -13,6 +13,7 @@ #include "base/memory/raw_ptr.h" #include "build/chromeos_buildflags.h" #include "chrome/browser/apps/intent_helper/apps_navigation_types.h" +#include "chrome/browser/apps/intent_helper/intent_picker_helpers.h" #include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/browser/ui/views/frame/test_with_browser_view.h" #include "chrome/browser/ui/views/toolbar/toolbar_view.h" @@ -342,12 +343,10 @@ bubble_->PressButtonForTesting(0, event); ASSERT_FALSE(bubble_->remember_selection_checkbox_->GetEnabled()); - // kWeb entries should allow persistence when kIntentPickerPWAPersistence is - // enabled. + // kWeb entries should allow persistence when PWA persistence is enabled. bubble_->PressButtonForTesting(1, event); - ASSERT_EQ( - bubble_->remember_selection_checkbox_->GetEnabled(), - base::FeatureList::IsEnabled(features::kIntentPickerPWAPersistence)); + ASSERT_EQ(bubble_->remember_selection_checkbox_->GetEnabled(), + apps::IntentPickerPwaPersistenceEnabled()); // Other app types can be persisted. bubble_->PressButtonForTesting(2, event);
diff --git a/chrome/browser/ui/views/page_info/page_info_bubble_view_browsertest.cc b/chrome/browser/ui/views/page_info/page_info_bubble_view_browsertest.cc index 8b77d2dd..551c4fb7 100644 --- a/chrome/browser/ui/views/page_info/page_info_bubble_view_browsertest.cc +++ b/chrome/browser/ui/views/page_info/page_info_bubble_view_browsertest.cc
@@ -9,6 +9,7 @@ #include "base/scoped_observation.h" #include "base/test/metrics/histogram_tester.h" #include "build/build_config.h" +#include "chrome/browser/certificate_viewer.h" #include "chrome/browser/optimization_guide/optimization_guide_keyed_service.h" #include "chrome/browser/optimization_guide/optimization_guide_keyed_service_factory.h" #include "chrome/browser/safe_browsing/chrome_password_protection_service.h" @@ -177,6 +178,7 @@ const PageInfoBubbleViewBrowserTest& test) = delete; void SetUp() override { + MockCertificateViewerForTesting(); ASSERT_TRUE(embedded_test_server()->Start()); InProcessBrowserTest::SetUp(); }
diff --git a/chrome/browser/ui/views/ssl_client_certificate_selector_browsertest.cc b/chrome/browser/ui/views/ssl_client_certificate_selector_browsertest.cc index 7f6af90..c66fdb7 100644 --- a/chrome/browser/ui/views/ssl_client_certificate_selector_browsertest.cc +++ b/chrome/browser/ui/views/ssl_client_certificate_selector_browsertest.cc
@@ -114,8 +114,10 @@ auth_requestor_2_ = new StrictMock<SSLClientAuthRequestorMock>(cert_request_info_2_); - AddTabAtIndex(1, GURL("about:blank"), ui::PAGE_TRANSITION_LINK); - AddTabAtIndex(2, GURL("about:blank"), ui::PAGE_TRANSITION_LINK); + ASSERT_TRUE( + AddTabAtIndex(1, GURL("about:blank"), ui::PAGE_TRANSITION_LINK)); + ASSERT_TRUE( + AddTabAtIndex(2, GURL("about:blank"), ui::PAGE_TRANSITION_LINK)); ASSERT_TRUE(NULL != browser()->tab_strip_model()->GetWebContentsAt(0)); ASSERT_TRUE(NULL != browser()->tab_strip_model()->GetWebContentsAt(1)); ASSERT_TRUE(NULL != browser()->tab_strip_model()->GetWebContentsAt(2));
diff --git a/chrome/browser/ui/views/web_apps/file_handler_launch_dialog_browsertest.cc b/chrome/browser/ui/views/web_apps/file_handler_launch_dialog_browsertest.cc index a4e665d..c70fe58 100644 --- a/chrome/browser/ui/views/web_apps/file_handler_launch_dialog_browsertest.cc +++ b/chrome/browser/ui/views/web_apps/file_handler_launch_dialog_browsertest.cc
@@ -63,8 +63,9 @@ command_line.AppendSwitchASCII(switches::kAppId, app_id_); command_line.AppendArgPath(path); - browser_creator.Start(command_line, profile_manager->user_data_dir(), - browser()->profile(), {}); + browser_creator.Start( + command_line, profile_manager->user_data_dir(), + {browser()->profile(), StartupProfileMode::kBrowserWindow}, {}); } void InstallTestWebApp() {
diff --git a/chrome/browser/ui/web_applications/sub_apps_renderer_host.h b/chrome/browser/ui/web_applications/sub_apps_renderer_host.h deleted file mode 100644 index 250e44a8..0000000 --- a/chrome/browser/ui/web_applications/sub_apps_renderer_host.h +++ /dev/null
@@ -1,42 +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. - -#ifndef CHROME_BROWSER_UI_WEB_APPLICATIONS_SUB_APPS_RENDERER_HOST_H_ -#define CHROME_BROWSER_UI_WEB_APPLICATIONS_SUB_APPS_RENDERER_HOST_H_ - -#include "content/public/browser/document_service.h" -#include "third_party/blink/public/mojom/subapps/sub_apps_provider.mojom.h" - -namespace content { -class RenderFrameHost; -} - -namespace web_app { - -class SubAppsRendererHost - : public content::DocumentService<blink::mojom::SubAppsProvider> { - public: - SubAppsRendererHost(const SubAppsRendererHost&) = delete; - SubAppsRendererHost& operator=(const SubAppsRendererHost&) = delete; - ~SubAppsRendererHost() override; - - // We only want to create this object when the Browser* associated with the - // WebContents is an installed web app and when the RFH is the main frame. - static void CreateIfAllowed( - content::RenderFrameHost* render_frame_host, - mojo::PendingReceiver<blink::mojom::SubAppsProvider> receiver); - - // blink::mojom::SubAppsProvider - void Add(const std::string& install_path, - AddCallback result_callback) override; - - private: - SubAppsRendererHost( - content::RenderFrameHost* render_frame_host, - mojo::PendingReceiver<blink::mojom::SubAppsProvider> receiver); -}; - -} // namespace web_app - -#endif // CHROME_BROWSER_UI_WEB_APPLICATIONS_SUB_APPS_RENDERER_HOST_H_
diff --git a/chrome/browser/ui/web_applications/sub_apps_renderer_host.cc b/chrome/browser/ui/web_applications/sub_apps_service_impl.cc similarity index 79% rename from chrome/browser/ui/web_applications/sub_apps_renderer_host.cc rename to chrome/browser/ui/web_applications/sub_apps_service_impl.cc index e2dd36b..8919877 100644 --- a/chrome/browser/ui/web_applications/sub_apps_renderer_host.cc +++ b/chrome/browser/ui/web_applications/sub_apps_service_impl.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/ui/web_applications/sub_apps_renderer_host.h" +#include "chrome/browser/ui/web_applications/sub_apps_service_impl.h" #include <string> #include <utility> @@ -18,7 +18,7 @@ #include "content/public/browser/web_contents.h" #include "url/gurl.h" -using blink::mojom::SubAppsProviderResult; +using blink::mojom::SubAppsServiceResult; namespace web_app { @@ -46,30 +46,30 @@ return origin.Resolve(origin.Resolve(path).PathForRequest()); } -void OnAdd(SubAppsRendererHost::AddCallback result_callback, +void OnAdd(SubAppsServiceImpl::AddCallback result_callback, const AppId& app_id, InstallResultCode code) { if (code == InstallResultCode::kSuccessAlreadyInstalled || code == InstallResultCode::kSuccessNewInstall) { - std::move(result_callback).Run(SubAppsProviderResult::kSuccess); + std::move(result_callback).Run(SubAppsServiceResult::kSuccess); } else { - std::move(result_callback).Run(SubAppsProviderResult::kFailure); + std::move(result_callback).Run(SubAppsServiceResult::kFailure); } } } // namespace -SubAppsRendererHost::SubAppsRendererHost( +SubAppsServiceImpl::SubAppsServiceImpl( content::RenderFrameHost* render_frame_host, - mojo::PendingReceiver<blink::mojom::SubAppsProvider> receiver) + mojo::PendingReceiver<blink::mojom::SubAppsService> receiver) : DocumentService(render_frame_host, std::move(receiver)) {} -SubAppsRendererHost::~SubAppsRendererHost() = default; +SubAppsServiceImpl::~SubAppsServiceImpl() = default; // static -void SubAppsRendererHost::CreateIfAllowed( +void SubAppsServiceImpl::CreateIfAllowed( content::RenderFrameHost* render_frame_host, - mojo::PendingReceiver<blink::mojom::SubAppsProvider> receiver) { + mojo::PendingReceiver<blink::mojom::SubAppsService> receiver) { // This class is created only on the main frame. DCHECK(!render_frame_host->GetParent()); @@ -82,18 +82,18 @@ // The object is bound to the lifetime of |render_frame_host| and the mojo // connection. See DocumentService for details. - new SubAppsRendererHost(render_frame_host, std::move(receiver)); + new SubAppsServiceImpl(render_frame_host, std::move(receiver)); } -void SubAppsRendererHost::Add(const std::string& install_path, - AddCallback result_callback) { +void SubAppsServiceImpl::Add(const std::string& install_path, + AddCallback result_callback) { // Verify that the calling app is installed itself. This check is done here // and not in |CreateIfAllowed| because of a potential race between doing the // check there and then running the current function, and the parent app being // installed/uninstalled. absl::optional<AppId> parent_app_id = GetAppId(render_frame_host()); if (!parent_app_id.has_value()) { - return std::move(result_callback).Run(SubAppsProviderResult::kFailure); + return std::move(result_callback).Run(SubAppsServiceResult::kFailure); } // Resolve the install_path in the origin context of the calling app.
diff --git a/chrome/browser/ui/web_applications/sub_apps_service_impl.h b/chrome/browser/ui/web_applications/sub_apps_service_impl.h new file mode 100644 index 0000000..c75e060 --- /dev/null +++ b/chrome/browser/ui/web_applications/sub_apps_service_impl.h
@@ -0,0 +1,42 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_WEB_APPLICATIONS_SUB_APPS_SERVICE_IMPL_H_ +#define CHROME_BROWSER_UI_WEB_APPLICATIONS_SUB_APPS_SERVICE_IMPL_H_ + +#include "content/public/browser/document_service.h" +#include "third_party/blink/public/mojom/subapps/sub_apps_service.mojom.h" + +namespace content { +class RenderFrameHost; +} + +namespace web_app { + +class SubAppsServiceImpl + : public content::DocumentService<blink::mojom::SubAppsService> { + public: + SubAppsServiceImpl(const SubAppsServiceImpl&) = delete; + SubAppsServiceImpl& operator=(const SubAppsServiceImpl&) = delete; + ~SubAppsServiceImpl() override; + + // We only want to create this object when the Browser* associated with the + // WebContents is an installed web app and when the RFH is the main frame. + static void CreateIfAllowed( + content::RenderFrameHost* render_frame_host, + mojo::PendingReceiver<blink::mojom::SubAppsService> receiver); + + // blink::mojom::SubAppsService + void Add(const std::string& install_path, + AddCallback result_callback) override; + + private: + SubAppsServiceImpl( + content::RenderFrameHost* render_frame_host, + mojo::PendingReceiver<blink::mojom::SubAppsService> receiver); +}; + +} // namespace web_app + +#endif // CHROME_BROWSER_UI_WEB_APPLICATIONS_SUB_APPS_SERVICE_IMPL_H_
diff --git a/chrome/browser/ui/web_applications/sub_apps_renderer_host_browsertest.cc b/chrome/browser/ui/web_applications/sub_apps_service_impl_browsertest.cc similarity index 80% rename from chrome/browser/ui/web_applications/sub_apps_renderer_host_browsertest.cc rename to chrome/browser/ui/web_applications/sub_apps_service_impl_browsertest.cc index 80ffe45..a1aab9b9 100644 --- a/chrome/browser/ui/web_applications/sub_apps_renderer_host_browsertest.cc +++ b/chrome/browser/ui/web_applications/sub_apps_service_impl_browsertest.cc
@@ -5,7 +5,7 @@ #include <string> #include <vector> -#include "chrome/browser/ui/web_applications/sub_apps_renderer_host.h" +#include "chrome/browser/ui/web_applications/sub_apps_service_impl.h" #include "base/test/scoped_feature_list.h" #include "base/test/test_future.h" @@ -24,7 +24,7 @@ #include "mojo/public/cpp/bindings/remote.h" #include "third_party/blink/public/common/features.h" -using blink::mojom::SubAppsProviderResult; +using blink::mojom::SubAppsServiceResult; namespace web_app { @@ -48,7 +48,7 @@ // TODO(isandrk): JS API interface tests should be in // third_party/blink/web_tests/wpt_internal/subapps/. -class SubAppsRendererHostBrowserTest : public WebAppControllerBrowserTest { +class SubAppsServiceImplBrowserTest : public WebAppControllerBrowserTest { public: content::RenderFrameHost* render_frame_host( content::WebContents* web_contents = nullptr) { @@ -78,14 +78,14 @@ void BindRemote(content::WebContents* web_contents = nullptr) { // Any navigation causes the remote to be destroyed (since the // render_frame_host that owns it gets destroyed.) - SubAppsRendererHost::CreateIfAllowed(render_frame_host(web_contents), - remote_.BindNewPipeAndPassReceiver()); + SubAppsServiceImpl::CreateIfAllowed(render_frame_host(web_contents), + remote_.BindNewPipeAndPassReceiver()); } // Calls the Add() method on the mojo interface which is async, and waits for // it to finish. - SubAppsProviderResult CallAdd(const std::string& install_path) { - base::test::TestFuture<SubAppsProviderResult> future; + SubAppsServiceResult CallAdd(const std::string& install_path) { + base::test::TestFuture<SubAppsServiceResult> future; remote_->Add(install_path, future.GetCallback()); return future.Get(); } @@ -93,11 +93,11 @@ protected: base::test::ScopedFeatureList features_{blink::features::kDesktopPWAsSubApps}; AppId parent_app_id_; - mojo::Remote<blink::mojom::SubAppsProvider> remote_; + mojo::Remote<blink::mojom::SubAppsService> remote_; }; // Simple end-to-end test for add(). -IN_PROC_BROWSER_TEST_F(SubAppsRendererHostBrowserTest, EndToEndAdd) { +IN_PROC_BROWSER_TEST_F(SubAppsServiceImplBrowserTest, EndToEndAdd) { InstallParentApp(); NavigateToParentApp(); EXPECT_EQ(0ul, GetAllSubAppIds(parent_app_id_).size()); @@ -118,7 +118,7 @@ // End-to-end. Test that adding a sub-app from a different origin or from a // different domain fails. -IN_PROC_BROWSER_TEST_F(SubAppsRendererHostBrowserTest, +IN_PROC_BROWSER_TEST_F(SubAppsServiceImplBrowserTest, EndToEndAddFailDifferentOrigin) { InstallParentApp(); NavigateToParentApp(); @@ -140,7 +140,7 @@ } // Add a single sub-app and verify all sorts of things. -IN_PROC_BROWSER_TEST_F(SubAppsRendererHostBrowserTest, AddSingle) { +IN_PROC_BROWSER_TEST_F(SubAppsServiceImplBrowserTest, AddSingle) { // Dependency graph: // NavigateToParentApp --> BindRemote --> CallAdd // \---------------->/ @@ -149,7 +149,7 @@ BindRemote(); InstallParentApp(); EXPECT_EQ(0ul, GetAllSubAppIds(parent_app_id_).size()); - EXPECT_EQ(SubAppsProviderResult::kSuccess, CallAdd(kSubAppPath)); + EXPECT_EQ(SubAppsServiceResult::kSuccess, CallAdd(kSubAppPath)); // Verify a bunch of things for the newly installed sub-app. AppId sub_app_id = @@ -173,74 +173,73 @@ // Add one sub-app, verify count is one. Add it again, still same count. Add a // second sub-app, verify count is two. -IN_PROC_BROWSER_TEST_F(SubAppsRendererHostBrowserTest, AddTwo) { +IN_PROC_BROWSER_TEST_F(SubAppsServiceImplBrowserTest, AddTwo) { InstallParentApp(); NavigateToParentApp(); BindRemote(); EXPECT_EQ(0ul, GetAllSubAppIds(parent_app_id_).size()); - EXPECT_EQ(SubAppsProviderResult::kSuccess, CallAdd(kSubAppPath)); + EXPECT_EQ(SubAppsServiceResult::kSuccess, CallAdd(kSubAppPath)); EXPECT_EQ(1ul, GetAllSubAppIds(parent_app_id_).size()); - EXPECT_EQ(SubAppsProviderResult::kSuccess, CallAdd(kSubAppPath)); + EXPECT_EQ(SubAppsServiceResult::kSuccess, CallAdd(kSubAppPath)); EXPECT_EQ(1ul, GetAllSubAppIds(parent_app_id_).size()); - EXPECT_EQ(SubAppsProviderResult::kSuccess, CallAdd(kSubAppPath2)); + EXPECT_EQ(SubAppsServiceResult::kSuccess, CallAdd(kSubAppPath2)); EXPECT_EQ(2ul, GetAllSubAppIds(parent_app_id_).size()); } // Add call should fail if the parent app isn't installed. -IN_PROC_BROWSER_TEST_F(SubAppsRendererHostBrowserTest, +IN_PROC_BROWSER_TEST_F(SubAppsServiceImplBrowserTest, AddFailParentAppNotInstalled) { NavigateToParentApp(); BindRemote(); - EXPECT_EQ(SubAppsProviderResult::kFailure, CallAdd(kSubAppPath)); + EXPECT_EQ(SubAppsServiceResult::kFailure, CallAdd(kSubAppPath)); } // Add call should fail if the call wasn't made from the context of parent app. -IN_PROC_BROWSER_TEST_F(SubAppsRendererHostBrowserTest, +IN_PROC_BROWSER_TEST_F(SubAppsServiceImplBrowserTest, AddFailNotInParentAppContext) { InstallParentApp(); BindRemote(); - EXPECT_EQ(SubAppsProviderResult::kFailure, CallAdd(kSubAppPath)); + EXPECT_EQ(SubAppsServiceResult::kFailure, CallAdd(kSubAppPath)); } // Make sure the Add API can't force manifest update. Add sub-app, verify // display mode, then add the same one again with different display mode in the // manifest, and verify that it didn't change. -IN_PROC_BROWSER_TEST_F(SubAppsRendererHostBrowserTest, - AddDoesntForceReinstall) { +IN_PROC_BROWSER_TEST_F(SubAppsServiceImplBrowserTest, AddDoesntForceReinstall) { InstallParentApp(); NavigateToParentApp(); BindRemote(); - EXPECT_EQ(SubAppsProviderResult::kSuccess, CallAdd(kSubAppPath)); + EXPECT_EQ(SubAppsServiceResult::kSuccess, CallAdd(kSubAppPath)); AppId sub_app_id = GenerateAppId(/*manifest_id=*/absl::nullopt, GetURL(kSubAppPath)); EXPECT_EQ(DisplayMode::kStandalone, provider().registrar().GetAppEffectiveDisplayMode(sub_app_id)); - EXPECT_EQ(SubAppsProviderResult::kSuccess, CallAdd(kSubAppPathMinimalUi)); + EXPECT_EQ(SubAppsServiceResult::kSuccess, CallAdd(kSubAppPathMinimalUi)); EXPECT_EQ(DisplayMode::kStandalone, provider().registrar().GetAppEffectiveDisplayMode(sub_app_id)); } // Verify that Add works if PWA is launched as standalone window. -IN_PROC_BROWSER_TEST_F(SubAppsRendererHostBrowserTest, AddStandaloneWindow) { +IN_PROC_BROWSER_TEST_F(SubAppsServiceImplBrowserTest, AddStandaloneWindow) { InstallParentApp(); content::WebContents* web_contents = OpenApplication(parent_app_id_); BindRemote(web_contents); - EXPECT_EQ(SubAppsProviderResult::kSuccess, CallAdd(kSubAppPath)); + EXPECT_EQ(SubAppsServiceResult::kSuccess, CallAdd(kSubAppPath)); } // Verify that Add fails for an invalid (non-existing) sub-app. -IN_PROC_BROWSER_TEST_F(SubAppsRendererHostBrowserTest, AddInvalid) { +IN_PROC_BROWSER_TEST_F(SubAppsServiceImplBrowserTest, AddInvalid) { InstallParentApp(); NavigateToParentApp(); BindRemote(); - EXPECT_EQ(SubAppsProviderResult::kFailure, CallAdd(kSubAppPathInvalid)); + EXPECT_EQ(SubAppsServiceResult::kFailure, CallAdd(kSubAppPathInvalid)); EXPECT_EQ(0ul, GetAllSubAppIds(parent_app_id_).size()); }
diff --git a/chrome/browser/ui/web_applications/web_app_engagement_browsertest.cc b/chrome/browser/ui/web_applications/web_app_engagement_browsertest.cc index 0dcda1c..a4a7ea1 100644 --- a/chrome/browser/ui/web_applications/web_app_engagement_browsertest.cc +++ b/chrome/browser/ui/web_applications/web_app_engagement_browsertest.cc
@@ -500,7 +500,7 @@ // The app should open as a window. EXPECT_TRUE(StartupBrowserCreator().ProcessCmdLineImpl( command_line, base::FilePath(), chrome::startup::IsProcessStartup::kNo, - browser()->profile(), {})); + {browser()->profile(), StartupProfileMode::kBrowserWindow}, {})); app_loaded_observer.Wait(); Browser* const app_browser = BrowserList::GetInstance()->GetLastActive(); @@ -551,7 +551,7 @@ // The app should open as a window. EXPECT_TRUE(StartupBrowserCreator().ProcessCmdLineImpl( command_line, base::FilePath(), chrome::startup::IsProcessStartup::kNo, - browser()->profile(), {})); + {browser()->profile(), StartupProfileMode::kBrowserWindow}, {})); app_loaded_observer.Wait(); Browser* const app_browser = BrowserList::GetInstance()->GetLastActive(); @@ -606,7 +606,7 @@ // The app should open as a tab. EXPECT_TRUE(StartupBrowserCreator().ProcessCmdLineImpl( command_line, base::FilePath(), chrome::startup::IsProcessStartup::kNo, - browser()->profile(), {})); + {browser()->profile(), StartupProfileMode::kBrowserWindow}, {})); app_loaded_observer.Wait(); {
diff --git a/chrome/browser/ui/web_applications/web_app_link_capturing_browsertest.cc b/chrome/browser/ui/web_applications/web_app_link_capturing_browsertest.cc index 6c0e3f82..f42c5f3 100644 --- a/chrome/browser/ui/web_applications/web_app_link_capturing_browsertest.cc +++ b/chrome/browser/ui/web_applications/web_app_link_capturing_browsertest.cc
@@ -325,27 +325,21 @@ #endif class WebAppDeclarativeLinkCapturingBrowserTest - : public WebAppLinkCapturingBrowserTest, - public ::testing::WithParamInterface<bool> { + : public WebAppLinkCapturingBrowserTest { public: - static std::string ParamToString( - const ::testing::TestParamInfo<bool> param_info) { - return param_info.param ? "PersistenceOn" : "PersistenceOff"; - } - WebAppDeclarativeLinkCapturingBrowserTest() { - if (GetParam()) { - features_.InitWithFeatures({blink::features::kWebAppEnableLinkCapturing, - features::kIntentPickerPWAPersistence}, - {}); - } else { - features_.InitWithFeatures({blink::features::kWebAppEnableLinkCapturing}, - {features::kIntentPickerPWAPersistence}); - } + features_.InitAndEnableFeature(blink::features::kWebAppEnableLinkCapturing); } bool IsIntentPickerPersistenceEnabled() { - return base::FeatureList::IsEnabled(features::kIntentPickerPWAPersistence); +#if BUILDFLAG(IS_CHROMEOS_ASH) + // TODO: Run these tests with persistence enabled on Lacros, and then + // replace this method with apps::IntentPickerPwaPersistenceEnabled(). + return true; +#else + // App service intent handling is not yet available outside of Chrome OS. + return false; +#endif } protected: @@ -355,7 +349,7 @@ base::test::ScopedFeatureList features_; }; -IN_PROC_BROWSER_TEST_P(WebAppDeclarativeLinkCapturingBrowserTest, +IN_PROC_BROWSER_TEST_F(WebAppDeclarativeLinkCapturingBrowserTest, CaptureLinksUnset) { InstallTestApp("/web_apps/basic.html", /*await_metric=*/false); @@ -380,7 +374,7 @@ } } -IN_PROC_BROWSER_TEST_P(WebAppDeclarativeLinkCapturingBrowserTest, +IN_PROC_BROWSER_TEST_F(WebAppDeclarativeLinkCapturingBrowserTest, CaptureLinksNone) { InstallTestApp("/web_apps/get_manifest.html?capture_links_none.json", /*await_metric=*/true); @@ -412,7 +406,7 @@ #else #define MAYBE_CaptureLinksNewClient CaptureLinksNewClient #endif -IN_PROC_BROWSER_TEST_P(WebAppDeclarativeLinkCapturingBrowserTest, +IN_PROC_BROWSER_TEST_F(WebAppDeclarativeLinkCapturingBrowserTest, MAYBE_CaptureLinksNewClient) { InstallTestApp("/web_apps/get_manifest.html?capture_links_new_client.json", /*await_metric=*/true); @@ -444,7 +438,7 @@ ExpectTabs(app_browser_2, {in_scope_2_}); } -IN_PROC_BROWSER_TEST_P(WebAppDeclarativeLinkCapturingBrowserTest, +IN_PROC_BROWSER_TEST_F(WebAppDeclarativeLinkCapturingBrowserTest, InAppScopeNavigationIgnored) { InstallTestApp("/web_apps/get_manifest.html?capture_links_new_client.json", /*await_metric=*/true); @@ -468,7 +462,7 @@ #if !BUILDFLAG(IS_CHROMEOS_LACROS) // TODO: Run these tests on Chrome OS with both Ash and Lacros processes active. -IN_PROC_BROWSER_TEST_P(WebAppDeclarativeLinkCapturingBrowserTest, +IN_PROC_BROWSER_TEST_F(WebAppDeclarativeLinkCapturingBrowserTest, CaptureLinksExistingClientNavigate) { InstallTestApp( "/web_apps/get_manifest.html?capture_links_existing_client_navigate.json", @@ -508,17 +502,6 @@ } #endif -INSTANTIATE_TEST_SUITE_P( - All, - WebAppDeclarativeLinkCapturingBrowserTest, -#if BUILDFLAG(IS_CHROMEOS_ASH) - /*persistence=*/testing::Values(true, false), -#else - // App service intent handling is not yet available outside of Chrome OS. - /*persistence=*/testing::Values(false), -#endif - &WebAppDeclarativeLinkCapturingBrowserTest::ParamToString); - #if !BUILDFLAG(IS_CHROMEOS_LACROS) // TODO: Run these tests on Chrome OS with both Ash and Lacros processes active. @@ -539,7 +522,7 @@ PrerenderTestHelper prerender_helper_; }; -IN_PROC_BROWSER_TEST_P(WebAppDeclarativeLinkCapturingPrerenderBrowserTest, +IN_PROC_BROWSER_TEST_F(WebAppDeclarativeLinkCapturingPrerenderBrowserTest, CaptureLinksCancelPrerendering) { WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); @@ -589,17 +572,7 @@ } } -INSTANTIATE_TEST_SUITE_P( - All, - WebAppDeclarativeLinkCapturingPrerenderBrowserTest, -#if BUILDFLAG(IS_CHROMEOS_ASH) - /*persistence=*/testing::Values(true, false), -#else - // App service intent handling is not yet available outside of Chrome OS. - /*persistence=*/testing::Values(false), -#endif - &WebAppDeclarativeLinkCapturingPrerenderBrowserTest::ParamToString); -#endif +#endif // !BUILDFLAG(IS_CHROMEOS_LACROS) class WebAppDeclarativeLinkCapturingOriginTrialBrowserTest : public WebAppLinkCapturingBrowserTest { @@ -607,8 +580,8 @@ WebAppDeclarativeLinkCapturingOriginTrialBrowserTest() { // Intent handling persistence enabled and DLC disable by default (needs // origin trial to enable). - features_.InitWithFeatures({features::kIntentPickerPWAPersistence}, - {blink::features::kWebAppEnableLinkCapturing}); + features_.InitAndDisableFeature( + blink::features::kWebAppEnableLinkCapturing); } void SetUpCommandLine(base::CommandLine* command_line) override { @@ -641,9 +614,8 @@ : public WebAppLinkCapturingBrowserTest { public: WebAppLaunchHandlerLinkCaptureBrowserTest() { - feature_list_.InitWithFeatures({blink::features::kWebAppEnableLaunchHandler, - features::kIntentPickerPWAPersistence}, - {}); + feature_list_.InitAndEnableFeature( + blink::features::kWebAppEnableLaunchHandler); } ~WebAppLaunchHandlerLinkCaptureBrowserTest() override = default;
diff --git a/chrome/browser/ui/webui/bluetooth_internals/BUILD.gn b/chrome/browser/ui/webui/bluetooth_internals/BUILD.gn index 0c6bc32..9553883 100644 --- a/chrome/browser/ui/webui/bluetooth_internals/BUILD.gn +++ b/chrome/browser/ui/webui/bluetooth_internals/BUILD.gn
@@ -33,6 +33,7 @@ mojom("mojo_bindings") { sources = [ "bluetooth_internals.mojom" ] + webui_module_path = "/" deps = [ "//device/bluetooth/public/mojom:deprecated_experimental_interfaces" ]
diff --git a/chrome/browser/ui/webui/chromeos/login/consolidated_consent_screen_handler.cc b/chrome/browser/ui/webui/chromeos/login/consolidated_consent_screen_handler.cc index 468244fe..b071d5e5 100644 --- a/chrome/browser/ui/webui/chromeos/login/consolidated_consent_screen_handler.cc +++ b/chrome/browser/ui/webui/chromeos/login/consolidated_consent_screen_handler.cc
@@ -52,34 +52,56 @@ IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_TITLE); builder->Add("consolidatedConsentUsageOptIn", IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN); + builder->Add("consolidatedConsentUsageOptInOwner", + IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_OWNER); builder->Add("consolidatedConsentUsageOptInChild", IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_CHILD); + builder->Add("consolidatedConsentUsageOptInChildOwner", + IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_CHILD_OWNER); builder->Add("consolidatedConsentUsageOptInArcDisabled", IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_ARC_DISABLED); + builder->Add("consolidatedConsentUsageOptInArcDisabledOwner", + IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_ARC_DISABLED_OWNER); + builder->Add("consolidatedConsentUsageOptInLearnMoreLink", + IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_LINK); builder->Add("consolidatedConsentBackupOptInTitle", IDS_CONSOLIDATED_CONSENT_BACKUP_OPT_IN_TITLE); builder->Add("consolidatedConsentBackupOptIn", IDS_CONSOLIDATED_CONSENT_BACKUP_OPT_IN); builder->Add("consolidatedConsentBackupOptInChild", IDS_CONSOLIDATED_CONSENT_BACKUP_OPT_IN_CHILD); + builder->Add("consolidatedConsenttBackupOptInLearnMoreLink", + IDS_CONSOLIDATED_CONSENT_BACKUP_OPT_IN_LEARN_MORE_LINK); builder->Add("consolidatedConsentLocationOptInTitle", IDS_CONSOLIDATED_CONSENT_LOCATION_OPT_IN_TITLE); builder->Add("consolidatedConsentLocationOptIn", IDS_CONSOLIDATED_CONSENT_LOCATION_OPT_IN); builder->Add("consolidatedConsentLocationOptInChild", IDS_CONSOLIDATED_CONSENT_LOCATION_OPT_IN_CHILD); + builder->Add("consolidatedConsenttLocationOptInLearnMoreLink", + IDS_CONSOLIDATED_CONSENT_LOCATION_OPT_IN_LEARN_MORE_LINK); builder->Add("consolidatedConsentFooter", IDS_CONSOLIDATED_CONSENT_FOOTER); builder->Add("consolidatedConsentFooterChild", IDS_CONSOLIDATED_CONSENT_FOOTER_CHILD); builder->Add("consolidatedConsentUsageOptInLearnMore", IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE); + builder->Add("consolidatedConsentUsageOptInLearnMoreOwner", + IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_OWNER); builder->Add("consolidatedConsentUsageOptInLearnMoreChild", IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_CHILD); + builder->Add("consolidatedConsentUsageOptInLearnMoreChildOwner", + IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_CHILD_OWNER); builder->Add("consolidatedConsentUsageOptInLearnMoreArcDisabled", IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_ARC_DISABLED); builder->Add( + "consolidatedConsentUsageOptInLearnMoreArcDisabledOwner", + IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_ARC_DISABLED_OWNER); + builder->Add( "consolidatedConsentUsageOptInLearnMoreArcDisabledChild", IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_ARC_DISABLED_CHILD); + builder->Add( + "consolidatedConsentUsageOptInLearnMoreArcDisabledChildOwner", + IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_ARC_DISABLED_CHILD_OWNER); builder->Add("consolidatedConsentBackupOptInLearnMore", IDS_CONSOLIDATED_CONSENT_BACKUP_OPT_IN_LEARN_MORE); builder->Add("consolidatedConsentBackupOptInLearnMoreChild", @@ -185,4 +207,7 @@ CallJS("login.ConsolidatedConsentScreen.setLocationMode", enabled, managed); } +void ConsolidatedConsentScreenHandler::SetIsDeviceOwner(bool is_owner) { + CallJS("login.ConsolidatedConsentScreen.setIsDeviceOwner", is_owner); +} } // namespace chromeos
diff --git a/chrome/browser/ui/webui/chromeos/login/consolidated_consent_screen_handler.h b/chrome/browser/ui/webui/chromeos/login/consolidated_consent_screen_handler.h index 327e18d..3fb71919 100644 --- a/chrome/browser/ui/webui/chromeos/login/consolidated_consent_screen_handler.h +++ b/chrome/browser/ui/webui/chromeos/login/consolidated_consent_screen_handler.h
@@ -62,6 +62,7 @@ virtual void SetUsageMode(bool enabled, bool managed) = 0; virtual void SetBackupMode(bool enabled, bool managed) = 0; virtual void SetLocationMode(bool enabled, bool managed) = 0; + virtual void SetIsDeviceOwner(bool is_owner) = 0; }; class ConsolidatedConsentScreenHandler : public ConsolidatedConsentScreenView, @@ -87,6 +88,7 @@ void SetUsageMode(bool enabled, bool managed) override; void SetBackupMode(bool enabled, bool managed) override; void SetLocationMode(bool enabled, bool managed) override; + void SetIsDeviceOwner(bool is_owner) override; // content::WebUIMessageHandler: void RegisterMessages() override;
diff --git a/chrome/browser/ui/webui/chromeos/login/guest_tos_screen_handler.cc b/chrome/browser/ui/webui/chromeos/login/guest_tos_screen_handler.cc index d16fb92b..fe1b0c7 100644 --- a/chrome/browser/ui/webui/chromeos/login/guest_tos_screen_handler.cc +++ b/chrome/browser/ui/webui/chromeos/login/guest_tos_screen_handler.cc
@@ -36,7 +36,7 @@ builder->Add("guestTosUsageOptin", IDS_GUEST_TOS_USAGE_OPT_IN); builder->Add("guestTosUsageOptInLearnMore", IDS_GUEST_TOS_USAGE_OPT_IN_LEARN_MORE); - builder->Add("guestTosLearnMore", IDS_GUEST_TOS_LEARN_MORE); + builder->Add("guestTosLearnMore", IDS_GUEST_TOS_USAGE_OPT_IN_LEARN_MORE_LINK); builder->Add("guestTosOk", IDS_GUEST_TOS_OK); builder->Add("guestTosLoading", IDS_GUEST_TOS_LOADING); }
diff --git a/chrome/browser/ui/webui/settings/ash/DIR_METADATA b/chrome/browser/ui/webui/settings/ash/DIR_METADATA new file mode 100644 index 0000000..e84643a --- /dev/null +++ b/chrome/browser/ui/webui/settings/ash/DIR_METADATA
@@ -0,0 +1 @@ +mixins: "//chrome/browser/resources/settings/chromeos/COMMON_METADATA"
diff --git a/chrome/browser/ui/webui/settings/ash/OWNERS b/chrome/browser/ui/webui/settings/ash/OWNERS new file mode 100644 index 0000000..96f54b2 --- /dev/null +++ b/chrome/browser/ui/webui/settings/ash/OWNERS
@@ -0,0 +1 @@ +file://chrome/browser/resources/settings/chromeos/OWNERS
diff --git a/chrome/browser/ui/webui/settings/chromeos/app_management/DIR_METADATA b/chrome/browser/ui/webui/settings/ash/app_management/DIR_METADATA similarity index 100% rename from chrome/browser/ui/webui/settings/chromeos/app_management/DIR_METADATA rename to chrome/browser/ui/webui/settings/ash/app_management/DIR_METADATA
diff --git a/chrome/browser/ui/webui/settings/chromeos/app_management/OWNERS b/chrome/browser/ui/webui/settings/ash/app_management/OWNERS similarity index 100% rename from chrome/browser/ui/webui/settings/chromeos/app_management/OWNERS rename to chrome/browser/ui/webui/settings/ash/app_management/OWNERS
diff --git a/chrome/browser/ui/webui/settings/chromeos/app_management/app_management_page_handler_factory.cc b/chrome/browser/ui/webui/settings/ash/app_management/app_management_page_handler_factory.cc similarity index 90% rename from chrome/browser/ui/webui/settings/chromeos/app_management/app_management_page_handler_factory.cc rename to chrome/browser/ui/webui/settings/ash/app_management/app_management_page_handler_factory.cc index fb66843..d5b8dbf 100644 --- a/chrome/browser/ui/webui/settings/chromeos/app_management/app_management_page_handler_factory.cc +++ b/chrome/browser/ui/webui/settings/ash/app_management/app_management_page_handler_factory.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 "chrome/browser/ui/webui/settings/chromeos/app_management/app_management_page_handler_factory.h" +#include "chrome/browser/ui/webui/settings/ash/app_management/app_management_page_handler_factory.h" #include <memory> #include <utility> @@ -25,6 +25,9 @@ #include "ui/base/resource/resource_bundle.h" #include "ui/webui/resources/cr_components/app_management/app_management.mojom.h" +namespace ash { +namespace settings { + AppManagementPageHandlerFactory::AppManagementPageHandlerFactory( Profile* profile) : profile_(profile) {} @@ -46,3 +49,6 @@ page_handler_ = std::make_unique<AppManagementPageHandler>( std::move(receiver), std::move(page), profile_); } + +} // namespace settings +} // namespace ash
diff --git a/chrome/browser/ui/webui/settings/chromeos/app_management/app_management_page_handler_factory.h b/chrome/browser/ui/webui/settings/ash/app_management/app_management_page_handler_factory.h similarity index 70% rename from chrome/browser/ui/webui/settings/chromeos/app_management/app_management_page_handler_factory.h rename to chrome/browser/ui/webui/settings/ash/app_management/app_management_page_handler_factory.h index 38af42a..31fc371 100644 --- a/chrome/browser/ui/webui/settings/chromeos/app_management/app_management_page_handler_factory.h +++ b/chrome/browser/ui/webui/settings/ash/app_management/app_management_page_handler_factory.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 CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_APP_MANAGEMENT_APP_MANAGEMENT_PAGE_HANDLER_FACTORY_H_ -#define CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_APP_MANAGEMENT_APP_MANAGEMENT_PAGE_HANDLER_FACTORY_H_ +#ifndef CHROME_BROWSER_UI_WEBUI_SETTINGS_ASH_APP_MANAGEMENT_APP_MANAGEMENT_PAGE_HANDLER_FACTORY_H_ +#define CHROME_BROWSER_UI_WEBUI_SETTINGS_ASH_APP_MANAGEMENT_APP_MANAGEMENT_PAGE_HANDLER_FACTORY_H_ #include <memory> @@ -16,6 +16,9 @@ class AppManagementPageHandler; +namespace ash { +namespace settings { + class AppManagementPageHandlerFactory : public app_management::mojom::PageHandlerFactory { public: @@ -46,4 +49,14 @@ Profile* profile_; }; -#endif // CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_APP_MANAGEMENT_APP_MANAGEMENT_PAGE_HANDLER_FACTORY_H_ +} // namespace settings +} // namespace ash + +// TODO(https://crbug.com/1164001): remove when the migration is finished. +namespace chromeos { +namespace settings { +using ::ash::settings::AppManagementPageHandlerFactory; +} +} // namespace chromeos + +#endif // CHROME_BROWSER_UI_WEBUI_SETTINGS_ASH_APP_MANAGEMENT_APP_MANAGEMENT_PAGE_HANDLER_FACTORY_H_
diff --git a/chrome/browser/ui/webui/settings/chromeos/app_management/app_management_uma.h b/chrome/browser/ui/webui/settings/ash/app_management/app_management_uma.h similarity index 74% rename from chrome/browser/ui/webui/settings/chromeos/app_management/app_management_uma.h rename to chrome/browser/ui/webui/settings/ash/app_management/app_management_uma.h index 8e734d92..38648318 100644 --- a/chrome/browser/ui/webui/settings/chromeos/app_management/app_management_uma.h +++ b/chrome/browser/ui/webui/settings/ash/app_management/app_management_uma.h
@@ -2,8 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_APP_MANAGEMENT_APP_MANAGEMENT_UMA_H_ -#define CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_APP_MANAGEMENT_APP_MANAGEMENT_UMA_H_ +#ifndef CHROME_BROWSER_UI_WEBUI_SETTINGS_ASH_APP_MANAGEMENT_APP_MANAGEMENT_UMA_H_ +#define CHROME_BROWSER_UI_WEBUI_SETTINGS_ASH_APP_MANAGEMENT_APP_MANAGEMENT_UMA_H_ + +namespace ash { +namespace settings { // These are used in histograms, do not remove/renumber entries. If you're // adding to this enum with the intention that it will be logged, update the @@ -28,4 +31,7 @@ kMaxValue = kPageInfoView, }; -#endif // CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_APP_MANAGEMENT_APP_MANAGEMENT_UMA_H_ +} // namespace settings +} // namespace ash + +#endif // CHROME_BROWSER_UI_WEBUI_SETTINGS_ASH_APP_MANAGEMENT_APP_MANAGEMENT_UMA_H_
diff --git a/chrome/browser/ui/webui/settings/chromeos/os_settings_ui.h b/chrome/browser/ui/webui/settings/chromeos/os_settings_ui.h index 67ed6ed7..90488d1a 100644 --- a/chrome/browser/ui/webui/settings/chromeos/os_settings_ui.h +++ b/chrome/browser/ui/webui/settings/chromeos/os_settings_ui.h
@@ -10,7 +10,7 @@ #include "base/time/time.h" #include "chrome/browser/ui/webui/nearby_share/nearby_share.mojom.h" #include "chrome/browser/ui/webui/nearby_share/public/mojom/nearby_share_settings.mojom.h" -#include "chrome/browser/ui/webui/settings/chromeos/app_management/app_management_page_handler_factory.h" +#include "chrome/browser/ui/webui/settings/ash/app_management/app_management_page_handler_factory.h" #include "chrome/browser/ui/webui/settings/chromeos/os_apps_page/mojom/app_notification_handler.mojom-forward.h" #include "chrome/browser/ui/webui/settings/chromeos/search/user_action_recorder.mojom-forward.h" #include "chrome/browser/ui/webui/webui_load_timer.h"
diff --git a/chrome/browser/ui/webui/sync_internals/sync_internals_message_handler.cc b/chrome/browser/ui/webui/sync_internals/sync_internals_message_handler.cc index 2d06a2c..5d96893 100644 --- a/chrome/browser/ui/webui/sync_internals/sync_internals_message_handler.cc +++ b/chrome/browser/ui/webui/sync_internals/sync_internals_message_handler.cc
@@ -183,7 +183,7 @@ base::Value type_list(base::Value::Type::LIST); syncer::ModelTypeSet protocol_types = syncer::ProtocolTypes(); for (syncer::ModelType type : protocol_types) { - type_list.Append(ModelTypeToString(type)); + type_list.Append(ModelTypeToDebugString(type)); } event_details.SetKey(syncer::sync_ui_util::kTypes, std::move(type_list)); FireWebUIListener(syncer::sync_ui_util::kOnReceivedListOfTypes, @@ -331,7 +331,7 @@ syncer::ModelType type = syncer::GetModelTypeFromSpecificsFieldNumber(field_number); if (IsRealDataType(type)) { - data_types_list.Append(syncer::ModelTypeToString(type)); + data_types_list.Append(syncer::ModelTypeToDebugString(type)); } } @@ -360,7 +360,7 @@ for (const syncer::TypeEntitiesCount& count : entity_counts) { DictionaryValue count_dictionary; count_dictionary.SetStringPath(syncer::sync_ui_util::kModelType, - ModelTypeToString(count.type)); + ModelTypeToDebugString(count.type)); count_dictionary.SetIntPath(syncer::sync_ui_util::kEntities, count.entities); count_dictionary.SetIntPath(syncer::sync_ui_util::kNonTombstoneEntities,
diff --git a/chrome/browser/web_applications/preinstalled_web_app_manager.cc b/chrome/browser/web_applications/preinstalled_web_app_manager.cc index 688bea5..3091b8c 100644 --- a/chrome/browser/web_applications/preinstalled_web_app_manager.cc +++ b/chrome/browser/web_applications/preinstalled_web_app_manager.cc
@@ -675,7 +675,7 @@ ++app_to_replace_still_installed_count; - if (!extensions::IsExtensionDefaultInstalled(profile_, replace_id)) + if (extensions::IsExtensionDefaultInstalled(profile_, replace_id)) ++app_to_replace_still_default_installed_count; if (ui_manager_->CanAddAppToQuickLaunchBar()) {
diff --git a/chrome/browser/web_applications/preinstalled_web_app_migration_browsertest.cc b/chrome/browser/web_applications/preinstalled_web_app_migration_browsertest.cc index 945c0cca..2ffcb0c 100644 --- a/chrome/browser/web_applications/preinstalled_web_app_migration_browsertest.cc +++ b/chrome/browser/web_applications/preinstalled_web_app_migration_browsertest.cc
@@ -608,7 +608,7 @@ histograms.ExpectUniqueSample( PreinstalledWebAppManager:: kHistogramAppToReplaceStillDefaultInstalledCount, - 1, 1); + 0, 1); // Neither app has been added to the shelf. histograms.ExpectUniqueSample(
diff --git a/chrome/build/linux.pgo.txt b/chrome/build/linux.pgo.txt index 0507e0aa8..6d3285d 100644 --- a/chrome/build/linux.pgo.txt +++ b/chrome/build/linux.pgo.txt
@@ -1 +1 @@ -chrome-linux-main-1642550315-109debcb95e05be97b1f2a74042e325a472f08ad.profdata +chrome-linux-main-1642571800-774c3b4060f7ec440a2c976030c5ce7dac4b88d6.profdata
diff --git a/chrome/build/mac.pgo.txt b/chrome/build/mac.pgo.txt index 609ca436..742eb55 100644 --- a/chrome/build/mac.pgo.txt +++ b/chrome/build/mac.pgo.txt
@@ -1 +1 @@ -chrome-mac-main-1642528769-dbb43462ddeb0d1260e6ec2d2f9b006e8b9ec975.profdata +chrome-mac-main-1642571800-f3a26a49418fcd8206999a88daf3ae2744183941.profdata
diff --git a/chrome/build/win32.pgo.txt b/chrome/build/win32.pgo.txt index 2d6212e..bf37795 100644 --- a/chrome/build/win32.pgo.txt +++ b/chrome/build/win32.pgo.txt
@@ -1 +1 @@ -chrome-win32-main-1642528769-f64a921f37803080ad5d6988a0f292c178dc8eaa.profdata +chrome-win32-main-1642571800-b24975915bc940d7c50628a7cca5ba7cee02d9a5.profdata
diff --git a/chrome/build/win64.pgo.txt b/chrome/build/win64.pgo.txt index af30e725..699c276 100644 --- a/chrome/build/win64.pgo.txt +++ b/chrome/build/win64.pgo.txt
@@ -1 +1 @@ -chrome-win64-main-1642539500-ca04c10767dc62e0b67cc500c6227b3b6ebc3c08.profdata +chrome-win64-main-1642571800-e2fa45e956f33a0d1b4c47af9acf5a885f70796b.profdata
diff --git a/chrome/common/chrome_features.cc b/chrome/common/chrome_features.cc index 5236fc4f..4dca795 100644 --- a/chrome/common/chrome_features.cc +++ b/chrome/common/chrome_features.cc
@@ -662,17 +662,6 @@ const base::Feature kUpdateHistoryEntryPointsInIncognito{ "UpdateHistoryEntryPointsInIncognito", base::FEATURE_DISABLED_BY_DEFAULT}; -#if !BUILDFLAG(IS_ANDROID) -// Allow user to have preference for PWA in the intent picker. -const base::Feature kIntentPickerPWAPersistence{ -#if BUILDFLAG(IS_CHROMEOS) - "IntentPickerPWAPersistence", base::FEATURE_ENABLED_BY_DEFAULT -#else - "IntentPickerPWAPersistence", base::FEATURE_DISABLED_BY_DEFAULT -#endif // BUILDFLAG(IS_CHROMEOS) -}; -#endif // !BUILDFLAG(IS_ANDROID) - // If enabled, CloudPolicyInvalidator and RemoteCommandInvalidator instances // will have unique owner name. const base::Feature kInvalidatorUniqueOwnerName{
diff --git a/chrome/common/chrome_features.h b/chrome/common/chrome_features.h index abbe726a..4f522d3 100644 --- a/chrome/common/chrome_features.h +++ b/chrome/common/chrome_features.h
@@ -446,11 +446,6 @@ COMPONENT_EXPORT(CHROME_FEATURES) extern const base::Feature kUpdateHistoryEntryPointsInIncognito; -#if !BUILDFLAG(IS_ANDROID) -COMPONENT_EXPORT(CHROME_FEATURES) -extern const base::Feature kIntentPickerPWAPersistence; -#endif // !BUILDFLAG(IS_ANDROID) - COMPONENT_EXPORT(CHROME_FEATURES) extern const base::Feature kInvalidatorUniqueOwnerName;
diff --git a/chrome/common/pref_names.cc b/chrome/common/pref_names.cc index 5df863c4..9f5e060 100644 --- a/chrome/common/pref_names.cc +++ b/chrome/common/pref_names.cc
@@ -3318,6 +3318,9 @@ // A time pref indicating the timestamp of when last cart discount fetch // happened. const char kCartDiscountLastFetchedTime[] = "cart_discount_last_fetched_time"; +// Boolean pref indicating whether the consent for discount has ever shown or +// not. +const char kCartDiscountConsentShown[] = "cart_discount_consent_shown"; #endif #if BUILDFLAG(IS_ANDROID)
diff --git a/chrome/common/pref_names.h b/chrome/common/pref_names.h index f5fbd851..1b972bab 100644 --- a/chrome/common/pref_names.h +++ b/chrome/common/pref_names.h
@@ -1158,6 +1158,7 @@ extern const char kCartDiscountEnabled[]; extern const char kCartUsedDiscounts[]; extern const char kCartDiscountLastFetchedTime[]; +extern const char kCartDiscountConsentShown[]; #endif #if BUILDFLAG(IS_ANDROID)
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index ecf223b6..fb1d9902 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -2043,7 +2043,7 @@ "../browser/ui/web_applications/app_browser_controller_browsertest.cc", "../browser/ui/web_applications/create_shortcut_browsertest.cc", "../browser/ui/web_applications/pwa_mixed_content_browsertest.cc", - "../browser/ui/web_applications/sub_apps_renderer_host_browsertest.cc", + "../browser/ui/web_applications/sub_apps_service_impl_browsertest.cc", "../browser/ui/web_applications/web_app_badging_browsertest.cc", "../browser/ui/web_applications/web_app_browsertest.cc", "../browser/ui/web_applications/web_app_dark_mode_browsertest.cc", @@ -6634,8 +6634,7 @@ "../browser/ui/app_list/search/mixer_unittest.cc", "../browser/ui/app_list/search/omnibox_result_unittest.cc", "../browser/ui/app_list/search/ranking/answer_ranker_unittest.cc", - "../browser/ui/app_list/search/ranking/category_item_ranker_unittest.cc", - "../browser/ui/app_list/search/ranking/category_usage_ranker_unittest.cc", + "../browser/ui/app_list/search/ranking/ftrl_ranker_unittest.cc", "../browser/ui/app_list/search/ranking/removed_results_ranker_unittest.cc", "../browser/ui/app_list/search/search_controller_impl_new_unittest.cc", "../browser/ui/app_list/search/search_controller_impl_unittest.cc",
diff --git a/chrome/test/data/webui/BUILD.gn b/chrome/test/data/webui/BUILD.gn index d616604..17b3027 100644 --- a/chrome/test/data/webui/BUILD.gn +++ b/chrome/test/data/webui/BUILD.gn
@@ -414,7 +414,6 @@ test_type = "mojo_lite_webui" sources = [ - "bluetooth_internals/bluetooth_internals_browsertest.js", "media/media_engagement_browsertest.js", "media/media_history_webui_browsertest.js", ] @@ -444,6 +443,7 @@ js2gtest("browser_tests_js_mojo_webui") { test_type = "mojo_webui" sources = [ + "bluetooth_internals/bluetooth_internals_browsertest.js", "cr_components/cr_components_mojo_browsertest.js", "downloads/downloads_browsertest.js", "engagement/site_engagement_browsertest.js",
diff --git a/chrome/test/data/webui/bluetooth_internals/bluetooth_internals_test.js b/chrome/test/data/webui/bluetooth_internals/bluetooth_internals_test.js index 6b1428f..f733d4b0 100644 --- a/chrome/test/data/webui/bluetooth_internals/bluetooth_internals_test.js +++ b/chrome/test/data/webui/bluetooth_internals/bluetooth_internals_test.js
@@ -2,9 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import 'chrome://test/mojo_webui_test_support.js'; + import {adapterBroker, devices, initializeViews, pageManager, sidebarObj} from 'chrome://bluetooth-internals/bluetooth_internals.js'; +import {BluetoothInternalsHandler} from 'chrome://bluetooth-internals/bluetooth_internals.mojom-webui.js'; import {connectedDevices} from 'chrome://bluetooth-internals/device_broker.js'; import {Snackbar} from 'chrome://bluetooth-internals/snackbar.js'; +import {UUID} from 'chrome://bluetooth-internals/uuid.mojom-webui.js'; import {ValueControl, ValueDataType} from 'chrome://bluetooth-internals/value_control.js'; import {assert} from 'chrome://resources/js/assert.m.js'; import {PromiseResolver} from 'chrome://resources/js/promise_resolver.m.js'; @@ -22,8 +26,8 @@ const EXPECTED_DEVICES = 2; suiteSetup(async function() { - let internalsHandlerInterceptor = new MojoInterfaceInterceptor( - mojom.BluetoothInternalsHandler.$interfaceName); + let internalsHandlerInterceptor = + new MojoInterfaceInterceptor(BluetoothInternalsHandler.$interfaceName); internalsHandlerInterceptor.oninterfacerequest = (e) => { internalsHandler = new TestBluetoothInternalsHandler(e.handle); @@ -125,7 +129,7 @@ /** * Format in a user readable way service UUIDs. - * @param ?Array<bluetooth.mojom.UUID> uuids + * @param ?Array<UUID> uuids * @return {string} */ function formatServiceUuids(serviceUuids) {
diff --git a/chrome/test/data/webui/bluetooth_internals/test_utils.js b/chrome/test/data/webui/bluetooth_internals/test_utils.js index 39109e5f..f9839c2 100644 --- a/chrome/test/data/webui/bluetooth_internals/test_utils.js +++ b/chrome/test/data/webui/bluetooth_internals/test_utils.js
@@ -2,11 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import {AdapterReceiver, ConnectResult} from 'chrome://bluetooth-internals/adapter.mojom-webui.js'; +import {BluetoothInternalsHandlerReceiver} from 'chrome://bluetooth-internals/bluetooth_internals.mojom-webui.js'; +import {DeviceCallbackRouter} from 'chrome://bluetooth-internals/device.mojom-webui.js'; import {assert} from 'chrome://resources/js/assert.m.js'; + import {TestBrowserProxy} from '../test_browser_proxy.js'; /** - * A mojom.BluetoothInternalsHandler for the chrome://bluetooth-internals + * A BluetoothInternalsHandler for the chrome://bluetooth-internals * page. Provides a fake BluetoothInternalsHandler::GetAdapter * implementation and acts as a root of all Test* classes by containing an * adapter member. @@ -21,7 +25,7 @@ 'getDebugLogsChangeHandler', ]); - this.receiver_ = new mojom.BluetoothInternalsHandlerReceiver(this); + this.receiver_ = new BluetoothInternalsHandlerReceiver(this); this.receiver_.$.bindHandle(handle); } @@ -46,7 +50,7 @@ } /** - * A bluetooth.mojom.Adapter implementation for the + * A Adapter implementation for the * chrome://bluetooth-internals page. */ export class TestAdapter extends TestBrowserProxy { @@ -57,12 +61,12 @@ 'addObserver', ]); - this.receiver = new bluetooth.mojom.AdapterReceiver(this); + this.receiver = new AdapterReceiver(this); this.deviceImplMap = new Map(); this.adapterInfo_ = adapterInfo; this.devices_ = []; - this.connectResult_ = bluetooth.mojom.ConnectResult.SUCCESS; + this.connectResult_ = ConnectResult.SUCCESS; } reset() { @@ -138,7 +142,7 @@ } /** - * A bluetooth.mojom.Device implementation for the + * A Device implementation for the * chrome://bluetooth-internals page. Remotes are returned by a * TestAdapter which provides the DeviceInfo. * @param {!device.DeviceInfo} info @@ -156,7 +160,7 @@ // NOTE: We use the generated CallbackRouter here because Device defines // lots of methods we don't care to mock here. DeviceCallbackRouter // callback silently discards messages that have no listeners. - this.router = new bluetooth.mojom.DeviceCallbackRouter; + this.router = new DeviceCallbackRouter; this.router.disconnect.addListener(() => this.router.$.close()); this.router.getInfo.addListener(() => this.getInfo()); this.router.getServices.addListener(() => this.getServices());
diff --git a/chrome/test/data/webui/settings/chromeos/app_management/uninstall_button_test.js b/chrome/test/data/webui/settings/chromeos/app_management/uninstall_button_test.js index d7195f1..b16c973 100644 --- a/chrome/test/data/webui/settings/chromeos/app_management/uninstall_button_test.js +++ b/chrome/test/data/webui/settings/chromeos/app_management/uninstall_button_test.js
@@ -30,17 +30,14 @@ installReason: installReason }; - // Add an app, and make it the currently selected app. app = await fakeHandler.addApp('app1_id', arcOptions); - app_management.AppManagementStore.getInstance().dispatch( - app_management.actions.updateSelectedAppId(app.id)); await fakeHandler.flushPipesForTesting(); assertTrue( !!app_management.AppManagementStore.getInstance().data.apps[app.id]); uninstallButton = document.createElement('app-management-uninstall-button'); - + uninstallButton.app = app; replaceBody(uninstallButton); await fakeHandler.flushPipesForTesting(); } @@ -48,7 +45,7 @@ test('Click uninstall', async () => { await setupUninstallButton(apps.mojom.InstallReason.kUser); - uninstallButton.$$('#uninstallButton').click(); + uninstallButton.shadowRoot.querySelector('#uninstallButton').click(); await fakeHandler.flushPipesForTesting(); assertFalse( !!app_management.AppManagementStore.getInstance().data.apps[app.id]); @@ -56,7 +53,7 @@ test('Disabled by policy', async () => { await setupUninstallButton(apps.mojom.InstallReason.kPolicy); - uninstallButton.$$('#uninstallButton').click(); + uninstallButton.shadowRoot.querySelector('#uninstallButton').click(); await fakeHandler.flushPipesForTesting(); // Disabled by policy, clicking should not remove app. assertTrue( @@ -65,7 +62,7 @@ test('System app, button hidden', async () => { await setupUninstallButton(apps.mojom.InstallReason.kSystem); - assertFalse(!!uninstallButton.$$('#uninstallButton')); + assertFalse(!!uninstallButton.shadowRoot.querySelector('#uninstallButton')); await fakeHandler.flushPipesForTesting(); // Disabled by policy, clicking should not remove app. assertTrue(
diff --git a/chrome/test/data/webui/settings/languages_page_metrics_test_browser.js b/chrome/test/data/webui/settings/languages_page_metrics_test_browser.js index 5fdbe45..ec2179f 100644 --- a/chrome/test/data/webui/settings/languages_page_metrics_test_browser.js +++ b/chrome/test/data/webui/settings/languages_page_metrics_test_browser.js
@@ -150,21 +150,22 @@ // Chooses the second language to change translate checkbox // as first language is the language used for translation. menuButtons[1].click(); + flush(); const actionMenu = languagesSubpage.shadowRoot.querySelector('#menu').get(); assertTrue(actionMenu.open); - const menuItems = actionMenu.querySelectorAll('.dropdown-item'); - for (const item of menuItems) { - if (item.id === 'offerTranslations') { - const checkedValue = item.checked; - item.click(); - assertEquals( - LanguageSettingsActionType.DISABLE_TRANSLATE_FOR_SINGLE_LANGUAGE + - item.checked, - await languageSettingsMetricsProxy.whenCalled( - 'recordSettingsMetric')); - return; - } - } + const item = actionMenu.querySelector('#offerTranslations'); + assertTrue(!!item); + + item.click(); + assertEquals( + LanguageSettingsActionType.DISABLE_TRANSLATE_FOR_SINGLE_LANGUAGE, + await languageSettingsMetricsProxy.whenCalled('recordSettingsMetric')); + + languageSettingsMetricsProxy.resetResolver('recordSettingsMetric'); + item.click(); + assertEquals( + LanguageSettingsActionType.ENABLE_TRANSLATE_FOR_SINGLE_LANGUAGE, + await languageSettingsMetricsProxy.whenCalled('recordSettingsMetric')); }); test('records on language list reorder', async () => {
diff --git a/chromeos/assistant/BUILD.gn b/chromeos/assistant/BUILD.gn index a2b7a9e..4a35552b 100644 --- a/chromeos/assistant/BUILD.gn +++ b/chromeos/assistant/BUILD.gn
@@ -2,6 +2,7 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +import("//ash/ambient/resources/resources.gni") import("//build/buildflag_header.gni") import("//chromeos/assistant/ambient.gni") import("//chromeos/assistant/assistant.gni") @@ -12,5 +13,6 @@ flags = [ "ENABLE_CROS_LIBASSISTANT=$enable_cros_libassistant", "ENABLE_CROS_AMBIENT_MODE_BACKEND=$enable_cros_ambient_mode_backend", + "HAS_ASH_AMBIENT_ANIMATION_RESOURCES=$include_ash_ambient_animation_resources", ] }
diff --git a/chromeos/dbus/concierge/fake_concierge_client.h b/chromeos/dbus/concierge/fake_concierge_client.h index 496df29..8b144229c 100644 --- a/chromeos/dbus/concierge/fake_concierge_client.h +++ b/chromeos/dbus/concierge/fake_concierge_client.h
@@ -316,6 +316,7 @@ void send_get_container_ssh_keys_response_delay(base::TimeDelta delay) { send_get_container_ssh_keys_response_delay_ = delay; } + void reset_get_vm_info_call_count() { get_vm_info_call_count_ = 0; } void NotifyVmStarted(const vm_tools::concierge::VmStartedSignal& signal); void NotifyVmStopped(const vm_tools::concierge::VmStoppedSignal& signal);
diff --git a/chromeos/profiles/orderfile.newest.txt b/chromeos/profiles/orderfile.newest.txt index 5da3da1..fed24e4 100644 --- a/chromeos/profiles/orderfile.newest.txt +++ b/chromeos/profiles/orderfile.newest.txt
@@ -1 +1 @@ -chromeos-chrome-orderfile-field-99-4807.0-1641812761-benchmark-99.0.4831.0-r1.orderfile.xz +chromeos-chrome-orderfile-field-99-4807.0-1641812761-benchmark-99.0.4833.0-r1.orderfile.xz
diff --git a/components/BUILD.gn b/components/BUILD.gn index 5734f9f7..7b6d99a4 100644 --- a/components/BUILD.gn +++ b/components/BUILD.gn
@@ -354,6 +354,7 @@ "//components/webapps/browser:unit_tests", "//components/webapps/services/web_app_origin_association:unit_tests", "//components/webcrypto:unit_tests", + "//components/webrtc_logging:unit_tests", "//components/webrtc_logging/browser:unit_tests", "//components/webrtc_logging/common:unit_tests", ] @@ -394,6 +395,7 @@ "//base:base_java_unittest_support", "//components/android_autofill/browser:unit_tests", "//components/autofill_assistant/browser:unit_tests", + "//components/autofill_assistant/content/renderer:unit_tests", "//components/browser_ui/sms/android:unit_tests", "//components/cdm/browser:unit_tests", "//components/component_updater/android:embedded_component_loader_java", @@ -786,15 +788,13 @@ "autofill_assistant/browser/mock_script_executor_delegate.cc", "autofill_assistant/browser/mock_script_executor_delegate.h", "autofill_assistant/browser/web/web_controller_browsertest.cc", - "autofill_assistant/content/renderer/autofill_assistant_agent_browsertest.cc", "browser_ui/client_certificate/android/ssl_client_certificate_request_browsertest.cc", "test/android/browsertests_apk/components_browser_tests_jni_onload.cc", ] deps += [ "//components/autofill_assistant/browser", "//components/autofill_assistant/browser:proto", - "//components/autofill_assistant/content/common:mojo_interfaces", - "//components/autofill_assistant/content/renderer", + "//components/autofill_assistant/content/renderer:browser_tests", "//components/browser_ui/client_certificate/android", "//components/browser_ui/client_certificate/android:java", "//components/download/internal/common:internal_java",
diff --git a/components/app_restore/BUILD.gn b/components/app_restore/BUILD.gn index c0c807ff..d04a6628 100644 --- a/components/app_restore/BUILD.gn +++ b/components/app_restore/BUILD.gn
@@ -31,6 +31,8 @@ "full_restore_save_handler.h", "full_restore_utils.cc", "full_restore_utils.h", + "lacros_read_handler.cc", + "lacros_read_handler.h", "lacros_save_handler.cc", "lacros_save_handler.h", "restore_data.cc",
diff --git a/components/app_restore/app_restore_utils.cc b/components/app_restore/app_restore_utils.cc index c5b6ccf..2d51c21 100644 --- a/components/app_restore/app_restore_utils.cc +++ b/components/app_restore/app_restore_utils.cc
@@ -209,10 +209,11 @@ return; } + full_restore::FullRestoreReadHandler::GetInstance() + ->OnLacrosBrowserWindowAdded(window, restored_browser_session_id); + full_restore::FullRestoreSaveHandler::GetInstance() ->OnLacrosBrowserWindowAdded(window, browser_session_id); - - // TODO(https://crbug.com/1239984): Restore Lacros windows. } } // namespace app_restore
diff --git a/components/app_restore/full_restore_read_handler.cc b/components/app_restore/full_restore_read_handler.cc index fd56e034..cefe1310 100644 --- a/components/app_restore/full_restore_read_handler.cc +++ b/components/app_restore/full_restore_read_handler.cc
@@ -15,9 +15,11 @@ #include "base/threading/thread_task_runner_handle.h" #include "components/app_restore/app_launch_info.h" #include "components/app_restore/desk_template_read_handler.h" +#include "components/app_restore/features.h" #include "components/app_restore/full_restore_file_handler.h" #include "components/app_restore/full_restore_info.h" #include "components/app_restore/full_restore_save_handler.h" +#include "components/app_restore/lacros_read_handler.h" #include "components/app_restore/restore_data.h" #include "components/app_restore/window_info.h" #include "components/app_restore/window_properties.h" @@ -33,6 +35,7 @@ // apps. constexpr base::TimeDelta kFullRestoreEstimateDuration = base::Seconds(5); constexpr base::TimeDelta kFullRestoreARCEstimateDuration = base::Minutes(5); +constexpr base::TimeDelta kFullRestoreLacrosEstimateDuration = base::Minutes(1); } // namespace @@ -139,6 +142,15 @@ arc_read_handler_->OnTaskDestroyed(task_id); } +void FullRestoreReadHandler::OnLacrosBrowserWindowAdded( + aura::Window* const window, + uint32_t restored_browser_session_id) { + if (lacros_read_handler_) { + lacros_read_handler_->OnLacrosBrowserWindowAdded( + window, restored_browser_session_id); + } +} + void FullRestoreReadHandler::SetActiveProfilePath( const base::FilePath& profile_path) { active_profile_path_ = profile_path; @@ -307,11 +319,21 @@ return false; base::TimeDelta elapsed_time = base::TimeTicks::Now() - it->second; + // We estimate that full restore is still running if it has been less than - // five seconds since it started, or five minutes if there is at least one ARC - // app. - return arc_read_handler_ ? elapsed_time < kFullRestoreARCEstimateDuration - : elapsed_time < kFullRestoreEstimateDuration; + // five minutes since it started, when there is at least one ARC app, since it + // might take long time to boot ARC. + if (arc_read_handler_) + return elapsed_time < kFullRestoreARCEstimateDuration; + + // We estimate that full restore is still running if it has been less than + // one minute since it started, when Lacros is available. + if (lacros_read_handler_) + return elapsed_time < kFullRestoreLacrosEstimateDuration; + + // We estimate that full restore is still running if it has been less than + // five seconds since it started. + return elapsed_time < kFullRestoreEstimateDuration; } void FullRestoreReadHandler::AddChromeBrowserLaunchInfoForTesting( @@ -354,6 +376,11 @@ if (restore_data) { profile_path_to_restore_data_[profile_path] = restore_data->Clone(); + if (::full_restore::features::IsFullRestoreForLacrosEnabled()) { + lacros_read_handler_ = + std::make_unique<app_restore::LacrosReadHandler>(profile_path); + } + for (auto it = restore_data->app_id_to_launch_list().begin(); it != restore_data->app_id_to_launch_list().end(); it++) { const std::string& app_id = it->first; @@ -370,6 +397,10 @@ } else { window_id_to_app_restore_info_[window_id] = std::make_pair(profile_path, app_id); + // TODO(crbug.com/1239984): Remove restore data from + // `lacros_read_handler_` for ash browser apps. + if (lacros_read_handler_ && app_id != extension_misc::kChromeAppId) + lacros_read_handler_->AddRestoreData(app_id, window_id); } } }
diff --git a/components/app_restore/full_restore_read_handler.h b/components/app_restore/full_restore_read_handler.h index 6b51372..d5caea3e 100644 --- a/components/app_restore/full_restore_read_handler.h +++ b/components/app_restore/full_restore_read_handler.h
@@ -25,6 +25,7 @@ namespace app_restore { struct AppLaunchInfo; +class LacrosReadHandler; class RestoreData; struct WindowInfo; } // namespace app_restore @@ -92,6 +93,11 @@ int32_t session_id) override; void OnTaskDestroyed(int32_t task_id) override; + // Invoked when Lacros window is created. `restored_browser_session_id` is the + // restored browser session id. + void OnLacrosBrowserWindowAdded(aura::Window* const window, + uint32_t restored_browser_session_id); + void SetActiveProfilePath(const base::FilePath& profile_path); // Sets whether we should check the restore data for `profile_path`. If the @@ -210,6 +216,8 @@ std::unique_ptr<app_restore::ArcReadHandler> arc_read_handler_; + std::unique_ptr<app_restore::LacrosReadHandler> lacros_read_handler_; + // Records whether we need to check the restore data for the profile path. If // the profile path is recorded, we should check the restore data. Otherwise, // we don't need to check the restore data, because the restore process hasn't
diff --git a/components/app_restore/lacros_read_handler.cc b/components/app_restore/lacros_read_handler.cc new file mode 100644 index 0000000..a183ea32 --- /dev/null +++ b/components/app_restore/lacros_read_handler.cc
@@ -0,0 +1,34 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/app_restore/lacros_read_handler.h" + +#include "ash/constants/app_types.h" +#include "components/app_restore/app_restore_utils.h" +#include "ui/aura/client/aura_constants.h" +#include "ui/aura/window.h" + +namespace app_restore { + +LacrosReadHandler::LacrosReadHandler(const base::FilePath& profile_path) + : profile_path_(profile_path) {} + +LacrosReadHandler::~LacrosReadHandler() = default; + +void LacrosReadHandler::AddRestoreData(const std::string& app_id, + int32_t window_id) { + restore_window_id_to_app_id_[window_id] = app_id; +} + +void LacrosReadHandler::OnLacrosBrowserWindowAdded( + aura::Window* const window, + uint32_t restored_browser_session_id) { + if (window->GetProperty(aura::client::kAppType) == + static_cast<int>(ash::AppType::LACROS)) { + lacros_window_id_to_restore_window_id_[app_restore::GetLacrosWindowId( + window)] = restored_browser_session_id; + } +} + +} // namespace app_restore
diff --git a/components/app_restore/lacros_read_handler.h b/components/app_restore/lacros_read_handler.h new file mode 100644 index 0000000..45cae80 --- /dev/null +++ b/components/app_restore/lacros_read_handler.h
@@ -0,0 +1,52 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_APP_RESTORE_LACROS_READ_HANDLER_H_ +#define COMPONENTS_APP_RESTORE_LACROS_READ_HANDLER_H_ + +#include <map> + +#include "base/component_export.h" +#include "base/files/file_path.h" + +namespace aura { +class Window; +} + +namespace app_restore { + +// LacrosSaveHandler is a helper class for FullRestoreReadHandler to restore +// Lacros windows. +// TODO(crbug.com/1239984): Restore Lacros windows. +class COMPONENT_EXPORT(APP_RESTORE) LacrosReadHandler { + public: + LacrosReadHandler(const base::FilePath& profile_path); + LacrosReadHandler(const LacrosReadHandler&) = delete; + LacrosReadHandler& operator=(const LacrosReadHandler&) = delete; + ~LacrosReadHandler(); + + // Sets `app_id` and `window_id` to `restore_window_id_to_app_id_` to record + // that there is a restore data for `app_id` and `window_id`. + void AddRestoreData(const std::string& app_id, int32_t window_id); + + // Invoked when Lacros window is created. `restored_browser_session_id` is the + // restored browser session id. + void OnLacrosBrowserWindowAdded(aura::Window* const window, + uint32_t restored_browser_session_id); + + private: + // The user profile path for Lacros windows. + base::FilePath profile_path_; + + // The map from the restore window id to the app id for Lacros windows. + std::map<int32_t, std::string> restore_window_id_to_app_id_; + + // The map from the lacros window id to the restore window id for browser + // windows. + std::map<std::string, int32_t> lacros_window_id_to_restore_window_id_; +}; + +} // namespace app_restore + +#endif // COMPONENTS_APP_RESTORE_LACROS_READ_HANDLER_H_
diff --git a/components/app_restore/lacros_save_handler.h b/components/app_restore/lacros_save_handler.h index 6eb88d4..94bbe90 100644 --- a/components/app_restore/lacros_save_handler.h +++ b/components/app_restore/lacros_save_handler.h
@@ -22,8 +22,6 @@ // LacrosSaveHandler is a helper class for FullRestoreSaveHandler to handle // Lacros windows special cases, e.g. Lacros window id, etc. -// TODO(crbug.com/1239984): -// 1. Use the browser session id as the window id. class COMPONENT_EXPORT(APP_RESTORE) LacrosSaveHandler { public: explicit LacrosSaveHandler(const base::FilePath& profile_path);
diff --git a/components/autofill_assistant/content/browser/content_autofill_assistant_driver.cc b/components/autofill_assistant/content/browser/content_autofill_assistant_driver.cc index 3b3c986..ac4589a8 100644 --- a/components/autofill_assistant/content/browser/content_autofill_assistant_driver.cc +++ b/components/autofill_assistant/content/browser/content_autofill_assistant_driver.cc
@@ -57,15 +57,15 @@ void ContentAutofillAssistantDriver::GetAnnotateDomModel( GetAnnotateDomModelCallback callback) { - DCHECK(annotate_dom_model_service_); if (!annotate_dom_model_service_) { + NOTREACHED() << "No model service"; std::move(callback).Run(base::File()); return; } absl::optional<base::File> file = annotate_dom_model_service_->GetModelFile(); if (file) { - std::move(callback).Run(file->Duplicate()); + std::move(callback).Run(*std::move(file)); return; } @@ -82,13 +82,13 @@ return; } - auto file_opt = annotate_dom_model_service_->GetModelFile(); - DCHECK(file_opt); - if (!file_opt) { + absl::optional<base::File> file = annotate_dom_model_service_->GetModelFile(); + if (!file) { + NOTREACHED() << "No model file where expected."; std::move(callback).Run(base::File()); return; } - std::move(callback).Run(file_opt->Duplicate()); + std::move(callback).Run(*std::move(file)); } } // namespace autofill_assistant
diff --git a/components/autofill_assistant/content/renderer/BUILD.gn b/components/autofill_assistant/content/renderer/BUILD.gn index 5eaa117..03287651 100644 --- a/components/autofill_assistant/content/renderer/BUILD.gn +++ b/components/autofill_assistant/content/renderer/BUILD.gn
@@ -4,7 +4,7 @@ import("//third_party/protobuf/proto_library.gni") -proto_library("proto") { +proto_library("model_metadata_proto") { sources = [ "model_metadata.proto" ] } @@ -12,16 +12,54 @@ sources = [ "autofill_assistant_agent.cc", "autofill_assistant_agent.h", + "autofill_assistant_model_executor.cc", + "autofill_assistant_model_executor.h", ] deps = [ - ":proto", + ":model_metadata_proto", + "//base", "//components/autofill_assistant/content/common:common", "//components/autofill_assistant/content/common:mojo_interfaces", + "//components/optimization_guide/core:model_executor", "//content/public/common:common", "//content/public/renderer:renderer", "//mojo/public/cpp/bindings", + "//third_party/abseil-cpp:absl", "//third_party/blink/public:blink", "//third_party/blink/public/common", ] + public_deps = [ + "//third_party/tflite", + "//third_party/tflite:tflite_public_headers", + "//third_party/tflite_support", + "//third_party/tflite_support:tflite_support_proto", + ] +} + +source_set("unit_tests") { + testonly = true + sources = [ "autofill_assistant_model_executor_unittest.cc" ] + + deps = [ + ":renderer", + "//base", + "//base/test:test_support", + "//third_party/blink/public:blink", + ] +} + +source_set("browser_tests") { + testonly = true + sources = [ "autofill_assistant_agent_browsertest.cc" ] + + deps = [ + ":renderer", + "//base", + "//base/test:test_support", + "//components/autofill_assistant/content/common:mojo_interfaces", + "//content/public/browser", + "//content/public/renderer", + "//content/test:test_support", + ] }
diff --git a/components/autofill_assistant/content/renderer/DEPS b/components/autofill_assistant/content/renderer/DEPS index f0556f5..a28ced16 100644 --- a/components/autofill_assistant/content/renderer/DEPS +++ b/components/autofill_assistant/content/renderer/DEPS
@@ -1,11 +1,15 @@ include_rules = [ + "+components/optimization_guide", "+content/public/common", "+content/public/renderer", "+content/public/test", + "+mojo/public/cpp/bindings", "+mojo/public/cpp/bindings/binding.h", "+services/service_manager/public/cpp", + "+third_party/abseil-cpp/absl/status/status.h", "+third_party/blink/public/common", "+third_party/blink/public/platform", "+third_party/blink/public/web", - "+mojo/public/cpp/bindings", + "+third_party/tflite", + "+third_party/tflite_support", ]
diff --git a/components/autofill_assistant/content/renderer/autofill_assistant_model_executor.cc b/components/autofill_assistant/content/renderer/autofill_assistant_model_executor.cc new file mode 100644 index 0000000..033205b --- /dev/null +++ b/components/autofill_assistant/content/renderer/autofill_assistant_model_executor.cc
@@ -0,0 +1,202 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/autofill_assistant/content/renderer/autofill_assistant_model_executor.h" + +#include "base/i18n/case_conversion.h" +#include "base/no_destructor.h" +#include "base/strings/utf_string_conversions.h" +#include "components/optimization_guide/core/execution_status.h" +#include "components/optimization_guide/core/tflite_op_resolver.h" +#include "third_party/abseil-cpp/absl/status/status.h" +#include "third_party/abseil-cpp/absl/types/optional.h" +#include "third_party/tflite_support/src/tensorflow_lite_support/cc/task/core/task_utils.h" +#include "third_party/tflite_support/src/tensorflow_lite_support/metadata/cc/metadata_extractor.h" + +namespace autofill_assistant { + +AutofillAssistantModelExecutor::AutofillAssistantModelExecutor() = default; +AutofillAssistantModelExecutor::~AutofillAssistantModelExecutor() = default; + +bool AutofillAssistantModelExecutor::InitializeModelFromFile( + base::File model_file) { + if (!model_file.IsValid() || !model_file_.Initialize(std::move(model_file))) { + return false; + } + + std::unique_ptr<tflite::task::core::TfLiteEngine> tflite_engine = + std::make_unique<tflite::task::core::TfLiteEngine>( + std::make_unique<optimization_guide::TFLiteOpResolver>()); + absl::Status model_load_status = tflite_engine->BuildModelFromFlatBuffer( + reinterpret_cast<const char*>(model_file_.data()), model_file_.length()); + if (!model_load_status.ok()) { + DLOG(ERROR) << "Failed to load model: " << model_load_status.ToString(); + return false; + } + absl::Status interpreter_status = tflite_engine->InitInterpreter( + tflite::proto::ComputeSettings(), /* num_threads= */ 1); + if (!interpreter_status.ok()) { + DLOG(ERROR) << "Failed to initialize model interpreter: " + << interpreter_status.ToString(); + return false; + } + + auto metadata_or = + tflite_engine->metadata_extractor()->GetAssociatedFile("metadata.pb"); + if (!metadata_or.ok()) { + DLOG(ERROR) << "Could not read metadata: " + << metadata_or.status().ToString(); + return false; + } + if (!model_metadata_.ParseFromArray(metadata_or->data(), + metadata_or->size())) { + DLOG(ERROR) << "Could not parse metadata."; + return false; + } + + InitializeTagsTokenizer("\\s+", model_metadata_.input().tag().vocabulary()); + InitializeTypesTokenizer("\\s+", model_metadata_.input().type().vocabulary()); + InitializeTextTokenizer(model_metadata_.input().text().regex(), + model_metadata_.input().text().vocabulary()); + + BuildExecutionTask(std::move(tflite_engine)); + + return true; +} + +void AutofillAssistantModelExecutor::BuildExecutionTask( + std::unique_ptr<tflite::task::core::TfLiteEngine> tflite_engine) { + execution_task_ = + std::make_unique<ExecutionTask>(std::move(tflite_engine), this); +} + +absl::optional<std::string> +AutofillAssistantModelExecutor::ExecuteModelWithInput( + const blink::AutofillAssistantNodeSignals& node_signals) { + if (!execution_task_) { + NOTREACHED() << "No available task"; + return absl::nullopt; + } + optimization_guide::ExecutionStatus out_status; + return Execute(execution_task_.get(), &out_status, node_signals); +} + +void AutofillAssistantModelExecutor::InitializeTagsTokenizer( + const std::string& pattern, + const std::string& vocabulary) { + DCHECK(!pattern.empty()); + DCHECK(!vocabulary.empty()); + tags_tokenizer_ = + std::make_unique<tflite::support::text::tokenizer::RegexTokenizer>( + pattern, vocabulary.data(), vocabulary.size()); +} + +void AutofillAssistantModelExecutor::InitializeTypesTokenizer( + const std::string& pattern, + const std::string& vocabulary) { + DCHECK(!pattern.empty()); + DCHECK(!vocabulary.empty()); + types_tokenizer_ = + std::make_unique<tflite::support::text::tokenizer::RegexTokenizer>( + pattern, vocabulary.data(), vocabulary.size()); +} + +void AutofillAssistantModelExecutor::InitializeTextTokenizer( + const std::string& pattern, + const std::string& vocabulary) { + DCHECK(!pattern.empty()); + DCHECK(!vocabulary.empty()); + text_tokenizer_ = + std::make_unique<tflite::support::text::tokenizer::RegexTokenizer>( + pattern, vocabulary.data(), vocabulary.size()); +} + +bool AutofillAssistantModelExecutor::Preprocess( + const std::vector<TfLiteTensor*>& input_tensors, + const blink::AutofillAssistantNodeSignals& node_signals) { + DCHECK_GE(input_tensors.size(), 5u); + std::vector<std::vector<float>> inputs; + for (const auto* input_tensor : input_tensors) { + if (!input_tensor->dims || input_tensor->dims->size < 1) { + return false; + } + inputs.emplace_back(std::vector(input_tensor->dims->data[1], 0.0f)); + } + + DCHECK(tags_tokenizer_); + Tokenize(node_signals.node_features.html_tag.Utf16(), tags_tokenizer_.get(), + &inputs[0]); + DCHECK(types_tokenizer_); + Tokenize(node_signals.node_features.type.Utf16(), types_tokenizer_.get(), + &inputs[1]); + DCHECK(text_tokenizer_); + Tokenize(node_signals.node_features.invisible_attributes.Utf16(), + text_tokenizer_.get(), &inputs[2]); + for (const auto& text : node_signals.node_features.text) { + Tokenize(text.Utf16(), text_tokenizer_.get(), &inputs[2]); + } + for (const auto& text : node_signals.label_features.text) { + Tokenize(text.Utf16(), text_tokenizer_.get(), &inputs[3]); + } + for (const auto& text : node_signals.context_features.header_text) { + Tokenize(text.Utf16(), text_tokenizer_.get(), &inputs[4]); + } + + for (size_t i = 0; i < inputs.size(); ++i) { + absl::Status tensor_status = + tflite::task::core::PopulateTensor<float>(inputs[i], input_tensors[i]); + if (!tensor_status.ok()) { + return false; + } + } + return true; +} + +// TODO(b/204841212): Implement this with use of ModelMetadata. +absl::optional<std::string> AutofillAssistantModelExecutor::Postprocess( + const std::vector<const TfLiteTensor*>& output_tensors) { + static const base::NoDestructor<std::vector<std::string>> output_roles( + {"UNKNOWN_ROLE", "NAME_FIRST", "NAME_LAST", "NAME_FULL", "ADDRESS_LINE1", + "ADDRESS_LINE2", "CITY", "STATE", "COUNTRY", "POSTAL_CODE", + "CREDIT_CARD_NUMBER", "CREDIT_CARD_EXP_MONTH", + "CREDIT_CARD_VERIFICATION_CODE", "ORGANIZATION", + "CREDIT_CARD_EXPIRATION", "PHONE_NUMBER", "USERNAME_OR_EMAIL", + "CREDIT_CARD_EXP_YEAR"}); + + DCHECK_GE(output_tensors.size(), 1u); + std::vector<float> data; + absl::Status vector_status = + tflite::task::core::PopulateVector<float>(output_tensors[0], &data); + if (!vector_status.ok()) { + return absl::nullopt; + } + + // TODO(b/204841212): The output is 24 floats, but we only care about the + // the first [0-17]. + DCHECK_GE(data.size(), output_roles->size()); + int index = std::distance( + data.begin(), + std::max_element(data.begin(), data.begin() + output_roles->size())); + return output_roles->at(index); +} + +void AutofillAssistantModelExecutor::Tokenize( + const std::u16string& input, + tflite::support::text::tokenizer::RegexTokenizer* tokenizer, + std::vector<float>* output) { + auto result = + tokenizer->Tokenize(base::UTF16ToUTF8(base::i18n::ToUpper(input))); + for (const auto& token : result.subwords) { + int index; + if (tokenizer->LookupId(token, &index)) { + if (static_cast<size_t>(index) >= output->size()) { + NOTREACHED(); + continue; + } + ++output->at(index); + } + } +} + +} // namespace autofill_assistant
diff --git a/components/autofill_assistant/content/renderer/autofill_assistant_model_executor.h b/components/autofill_assistant/content/renderer/autofill_assistant_model_executor.h new file mode 100644 index 0000000..da9cde8 --- /dev/null +++ b/components/autofill_assistant/content/renderer/autofill_assistant_model_executor.h
@@ -0,0 +1,98 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_AUTOFILL_ASSISTANT_CONTENT_RENDERER_AUTOFILL_ASSISTANT_MODEL_EXECUTOR_H_ +#define COMPONENTS_AUTOFILL_ASSISTANT_CONTENT_RENDERER_AUTOFILL_ASSISTANT_MODEL_EXECUTOR_H_ + +#include <string> +#include <vector> + +#include "base/files/file.h" +#include "base/files/memory_mapped_file.h" +#include "components/autofill_assistant/content/renderer/model_metadata.pb.h" +#include "components/optimization_guide/core/base_model_executor.h" +#include "components/optimization_guide/core/base_model_executor_helpers.h" +#include "third_party/abseil-cpp/absl/types/optional.h" +#include "third_party/blink/public/web/modules/autofill_assistant/node_signals.h" +#include "third_party/tflite/src/tensorflow/lite/c/common.h" +#include "third_party/tflite_support/src/tensorflow_lite_support/cc/task/core/base_task_api.h" +#include "third_party/tflite_support/src/tensorflow_lite_support/cc/task/core/tflite_engine.h" +#include "third_party/tflite_support/src/tensorflow_lite_support/cc/text/tokenizers/regex_tokenizer.h" + +namespace autofill_assistant { + +// Holds and executes the AnnotateDOM model to predict semantic roles based on +// node signals. +class AutofillAssistantModelExecutor + : public optimization_guide::BaseModelExecutor< + std::string, + const blink::AutofillAssistantNodeSignals&> { + public: + using ExecutionTask = optimization_guide::GenericModelExecutionTask< + std::string, + const blink::AutofillAssistantNodeSignals&>; + + AutofillAssistantModelExecutor(); + ~AutofillAssistantModelExecutor() override; + + AutofillAssistantModelExecutor(const AutofillAssistantModelExecutor&) = + delete; + void operator=(const AutofillAssistantModelExecutor&) = delete; + + // Initialize the model from the |model_file|. Sets |model_initialized_|. + bool InitializeModelFromFile(base::File model_file); + + // Execute the model with the given input. + absl::optional<std::string> ExecuteModelWithInput( + const blink::AutofillAssistantNodeSignals& node_signals); + + protected: + // optimization_guide::InferenceDelegate: + bool Preprocess( + const std::vector<TfLiteTensor*>& input_tensors, + const blink::AutofillAssistantNodeSignals& node_signals) override; + absl::optional<std::string> Postprocess( + const std::vector<const TfLiteTensor*>& output_tensors) override; + + private: + // Initialize Tokenizers with |pattern| for splitting and the |vocabulary| in + // the form of "<word> <index>" per line. + void InitializeTagsTokenizer(const std::string& pattern, + const std::string& vocabulary); + void InitializeTypesTokenizer(const std::string& pattern, + const std::string& vocabulary); + void InitializeTextTokenizer(const std::string& pattern, + const std::string& vocabulary); + + // Build the execution task from the model file. + void BuildExecutionTask( + std::unique_ptr<tflite::task::core::TfLiteEngine> tflite_engine); + + // Tokenize the |input| and count words into the |output| vector. The |output| + // can be reused for all relevant inputs for a signal. + void Tokenize(const std::u16string& input, + tflite::support::text::tokenizer::RegexTokenizer* tokenizer, + std::vector<float>* output); + + // Tokenizer for HTML tag. + std::unique_ptr<tflite::support::text::tokenizer::RegexTokenizer> + tags_tokenizer_; + // Tokenizer for HTML attribute "type". + std::unique_ptr<tflite::support::text::tokenizer::RegexTokenizer> + types_tokenizer_; + // Tokenizer for arbitrary text. + std::unique_ptr<tflite::support::text::tokenizer::RegexTokenizer> + text_tokenizer_; + + // The task for this executor. + std::unique_ptr<ExecutionTask> execution_task_; + // Model file held in memory by this instance. + base::MemoryMappedFile model_file_; + // Model Metadata for handling input/output. + ModelMetadata model_metadata_; +}; + +} // namespace autofill_assistant + +#endif // COMPONENTS_AUTOFILL_ASSISTANT_CONTENT_RENDERER_AUTOFILL_ASSISTANT_MODEL_EXECUTOR_H_
diff --git a/components/autofill_assistant/content/renderer/autofill_assistant_model_executor_unittest.cc b/components/autofill_assistant/content/renderer/autofill_assistant_model_executor_unittest.cc new file mode 100644 index 0000000..0074e50f --- /dev/null +++ b/components/autofill_assistant/content/renderer/autofill_assistant_model_executor_unittest.cc
@@ -0,0 +1,88 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/autofill_assistant/content/renderer/autofill_assistant_model_executor.h" + +#include <fstream> +#include <string> +#include <vector> + +#include "base/files/file.h" +#include "base/files/file_path.h" +#include "base/path_service.h" +#include "base/strings/strcat.h" +#include "base/strings/string_number_conversions.h" +#include "base/strings/string_util.h" +#include "components/autofill_assistant/content/renderer/autofill_assistant_model_executor.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/public/platform/web_string.h" +#include "third_party/blink/public/platform/web_vector.h" +#include "third_party/blink/public/web/modules/autofill_assistant/node_signals.h" + +namespace autofill_assistant { +namespace { + +class AutofillAssistantModelExecutorTest : public testing::Test { + public: + AutofillAssistantModelExecutorTest() { + base::FilePath model_file_path = + GetTestDataDir().AppendASCII("model.tflite"); + model_file_ = base::File(model_file_path, + (base::File::FLAG_OPEN | base::File::FLAG_READ)); + } + + ~AutofillAssistantModelExecutorTest() override = default; + + protected: + base::File model_file_; + AutofillAssistantModelExecutor model_executor_; + + private: + base::FilePath GetTestDataDir() { + base::FilePath source_root_dir; + base::PathService::Get(base::DIR_SOURCE_ROOT, &source_root_dir); + return source_root_dir.AppendASCII("components") + .AppendASCII("test") + .AppendASCII("data") + .AppendASCII("autofill_assistant") + .AppendASCII("model"); + } +}; + +TEST_F(AutofillAssistantModelExecutorTest, DoesNotInitializeFromEmptyFile) { + EXPECT_FALSE(model_executor_.InitializeModelFromFile(base::File())); +} + +TEST_F(AutofillAssistantModelExecutorTest, OnlyInitializesModelOnce) { + EXPECT_TRUE(model_executor_.InitializeModelFromFile(model_file_.Duplicate())); + EXPECT_FALSE( + model_executor_.InitializeModelFromFile(model_file_.Duplicate())); +} + +TEST_F(AutofillAssistantModelExecutorTest, ExecuteWithLoadedModel) { + ASSERT_TRUE(model_executor_.InitializeModelFromFile(model_file_.Duplicate())); + + blink::AutofillAssistantNodeSignals node_signals; + node_signals.node_features.html_tag = blink::WebString::FromUTF8("INPUT"); + node_signals.node_features.type = blink::WebString::FromUTF8("TEXT"); + node_signals.node_features.text.push_back( + blink::WebString::FromUTF8("street")); + node_signals.label_features.text.push_back( + blink::WebString::FromUTF8("Street Address:")); + node_signals.label_features.text.push_back( + blink::WebString::FromUTF8("Line 1")); + node_signals.context_features.header_text.push_back( + blink::WebString::FromUTF8("Street Address")); + node_signals.context_features.header_text.push_back( + blink::WebString::FromUTF8("Checkout")); + node_signals.context_features.header_text.push_back( + blink::WebString::FromUTF8("SHIPPING")); + + EXPECT_EQ(model_executor_.ExecuteModelWithInput(node_signals), + "ADDRESS_LINE1"); +} + +} // namespace +} // namespace autofill_assistant
diff --git a/components/exo/wayland/clients/test/wayland_client_test_server.cc b/components/exo/wayland/clients/test/wayland_client_test_server.cc index b641b74..1956e50 100644 --- a/components/exo/wayland/clients/test/wayland_client_test_server.cc +++ b/components/exo/wayland/clients/test/wayland_client_test_server.cc
@@ -38,6 +38,9 @@ base::Thread client_thread("ClientThread"); client_thread.Start(); + // |task_environment_| main thread will be ClientThread while running tests. + task_environment_->DetachFromThread(); + base::RunLoop run_loop; client_thread.task_runner()->PostTask( FROM_HERE, @@ -45,6 +48,10 @@ base::Unretained(this), run_loop.QuitWhenIdleClosure())); run_loop.Run(); + // |task_environment_| destruction will be performed on the test suite's main + // thread, detach from the ClientThread. + task_environment_->DetachFromThread(); + Shutdown(); return result_; }
diff --git a/components/nacl/common/nacl_messages.h b/components/nacl/common/nacl_messages.h index 26376ca..1dba681 100644 --- a/components/nacl/common/nacl_messages.h +++ b/components/nacl/common/nacl_messages.h
@@ -4,6 +4,7 @@ // Defines messages between the browser and NaCl process. +// no-include-guard-because-multiply-included // Multiply-included message file, no traditional include guard. #include <stdint.h> @@ -29,12 +30,6 @@ #if BUILDFLAG(IS_POSIX) IPC_STRUCT_TRAITS_MEMBER(debug_stub_server_bound_socket) #endif -#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) - IPC_STRUCT_TRAITS_MEMBER(ppapi_browser_channel_handle) - IPC_STRUCT_TRAITS_MEMBER(ppapi_renderer_channel_handle) - IPC_STRUCT_TRAITS_MEMBER(trusted_service_channel_handle) - IPC_STRUCT_TRAITS_MEMBER(manifest_service_channel_handle) -#endif IPC_STRUCT_TRAITS_MEMBER(validation_cache_enabled) IPC_STRUCT_TRAITS_MEMBER(validation_cache_key) IPC_STRUCT_TRAITS_MEMBER(version) @@ -129,8 +124,6 @@ // Notify the browser process that the server side of the PPAPI channel was // created successfully. -// This is used for SFI mode only. Non-SFI mode passes channel handles in -// NaClStartParams instead. IPC_MESSAGE_CONTROL5( NaClProcessHostMsg_PpapiChannelsCreated, IPC::ChannelHandle, /* browser_channel_handle */
diff --git a/components/nacl/common/nacl_types.h b/components/nacl/common/nacl_types.h index 6c2d18ef..426f8904 100644 --- a/components/nacl/common/nacl_types.h +++ b/components/nacl/common/nacl_types.h
@@ -85,18 +85,6 @@ IPC::PlatformFileForTransit debug_stub_server_bound_socket; #endif -#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) - // These are for Non-SFI mode IPC channels. - // For security hardening, unlike in SFI mode, we cannot create socket pairs - // in a NaCl loader process. Thus, the browser process creates the - // ChannelHandle instances, and passes them to the NaCl loader process. - // SFI mode uses NaClProcessHostMsg_PpapiChannelsCreated instead. - IPC::ChannelHandle ppapi_browser_channel_handle; - IPC::ChannelHandle ppapi_renderer_channel_handle; - IPC::ChannelHandle trusted_service_channel_handle; - IPC::ChannelHandle manifest_service_channel_handle; -#endif - bool validation_cache_enabled; std::string validation_cache_key; // Chrome version string. Sending the version string over IPC avoids linkage
diff --git a/components/nacl/loader/DEPS b/components/nacl/loader/DEPS index 5aa3158..599397f 100644 --- a/components/nacl/loader/DEPS +++ b/components/nacl/loader/DEPS
@@ -29,9 +29,6 @@ "+ppapi/proxy/nacl_message_scanner.h", "+ppapi/proxy/serialized_handle.h", - # For setting FDs in non-SFI mode. - "+ppapi/nacl_irt", - # For sending PpapiHostMsg_ChannelCreated in nacl_ipc_adapter.cc: "+ppapi/proxy/ppapi_messages.h", ]
diff --git a/components/nacl/loader/nacl_helper_linux.cc b/components/nacl/loader/nacl_helper_linux.cc index 49c681c..51e72f8 100644 --- a/components/nacl/loader/nacl_helper_linux.cc +++ b/components/nacl/loader/nacl_helper_linux.cc
@@ -359,9 +359,6 @@ // dynamic linker's structure into the address provided by the option. // Hereafter, if someone attaches a debugger (or examines a core dump), // the debugger will find all the symbols in the normal way. -// -// Non-SFI mode does not use nacl_helper_bootstrap, so it doesn't need to -// process the --r_debug option. static void CheckRDebug(char* argv0) { std::string r_debug_switch_value = base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
diff --git a/components/nacl/loader/nacl_trusted_listener.cc b/components/nacl/loader/nacl_trusted_listener.cc index 4ad4ad6..b3014e0f 100644 --- a/components/nacl/loader/nacl_trusted_listener.cc +++ b/components/nacl/loader/nacl_trusted_listener.cc
@@ -30,9 +30,8 @@ // element was removed (perhaps implicitly if the tab was closed) or because // the renderer crashed. The NaCl loader process should therefore exit. // - // For SFI NaCl, trusted code does this exit voluntarily, but untrusted - // code cannot disable it. However, for Non-SFI NaCl, the following exit - // call could be disabled by untrusted code. + // Trusted code does this exit voluntarily, but untrusted code cannot + // disable it. NaClExit(0); } };
diff --git a/components/nacl/renderer/ppb_nacl_private.h b/components/nacl/renderer/ppb_nacl_private.h index 5ba352a2..2eb30bcc 100644 --- a/components/nacl/renderer/ppb_nacl_private.h +++ b/components/nacl/renderer/ppb_nacl_private.h
@@ -219,8 +219,8 @@ public: /* Launches NaCl's sel_ldr process. Returns PP_EXTERNAL_PLUGIN_OK on success. * Returns PP_EXTERNAL_PLUGIN_FAILED on failure. - * The |nexe_file_info| is currently used only in non-SFI mode. It is the - * file handle for the main nexe file, which should be initially loaded. + * The |nexe_file_info| is the file handle for the main nexe file, which + * should be initially loaded. * LaunchSelLdr takes the ownership of the file handle. * |translator_channel| is filled out when launching PNaCl translator * processes.
diff --git a/components/optimization_guide/features.gni b/components/optimization_guide/features.gni index 26d60df..1695d00 100644 --- a/components/optimization_guide/features.gni +++ b/components/optimization_guide/features.gni
@@ -13,6 +13,8 @@ # You can set the variable 'build_with_internal_optimization_guide' to true # even in a developer build in args.gn. Setting this variable explicitly to true will # cause your build to fail if the internal files are missing. - build_with_internal_optimization_guide = - is_chrome_branded && !is_android && !is_ios + build_with_internal_optimization_guide = false + + # TODO(crbug/1266935): Add this back when the API boundary is sane again. + # is_chrome_branded && !is_android && !is_ios }
diff --git a/components/printing/renderer/print_render_frame_helper.cc b/components/printing/renderer/print_render_frame_helper.cc index d046a79..ae23ffe 100644 --- a/components/printing/renderer/print_render_frame_helper.cc +++ b/components/printing/renderer/print_render_frame_helper.cc
@@ -52,7 +52,6 @@ #include "third_party/blink/public/platform/scheduler/web_agent_group_scheduler.h" #include "third_party/blink/public/platform/scheduler/web_thread_scheduler.h" #include "third_party/blink/public/platform/web_data.h" -#include "third_party/blink/public/platform/web_double_size.h" #include "third_party/blink/public/platform/web_url.h" #include "third_party/blink/public/platform/web_url_request.h" #include "third_party/blink/public/web/web_console_message.h" @@ -172,9 +171,9 @@ int dpi = GetDPI(page_params); blink::WebPrintPageDescription description; - description.size = blink::WebDoubleSize( - ConvertUnitDouble(page_params.page_size.width(), dpi, kPixelsPerInch), - ConvertUnitDouble(page_params.page_size.height(), dpi, kPixelsPerInch)); + description.size.SetSize( + ConvertUnitFloat(page_params.page_size.width(), dpi, kPixelsPerInch), + ConvertUnitFloat(page_params.page_size.height(), dpi, kPixelsPerInch)); description.margin_top = ConvertUnit(page_params.margin_top, dpi, kPixelsPerInch); description.margin_right = ConvertUnit(page_params.page_size.width() - @@ -191,11 +190,10 @@ if (frame) frame->GetPageDescription(page_index, &description); - double new_content_width = description.size.Width() - - description.margin_left - description.margin_right; - double new_content_height = description.size.Height() - - description.margin_top - - description.margin_bottom; + float new_content_width = description.size.width() - description.margin_left - + description.margin_right; + float new_content_height = description.size.height() - + description.margin_top - description.margin_bottom; // Invalid page size and/or margins. We just use the default setting. if (new_content_width < 1 || new_content_height < 1) { @@ -208,8 +206,8 @@ FromBlinkPageOrientation(description.orientation); page_css_params->page_size = - gfx::Size(ConvertUnit(description.size.Width(), kPixelsPerInch, dpi), - ConvertUnit(description.size.Height(), kPixelsPerInch, dpi)); + gfx::Size(ConvertUnit(description.size.width(), kPixelsPerInch, dpi), + ConvertUnit(description.size.height(), kPixelsPerInch, dpi)); page_css_params->content_size = gfx::Size(ConvertUnit(new_content_width, kPixelsPerInch, dpi), ConvertUnit(new_content_height, kPixelsPerInch, dpi));
diff --git a/components/privacy_sandbox/privacy_sandbox_settings.cc b/components/privacy_sandbox/privacy_sandbox_settings.cc index 95fc1ed..b739a16 100644 --- a/components/privacy_sandbox/privacy_sandbox_settings.cc +++ b/components/privacy_sandbox/privacy_sandbox_settings.cc
@@ -72,7 +72,7 @@ PrivacySandboxSettings::PrivacySandboxSettings( HostContentSettingsMap* host_content_settings_map, - content_settings::CookieSettings* cookie_settings, + scoped_refptr<content_settings::CookieSettings> cookie_settings, PrefService* pref_service) : host_content_settings_map_(host_content_settings_map), cookie_settings_(cookie_settings),
diff --git a/components/privacy_sandbox/privacy_sandbox_settings.h b/components/privacy_sandbox/privacy_sandbox_settings.h index c06be5c..ceb8bc25 100644 --- a/components/privacy_sandbox/privacy_sandbox_settings.h +++ b/components/privacy_sandbox/privacy_sandbox_settings.h
@@ -39,9 +39,10 @@ virtual void OnFlocDataAccessibleSinceUpdated(bool reset_compute_timer) = 0; }; - PrivacySandboxSettings(HostContentSettingsMap* host_content_settings_map, - content_settings::CookieSettings* cookie_settings, - PrefService* pref_service); + PrivacySandboxSettings( + HostContentSettingsMap* host_content_settings_map, + scoped_refptr<content_settings::CookieSettings> cookie_settings, + PrefService* pref_service); ~PrivacySandboxSettings() override; // Returns whether FLoC is allowed at all. If false, FLoC calculations should @@ -146,7 +147,7 @@ base::ObserverList<Observer>::Unchecked observers_; raw_ptr<HostContentSettingsMap> host_content_settings_map_; - raw_ptr<content_settings::CookieSettings> cookie_settings_; + scoped_refptr<content_settings::CookieSettings> cookie_settings_; raw_ptr<PrefService> pref_service_; };
diff --git a/components/privacy_sandbox/privacy_sandbox_settings_unittest.cc b/components/privacy_sandbox/privacy_sandbox_settings_unittest.cc index 08744a2..634232e 100644 --- a/components/privacy_sandbox/privacy_sandbox_settings_unittest.cc +++ b/components/privacy_sandbox/privacy_sandbox_settings_unittest.cc
@@ -41,7 +41,7 @@ InitializePrefsBeforeStart(); privacy_sandbox_settings_ = std::make_unique<PrivacySandboxSettings>( - host_content_settings_map(), cookie_settings(), prefs()); + host_content_settings_map(), cookie_settings_, prefs()); } virtual void InitializePrefsBeforeStart() {}
diff --git a/components/sync/base/model_type.cc b/components/sync/base/model_type.cc index e56e568..c434931 100644 --- a/components/sync/base/model_type.cc +++ b/components/sync/base/model_type.cc
@@ -31,7 +31,7 @@ // String value for Model Type // This should be the same as the model type but space separated and the // first letter of every word capitalized. - const char* const model_type_string; + const char* const model_type_debug_string; // Field number of the model type specifics in EntitySpecifics. const int specifics_field_number; // Model type value from SyncModelTypes enum in enums.xml. Must always be in @@ -182,7 +182,8 @@ void AddDefaultFieldValue(ModelType type, sync_pb::EntitySpecifics* specifics) { switch (type) { case UNSPECIFIED: - NOTREACHED() << "No default field value for " << ModelTypeToString(type); + NOTREACHED() << "No default field value for " + << ModelTypeToDebugString(type); break; case BOOKMARKS: specifics->mutable_bookmark(); @@ -272,7 +273,8 @@ specifics->mutable_send_tab_to_self(); break; case PROXY_TABS: - NOTREACHED() << "No default field value for " << ModelTypeToString(type); + NOTREACHED() << "No default field value for " + << ModelTypeToDebugString(type); break; case NIGORI: specifics->mutable_nigori(); @@ -419,11 +421,9 @@ return encryptable_user_types; } -const char* ModelTypeToString(ModelType model_type) { - // This is used in serialization routines as well as for displaying debug - // information. Do not attempt to change these string values unless you know - // what you're doing. - return kModelTypeInfoMap[model_type].model_type_string; +const char* ModelTypeToDebugString(ModelType model_type) { + // This is used for displaying debug information. + return kModelTypeInfoMap[model_type].model_type_debug_string; } const char* ModelTypeToHistogramSuffix(ModelType model_type) { @@ -442,13 +442,13 @@ } std::unique_ptr<base::Value> ModelTypeToValue(ModelType model_type) { - return std::make_unique<base::Value>(ModelTypeToString(model_type)); + return std::make_unique<base::Value>(ModelTypeToDebugString(model_type)); } -ModelType ModelTypeFromString(const std::string& model_type_string) { +ModelType ModelTypeFromDebugString(const std::string& model_type_string) { auto* iter = base::ranges::find( kModelTypeInfoMap, model_type_string, - [](const ModelTypeInfo& info) { return info.model_type_string; }); + [](const ModelTypeInfo& info) { return info.model_type_debug_string; }); return iter != std::end(kModelTypeInfoMap) ? iter->model_type : UNSPECIFIED; } @@ -458,7 +458,7 @@ if (!result.empty()) { result += ", "; } - result += ModelTypeToString(type); + result += ModelTypeToDebugString(type); } return result; } @@ -484,7 +484,7 @@ } else { type_str = working_copy.substr(0, end); } - ModelType type = ModelTypeFromString(type_str); + ModelType type = ModelTypeFromDebugString(type_str); if (IsRealDataType(type)) model_types.Put(type); working_copy = working_copy.substr(end + 1); @@ -495,7 +495,7 @@ std::unique_ptr<base::ListValue> ModelTypeSetToValue(ModelTypeSet model_types) { std::unique_ptr<base::ListValue> value(new base::ListValue()); for (ModelType type : model_types) { - value->Append(ModelTypeToString(type)); + value->Append(ModelTypeToDebugString(type)); } return value; }
diff --git a/components/sync/base/model_type.h b/components/sync/base/model_type.h index f4255cf..a2855bd 100644 --- a/components/sync/base/model_type.h +++ b/components/sync/base/model_type.h
@@ -363,7 +363,7 @@ // Returns a string with application lifetime that represents the name of // |model_type|. -const char* ModelTypeToString(ModelType model_type); +const char* ModelTypeToDebugString(ModelType model_type); // Returns a string with application lifetime that is used as the histogram // suffix for |model_type|. @@ -383,7 +383,7 @@ std::unique_ptr<base::Value> ModelTypeToValue(ModelType model_type); // Returns the ModelType corresponding to the name |model_type_string|. -ModelType ModelTypeFromString(const std::string& model_type_string); +ModelType ModelTypeFromDebugString(const std::string& model_type_string); // Returns the comma-separated string representation of |model_types|. std::string ModelTypeSetToDebugString(ModelTypeSet model_types);
diff --git a/components/sync/base/model_type_unittest.cc b/components/sync/base/model_type_unittest.cc index 2a790e5c..58c81fc6 100644 --- a/components/sync/base/model_type_unittest.cc +++ b/components/sync/base/model_type_unittest.cc
@@ -21,7 +21,7 @@ TEST_F(ModelTypeTest, ModelTypeToValue) { for (int i = 0; i < GetNumModelTypes(); ++i) { ModelType model_type = ModelTypeFromInt(i); - base::ExpectStringValue(ModelTypeToString(model_type), + base::ExpectStringValue(ModelTypeToDebugString(model_type), *ModelTypeToValue(model_type)); } } @@ -68,7 +68,7 @@ std::set<ModelTypeForHistograms> histogram_values; ModelTypeSet all_types = ModelTypeSet::All(); for (ModelType type : all_types) { - SCOPED_TRACE(ModelTypeToString(type)); + SCOPED_TRACE(ModelTypeToDebugString(type)); ModelTypeForHistograms histogram_value = ModelTypeHistogramValue(type); EXPECT_TRUE(histogram_values.insert(histogram_value).second) @@ -83,7 +83,7 @@ std::set<int> identifiers; ModelTypeSet all_types = ModelTypeSet::All(); for (ModelType type : all_types) { - SCOPED_TRACE(ModelTypeToString(type)); + SCOPED_TRACE(ModelTypeToDebugString(type)); int stable_identifier = ModelTypeToStableIdentifier(type); EXPECT_GT(stable_identifier, 0); EXPECT_TRUE(identifiers.insert(stable_identifier).second) @@ -111,7 +111,7 @@ TEST_F(ModelTypeTest, DefaultFieldValues) { ModelTypeSet types = ProtocolTypes(); for (ModelType type : types) { - SCOPED_TRACE(ModelTypeToString(type)); + SCOPED_TRACE(ModelTypeToDebugString(type)); sync_pb::EntitySpecifics specifics; AddDefaultFieldValue(type, &specifics); @@ -143,8 +143,9 @@ TEST_F(ModelTypeTest, ModelTypeStringMapping) { ModelTypeSet all_types = ModelTypeSet::All(); for (ModelType model_type : all_types) { - const char* model_type_string = ModelTypeToString(model_type); - ModelType converted_model_type = ModelTypeFromString(model_type_string); + const char* model_type_string = ModelTypeToDebugString(model_type); + ModelType converted_model_type = + ModelTypeFromDebugString(model_type_string); if (IsRealDataType(model_type)) EXPECT_EQ(converted_model_type, model_type); else
diff --git a/components/sync/base/progress_marker_map.cc b/components/sync/base/progress_marker_map.cc index 78787b5..9056856 100644 --- a/components/sync/base/progress_marker_map.cc +++ b/components/sync/base/progress_marker_map.cc
@@ -19,7 +19,7 @@ base::EscapeJSONString(progress_marker, false /* put_in_quotes */, &printable_payload); base::Base64Encode(printable_payload, &printable_payload); - value->SetString(ModelTypeToString(model_type), printable_payload); + value->SetString(ModelTypeToDebugString(model_type), printable_payload); } return value; }
diff --git a/components/sync/driver/data_type_controller.h b/components/sync/driver/data_type_controller.h index 7521af4..069fa89 100644 --- a/components/sync/driver/data_type_controller.h +++ b/components/sync/driver/data_type_controller.h
@@ -86,7 +86,7 @@ virtual void Stop(ShutdownReason shutdown_reason, StopCallback callback) = 0; // Name of this data type. For logging purposes only. - std::string name() const { return ModelTypeToString(type()); } + std::string name() const { return ModelTypeToDebugString(type()); } // Current state of the data type controller. virtual State state() const = 0;
diff --git a/components/sync/driver/model_load_manager.cc b/components/sync/driver/model_load_manager.cc index 7162d80f..ce8e990 100644 --- a/components/sync/driver/model_load_manager.cc +++ b/components/sync/driver/model_load_manager.cc
@@ -170,7 +170,7 @@ void ModelLoadManager::ModelLoadCallback(ModelType type, const SyncError& error) { DVLOG(1) << "ModelLoadManager: ModelLoadCallback for " - << ModelTypeToString(type); + << ModelTypeToDebugString(type); if (error.IsSet()) { DVLOG(1) << "ModelLoadManager: Type encountered an error.";
diff --git a/components/sync/driver/model_type_controller.cc b/components/sync/driver/model_type_controller.cc index c53e1a1..fb71e1c 100644 --- a/components/sync/driver/model_type_controller.cc +++ b/components/sync/driver/model_type_controller.cc
@@ -84,11 +84,11 @@ DCHECK_EQ(NOT_RUNNING, state_); auto it = delegate_map_.find(configure_context.sync_mode); - DCHECK(it != delegate_map_.end()) << ModelTypeToString(type()); + DCHECK(it != delegate_map_.end()) << ModelTypeToDebugString(type()); delegate_ = it->second.get(); DCHECK(delegate_); - DVLOG(1) << "Sync starting for " << ModelTypeToString(type()); + DVLOG(1) << "Sync starting for " << ModelTypeToDebugString(type()); state_ = MODEL_STARTING; model_load_callback_ = model_load_callback; @@ -117,7 +117,7 @@ DCHECK_EQ(MODEL_LOADED, state_); state_ = RUNNING; - DVLOG(1) << "Sync running for " << ModelTypeToString(type()); + DVLOG(1) << "Sync running for " << ModelTypeToDebugString(type()); return std::move(activation_response_); } @@ -156,7 +156,7 @@ case MODEL_STARTING: DCHECK(model_load_callback_); DCHECK(model_stop_callbacks_.empty()); - DLOG(WARNING) << "Deferring stop for " << ModelTypeToString(type()) + DLOG(WARNING) << "Deferring stop for " << ModelTypeToDebugString(type()) << " because it's still starting"; model_load_callback_.Reset(); model_stop_metadata_fate_ = metadata_fate; @@ -167,7 +167,7 @@ case MODEL_LOADED: case RUNNING: - DVLOG(1) << "Stopping sync for " << ModelTypeToString(type()); + DVLOG(1) << "Stopping sync for " << ModelTypeToDebugString(type()); model_load_callback_.Reset(); state_ = NOT_RUNNING; delegate_->OnSyncStopping(metadata_fate); @@ -275,7 +275,7 @@ [[fallthrough]]; case FAILED: DVLOG(1) << "Successful sync start completion received late for " - << ModelTypeToString(type()) + << ModelTypeToDebugString(type()) << ", it has been stopped meanwhile"; delegate_->OnSyncStopping(model_stop_metadata_fate_); delegate_ = nullptr; @@ -285,12 +285,12 @@ // Hold on to the activation context until Connect is called. activation_response_ = std::move(activation_response); state_ = MODEL_LOADED; - DVLOG(1) << "Sync start completed for " << ModelTypeToString(type()); + DVLOG(1) << "Sync start completed for " << ModelTypeToDebugString(type()); break; case MODEL_LOADED: case RUNNING: case NOT_RUNNING: - NOTREACHED() << " type " << ModelTypeToString(type()) << " state " + NOTREACHED() << " type " << ModelTypeToDebugString(type()) << " state " << StateToString(state_); }
diff --git a/components/sync/driver/startup_controller.cc b/components/sync/driver/startup_controller.cc index 8b30c9b..af155dc 100644 --- a/components/sync/driver/startup_controller.cc +++ b/components/sync/driver/startup_controller.cc
@@ -224,7 +224,7 @@ void StartupController::OnDataTypeRequestsSyncStartup(ModelType type) { if (!IsDeferredStartupEnabled()) { DVLOG(2) << "Ignoring data type request for sync startup: " - << ModelTypeToString(type); + << ModelTypeToDebugString(type); return; } @@ -232,7 +232,8 @@ return; } - DVLOG(2) << "Data type requesting sync startup: " << ModelTypeToString(type); + DVLOG(2) << "Data type requesting sync startup: " + << ModelTypeToDebugString(type); if (!start_up_time_.is_null()) { RecordTimeDeferred(DeferredInitTrigger::kDataTypeRequest); }
diff --git a/components/sync/driver/sync_service_impl.cc b/components/sync/driver/sync_service_impl.cc index d685d46..0e3f414 100644 --- a/components/sync/driver/sync_service_impl.cc +++ b/components/sync/driver/sync_service_impl.cc
@@ -413,7 +413,7 @@ // We can get here as datatype SyncableServices are typically wired up // to the native datatype even if sync isn't enabled. DVLOG(1) << "Dropping sync startup request because type " - << ModelTypeToString(type) << "not enabled."; + << ModelTypeToDebugString(type) << "not enabled."; return; } @@ -1306,7 +1306,7 @@ for (const auto& [type, controller] : data_type_controllers_) { auto type_status = std::make_unique<base::DictionaryValue>(); - type_status->SetString("name", ModelTypeToString(type)); + type_status->SetString("name", ModelTypeToDebugString(type)); if (data_type_error_map_.find(type) != data_type_error_map_.end()) { const SyncError& error = data_type_error_map_.find(type)->second; @@ -1577,7 +1577,7 @@ // Add these results to our list. base::DictionaryValue type_dict; - type_dict.SetKey("type", base::Value(ModelTypeToString(type))); + type_dict.SetKey("type", base::Value(ModelTypeToDebugString(type))); type_dict.SetKey("nodes", base::Value::FromUniquePtrValue(std::move(node_list))); result_accumulator_->Append(std::move(type_dict));
diff --git a/components/sync/engine/commit.cc b/components/sync/engine/commit.cc index 1b84177..dcaaa12 100644 --- a/components/sync/engine/commit.cc +++ b/components/sync/engine/commit.cc
@@ -218,7 +218,7 @@ // Let the contributors process the responses to each of their requests. SyncerError processing_result = SyncerError(SyncerError::SYNCER_OK); for (const auto& [type, contributions] : contributions_) { - const char* model_type_str = ModelTypeToString(type); + const char* model_type_str = ModelTypeToDebugString(type); TRACE_EVENT1("sync", "ProcessCommitResponse", "type", model_type_str); SyncerError type_result = contributions->ProcessCommitResponse(response, status);
diff --git a/components/sync/engine/commit_processor.cc b/components/sync/engine/commit_processor.cc index 2a46d6f..a8ecab9 100644 --- a/components/sync/engine/commit_processor.cc +++ b/components/sync/engine/commit_processor.cc
@@ -109,8 +109,8 @@ } auto cm_it = commit_contributor_map_->find(type); if (cm_it == commit_contributor_map_->end()) { - DLOG(ERROR) << "Could not find requested type " << ModelTypeToString(type) - << " in contributor map."; + DLOG(ERROR) << "Could not find requested type " + << ModelTypeToDebugString(type) << " in contributor map."; return 0; }
diff --git a/components/sync/engine/cycle/nudge_tracker.cc b/components/sync/engine/cycle/nudge_tracker.cc index 009c935..41677e04 100644 --- a/components/sync/engine/cycle/nudge_tracker.cc +++ b/components/sync/engine/cycle/nudge_tracker.cc
@@ -36,7 +36,7 @@ for (ModelType type : types) { TypeTrackerMap::const_iterator tracker_it = type_trackers_.find(type); - DCHECK(tracker_it != type_trackers_.end()) << ModelTypeToString(type); + DCHECK(tracker_it != type_trackers_.end()) << ModelTypeToDebugString(type); if (tracker_it->second->IsSyncRequired()) { return true; } @@ -56,7 +56,7 @@ for (ModelType type : types) { TypeTrackerMap::const_iterator tracker_it = type_trackers_.find(type); - DCHECK(tracker_it != type_trackers_.end()) << ModelTypeToString(type); + DCHECK(tracker_it != type_trackers_.end()) << ModelTypeToDebugString(type); if (tracker_it->second->IsGetUpdatesRequired()) { return true; } @@ -79,7 +79,7 @@ void NudgeTracker::RecordSuccessfulCommitMessage(ModelTypeSet types) { for (ModelType type : types) { TypeTrackerMap::const_iterator tracker_it = type_trackers_.find(type); - DCHECK(tracker_it != type_trackers_.end()) << ModelTypeToString(type); + DCHECK(tracker_it != type_trackers_.end()) << ModelTypeToDebugString(type); tracker_it->second->RecordSuccessfulCommitMessage(); } } @@ -95,7 +95,7 @@ for (ModelType type : types) { TypeTrackerMap::const_iterator tracker_it = type_trackers_.find(type); - DCHECK(tracker_it != type_trackers_.end()) << ModelTypeToString(type); + DCHECK(tracker_it != type_trackers_.end()) << ModelTypeToDebugString(type); tracker_it->second->RecordSuccessfulSyncCycle(); } } @@ -103,7 +103,7 @@ void NudgeTracker::RecordInitialSyncDone(ModelTypeSet types) { for (ModelType type : types) { TypeTrackerMap::const_iterator tracker_it = type_trackers_.find(type); - DCHECK(tracker_it != type_trackers_.end()) << ModelTypeToString(type); + DCHECK(tracker_it != type_trackers_.end()) << ModelTypeToDebugString(type); tracker_it->second->RecordInitialSyncDone(); } } @@ -117,7 +117,7 @@ base::TimeDelta NudgeTracker::RecordLocalRefreshRequest(ModelTypeSet types) { for (ModelType type : types) { TypeTrackerMap::const_iterator tracker_it = type_trackers_.find(type); - DCHECK(tracker_it != type_trackers_.end()) << ModelTypeToString(type); + DCHECK(tracker_it != type_trackers_.end()) << ModelTypeToDebugString(type); tracker_it->second->RecordLocalRefreshRequest(); } return kLocalRefreshDelay; @@ -188,7 +188,7 @@ bool NudgeTracker::IsTypeBlocked(ModelType type) const { DCHECK(type_trackers_.find(type) != type_trackers_.end()) - << ModelTypeToString(type); + << ModelTypeToDebugString(type); return type_trackers_.find(type)->second->IsBlocked(); }
diff --git a/components/sync/engine/cycle/sync_cycle_snapshot.cc b/components/sync/engine/cycle/sync_cycle_snapshot.cc index f2d4d4eb..60bb60cf 100644 --- a/components/sync/engine/cycle/sync_cycle_snapshot.cc +++ b/components/sync/engine/cycle/sync_cycle_snapshot.cc
@@ -121,7 +121,8 @@ type_entries.SetInteger("numToDeleteEntries", num_to_delete_entries_by_type_[type]); - counter_entries.SetKey(ModelTypeToString(type), std::move(type_entries)); + counter_entries.SetKey(ModelTypeToDebugString(type), + std::move(type_entries)); } value->SetKey("counter_entries", std::move(counter_entries)); value->SetBoolean("hasRemainingLocalChanges", has_remaining_local_changes_);
diff --git a/components/sync/engine/get_updates_processor.cc b/components/sync/engine/get_updates_processor.cc index 907c449..abe35fd 100644 --- a/components/sync/engine/get_updates_processor.cc +++ b/components/sync/engine/get_updates_processor.cc
@@ -95,7 +95,7 @@ if (it == updates_by_type->end()) { DLOG(WARNING) << "Received update for unexpected type, or the type is " "throttled or failed with partial failure:" - << ModelTypeToString(type); + << ModelTypeToDebugString(type); continue; } @@ -119,7 +119,7 @@ if (!request_types.Has(model_type)) { DLOG(WARNING) << "Skipping unexpected progress marker for non-enabled type " - << ModelTypeToString(model_type); + << ModelTypeToDebugString(model_type); continue; } index_map->insert(std::make_pair(model_type, i)); @@ -140,7 +140,7 @@ if (!request_types.Has(model_type)) { DLOG(WARNING) << "Skipping unexpected context mutation for non-enabled type " - << ModelTypeToString(model_type); + << ModelTypeToDebugString(model_type); continue; } index_map->insert(std::make_pair(model_type, i)); @@ -203,7 +203,7 @@ for (ModelType type : gu_types) { auto handler_it = update_handler_map_->find(type); DCHECK(handler_it != update_handler_map_->end()) - << "Failed to look up handler for " << ModelTypeToString(type); + << "Failed to look up handler for " << ModelTypeToDebugString(type); sync_pb::DataTypeProgressMarker* progress_marker = get_updates->add_from_progress_marker(); *progress_marker = handler_it->second->GetDownloadProgress(); @@ -342,7 +342,7 @@ context, updates_iter->second, status_controller); } else { DLOG(WARNING) << "Ignoring received updates of a type we can't handle. " - << "Type is: " << ModelTypeToString(type); + << "Type is: " << ModelTypeToDebugString(type); continue; } }
diff --git a/components/sync/engine/loopback_server/loopback_server.cc b/components/sync/engine/loopback_server/loopback_server.cc index 3e71bb1..b155c303 100644 --- a/components/sync/engine/loopback_server/loopback_server.cc +++ b/components/sync/engine/loopback_server/loopback_server.cc
@@ -747,7 +747,7 @@ // Initialize an empty ListValue for all ModelTypes. ModelTypeSet all_types = ModelTypeSet::All(); for (ModelType type : all_types) { - dictionary->SetKey(ModelTypeToString(type), base::ListValue()); + dictionary->SetKey(ModelTypeToDebugString(type), base::ListValue()); } for (const auto& [id, entity] : entities_) { @@ -758,7 +758,7 @@ continue; } base::ListValue* list_value; - if (!dictionary->GetList(ModelTypeToString(entity->GetModelType()), + if (!dictionary->GetList(ModelTypeToDebugString(entity->GetModelType()), &list_value)) { return nullptr; }
diff --git a/components/sync/engine/loopback_server/loopback_server.h b/components/sync/engine/loopback_server/loopback_server.h index 67f1383..a107f2f 100644 --- a/components/sync/engine/loopback_server/loopback_server.h +++ b/components/sync/engine/loopback_server/loopback_server.h
@@ -179,11 +179,11 @@ std::vector<sync_pb::SyncEntity> GetPermanentSyncEntitiesByModelType( syncer::ModelType model_type); - // Creates a DicionaryValue representation of all entities present in the - // server. The dictionary keys are the strings generated by ModelTypeToString - // and the values are ListValues containing StringValue versions of entity - // names. Permanent entities are excluded. Used by test to verify the contents - // of the server state. + // Creates a DictionaryValue representation of all entities present in the + // server. The dictionary keys are the strings generated by + // ModelTypeToDebugString and the values are ListValues containing StringValue + // versions of entity names. Permanent entities are excluded. Used by test to + // verify the contents of the server state. std::unique_ptr<base::DictionaryValue> GetEntitiesAsDictionaryValue(); // Modifies the entity on the server with the given |id|. The entity's
diff --git a/components/sync/engine/loopback_server/persistent_permanent_entity.cc b/components/sync/engine/loopback_server/persistent_permanent_entity.cc index a0c8f4b..a173bb9 100644 --- a/components/sync/engine/loopback_server/persistent_permanent_entity.cc +++ b/components/sync/engine/loopback_server/persistent_permanent_entity.cc
@@ -74,7 +74,7 @@ } string server_tag = syncer::ModelTypeToRootTag(model_type); - string name = syncer::ModelTypeToString(model_type); + string name = syncer::ModelTypeToDebugString(model_type); string id = LoopbackServerEntity::GetTopLevelId(model_type); sync_pb::EntitySpecifics entity_specifics; AddDefaultFieldValue(model_type, &entity_specifics);
diff --git a/components/sync/engine/model_type_registry.cc b/components/sync/engine/model_type_registry.cc index c41f9870..ea32138a1 100644 --- a/components/sync/engine/model_type_registry.cc +++ b/components/sync/engine/model_type_registry.cc
@@ -44,7 +44,8 @@ DCHECK(!activation_response->skip_engine_connection); DCHECK(activation_response->type_processor); - DVLOG(1) << "Enabling an off-thread sync type: " << ModelTypeToString(type); + DVLOG(1) << "Enabling an off-thread sync type: " + << ModelTypeToDebugString(type); auto worker = std::make_unique<ModelTypeWorker>( type, activation_response->model_type_state, @@ -68,7 +69,8 @@ return; } - DVLOG(1) << "Disabling an off-thread sync type: " << ModelTypeToString(type); + DVLOG(1) << "Disabling an off-thread sync type: " + << ModelTypeToDebugString(type); DCHECK(ProtocolTypes().Has(type)); DCHECK(update_handler_map_.find(type) != update_handler_map_.end());
diff --git a/components/sync/engine/model_type_worker.cc b/components/sync/engine/model_type_worker.cc index a0a3c3a..ad6e405 100644 --- a/components/sync/engine/model_type_worker.cc +++ b/components/sync/engine/model_type_worker.cc
@@ -501,7 +501,7 @@ !model_type_state_.encryption_key_name().empty()); DCHECK(entries_pending_decryption_.empty()); - DVLOG(1) << ModelTypeToString(type_) << ": " + DVLOG(1) << ModelTypeToDebugString(type_) << ": " << base::StringPrintf("Delivering %" PRIuS " applicable updates.", pending_updates_.size()); @@ -659,7 +659,7 @@ if (model_type_state_.encryption_key_name().empty()) { return false; } - DLOG(WARNING) << ModelTypeToString(type_) + DLOG(WARNING) << ModelTypeToDebugString(type_) << " : Had encryption disabled but non-empty encryption key " << model_type_state_.encryption_key_name() << ". Setting key to empty."; @@ -675,7 +675,7 @@ std::string default_key_name = cryptographer_->GetDefaultEncryptionKeyName(); DCHECK(!default_key_name.empty()); - DVLOG(1) << ModelTypeToString(type_) << ": Updating encryption key " + DVLOG(1) << ModelTypeToDebugString(type_) << ": Updating encryption key " << model_type_state_.encryption_key_name() << " -> " << default_key_name; model_type_state_.set_encryption_key_name(default_key_name);
diff --git a/components/sync/engine/sync_scheduler_impl.cc b/components/sync/engine/sync_scheduler_impl.cc index 7828df7..45a0643 100644 --- a/components/sync/engine/sync_scheduler_impl.cc +++ b/components/sync/engine/sync_scheduler_impl.cc
@@ -311,7 +311,7 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); SDVLOG(2) << "Scheduling sync because of local change to " - << ModelTypeToString(type); + << ModelTypeToDebugString(type); base::TimeDelta nudge_delay = nudge_tracker_.RecordLocalChange(type); ScheduleNudgeImpl(nudge_delay); } @@ -333,7 +333,7 @@ DCHECK(!syncer_->IsSyncing()); SDVLOG(2) << "Scheduling sync because we received invalidation for " - << ModelTypeToString(model_type); + << ModelTypeToDebugString(model_type); base::TimeDelta nudge_delay = nudge_tracker_.RecordRemoteInvalidation( model_type, std::move(invalidation)); ScheduleNudgeImpl(nudge_delay); @@ -344,7 +344,7 @@ DCHECK(!syncer_->IsSyncing()); SDVLOG(2) << "Scheduling non-blocking initial sync for " - << ModelTypeToString(model_type); + << ModelTypeToDebugString(model_type); nudge_tracker_.RecordInitialSyncRequired(model_type); ScheduleNudgeImpl(base::Seconds(0)); } @@ -811,7 +811,7 @@ base::TimeDelta length = delay_provider_->GetDelay(last_backoff_time); nudge_tracker_.SetTypeBackedOff(type, length, TimeTicks::Now()); - SDVLOG(1) << "Backing off " << ModelTypeToString(type) << " for " + SDVLOG(1) << "Backing off " << ModelTypeToDebugString(type) << " for " << length.InSeconds() << " second."; } RestartWaiting();
diff --git a/components/sync/model/client_tag_based_model_type_processor.cc b/components/sync/model/client_tag_based_model_type_processor.cc index a4ba2d56..e3ee59c 100644 --- a/components/sync/model/client_tag_based_model_type_processor.cc +++ b/components/sync/model/client_tag_based_model_type_processor.cc
@@ -78,11 +78,11 @@ const DataTypeActivationRequest& request, StartCallback start_callback) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DVLOG(1) << "Sync is starting for " << ModelTypeToString(type_); - DCHECK(request.IsValid()) << ModelTypeToString(type_); - DCHECK(start_callback) << ModelTypeToString(type_); - DCHECK(!start_callback_) << ModelTypeToString(type_); - DCHECK(!IsConnected()) << ModelTypeToString(type_); + DVLOG(1) << "Sync is starting for " << ModelTypeToDebugString(type_); + DCHECK(request.IsValid()) << ModelTypeToDebugString(type_); + DCHECK(start_callback) << ModelTypeToDebugString(type_); + DCHECK(!start_callback_) << ModelTypeToDebugString(type_); + DCHECK(!IsConnected()) << ModelTypeToDebugString(type_); start_callback_ = std::move(start_callback); activation_request_ = request; @@ -125,7 +125,7 @@ // TODO(crbug.com/872360): This DCHECK can currently trigger if the user's // persisted Sync metadata is in an inconsistent state. DCHECK(commit_only_ || batch->TakeAllMetadata().empty()) - << ModelTypeToString(type_); + << ModelTypeToDebugString(type_); } DCHECK(model_ready_to_sync_); @@ -354,7 +354,7 @@ void ClientTagBasedModelTypeProcessor::ConnectSync( std::unique_ptr<CommitQueue> worker) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DVLOG(1) << "Successfully connected " << ModelTypeToString(type_); + DVLOG(1) << "Successfully connected " << ModelTypeToDebugString(type_); worker_ = std::move(worker); @@ -365,7 +365,7 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(IsConnected()); - DVLOG(1) << "Disconnecting sync for " << ModelTypeToString(type_); + DVLOG(1) << "Disconnecting sync for " << ModelTypeToDebugString(type_); weak_ptr_factory_for_worker_.InvalidateWeakPtrs(); worker_.reset(); @@ -619,7 +619,7 @@ DCHECK(entity_tracker_) << "Received commit response when entity tracker is null. Type: " - << ModelTypeToString(type_); + << ModelTypeToDebugString(type_); // |error_response_list| is ignored, because all errors are treated as // transientand the processor with eventually retry. @@ -637,7 +637,7 @@ entity_tracker_->GetEntityForTagHash(data.client_tag_hash); if (entity == nullptr) { NOTREACHED() << "Received commit response for missing item." - << " type: " << ModelTypeToString(type_) + << " type: " << ModelTypeToDebugString(type_) << " client_tag_hash: " << data.client_tag_hash; continue; } @@ -858,7 +858,7 @@ UpdateDropReason::kTombstoneInFullUpdate, type_); DLOG(WARNING) << "Ignoring tombstone found during initial update: " << "client_tag_hash = " << client_tag_hash << " for " - << ModelTypeToString(type_); + << ModelTypeToDebugString(type_); continue; } if (bridge_->SupportsGetClientTag() && @@ -867,7 +867,8 @@ SyncRecordModelTypeUpdateDropReason( UpdateDropReason::kInconsistentClientTag, type_); DLOG(WARNING) << "Received unexpected client tag hash: " - << client_tag_hash << " for " << ModelTypeToString(type_); + << client_tag_hash << " for " + << ModelTypeToDebugString(type_); continue; } @@ -878,7 +879,7 @@ SyncRecordModelTypeUpdateDropReason( UpdateDropReason::kCannotGenerateStorageKey, type_); DLOG(WARNING) << "Received entity with invalid update for " - << ModelTypeToString(type_); + << ModelTypeToDebugString(type_); continue; } } @@ -888,7 +889,7 @@ // does. if (entity_tracker_->GetEntityForTagHash(client_tag_hash)) { DLOG(ERROR) << "Received duplicate client_tag_hash " << client_tag_hash - << " for " << ModelTypeToString(type_); + << " for " << ModelTypeToDebugString(type_); } #endif // DCHECK_IS_ON() ProcessorEntity* entity = CreateEntity(storage_key, update.entity); @@ -1108,7 +1109,7 @@ std::unique_ptr<DataBatch> batch) { std::unique_ptr<base::ListValue> all_nodes = std::make_unique<base::ListValue>(); - std::string type_string = ModelTypeToString(type_); + std::string type_string = ModelTypeToDebugString(type_); while (batch->HasNext()) { const auto& [storage_key, data] = batch->Next();
diff --git a/components/sync/model/client_tag_based_remote_update_handler.cc b/components/sync/model/client_tag_based_remote_update_handler.cc index cf221927..477bd878 100644 --- a/components/sync/model/client_tag_based_remote_update_handler.cc +++ b/components/sync/model/client_tag_based_remote_update_handler.cc
@@ -131,7 +131,7 @@ SyncRecordModelTypeUpdateDropReason( UpdateDropReason::kInconsistentClientTag, type_); DLOG(WARNING) << "Received unexpected client tag hash: " << client_tag_hash - << " for " << ModelTypeToString(type_); + << " for " << ModelTypeToDebugString(type_); return nullptr; } @@ -145,7 +145,7 @@ UpdateDropReason::kTombstoneForNonexistentInIncrementalUpdate, type_); DLOG(WARNING) << "Received remote delete for a non-existing item." << " client_tag_hash: " << client_tag_hash << " for " - << ModelTypeToString(type_); + << ModelTypeToDebugString(type_); return nullptr; } @@ -204,8 +204,9 @@ if (!update_is_tombstone && entity_tracker_->model_type_state().encryption_key_name() != update_encryption_key_name) { - DVLOG(2) << ModelTypeToString(type_) << ": Requesting re-encrypt commit " - << update_encryption_key_name << " -> " + DVLOG(2) << ModelTypeToDebugString(type_) + << ": Requesting re-encrypt commit " << update_encryption_key_name + << " -> " << entity_tracker_->model_type_state().encryption_key_name(); entity->IncrementSequenceNumber(base::Time::Now());
diff --git a/components/sync/model/sync_data.cc b/components/sync/model/sync_data.cc index 66a858c9..8ac579b 100644 --- a/components/sync/model/sync_data.cc +++ b/components/sync/model/sync_data.cc
@@ -104,7 +104,7 @@ if (!IsValid()) return "<Invalid SyncData>"; - std::string type = ModelTypeToString(GetDataType()); + std::string type = ModelTypeToDebugString(GetDataType()); std::string specifics; base::JSONWriter::WriteWithOptions(*EntitySpecificsToValue(GetSpecifics()), base::JSONWriter::OPTIONS_PRETTY_PRINT,
diff --git a/components/sync/model/sync_error.cc b/components/sync/model/sync_error.cc index d36ab56..1a577d0 100644 --- a/components/sync/model/sync_error.cc +++ b/components/sync/model/sync_error.cc
@@ -134,8 +134,8 @@ if (!IsSet()) { return std::string(); } - return location_->ToString() + ", " + ModelTypeToString(model_type_) + " " + - GetMessagePrefix() + message_; + return location_->ToString() + ", " + ModelTypeToDebugString(model_type_) + + " " + GetMessagePrefix() + message_; } void SyncError::PrintLogError() const { @@ -147,7 +147,7 @@ location_->line_number(), logSeverity) .stream(), logSeverity >= ::logging::GetMinLogLevel()) - << ModelTypeToString(model_type_) << " " << GetMessagePrefix() + << ModelTypeToDebugString(model_type_) << " " << GetMessagePrefix() << message_; }
diff --git a/components/sync/model/sync_error_unittest.cc b/components/sync/model/sync_error_unittest.cc index 05e9219..1f82fd7 100644 --- a/components/sync/model/sync_error_unittest.cc +++ b/components/sync/model/sync_error_unittest.cc
@@ -133,7 +133,7 @@ base::Location location = FROM_HERE; std::string msg = "test"; ModelType type = PREFERENCES; - std::string expected = std::string(ModelTypeToString(type)) + + std::string expected = std::string(ModelTypeToDebugString(type)) + " datatype error was encountered: " + msg; LOG(INFO) << "Expect " << expected; SyncError error(location, SyncError::DATATYPE_ERROR, msg, type);
diff --git a/components/sync/model/syncable_service_based_bridge.cc b/components/sync/model/syncable_service_based_bridge.cc index da5892e8..0371c52 100644 --- a/components/sync/model/syncable_service_based_bridge.cc +++ b/components/sync/model/syncable_service_based_bridge.cc
@@ -527,7 +527,7 @@ case EntityChange::ACTION_DELETE: { const std::string& storage_key = change->storage_key(); DCHECK_NE(0U, in_memory_store_.count(storage_key)); - DVLOG(1) << ModelTypeToString(type_) + DVLOG(1) << ModelTypeToDebugString(type_) << ": Processing deletion with storage key: " << storage_key; output_sync_change_list.emplace_back( FROM_HERE, SyncChange::ACTION_DELETE, @@ -553,7 +553,7 @@ case EntityChange::ACTION_UPDATE: { const std::string& storage_key = change->data().client_tag_hash.value(); - DVLOG(1) << ModelTypeToString(type_) + DVLOG(1) << ModelTypeToDebugString(type_) << ": Processing add/update with key: " << storage_key; output_sync_change_list.emplace_back(
diff --git a/components/sync/nigori/nigori_model_type_processor.cc b/components/sync/nigori/nigori_model_type_processor.cc index 38f3bfe..b86fbda7 100644 --- a/components/sync/nigori/nigori_model_type_processor.cc +++ b/components/sync/nigori/nigori_model_type_processor.cc
@@ -265,7 +265,7 @@ // data node. root_node->SetString("PARENT_ID", "r"); root_node->SetString("UNIQUE_SERVER_TAG", "Nigori"); - root_node->SetString("modelType", ModelTypeToString(NIGORI)); + root_node->SetString("modelType", ModelTypeToDebugString(NIGORI)); auto all_nodes = std::make_unique<base::ListValue>(); all_nodes->Append(std::move(root_node));
diff --git a/components/sync/test/engine/mock_connection_manager.cc b/components/sync/test/engine/mock_connection_manager.cc index 6b1a312f..a99db970 100644 --- a/components/sync/test/engine/mock_connection_manager.cc +++ b/components/sync/test/engine/mock_connection_manager.cc
@@ -571,7 +571,7 @@ id_string = base::GenerateGUID(); } else { ADD_FAILURE() << " for specifics type " - << ModelTypeToString(model_type); + << ModelTypeToDebugString(model_type); return false; } }
diff --git a/components/sync/test/engine/mock_update_handler.cc b/components/sync/test/engine/mock_update_handler.cc index 898568c..c2d29f3 100644 --- a/components/sync/test/engine/mock_update_handler.cc +++ b/components/sync/test/engine/mock_update_handler.cc
@@ -11,7 +11,7 @@ MockUpdateHandler::MockUpdateHandler(ModelType type) { progress_marker_.set_data_type_id(GetSpecificsFieldNumberFromModelType(type)); const std::string& token_str = - std::string("Mock token: ") + std::string(ModelTypeToString(type)); + std::string("Mock token: ") + std::string(ModelTypeToDebugString(type)); progress_marker_.set_token(token_str); }
diff --git a/components/sync/test/fake_server/fake_server.h b/components/sync/test/fake_server/fake_server.h index 10826a46..9cded10 100644 --- a/components/sync/test/fake_server/fake_server.h +++ b/components/sync/test/fake_server/fake_server.h
@@ -91,10 +91,10 @@ bool GetLastCommitMessage(sync_pb::ClientToServerMessage* message); bool GetLastGetUpdatesMessage(sync_pb::ClientToServerMessage* message); - // Creates a DicionaryValue representation of all entities present in the - // server. The dictionary keys are the strings generated by ModelTypeToString - // and the values are ListValues containing StringValue versions of entity - // names. + // Creates a DictionaryValue representation of all entities present in the + // server. The dictionary keys are the strings generated by + // ModelTypeToDebugString and the values are ListValues containing StringValue + // versions of entity names. std::unique_ptr<base::DictionaryValue> GetEntitiesAsDictionaryValue(); // Returns all entities stored by the server of the given |model_type|.
diff --git a/components/sync/test/fake_server/fake_server_verifier.cc b/components/sync/test/fake_server/fake_server_verifier.cc index 67f5e2f..24cf320 100644 --- a/components/sync/test/fake_server/fake_server_verifier.cc +++ b/components/sync/test/fake_server/fake_server_verifier.cc
@@ -76,7 +76,7 @@ return DictionaryCreationAssertionFailure(); } - string model_type_string = ModelTypeToString(model_type); + string model_type_string = ModelTypeToDebugString(model_type); base::ListValue* entity_list = nullptr; if (!entities->GetList(model_type_string, &entity_list)) { return UnknownTypeAssertionFailure(model_type_string); @@ -100,7 +100,7 @@ return DictionaryCreationAssertionFailure(); } - string model_type_string = ModelTypeToString(model_type); + string model_type_string = ModelTypeToDebugString(model_type); base::ListValue* entity_list = nullptr; size_t actual_count = 0; if (entities->GetList(model_type_string, &entity_list)) {
diff --git a/components/test/data/autofill_assistant/model/model.tflite b/components/test/data/autofill_assistant/model/model.tflite new file mode 100644 index 0000000..f74253d --- /dev/null +++ b/components/test/data/autofill_assistant/model/model.tflite Binary files differ
diff --git a/components/viz/service/display_embedder/compositor_gpu_thread.cc b/components/viz/service/display_embedder/compositor_gpu_thread.cc index 7e8c7b2..f935a02 100644 --- a/components/viz/service/display_embedder/compositor_gpu_thread.cc +++ b/components/viz/service/display_embedder/compositor_gpu_thread.cc
@@ -59,8 +59,8 @@ compositor_thread_device_queue->InitializeForCompositorGpuThread( device_queue->GetVulkanPhysicalDevice(), device_queue->GetVulkanDevice(), device_queue->GetVulkanQueue(), - device_queue->GetVulkanQueueIndex(), - device_queue->enabled_extensions()); + device_queue->GetVulkanQueueIndex(), device_queue->enabled_extensions(), + device_queue->enabled_device_features_2()); vulkan_context_provider = VulkanInProcessContextProvider::CreateForCompositorGpuThread( vulkan_implementation, std::move(compositor_thread_device_queue),
diff --git a/components/webrtc_logging/BUILD.gn b/components/webrtc_logging/BUILD.gn new file mode 100644 index 0000000..7b179842 --- /dev/null +++ b/components/webrtc_logging/BUILD.gn
@@ -0,0 +1,16 @@ +# Copyright 2022 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +source_set("unit_tests") { + testonly = true + + sources = [ "logging_unittest.cc" ] + + deps = [ + "//base", + "//testing/gmock", + "//testing/gtest", + "//third_party/webrtc_overrides:webrtc_component", + ] +}
diff --git a/components/webrtc_logging/DEPS b/components/webrtc_logging/DEPS new file mode 100644 index 0000000..8aba71e1 --- /dev/null +++ b/components/webrtc_logging/DEPS
@@ -0,0 +1,5 @@ +specific_include_rules = { + 'logging_unittest\.cc': [ + "+third_party/webrtc_overrides", + ] +}
diff --git a/jingle/glue/logging_unittest.cc b/components/webrtc_logging/logging_unittest.cc similarity index 78% rename from jingle/glue/logging_unittest.cc rename to components/webrtc_logging/logging_unittest.cc index 451d65a..284a12b 100644 --- a/jingle/glue/logging_unittest.cc +++ b/components/webrtc_logging/logging_unittest.cc
@@ -15,17 +15,17 @@ #include "build/build_config.h" #include "testing/gtest/include/gtest/gtest.h" -// The following include come before including logging.h. It ensures that -// libjingle style logging is used. +// The following #include come before including logging.h. It ensures that +// WebRTC-style logging is used. #define LOGGING_INSIDE_WEBRTC #include "build/build_config.h" #include "third_party/webrtc_overrides/rtc_base/logging.h" #if BUILDFLAG(IS_WIN) -static const wchar_t* const log_file_name = L"libjingle_logging.log"; +static const wchar_t* const log_file_name = L"webrtc_logging.log"; #else -static const char* const log_file_name = "libjingle_logging.log"; +static const char* const log_file_name = "webrtc_logging.log"; #endif static const int kDefaultVerbosity = 0; @@ -76,7 +76,15 @@ return true; } -TEST(LibjingleLogTest, DefaultConfiguration) { +// LibjingleLogTest fail on Android (crbug.com/843104) and Fuchsia +// (crbug.com/1241660). +#if defined(OS_ANDROID) || defined(OS_FUCHSIA) +#define MAYBE_WebRtcTextLogTest DISABLED_WebRtcTextLogTest +#else +#define MAYBE_WebRtcTextLogTest WebRtcTextLogTest +#endif + +TEST(MAYBE_WebRtcTextLogTest, DefaultConfiguration) { ASSERT_TRUE(Initialize(kDefaultVerbosity)); // In the default configuration only warnings and errors should be logged. @@ -95,13 +103,11 @@ EXPECT_TRUE(ContainsString(contents_of_file, AsString(rtc::LS_ERROR))); EXPECT_TRUE(ContainsString(contents_of_file, AsString(rtc::LS_WARNING))); EXPECT_FALSE(ContainsString(contents_of_file, AsString(rtc::LS_INFO))); - EXPECT_FALSE(ContainsString(contents_of_file, - AsString(rtc::LS_VERBOSE))); - EXPECT_FALSE(ContainsString(contents_of_file, - AsString(rtc::LS_SENSITIVE))); + EXPECT_FALSE(ContainsString(contents_of_file, AsString(rtc::LS_VERBOSE))); + EXPECT_FALSE(ContainsString(contents_of_file, AsString(rtc::LS_SENSITIVE))); } -TEST(LibjingleLogTest, InfoConfiguration) { +TEST(MAYBE_WebRtcTextLogTest, InfoConfiguration) { ASSERT_TRUE(Initialize(0)); // 0 == Chrome's 'info' level. // In this configuration everything lower or equal to LS_INFO should be @@ -119,13 +125,10 @@ // Make sure string contains the expected values. EXPECT_TRUE(ContainsString(contents_of_file, AsString(rtc::LS_ERROR))); - EXPECT_TRUE(ContainsString(contents_of_file, - AsString(rtc::LS_WARNING))); + EXPECT_TRUE(ContainsString(contents_of_file, AsString(rtc::LS_WARNING))); EXPECT_FALSE(ContainsString(contents_of_file, AsString(rtc::LS_INFO))); - EXPECT_FALSE(ContainsString(contents_of_file, - AsString(rtc::LS_VERBOSE))); - EXPECT_FALSE(ContainsString(contents_of_file, - AsString(rtc::LS_SENSITIVE))); + EXPECT_FALSE(ContainsString(contents_of_file, AsString(rtc::LS_VERBOSE))); + EXPECT_FALSE(ContainsString(contents_of_file, AsString(rtc::LS_SENSITIVE))); // Also check that the log is proper. EXPECT_TRUE(ContainsString(contents_of_file, "logging_unittest.cc")); @@ -133,7 +136,7 @@ EXPECT_FALSE(ContainsString(contents_of_file, "logging.cc")); } -TEST(LibjingleLogTest, LogEverythingConfiguration) { +TEST(MAYBE_WebRtcTextLogTest, LogEverythingConfiguration) { ASSERT_TRUE(Initialize(2)); // verbosity at level 2 allows LS_SENSITIVE. // In this configuration everything should be logged. @@ -141,8 +144,8 @@ RTC_LOG_V(rtc::LS_WARNING) << AsString(rtc::LS_WARNING); RTC_LOG(LS_INFO) << AsString(rtc::LS_INFO); static const int kFakeError = 1; - RTC_LOG_E(LS_INFO, EN, kFakeError) << "RTC_LOG_E(" << AsString(rtc::LS_INFO) - << ")"; + RTC_LOG_E(LS_INFO, EN, kFakeError) + << "RTC_LOG_E(" << AsString(rtc::LS_INFO) << ")"; RTC_LOG_V(rtc::LS_VERBOSE) << AsString(rtc::LS_VERBOSE); RTC_LOG_V(rtc::LS_SENSITIVE) << AsString(rtc::LS_SENSITIVE); @@ -153,13 +156,10 @@ // Make sure string contains the expected values. EXPECT_TRUE(ContainsString(contents_of_file, AsString(rtc::LS_ERROR))); - EXPECT_TRUE(ContainsString(contents_of_file, - AsString(rtc::LS_WARNING))); + EXPECT_TRUE(ContainsString(contents_of_file, AsString(rtc::LS_WARNING))); EXPECT_TRUE(ContainsString(contents_of_file, AsString(rtc::LS_INFO))); // RTC_LOG_E EXPECT_TRUE(ContainsString(contents_of_file, strerror(kFakeError))); - EXPECT_TRUE(ContainsString(contents_of_file, - AsString(rtc::LS_VERBOSE))); - EXPECT_TRUE(ContainsString(contents_of_file, - AsString(rtc::LS_SENSITIVE))); + EXPECT_TRUE(ContainsString(contents_of_file, AsString(rtc::LS_VERBOSE))); + EXPECT_TRUE(ContainsString(contents_of_file, AsString(rtc::LS_SENSITIVE))); }
diff --git a/content/browser/interest_group/ad_auction_service_impl.cc b/content/browser/interest_group/ad_auction_service_impl.cc index f4b99ae..f379c9a 100644 --- a/content/browser/interest_group/ad_auction_service_impl.cc +++ b/content/browser/interest_group/ad_auction_service_impl.cc
@@ -141,29 +141,30 @@ return false; } - const auto& shareable_config = config.shareable_auction_ad_config; + const auto& non_shared_params = config.auction_ad_config_non_shared_params; // This isn't marked as optional in the Mojo struct, so Mojo should make sure // it is non-null. - DCHECK(shareable_config); + DCHECK(non_shared_params); - if (!shareable_config->interest_group_buyers || - shareable_config->interest_group_buyers->is_all_buyers()) { + if (!non_shared_params->interest_group_buyers || + non_shared_params->interest_group_buyers->is_all_buyers()) { return false; } - DCHECK(shareable_config->interest_group_buyers->is_buyers()); + DCHECK(non_shared_params->interest_group_buyers->is_buyers()); // All interest group owners must be HTTPS. for (const url::Origin& buyer : - shareable_config->interest_group_buyers->get_buyers()) { + non_shared_params->interest_group_buyers->get_buyers()) { if (buyer.scheme() != url::kHttpsScheme) return false; } // All buyer signals must be for listed buyers. - if (shareable_config->per_buyer_signals) { - for (const auto& it : shareable_config->per_buyer_signals.value()) { - if (!base::Contains(shareable_config->interest_group_buyers->get_buyers(), - it.first)) { + if (non_shared_params->per_buyer_signals) { + for (const auto& it : non_shared_params->per_buyer_signals.value()) { + if (!base::Contains( + non_shared_params->interest_group_buyers->get_buyers(), + it.first)) { return false; } } @@ -306,8 +307,8 @@ // Filter out buyers for whom the interest group API is not allowed. std::vector<url::Origin> filtered_buyers; - const auto& buyers = - config->shareable_auction_ad_config->interest_group_buyers->get_buyers(); + const auto& buyers = config->auction_ad_config_non_shared_params + ->interest_group_buyers->get_buyers(); std::copy_if( buyers.begin(), buyers.end(), std::back_inserter(filtered_buyers), [browser_context, &frame_origin](const url::Origin& buyer) {
diff --git a/content/browser/interest_group/ad_auction_service_impl_unittest.cc b/content/browser/interest_group/ad_auction_service_impl_unittest.cc index 5228d3c..6bd4fcd 100644 --- a/content/browser/interest_group/ad_auction_service_impl_unittest.cc +++ b/content/browser/interest_group/ad_auction_service_impl_unittest.cc
@@ -2219,9 +2219,9 @@ auto auction_config = blink::mojom::AuctionAdConfig::New(); auction_config->seller = kOriginA; auction_config->decision_logic_url = kUrlA.Resolve(kDecisionUrlPath); - auction_config->shareable_auction_ad_config = - blink::mojom::ShareableAuctionAdConfig::New(); - auction_config->shareable_auction_ad_config->interest_group_buyers = + auction_config->auction_ad_config_non_shared_params = + blink::mojom::AuctionAdConfigNonSharedParams::New(); + auction_config->auction_ad_config_non_shared_params->interest_group_buyers = blink::mojom::InterestGroupBuyers::NewBuyers({kOriginA}); absl::optional<GURL> auction_result = RunAdAuctionAndFlush(std::move(auction_config)); @@ -2278,9 +2278,9 @@ auto auction_config = blink::mojom::AuctionAdConfig::New(); auction_config->seller = kOriginA; auction_config->decision_logic_url = kUrlA.Resolve(kDecisionUrlPath); - auction_config->shareable_auction_ad_config = - blink::mojom::ShareableAuctionAdConfig::New(); - auction_config->shareable_auction_ad_config->interest_group_buyers = + auction_config->auction_ad_config_non_shared_params = + blink::mojom::AuctionAdConfigNonSharedParams::New(); + auction_config->auction_ad_config_non_shared_params->interest_group_buyers = blink::mojom::InterestGroupBuyers::NewBuyers({kOriginA}); absl::optional<GURL> auction_result = RunAdAuctionAndFlush(std::move(auction_config)); @@ -2359,18 +2359,20 @@ auto succeed_auction_config = blink::mojom::AuctionAdConfig::New(); succeed_auction_config->seller = kOriginA; succeed_auction_config->decision_logic_url = kUrlA.Resolve(kDecisionUrlPath); - succeed_auction_config->shareable_auction_ad_config = - blink::mojom::ShareableAuctionAdConfig::New(); - succeed_auction_config->shareable_auction_ad_config->interest_group_buyers = + succeed_auction_config->auction_ad_config_non_shared_params = + blink::mojom::AuctionAdConfigNonSharedParams::New(); + succeed_auction_config->auction_ad_config_non_shared_params + ->interest_group_buyers = blink::mojom::InterestGroupBuyers::NewBuyers({kOriginA}); auto fail_auction_config = blink::mojom::AuctionAdConfig::New(); fail_auction_config->seller = kOriginA; fail_auction_config->decision_logic_url = kUrlA.Resolve(kDecisionFailAllUrlPath); - fail_auction_config->shareable_auction_ad_config = - blink::mojom::ShareableAuctionAdConfig::New(); - fail_auction_config->shareable_auction_ad_config->interest_group_buyers = + fail_auction_config->auction_ad_config_non_shared_params = + blink::mojom::AuctionAdConfigNonSharedParams::New(); + fail_auction_config->auction_ad_config_non_shared_params + ->interest_group_buyers = blink::mojom::InterestGroupBuyers::NewBuyers({kOriginA}); // 1st auction @@ -2523,18 +2525,20 @@ auto succeed_auction_config = blink::mojom::AuctionAdConfig::New(); succeed_auction_config->seller = kOriginA; succeed_auction_config->decision_logic_url = kUrlA.Resolve(kDecisionUrlPath); - succeed_auction_config->shareable_auction_ad_config = - blink::mojom::ShareableAuctionAdConfig::New(); - succeed_auction_config->shareable_auction_ad_config->interest_group_buyers = + succeed_auction_config->auction_ad_config_non_shared_params = + blink::mojom::AuctionAdConfigNonSharedParams::New(); + succeed_auction_config->auction_ad_config_non_shared_params + ->interest_group_buyers = blink::mojom::InterestGroupBuyers::NewBuyers({kOriginA}); auto fail_auction_config = blink::mojom::AuctionAdConfig::New(); fail_auction_config->seller = kOriginA; fail_auction_config->decision_logic_url = kUrlA.Resolve(kDecisionFailAllUrlPath); - fail_auction_config->shareable_auction_ad_config = - blink::mojom::ShareableAuctionAdConfig::New(); - fail_auction_config->shareable_auction_ad_config->interest_group_buyers = + fail_auction_config->auction_ad_config_non_shared_params = + blink::mojom::AuctionAdConfigNonSharedParams::New(); + fail_auction_config->auction_ad_config_non_shared_params + ->interest_group_buyers = blink::mojom::InterestGroupBuyers::NewBuyers({kOriginA}); // 1st auction @@ -2682,9 +2686,10 @@ auto succeed_auction_config = blink::mojom::AuctionAdConfig::New(); succeed_auction_config->seller = kOriginA; succeed_auction_config->decision_logic_url = kUrlA.Resolve(kDecisionUrlPath); - succeed_auction_config->shareable_auction_ad_config = - blink::mojom::ShareableAuctionAdConfig::New(); - succeed_auction_config->shareable_auction_ad_config->interest_group_buyers = + succeed_auction_config->auction_ad_config_non_shared_params = + blink::mojom::AuctionAdConfigNonSharedParams::New(); + succeed_auction_config->auction_ad_config_non_shared_params + ->interest_group_buyers = blink::mojom::InterestGroupBuyers::NewBuyers({kOriginA}); for (int i = 0; i < kNumAuctions; i++) { @@ -2804,18 +2809,20 @@ auto succeed_auction_config = blink::mojom::AuctionAdConfig::New(); succeed_auction_config->seller = kOriginA; succeed_auction_config->decision_logic_url = kUrlA.Resolve(kDecisionUrlPath); - succeed_auction_config->shareable_auction_ad_config = - blink::mojom::ShareableAuctionAdConfig::New(); - succeed_auction_config->shareable_auction_ad_config->interest_group_buyers = + succeed_auction_config->auction_ad_config_non_shared_params = + blink::mojom::AuctionAdConfigNonSharedParams::New(); + succeed_auction_config->auction_ad_config_non_shared_params + ->interest_group_buyers = blink::mojom::InterestGroupBuyers::NewBuyers({kOriginA}); auto fail_auction_config = blink::mojom::AuctionAdConfig::New(); fail_auction_config->seller = kOriginA; fail_auction_config->decision_logic_url = kUrlA.Resolve(kDecisionFailAllUrlPath); - fail_auction_config->shareable_auction_ad_config = - blink::mojom::ShareableAuctionAdConfig::New(); - fail_auction_config->shareable_auction_ad_config->interest_group_buyers = + fail_auction_config->auction_ad_config_non_shared_params = + blink::mojom::AuctionAdConfigNonSharedParams::New(); + fail_auction_config->auction_ad_config_non_shared_params + ->interest_group_buyers = blink::mojom::InterestGroupBuyers::NewBuyers({kOriginA}); // 1st auction @@ -2920,9 +2927,10 @@ auto succeed_auction_config = blink::mojom::AuctionAdConfig::New(); succeed_auction_config->seller = kOriginA; succeed_auction_config->decision_logic_url = kUrlA.Resolve(kDecisionUrlPath); - succeed_auction_config->shareable_auction_ad_config = - blink::mojom::ShareableAuctionAdConfig::New(); - succeed_auction_config->shareable_auction_ad_config->interest_group_buyers = + succeed_auction_config->auction_ad_config_non_shared_params = + blink::mojom::AuctionAdConfigNonSharedParams::New(); + succeed_auction_config->auction_ad_config_non_shared_params + ->interest_group_buyers = blink::mojom::InterestGroupBuyers::NewBuyers({kOriginA}); // Pick some large number, larger than the auction limit. @@ -3174,8 +3182,8 @@ // An empty config will cause FinalizeAd to fail and run the supplied callback. TEST_F(AdAuctionServiceImplTest, FinalizeAdRejectsEmptyConfig) { auto mojo_config = blink::mojom::AuctionAdConfig::New(); - mojo_config->shareable_auction_ad_config = - blink::mojom::ShareableAuctionAdConfig::New(); + mojo_config->auction_ad_config_non_shared_params = + blink::mojom::AuctionAdConfigNonSharedParams::New(); bool callback_fired = false; FinalizeAd( @@ -3189,8 +3197,8 @@ TEST_F(AdAuctionServiceImplTest, FinalizeAdRejectsHTTPDecisionUrl) { auto mojo_config = blink::mojom::AuctionAdConfig::New(); - mojo_config->shareable_auction_ad_config = - blink::mojom::ShareableAuctionAdConfig::New(); + mojo_config->auction_ad_config_non_shared_params = + blink::mojom::AuctionAdConfigNonSharedParams::New(); mojo_config->seller = url::Origin::Create(GURL("https://site.test")); mojo_config->decision_logic_url = GURL("http://site.test/"); @@ -3207,8 +3215,8 @@ // An empty GUID should trigger any FinalizeAd request to fail. TEST_F(AdAuctionServiceImplTest, FinalizeAdRejectsMissingGuid) { auto mojo_config = blink::mojom::AuctionAdConfig::New(); - mojo_config->shareable_auction_ad_config = - blink::mojom::ShareableAuctionAdConfig::New(); + mojo_config->auction_ad_config_non_shared_params = + blink::mojom::AuctionAdConfigNonSharedParams::New(); mojo_config->seller = url::Origin::Create(GURL("https://site.test")); mojo_config->decision_logic_url = GURL("https://site.test/");
diff --git a/content/browser/interest_group/auction_runner.cc b/content/browser/interest_group/auction_runner.cc index b35747b..7fb212a 100644 --- a/content/browser/interest_group/auction_runner.cc +++ b/content/browser/interest_group/auction_runner.cc
@@ -12,11 +12,13 @@ #include "base/callback.h" #include "base/callback_forward.h" +#include "base/location.h" #include "base/memory/ptr_util.h" #include "base/metrics/histogram_macros.h" #include "base/rand_util.h" #include "base/strings/strcat.h" #include "base/strings/stringprintf.h" +#include "base/threading/sequenced_task_runner_handle.h" #include "base/time/time.h" #include "content/browser/interest_group/auction_process_manager.h" #include "content/browser/interest_group/auction_url_loader_factory_proxy.h" @@ -284,11 +286,31 @@ interest_group.name, interest_group.trusted_bidding_signals_keys, interest_group.user_bidding_signals, interest_group.ads, interest_group.ad_components), - auction_config_->shareable_auction_ad_config->auction_signals, + auction_config_->auction_ad_config_non_shared_params->auction_signals, PerBuyerSignals(bid_state), browser_signals_->seller, bid_state->bidder.bidding_browser_signals.Clone(), auction_start_time_, base::BindOnce(&AuctionRunner::OnGenerateBidComplete, weak_ptr_factory_.GetWeakPtr(), bid_state)); + + // Invoke SendPendingSignalsRequests() asynchronously, if necessary. Do this + // asynchronously so that all GenerateBid() calls that share a BidderWorklet + // will have been invoked before the first SendPendingSignalsRequests() call. + // + // This relies on AuctionWorkletManager::Handle invoking all the callbacks + // listening for creation of the same BidderWorklet synchronously. + if (interest_group.trusted_bidding_signals_keys && + interest_group.trusted_bidding_signals_keys->size() > 0) { + base::SequencedTaskRunnerHandle::Get()->PostTask( + FROM_HERE, + base::BindOnce(&AuctionRunner::SendPendingSignalsRequestsForBidder, + weak_ptr_factory_.GetWeakPtr(), bid_state)); + } +} + +void AuctionRunner::SendPendingSignalsRequestsForBidder(BidState* bid_state) { + // Don't invoke callback if worklet was unloaded in the meantime. + if (bid_state->worklet_handle) + bid_state->worklet_handle->GetBidderWorklet()->SendPendingSignalsRequests(); } void AuctionRunner::OnBidderWorkletGenerateBidFatalError( @@ -361,7 +383,7 @@ seller_worklet_handle_->GetSellerWorklet()->ScoreAd( state->bid_result->ad, state->bid_result->bid, - auction_config_->shareable_auction_ad_config.Clone(), + auction_config_->auction_ad_config_non_shared_params.Clone(), state->bidder.interest_group.owner, state->bid_result->render_url, state->bid_result->ad_components ? *state->bid_result->ad_components : std::vector<GURL>(), @@ -410,7 +432,7 @@ absl::optional<std::string> AuctionRunner::PerBuyerSignals( const BidState* state) { const auto& per_buyer_signals = - auction_config_->shareable_auction_ad_config->per_buyer_signals; + auction_config_->auction_ad_config_non_shared_params->per_buyer_signals; if (per_buyer_signals.has_value()) { auto it = per_buyer_signals.value().find(state->bidder.interest_group.owner); @@ -459,7 +481,7 @@ DCHECK_GT(top_bidder_->seller_score, 0); seller_worklet_handle_->GetSellerWorklet()->ReportResult( - auction_config_->shareable_auction_ad_config.Clone(), + auction_config_->auction_ad_config_non_shared_params.Clone(), top_bidder_->bidder.interest_group.owner, top_bidder_->bid_result->render_url, top_bidder_->bid_result->bid, top_bidder_->seller_score, @@ -519,7 +541,7 @@ top_bidder_->worklet_handle->GetBidderWorklet()->ReportWin( top_bidder_->bidder.interest_group.name, - auction_config_->shareable_auction_ad_config->auction_signals, + auction_config_->auction_ad_config_non_shared_params->auction_signals, PerBuyerSignals(top_bidder_), signals_for_winner_arg, top_bidder_->bid_result->render_url, top_bidder_->bid_result->bid, auction_config_->seller,
diff --git a/content/browser/interest_group/auction_runner.h b/content/browser/interest_group/auction_runner.h index 30385da..a9aa2d9 100644 --- a/content/browser/interest_group/auction_runner.h +++ b/content/browser/interest_group/auction_runner.h
@@ -234,6 +234,16 @@ // the bidder identified by `bid_state`. Starts generating a bid. void OnBidderWorkletReceived(BidState* bid_state); + // Calls SendPendingSignalsRequests() for the BidderWorklet of `bid_state`, if + // it hasn't been destroyed. This is done asynchronously, so that BidStates + // that share a BidderWorklet all call GenerateBid() before this is invoked + // for all of them. + // + // This does result in invoking SendPendingSignalsRequests() multiple times + // for BidStates that share BidderWorklets, though that should be fairly low + // overhead. + void SendPendingSignalsRequestsForBidder(BidState* bid_state); + // Called when the `bid_state` BidderWorklet crashes or fails to load, and // `bid_state` is in state kGeneratingBid. Fails the GenerateBid() call and // releases the worklet handle, as the callback passed to the GenerateBid Mojo
diff --git a/content/browser/interest_group/auction_runner_unittest.cc b/content/browser/interest_group/auction_runner_unittest.cc index 3ed010b..cc2320b 100644 --- a/content/browser/interest_group/auction_runner_unittest.cc +++ b/content/browser/interest_group/auction_runner_unittest.cc
@@ -308,7 +308,14 @@ MockBidderWorklet(const MockBidderWorklet&) = delete; const MockBidderWorklet& operator=(const MockBidderWorklet&) = delete; - ~MockBidderWorklet() override = default; + ~MockBidderWorklet() override { + // `send_pending_signals_requests_called_` should always be called if any + // bids are generated, except in the unlikely event that the Mojo pipe is + // closed before a posted task is executed (this cannot be simulated by + // closing a pipe in tests, due to vagaries of timing of the two messages). + if (generate_bid_called_) + EXPECT_TRUE(send_pending_signals_requests_called_); + } // auction_worklet::mojom::BidderWorklet implementation: @@ -321,14 +328,25 @@ auction_worklet::mojom::BiddingBrowserSignalsPtr bidding_browser_signals, base::Time auction_start_time, GenerateBidCallback generate_bid_callback) override { + generate_bid_called_ = true; // While the real BidderWorklet implementation supports multiple pending // callbacks, this class does not. DCHECK(!generate_bid_callback_); + + // Single auctions should invoke all GenerateBid() calls on a worklet + // before invoking SendPendingSignalsRequests(). + EXPECT_FALSE(send_pending_signals_requests_called_); + generate_bid_callback_ = std::move(generate_bid_callback); if (generate_bid_run_loop_) generate_bid_run_loop_->Quit(); } + void SendPendingSignalsRequests() override { + // This allows multiple calls. + send_pending_signals_requests_called_ = true; + } + void ReportWin(const std::string& interest_group_name, const absl::optional<std::string>& auction_signals_json, const absl::optional<std::string>& per_buyer_signals_json, @@ -416,6 +434,9 @@ std::unique_ptr<base::RunLoop> report_win_run_loop_; ReportWinCallback report_win_callback_; + bool generate_bid_called_ = false; + bool send_pending_signals_requests_called_ = false; + // Receiver is last so that destroying `this` while there's a pending callback // over the pipe will not DCHECK. mojo::Receiver<auction_worklet::mojom::BidderWorklet> receiver_; @@ -452,7 +473,8 @@ void ScoreAd(const std::string& ad_metadata_json, double bid, - blink::mojom::ShareableAuctionAdConfigPtr shareable_config, + blink::mojom::AuctionAdConfigNonSharedParamsPtr + auction_ad_config_non_shared_params, const url::Origin& browser_signal_interest_group_owner, const GURL& browser_signal_render_url, const std::vector<GURL>& browser_signal_ad_components, @@ -479,7 +501,8 @@ send_pending_signals_requests_called_ = true; } - void ReportResult(blink::mojom::ShareableAuctionAdConfigPtr shareable_config, + void ReportResult(blink::mojom::AuctionAdConfigNonSharedParamsPtr + auction_ad_config_non_shared_params, const url::Origin& browser_signal_interest_group_owner, const GURL& browser_signal_render_url, double browser_signal_bid, @@ -838,22 +861,22 @@ auction_config->seller = url::Origin::Create(seller_decision_logic_url); auction_config->decision_logic_url = seller_decision_logic_url; auction_config->trusted_scoring_signals_url = trusted_scoring_signals_url_; - auction_config->shareable_auction_ad_config = - blink::mojom::ShareableAuctionAdConfig::New(); + auction_config->auction_ad_config_non_shared_params = + blink::mojom::AuctionAdConfigNonSharedParams::New(); // This is ignored by AuctionRunner, in favor of its `filtered_buyers` // parameter. - auction_config->shareable_auction_ad_config->interest_group_buyers = + auction_config->auction_ad_config_non_shared_params->interest_group_buyers = blink::mojom::InterestGroupBuyers::NewAllBuyers( blink::mojom::AllBuyers::New()); - auction_config->shareable_auction_ad_config->auction_signals = + auction_config->auction_ad_config_non_shared_params->auction_signals = auction_signals_json; - auction_config->shareable_auction_ad_config->seller_signals = + auction_config->auction_ad_config_non_shared_params->seller_signals = R"({"isSellerSignals": true})"; base::flat_map<url::Origin, std::string> per_buyer_signals; per_buyer_signals[kBidder1] = R"({"signalsFor": ")" + kBidder1Name + "\"}"; per_buyer_signals[kBidder2] = R"({"signalsFor": ")" + kBidder2Name + "\"}"; - auction_config->shareable_auction_ad_config->per_buyer_signals = + auction_config->auction_ad_config_non_shared_params->per_buyer_signals = std::move(per_buyer_signals); interest_group_manager_ = std::make_unique<InterestGroupManager>( @@ -2345,6 +2368,83 @@ 2 /* expected_interest_groups */, 2 /* expected_owners */); } +// Test the case where two interest groups use the same BidderWorklet, with a +// trusted bidding signals URL. The requests should be batched. This test +// basically makes sure that SendPendingSignalsRequests() is only invoked on the +// BidderWorklet after both GenerateBid() calls have been invoked. +TEST_F(AuctionRunnerTest, ReusedBidderWorkletBatchesSignalsRequests) { + // Bidding script used by both interest groups. Since the default bid script + // checks the interest group name, and this test uses two interest groups with + // the same bidder script, have to use a different script for this test. + // + // This script uses trusted bidding signals and the interest group name to + // select a winner, to make sure the trusted bidding signals makes it to the + // bidder. + const char kBidderScript[] = R"( + function generateBid(interestGroup, auctionSignals, perBuyerSignals, + trustedBiddingSignals, browserSignals) { + return { + ad: 0, + bid: trustedBiddingSignals[interestGroup.name], + render: interestGroup.ads[0].renderUrl + }; + } + + // Prevent an error about this method not existing. + function reportWin() {} + )"; + + // Need to use a different seller script as well, due to the validation logic + // in the default one being dependent on the details of the default bidder + // script. + const char kSellerScript[] = R"( + function scoreAd(adMetadata, bid, auctionConfig, trustedScoringSignals, + browserSignals) { + return 2 * bid; + } + + // Prevent an error about this method not existing. + function reportResult() {} + )"; + + // Two interest groups with all of the same URLs. They vary only in name, + // render URL, and bidding signals key. + std::vector<StorageInterestGroup> bidders; + bidders.emplace_back(MakeInterestGroup( + kBidder1, /*name=*/"0", kBidder1Url, kBidder1TrustedSignalsUrl, + /*trusted_bidding_signals_keys=*/{"0"}, GURL("https://ad1.com"))); + bidders.emplace_back(MakeInterestGroup( + kBidder1, /*name=*/"1", kBidder1Url, kBidder1TrustedSignalsUrl, + /*trusted_bidding_signals_keys=*/{"1"}, GURL("https://ad2.com"))); + + auction_worklet::AddJavascriptResponse(&url_loader_factory_, kBidder1Url, + kBidderScript); + + // Trusted signals response for the single expected request. Interest group + // "0" bids 2, interest group "1" bids 1. + auction_worklet::AddJsonResponse(&url_loader_factory_, + GURL(kBidder1TrustedSignalsUrl.spec() + + "?hostname=publisher1.com&keys=0,1"), + R"({"0":2, "1": 1})"); + + auction_worklet::AddJavascriptResponse(&url_loader_factory_, kSellerUrl, + kSellerScript); + + StartAuction(kSellerUrl, std::move(bidders), + /*auction_signals_json=*/"null", + auction_worklet::mojom::BrowserSignals::New( + url::Origin::Create(GURL("https://publisher1.com")), + url::Origin::Create(kSellerUrl))); + auction_run_loop_->Run(); + EXPECT_TRUE(auction_complete_); + + EXPECT_EQ(GURL("https://ad1.com/"), result_.ad_url); + EXPECT_FALSE(result_.ad_component_urls); + EXPECT_FALSE(result_.bidder_report_url); + EXPECT_FALSE(result_.seller_report_url); + EXPECT_THAT(result_.errors, testing::ElementsAre()); +} + TEST_F(AuctionRunnerTest, AllBiddersCrashBeforeBidding) { StartStandardAuctionWithMockService(); auto seller_worklet = mock_auction_process_manager_->TakeSellerWorklet();
diff --git a/content/browser/interest_group/auction_worklet_manager_unittest.cc b/content/browser/interest_group/auction_worklet_manager_unittest.cc index 18b8e69..9bf28c4 100644 --- a/content/browser/interest_group/auction_worklet_manager_unittest.cc +++ b/content/browser/interest_group/auction_worklet_manager_unittest.cc
@@ -112,7 +112,12 @@ MockBidderWorklet(const MockBidderWorklet&) = delete; const MockBidderWorklet& operator=(const MockBidderWorklet&) = delete; - ~MockBidderWorklet() override = default; + ~MockBidderWorklet() override { + // Process any pending SendPendingSignalsRequests() calls. + base::RunLoop().RunUntilIdle(); + EXPECT_EQ(expected_num_send_pending_signals_requests_calls_, + num_send_pending_signals_requests_calls_); + } // auction_worklet::mojom::SellerWorklet implementation: @@ -128,6 +133,14 @@ NOTREACHED(); } + void SendPendingSignalsRequests() override { + ++num_send_pending_signals_requests_calls_; + if (num_send_pending_signals_requests_calls_ == + expected_num_send_pending_signals_requests_calls_) { + send_pending_signals_requests_called_loop_->Quit(); + } + } + void ReportWin(const std::string& interest_group_name, const absl::optional<std::string>& auction_signals_json, const absl::optional<std::string>& per_buyer_signals_json, @@ -150,6 +163,24 @@ receiver_.ResetWithReason(/*custom_reason_code=*/0, error); } + void WaitForSendPendingSignalsRequests( + int expected_num_send_pending_signals_requests_calls) { + DCHECK_LT(expected_num_send_pending_signals_requests_calls_, + expected_num_send_pending_signals_requests_calls); + + expected_num_send_pending_signals_requests_calls_ = + expected_num_send_pending_signals_requests_calls; + if (num_send_pending_signals_requests_calls_ < + expected_num_send_pending_signals_requests_calls_) { + send_pending_signals_requests_called_loop_ = + std::make_unique<base::RunLoop>(); + send_pending_signals_requests_called_loop_->Run(); + } + + EXPECT_EQ(expected_num_send_pending_signals_requests_calls_, + num_send_pending_signals_requests_calls_); + } + mojo::Remote<network::mojom::URLLoaderFactory>& url_loader_factory() { return url_loader_factory_; } @@ -161,6 +192,10 @@ } const url::Origin& top_window_origin() const { return top_window_origin_; } + int num_send_pending_signals_requests_calls() const { + return num_send_pending_signals_requests_calls_; + } + private: mojo::Remote<network::mojom::URLLoaderFactory> url_loader_factory_; @@ -169,6 +204,17 @@ const absl::optional<GURL> trusted_bidding_signals_url_; const url::Origin top_window_origin_; + // Number of times SendPendingSignalsRequests() has been invoked. Used to + // check that calls through Mojo BidderWorklet interfaces make it to the + // correct MockBidderWorklet. + int num_send_pending_signals_requests_calls_ = 0; + // Number of SendPendingSignalsRequests() to wait for. Once this is hit, + // `send_pending_signals_requests_called_loop_` is invoked. Must match + // num_send_pending_signals_requests_calls_ on destruction (which catches + // unexpected extra calls). + int expected_num_send_pending_signals_requests_calls_ = 0; + std::unique_ptr<base::RunLoop> send_pending_signals_requests_called_loop_; + // Receiver is last so that destroying `this` while there's a pending callback // over the pipe will not DCHECK. mojo::Receiver<auction_worklet::mojom::BidderWorklet> receiver_; @@ -206,7 +252,8 @@ void ScoreAd(const std::string& ad_metadata_json, double bid, - blink::mojom::ShareableAuctionAdConfigPtr shareable_config, + blink::mojom::AuctionAdConfigNonSharedParamsPtr + auction_ad_config_non_shared_params, const url::Origin& browser_signal_interest_group_owner, const GURL& browser_signal_render_url, const std::vector<GURL>& browser_signal_ad_components, @@ -223,7 +270,8 @@ } } - void ReportResult(blink::mojom::ShareableAuctionAdConfigPtr shareable_config, + void ReportResult(blink::mojom::AuctionAdConfigNonSharedParamsPtr + auction_ad_config_non_shared_params, const url::Origin& browser_signal_interest_group_owner, const GURL& browser_signal_render_url, double browser_signal_bid, @@ -283,8 +331,8 @@ const url::Origin top_window_origin_; // Number of times SendPendingSignalsRequests() has been invoked. Used to - // check that SellerWorklet calls make it to the SellerWorklet as expected, - // and that worklets are being shared correctly. + // check that calls through Mojo SellerWorklet interfaces make it to the + // correct MockSellerWorklet. int num_send_pending_signals_requests_calls_ = 0; // Number of SendPendingSignalsRequests() to wait for. Once this is hit, // `send_pending_signals_requests_called_loop_` is invoked. Must match @@ -518,6 +566,10 @@ EXPECT_EQ(kWasmUrl, bidder_worklet->wasm_url()); EXPECT_EQ(kTrustedSignalsUrl, bidder_worklet->trusted_bidding_signals_url()); EXPECT_EQ(kTopWindowOrigin, bidder_worklet->top_window_origin()); + + EXPECT_EQ(0, bidder_worklet->num_send_pending_signals_requests_calls()); + handle->GetBidderWorklet()->SendPendingSignalsRequests(); + bidder_worklet->WaitForSendPendingSignalsRequests(1); } TEST_F(AuctionWorkletManagerTest, SingleSellerWorklet) { @@ -573,6 +625,10 @@ EXPECT_EQ(absl::nullopt, bidder_worklet->trusted_bidding_signals_url()); EXPECT_EQ(kTopWindowOrigin, bidder_worklet->top_window_origin()); + EXPECT_EQ(0, bidder_worklet->num_send_pending_signals_requests_calls()); + handle->GetBidderWorklet()->SendPendingSignalsRequests(); + bidder_worklet->WaitForSendPendingSignalsRequests(1); + handles.emplace_back(std::move(handle)); bidder_worklets.emplace_back(std::move(bidder_worklet)); } @@ -607,6 +663,10 @@ EXPECT_EQ(kTrustedSignalsUrl, bidder_worklet->trusted_bidding_signals_url()); EXPECT_EQ(kTopWindowOrigin, bidder_worklet->top_window_origin()); + EXPECT_EQ(0, bidder_worklet->num_send_pending_signals_requests_calls()); + handle->GetBidderWorklet()->SendPendingSignalsRequests(); + bidder_worklet->WaitForSendPendingSignalsRequests(1); + // Should still be at the process limit. EXPECT_EQ(AuctionProcessManager::kMaxBidderProcesses, auction_process_manager_.GetBidderProcessCountForTesting()); @@ -705,6 +765,8 @@ EXPECT_EQ(kWasmUrl, bidder_worklet1->wasm_url()); EXPECT_EQ(kTrustedSignalsUrl, bidder_worklet1->trusted_bidding_signals_url()); EXPECT_EQ(kTopWindowOrigin, bidder_worklet1->top_window_origin()); + handle1->GetBidderWorklet()->SendPendingSignalsRequests(); + bidder_worklet1->WaitForSendPendingSignalsRequests(1); // Should only be one process. EXPECT_EQ(1u, auction_process_manager_.GetBidderProcessCountForTesting()); @@ -717,6 +779,8 @@ handle2)); EXPECT_EQ(handle1->GetBidderWorklet(), handle2->GetBidderWorklet()); EXPECT_FALSE(auction_process_manager_.HasBidderWorkletRequest()); + handle2->GetBidderWorklet()->SendPendingSignalsRequests(); + bidder_worklet1->WaitForSendPendingSignalsRequests(2); // Should still only be one process. EXPECT_EQ(1u, auction_process_manager_.GetBidderProcessCountForTesting()); @@ -734,6 +798,8 @@ handle3)); EXPECT_EQ(handle2->GetBidderWorklet(), handle3->GetBidderWorklet()); EXPECT_FALSE(auction_process_manager_.HasBidderWorkletRequest()); + handle3->GetBidderWorklet()->SendPendingSignalsRequests(); + bidder_worklet1->WaitForSendPendingSignalsRequests(3); // Should still only be one process. EXPECT_EQ(1u, auction_process_manager_.GetBidderProcessCountForTesting()); @@ -758,6 +824,8 @@ EXPECT_EQ(kWasmUrl, bidder_worklet2->wasm_url()); EXPECT_EQ(kTrustedSignalsUrl, bidder_worklet2->trusted_bidding_signals_url()); EXPECT_EQ(kTopWindowOrigin, bidder_worklet2->top_window_origin()); + handle4->GetBidderWorklet()->SendPendingSignalsRequests(); + bidder_worklet2->WaitForSendPendingSignalsRequests(1); EXPECT_EQ(1u, auction_process_manager_.GetBidderProcessCountForTesting()); } @@ -996,6 +1064,11 @@ EXPECT_EQ(AuctionWorkletManager::FatalErrorType::kScriptLoadFailed, load_error_helper.fatal_error_type()); + // Should be safe to call into the worklet, even after the error. This allows + // errors to be handled asynchronously. + handle->GetBidderWorklet()->SendPendingSignalsRequests(); + task_environment_.RunUntilIdle(); + // Another request for the same worklet should trigger creation of a new // worklet, even though the old handle for the worklet hasn't been deleted // yet. @@ -1074,6 +1147,12 @@ EXPECT_EQ(AuctionWorkletManager::FatalErrorType::kWorkletCrash, load_error_helper.fatal_error_type()); + // Should be safe to call into the worklet, even after the error. This allows + // errors to be handled asynchronously. + handle->GetBidderWorklet()->SendPendingSignalsRequests(); + task_environment_.RunUntilIdle(); + handle->GetBidderWorklet()->SendPendingSignalsRequests(); + // Another request for the same worklet should trigger creation of a new // worklet, even though the old handle for the worklet hasn't been deleted // yet.
diff --git a/content/browser/interest_group/interest_group_browsertest.cc b/content/browser/interest_group/interest_group_browsertest.cc index dde56a2c..c17bd47 100644 --- a/content/browser/interest_group/interest_group_browsertest.cc +++ b/content/browser/interest_group/interest_group_browsertest.cc
@@ -3744,8 +3744,8 @@ base::RunLoop run_loop; auto auction_config = blink::mojom::AuctionAdConfig::New(); - auction_config->shareable_auction_ad_config = - blink::mojom::ShareableAuctionAdConfig::New(); + auction_config->auction_ad_config_non_shared_params = + blink::mojom::AuctionAdConfigNonSharedParams::New(); auction_service->RunAdAuction( std::move(auction_config), @@ -3843,12 +3843,12 @@ config->seller = test_origin_b; config->decision_logic_url = https_server_->GetURL("b.test", "/interest_group/decision_logic.js"); - config->shareable_auction_ad_config = - blink::mojom::ShareableAuctionAdConfig::New(); - config->shareable_auction_ad_config->interest_group_buyers = + config->auction_ad_config_non_shared_params = + blink::mojom::AuctionAdConfigNonSharedParams::New(); + config->auction_ad_config_non_shared_params->interest_group_buyers = blink::mojom::InterestGroupBuyers::New(); - config->shareable_auction_ad_config->interest_group_buyers->set_buyers( - {test_origin_a_}); + config->auction_ad_config_non_shared_params->interest_group_buyers + ->set_buyers({test_origin_a_}); EXPECT_THAT(RunAuctionBypassBlink(std::move(config)), Optional(Eq(ad_url_))); } @@ -3864,12 +3864,12 @@ config->decision_logic_url = embedded_test_server()->GetURL( "b.test", "/interest_group/decision_logic.js"); ASSERT_TRUE(config->decision_logic_url.SchemeIs(url::kHttpScheme)); - config->shareable_auction_ad_config = - blink::mojom::ShareableAuctionAdConfig::New(); - config->shareable_auction_ad_config->interest_group_buyers = + config->auction_ad_config_non_shared_params = + blink::mojom::AuctionAdConfigNonSharedParams::New(); + config->auction_ad_config_non_shared_params->interest_group_buyers = blink::mojom::InterestGroupBuyers::New(); - config->shareable_auction_ad_config->interest_group_buyers->set_buyers( - {test_origin_a_}); + config->auction_ad_config_non_shared_params->interest_group_buyers + ->set_buyers({test_origin_a_}); EXPECT_THAT(RunAuctionBypassBlink(std::move(config)), Eq(absl::nullopt)); } @@ -3881,12 +3881,12 @@ config->seller = test_origin_a_; config->decision_logic_url = https_server_->GetURL("b.test", "/interest_group/decision_logic.js"); - config->shareable_auction_ad_config = - blink::mojom::ShareableAuctionAdConfig::New(); - config->shareable_auction_ad_config->interest_group_buyers = + config->auction_ad_config_non_shared_params = + blink::mojom::AuctionAdConfigNonSharedParams::New(); + config->auction_ad_config_non_shared_params->interest_group_buyers = blink::mojom::InterestGroupBuyers::New(); - config->shareable_auction_ad_config->interest_group_buyers->set_buyers( - {test_origin_a_}); + config->auction_ad_config_non_shared_params->interest_group_buyers + ->set_buyers({test_origin_a_}); EXPECT_THAT(RunAuctionBypassBlink(std::move(config)), Eq(absl::nullopt)); } @@ -3908,12 +3908,12 @@ config->seller = test_origin_b; config->decision_logic_url = https_server_->GetURL("b.test", "/interest_group/decision_logic.js"); - config->shareable_auction_ad_config = - blink::mojom::ShareableAuctionAdConfig::New(); - config->shareable_auction_ad_config->interest_group_buyers = + config->auction_ad_config_non_shared_params = + blink::mojom::AuctionAdConfigNonSharedParams::New(); + config->auction_ad_config_non_shared_params->interest_group_buyers = blink::mojom::InterestGroupBuyers::New(); - config->shareable_auction_ad_config->interest_group_buyers->set_buyers( - {test_origin_a_http}); + config->auction_ad_config_non_shared_params->interest_group_buyers + ->set_buyers({test_origin_a_http}); EXPECT_THAT(RunAuctionBypassBlink(std::move(config)), Eq(absl::nullopt)); } @@ -3936,12 +3936,12 @@ config->seller = test_origin_b; config->decision_logic_url = https_server_->GetURL("b.test", "/interest_group/decision_logic.js"); - config->shareable_auction_ad_config = - blink::mojom::ShareableAuctionAdConfig::New(); - config->shareable_auction_ad_config->interest_group_buyers = + config->auction_ad_config_non_shared_params = + blink::mojom::AuctionAdConfigNonSharedParams::New(); + config->auction_ad_config_non_shared_params->interest_group_buyers = blink::mojom::InterestGroupBuyers::New(); - config->shareable_auction_ad_config->interest_group_buyers->set_buyers( - {test_origin_a_, test_origin_a_http}); + config->auction_ad_config_non_shared_params->interest_group_buyers + ->set_buyers({test_origin_a_, test_origin_a_http}); EXPECT_THAT(RunAuctionBypassBlink(std::move(config)), Eq(absl::nullopt)); } @@ -3964,12 +3964,12 @@ config->seller = test_origin_b; config->decision_logic_url = https_server_->GetURL("b.test", "/interest_group/decision_logic.js"); - config->shareable_auction_ad_config = - blink::mojom::ShareableAuctionAdConfig::New(); - config->shareable_auction_ad_config->interest_group_buyers = + config->auction_ad_config_non_shared_params = + blink::mojom::AuctionAdConfigNonSharedParams::New(); + config->auction_ad_config_non_shared_params->interest_group_buyers = blink::mojom::InterestGroupBuyers::New(); - config->shareable_auction_ad_config->interest_group_buyers->set_buyers( - {test_origin_a_, test_origin_c}); + config->auction_ad_config_non_shared_params->interest_group_buyers + ->set_buyers({test_origin_a_, test_origin_c}); EXPECT_THAT(RunAuctionBypassBlink(std::move(config)), Optional(Eq(ad_url_))); } @@ -3985,12 +3985,12 @@ config->seller = test_origin_b; config->decision_logic_url = https_server_->GetURL("b.test", "/interest_group/decision_logic.js"); - config->shareable_auction_ad_config = - blink::mojom::ShareableAuctionAdConfig::New(); - config->shareable_auction_ad_config->interest_group_buyers = + config->auction_ad_config_non_shared_params = + blink::mojom::AuctionAdConfigNonSharedParams::New(); + config->auction_ad_config_non_shared_params->interest_group_buyers = blink::mojom::InterestGroupBuyers::New(); - config->shareable_auction_ad_config->interest_group_buyers->set_all_buyers( - blink::mojom::AllBuyers::New()); + config->auction_ad_config_non_shared_params->interest_group_buyers + ->set_all_buyers(blink::mojom::AllBuyers::New()); // All buyers isn't supported. EXPECT_THAT(RunAuctionBypassBlink(std::move(config)), Eq(absl::nullopt)); @@ -4009,14 +4009,14 @@ config->seller = test_origin_b; config->decision_logic_url = https_server_->GetURL("b.test", "/interest_group/decision_logic.js"); - config->shareable_auction_ad_config = - blink::mojom::ShareableAuctionAdConfig::New(); - config->shareable_auction_ad_config->interest_group_buyers = + config->auction_ad_config_non_shared_params = + blink::mojom::AuctionAdConfigNonSharedParams::New(); + config->auction_ad_config_non_shared_params->interest_group_buyers = blink::mojom::InterestGroupBuyers::New(); - config->shareable_auction_ad_config->interest_group_buyers->set_buyers( - {test_origin_a_}); - config->shareable_auction_ad_config->per_buyer_signals.emplace(); - config->shareable_auction_ad_config->per_buyer_signals + config->auction_ad_config_non_shared_params->interest_group_buyers + ->set_buyers({test_origin_a_}); + config->auction_ad_config_non_shared_params->per_buyer_signals.emplace(); + config->auction_ad_config_non_shared_params->per_buyer_signals .value()[test_origin_a_] = "{\"even\": \"more\", \"x\": 4.5}"; EXPECT_THAT(RunAuctionBypassBlink(std::move(config)), Optional(Eq(ad_url_))); @@ -4035,15 +4035,15 @@ config->seller = test_origin_b; config->decision_logic_url = https_server_->GetURL("b.test", "/interest_group/decision_logic.js"); - config->shareable_auction_ad_config = - blink::mojom::ShareableAuctionAdConfig::New(); - config->shareable_auction_ad_config->interest_group_buyers = + config->auction_ad_config_non_shared_params = + blink::mojom::AuctionAdConfigNonSharedParams::New(); + config->auction_ad_config_non_shared_params->interest_group_buyers = blink::mojom::InterestGroupBuyers::New(); - config->shareable_auction_ad_config->interest_group_buyers->set_buyers( - {test_origin_a_}); - config->shareable_auction_ad_config->per_buyer_signals.emplace(); + config->auction_ad_config_non_shared_params->interest_group_buyers + ->set_buyers({test_origin_a_}); + config->auction_ad_config_non_shared_params->per_buyer_signals.emplace(); // `test_origin_b` isn't in `interest_group_buyers`. - config->shareable_auction_ad_config->per_buyer_signals + config->auction_ad_config_non_shared_params->per_buyer_signals .value()[test_origin_b] = "{\"even\": \"more\", \"x\": 4.5}"; EXPECT_THAT(RunAuctionBypassBlink(std::move(config)), Eq(absl::nullopt)); @@ -4062,12 +4062,12 @@ https_server_->GetURL("b.test", "/interest_group/decision_logic.js"); config->trusted_scoring_signals_url = https_server_->GetURL( "not-b.test", "/interest_group/trusted_scoring_signals.json"); - config->shareable_auction_ad_config = - blink::mojom::ShareableAuctionAdConfig::New(); - config->shareable_auction_ad_config->interest_group_buyers = + config->auction_ad_config_non_shared_params = + blink::mojom::AuctionAdConfigNonSharedParams::New(); + config->auction_ad_config_non_shared_params->interest_group_buyers = blink::mojom::InterestGroupBuyers::New(); - config->shareable_auction_ad_config->interest_group_buyers->set_buyers( - {test_origin_a_}); + config->auction_ad_config_non_shared_params->interest_group_buyers + ->set_buyers({test_origin_a_}); EXPECT_THAT(RunAuctionBypassBlink(std::move(config)), Eq(absl::nullopt)); }
diff --git a/content/browser/service_worker/service_worker_new_script_fetcher.cc b/content/browser/service_worker/service_worker_new_script_fetcher.cc index 84dfcb85..54ea71b 100644 --- a/content/browser/service_worker/service_worker_new_script_fetcher.cc +++ b/content/browser/service_worker/service_worker_new_script_fetcher.cc
@@ -170,6 +170,9 @@ // header and the body. if (status.error_code == net::OK) { mojo::ReportBadMessage("SWNSF_BAD_OK"); + // Do not continue with further script processing, but let the |callback_| + // hang. This renderer process would be killed soon anyways. + return; } std::move(callback_).Run(/*main_script_load_params=*/nullptr); }
diff --git a/content/services/auction_worklet/bidder_worklet.cc b/content/services/auction_worklet/bidder_worklet.cc index bd73deb4..760308d7 100644 --- a/content/services/auction_worklet/bidder_worklet.cc +++ b/content/services/auction_worklet/bidder_worklet.cc
@@ -23,6 +23,7 @@ #include "content/services/auction_worklet/public/mojom/auction_worklet_service.mojom.h" #include "content/services/auction_worklet/report_bindings.h" #include "content/services/auction_worklet/trusted_signals.h" +#include "content/services/auction_worklet/trusted_signals_request_manager.h" #include "content/services/auction_worklet/worklet_loader.h" #include "gin/converter.h" #include "gin/dictionary.h" @@ -158,15 +159,23 @@ v8_helper_(v8_helper), debug_id_( base::MakeRefCounted<AuctionV8Helper::DebugId>(v8_helper.get())), + url_loader_factory_(std::move(pending_url_loader_factory)), script_source_url_(script_source_url), wasm_helper_url_(wasm_helper_url), - trusted_bidding_signals_url_(trusted_bidding_signals_url), + trusted_signals_request_manager_( + trusted_bidding_signals_url + ? std::make_unique<TrustedSignalsRequestManager>( + TrustedSignalsRequestManager::Type::kBiddingSignals, + url_loader_factory_.get(), + /*automatically_send_requests=*/false, + top_window_origin, + *trusted_bidding_signals_url, + v8_helper_.get()) + : nullptr), top_window_origin_(top_window_origin), v8_state_(nullptr, base::OnTaskRunnerDeleter(v8_runner_)) { DCHECK_CALLED_ON_VALID_SEQUENCE(user_sequence_checker_); - url_loader_factory_.Bind(std::move(pending_url_loader_factory)); - v8_state_ = std::unique_ptr<V8State, base::OnTaskRunnerDeleter>( new V8State(v8_helper, debug_id_, script_source_url_, top_window_origin_, weak_ptr_factory_.GetWeakPtr()), @@ -211,16 +220,12 @@ const auto& trusted_bidding_signals_keys = generate_bid_task->bidder_worklet_non_shared_params ->trusted_bidding_signals_keys; - if (trusted_bidding_signals_url_.has_value() && + if (trusted_signals_request_manager_ && trusted_bidding_signals_keys.has_value() && !trusted_bidding_signals_keys->empty()) { - generate_bid_task->trusted_bidding_signals = - TrustedSignals::LoadBiddingSignals( - url_loader_factory_.get(), - std::set<std::string>(trusted_bidding_signals_keys->begin(), - trusted_bidding_signals_keys->end()), - top_window_origin_.host(), *trusted_bidding_signals_url_, - v8_helper_, + generate_bid_task->trusted_bidding_signals_request = + trusted_signals_request_manager_->RequestBiddingSignals( + *trusted_bidding_signals_keys, base::BindOnce(&BidderWorklet::OnTrustedBiddingSignalsDownloaded, base::Unretained(this), generate_bid_task)); return; @@ -229,6 +234,11 @@ GenerateBidIfReady(generate_bid_task); } +void BidderWorklet::SendPendingSignalsRequests() { + if (trusted_signals_request_manager_) + trusted_signals_request_manager_->StartBatchedTrustedSignalsRequest(); +} + void BidderWorklet::ReportWin( const std::string& interest_group_name, const absl::optional<std::string>& auction_signals_json, @@ -781,14 +791,14 @@ task->trusted_bidding_signals_error_msg = std::move(error_msg); task->trusted_bidding_signals_result = std::move(result); - task->trusted_bidding_signals.reset(); + task->trusted_bidding_signals_request.reset(); GenerateBidIfReady(task); } void BidderWorklet::GenerateBidIfReady(GenerateBidTaskList::iterator task) { DCHECK_CALLED_ON_VALID_SEQUENCE(user_sequence_checker_); - if (task->trusted_bidding_signals || !IsCodeReady()) + if (task->trusted_bidding_signals_request || !IsCodeReady()) return; // Other than the callback field, no fields of `task` are needed after this
diff --git a/content/services/auction_worklet/bidder_worklet.h b/content/services/auction_worklet/bidder_worklet.h index db4b1ca6..d53715fb 100644 --- a/content/services/auction_worklet/bidder_worklet.h +++ b/content/services/auction_worklet/bidder_worklet.h
@@ -19,6 +19,7 @@ #include "content/services/auction_worklet/public/mojom/auction_worklet_service.mojom.h" #include "content/services/auction_worklet/public/mojom/bidder_worklet.mojom.h" #include "content/services/auction_worklet/trusted_signals.h" +#include "content/services/auction_worklet/trusted_signals_request_manager.h" #include "content/services/auction_worklet/worklet_loader.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "mojo/public/cpp/bindings/remote.h" @@ -97,6 +98,7 @@ mojom::BiddingBrowserSignalsPtr bidding_browser_signals, base::Time auction_start_time, GenerateBidCallback generate_bid_callback) override; + void SendPendingSignalsRequests() override; void ReportWin(const std::string& interest_group_name, const absl::optional<std::string>& auction_signals_json, const absl::optional<std::string>& per_buyer_signals_json, @@ -121,7 +123,8 @@ base::Time auction_start_time; // Set while loading is in progress. - std::unique_ptr<TrustedSignals> trusted_bidding_signals; + std::unique_ptr<TrustedSignalsRequestManager::Request> + trusted_bidding_signals_request; // Results of loading trusted bidding signals. scoped_refptr<TrustedSignals::Result> trusted_bidding_signals_result; // Error message returned by attempt to load `trusted_bidding_signals_`. @@ -286,7 +289,11 @@ // for. const GURL script_source_url_; absl::optional<GURL> wasm_helper_url_; - const absl::optional<GURL> trusted_bidding_signals_url_; + + // Populated only if `this` was created with a non-null + // `trusted_scoring_signals_url`. + std::unique_ptr<TrustedSignalsRequestManager> + trusted_signals_request_manager_; // Top window origin for the auctions sharing this BidderWorklet. const url::Origin top_window_origin_;
diff --git a/content/services/auction_worklet/bidder_worklet_unittest.cc b/content/services/auction_worklet/bidder_worklet_unittest.cc index b8fd29f2..95d5b2604 100644 --- a/content/services/auction_worklet/bidder_worklet_unittest.cc +++ b/content/services/auction_worklet/bidder_worklet_unittest.cc
@@ -306,6 +306,7 @@ CreateBiddingBrowserSignals(), auction_start_time_, base::BindOnce(&BidderWorkletTest::GenerateBidCallback, base::Unretained(this))); + bidder_worklet->SendPendingSignalsRequests(); } // Calls GenerateBid(), expecting the callback never to be invoked. @@ -319,6 +320,7 @@ const std::vector<std::string>& errors) { ADD_FAILURE() << "Callback should not be invoked."; })); + bidder_worklet->SendPendingSignalsRequests(); } // Create a BidderWorklet and invokes GenerateBid(), waiting for the @@ -1022,28 +1024,28 @@ // 1) GenerateBid() calls are made. // 2) The worklet script load completes. // 3) The trusted bidding signals are loaded. -TEST_F(BidderWorkletTest, GenerateBidTrustedBiddingSignalsParallel1) { +TEST_F(BidderWorkletTest, GenerateBidTrustedBiddingSignalsParallelBatched1) { interest_group_trusted_bidding_signals_url_ = GURL("https://signals.test/"); - interest_group_trusted_bidding_signals_keys_ = - std::vector<std::string>({"key"}); + interest_group_trusted_bidding_signals_keys_.emplace(); - // Each GenerateBid call provides a different `auctionSignals` value. Use that - // in the result for testing. + // Each GenerateBid() call provides a different `auctionSignals` value. The + // `i` generateBid() call should have trusted scoring signals of {"i":i+1}, + // and this function uses the key as the "ad" parameter, and the value as the + // bid. const char kBidderScriptReturnValue[] = R"({ - ad: trustedBiddingSignals.key, - bid: trustedBiddingSignals.key, + ad: Number(Object.keys(trustedBiddingSignals)[0]), + bid: trustedBiddingSignals[Object.keys(trustedBiddingSignals)[0]], render:"https://response.test/" })"; auto bidder_worklet = CreateWorklet(); - // 1) GenerateBid() calls are made + // 1) GenerateBid() calls are made. base::RunLoop run_loop; const size_t kNumGenerateBidCalls = 10; size_t num_generate_bid_calls = 0; for (size_t i = 0; i < kNumGenerateBidCalls; ++i) { - size_t bid_value = i + 1; - // Append a different key for each request, so they request distinct URLs. + // Append a different key for each request. auto interest_group_fields = CreateBidderWorkletNonSharedParams(); interest_group_fields->trusted_bidding_signals_keys->push_back( base::NumberToString(i)); @@ -1051,19 +1053,20 @@ std::move(interest_group_fields), auction_signals_, per_buyer_signals_, browser_signal_seller_origin_, CreateBiddingBrowserSignals(), auction_start_time_, - base::BindLambdaForTesting( - [&run_loop, &num_generate_bid_calls, bid_value]( - mojom::BidderWorkletBidPtr bid, - const std::vector<std::string>& errors) { - EXPECT_EQ(bid_value, bid->bid); - EXPECT_EQ(base::NumberToString(bid_value), bid->ad); - EXPECT_EQ(GURL("https://response.test/"), bid->render_url); - EXPECT_TRUE(errors.empty()); - ++num_generate_bid_calls; - if (num_generate_bid_calls == kNumGenerateBidCalls) - run_loop.Quit(); - })); + base::BindLambdaForTesting([&run_loop, &num_generate_bid_calls, i]( + mojom::BidderWorkletBidPtr bid, + const std::vector<std::string>& errors) { + EXPECT_EQ(base::NumberToString(i), bid->ad); + EXPECT_EQ(i + 1, bid->bid); + EXPECT_EQ(GURL("https://response.test/"), bid->render_url); + EXPECT_TRUE(errors.empty()); + ++num_generate_bid_calls; + if (num_generate_bid_calls == kNumGenerateBidCalls) + run_loop.Quit(); + })); } + // This should trigger a single network request for all needed signals. + bidder_worklet->SendPendingSignalsRequests(); // Calling GenerateBid() shouldn't cause any callbacks to be invoked - the // BidderWorklet is waiting on both the trusted bidding signals and Javascript @@ -1082,13 +1085,21 @@ EXPECT_EQ(0u, num_generate_bid_calls); // 3) The trusted bidding signals are loaded. + std::string keys; + std::string json; for (size_t i = 0; i < kNumGenerateBidCalls; ++i) { - AddJsonResponse( - &url_loader_factory_, - GURL(base::StringPrintf( - "https://signals.test/?hostname=top.window.test&keys=%zu,key", i)), - base::StringPrintf(R"({"key":%zu})", i + 1)); + if (i != 0) { + keys.append(","); + json.append(","); + } + keys.append(base::NumberToString(i)); + json.append(base::StringPrintf(R"("%zu":%zu)", i, i + 1)); } + AddJsonResponse(&url_loader_factory_, + GURL(base::StringPrintf( + "https://signals.test/?hostname=top.window.test&keys=%s", + keys.c_str())), + base::StringPrintf("{%s}", json.c_str())); // The worklets can now generate bids. run_loop.Run(); @@ -1102,16 +1113,17 @@ // 1) GenerateBid() calls are made // 2) The trusted bidding signals are loaded. // 3) The worklet script load completes. -TEST_F(BidderWorkletTest, GenerateBidTrustedBiddingSignalsParallel2) { +TEST_F(BidderWorkletTest, GenerateBidTrustedBiddingSignalsParallelBatched2) { interest_group_trusted_bidding_signals_url_ = GURL("https://signals.test/"); - interest_group_trusted_bidding_signals_keys_ = - std::vector<std::string>({"key"}); + interest_group_trusted_bidding_signals_keys_.emplace(); - // Each GenerateBid call provides a different `auctionSignals` value. Use that - // in the result for testing. + // Each GenerateBid() call provides a different `auctionSignals` value. The + // `i` generateBid() call should have trusted scoring signals of {"i":i+1}, + // and this function uses the key as the "ad" parameter, and the value as the + // bid. const char kBidderScriptReturnValue[] = R"({ - ad: trustedBiddingSignals.key, - bid: trustedBiddingSignals.key, + ad: Number(Object.keys(trustedBiddingSignals)[0]), + bid: trustedBiddingSignals[Object.keys(trustedBiddingSignals)[0]], render:"https://response.test/" })"; @@ -1122,8 +1134,7 @@ const size_t kNumGenerateBidCalls = 10; size_t num_generate_bid_calls = 0; for (size_t i = 0; i < kNumGenerateBidCalls; ++i) { - size_t bid_value = i + 1; - // Append a different key for each request, so they request distinct URLs. + // Append a different key for each request. auto interest_group_fields = CreateBidderWorkletNonSharedParams(); interest_group_fields->trusted_bidding_signals_keys->push_back( base::NumberToString(i)); @@ -1131,19 +1142,20 @@ std::move(interest_group_fields), auction_signals_, per_buyer_signals_, browser_signal_seller_origin_, CreateBiddingBrowserSignals(), auction_start_time_, - base::BindLambdaForTesting( - [&run_loop, &num_generate_bid_calls, bid_value]( - mojom::BidderWorkletBidPtr bid, - const std::vector<std::string>& errors) { - EXPECT_EQ(bid_value, bid->bid); - EXPECT_EQ(base::NumberToString(bid_value), bid->ad); - EXPECT_EQ(GURL("https://response.test/"), bid->render_url); - EXPECT_TRUE(errors.empty()); - ++num_generate_bid_calls; - if (num_generate_bid_calls == kNumGenerateBidCalls) - run_loop.Quit(); - })); + base::BindLambdaForTesting([&run_loop, &num_generate_bid_calls, i]( + mojom::BidderWorkletBidPtr bid, + const std::vector<std::string>& errors) { + EXPECT_EQ(base::NumberToString(i), bid->ad); + EXPECT_EQ(i + 1, bid->bid); + EXPECT_EQ(GURL("https://response.test/"), bid->render_url); + EXPECT_TRUE(errors.empty()); + ++num_generate_bid_calls; + if (num_generate_bid_calls == kNumGenerateBidCalls) + run_loop.Quit(); + })); } + // This should trigger a single network request for all needed signals. + bidder_worklet->SendPendingSignalsRequests(); // Calling GenerateBid() shouldn't cause any callbacks to be invoked - the // BidderWorklet is waiting on both the trusted bidding signals and Javascript @@ -1153,13 +1165,21 @@ EXPECT_EQ(0u, num_generate_bid_calls); // 2) The trusted bidding signals are loaded. + std::string keys; + std::string json; for (size_t i = 0; i < kNumGenerateBidCalls; ++i) { - AddJsonResponse( - &url_loader_factory_, - GURL(base::StringPrintf( - "https://signals.test/?hostname=top.window.test&keys=%zu,key", i)), - base::StringPrintf(R"({"key":%zu})", i + 1)); + if (i != 0) { + keys.append(","); + json.append(","); + } + keys.append(base::NumberToString(i)); + json.append(base::StringPrintf(R"("%zu":%zu)", i, i + 1)); } + AddJsonResponse(&url_loader_factory_, + GURL(base::StringPrintf( + "https://signals.test/?hostname=top.window.test&keys=%s", + keys.c_str())), + base::StringPrintf("{%s}", json.c_str())); // No callbacks should have been invoked, since the worklet script hasn't // loaded yet. @@ -1183,16 +1203,17 @@ // 1) The worklet script load completes. // 2) GenerateBid() calls are made. // 3) The trusted bidding signals are loaded. -TEST_F(BidderWorkletTest, GenerateBidTrustedBiddingSignalsParallel3) { +TEST_F(BidderWorkletTest, GenerateBidTrustedBiddingSignalsParallelBatched3) { interest_group_trusted_bidding_signals_url_ = GURL("https://signals.test/"); - interest_group_trusted_bidding_signals_keys_ = - std::vector<std::string>({"key"}); + interest_group_trusted_bidding_signals_keys_.emplace(); - // Each GenerateBid call provides a different `auctionSignals` value. Use that - // in the result for testing. + // Each GenerateBid() call provides a different `auctionSignals` value. The + // `i` generateBid() call should have trusted scoring signals of {"i":i+1}, + // and this function uses the key as the "ad" parameter, and the value as the + // bid. const char kBidderScriptReturnValue[] = R"({ - ad: trustedBiddingSignals.key, - bid: trustedBiddingSignals.key, + ad: Number(Object.keys(trustedBiddingSignals)[0]), + bid: trustedBiddingSignals[Object.keys(trustedBiddingSignals)[0]], render:"https://response.test/" })"; @@ -1208,8 +1229,7 @@ const size_t kNumGenerateBidCalls = 10; size_t num_generate_bid_calls = 0; for (size_t i = 0; i < kNumGenerateBidCalls; ++i) { - size_t bid_value = i + 1; - // Append a different key for each request, so they request distinct URLs. + // Append a different key for each request. auto interest_group_fields = CreateBidderWorkletNonSharedParams(); interest_group_fields->trusted_bidding_signals_keys->push_back( base::NumberToString(i)); @@ -1217,19 +1237,20 @@ std::move(interest_group_fields), auction_signals_, per_buyer_signals_, browser_signal_seller_origin_, CreateBiddingBrowserSignals(), auction_start_time_, - base::BindLambdaForTesting( - [&run_loop, &num_generate_bid_calls, bid_value]( - mojom::BidderWorkletBidPtr bid, - const std::vector<std::string>& errors) { - EXPECT_EQ(bid_value, bid->bid); - EXPECT_EQ(base::NumberToString(bid_value), bid->ad); - EXPECT_EQ(GURL("https://response.test/"), bid->render_url); - EXPECT_TRUE(errors.empty()); - ++num_generate_bid_calls; - if (num_generate_bid_calls == kNumGenerateBidCalls) - run_loop.Quit(); - })); + base::BindLambdaForTesting([&run_loop, &num_generate_bid_calls, i]( + mojom::BidderWorkletBidPtr bid, + const std::vector<std::string>& errors) { + EXPECT_EQ(base::NumberToString(i), bid->ad); + EXPECT_EQ(i + 1, bid->bid); + EXPECT_EQ(GURL("https://response.test/"), bid->render_url); + EXPECT_TRUE(errors.empty()); + ++num_generate_bid_calls; + if (num_generate_bid_calls == kNumGenerateBidCalls) + run_loop.Quit(); + })); } + // This should trigger a single network request for all needed signals. + bidder_worklet->SendPendingSignalsRequests(); // No callbacks should have been invoked yet, since the trusted bidding // signals haven't loaded yet. @@ -1238,17 +1259,102 @@ EXPECT_EQ(0u, num_generate_bid_calls); // 3) The trusted bidding signals are loaded. + std::string keys; + std::string json; + for (size_t i = 0; i < kNumGenerateBidCalls; ++i) { + if (i != 0) { + keys.append(","); + json.append(","); + } + keys.append(base::NumberToString(i)); + json.append(base::StringPrintf(R"("%zu":%zu)", i, i + 1)); + } + AddJsonResponse(&url_loader_factory_, + GURL(base::StringPrintf( + "https://signals.test/?hostname=top.window.test&keys=%s", + keys.c_str())), + base::StringPrintf("{%s}", json.c_str())); + + // The worklets can now generate bids. + run_loop.Run(); + EXPECT_EQ(num_generate_bid_calls, kNumGenerateBidCalls); +} + +// Same as the first batched test, but without batching requests. No need to +// test all not batched order variations. +TEST_F(BidderWorkletTest, GenerateBidTrustedBiddingSignalsParallelNotBatched) { + interest_group_trusted_bidding_signals_url_ = GURL("https://signals.test/"); + interest_group_trusted_bidding_signals_keys_.emplace(); + + // Each GenerateBid() call provides a different `auctionSignals` value. The + // `i` generateBid() call should have trusted scoring signals of {"i":i+1}, + // and this function uses the key as the "ad" parameter, and the value as the + // bid. + const char kBidderScriptReturnValue[] = R"({ + ad: Number(Object.keys(trustedBiddingSignals)[0]), + bid: trustedBiddingSignals[Object.keys(trustedBiddingSignals)[0]], + render:"https://response.test/" + })"; + + auto bidder_worklet = CreateWorklet(); + + // 1) GenerateBid() calls are made + base::RunLoop run_loop; + const size_t kNumGenerateBidCalls = 10; + size_t num_generate_bid_calls = 0; + for (size_t i = 0; i < kNumGenerateBidCalls; ++i) { + // Append a different key for each request. + auto interest_group_fields = CreateBidderWorkletNonSharedParams(); + interest_group_fields->trusted_bidding_signals_keys->push_back( + base::NumberToString(i)); + bidder_worklet->GenerateBid( + std::move(interest_group_fields), auction_signals_, per_buyer_signals_, + browser_signal_seller_origin_, CreateBiddingBrowserSignals(), + auction_start_time_, + base::BindLambdaForTesting([&run_loop, &num_generate_bid_calls, i]( + mojom::BidderWorkletBidPtr bid, + const std::vector<std::string>& errors) { + EXPECT_EQ(base::NumberToString(i), bid->ad); + EXPECT_EQ(i + 1, bid->bid); + EXPECT_EQ(GURL("https://response.test/"), bid->render_url); + EXPECT_TRUE(errors.empty()); + ++num_generate_bid_calls; + if (num_generate_bid_calls == kNumGenerateBidCalls) + run_loop.Quit(); + })); + + // Send one request at a time. + bidder_worklet->SendPendingSignalsRequests(); + } + + // Calling GenerateBid() shouldn't cause any callbacks to be invoked - the + // BidderWorklet is waiting on both the trusted bidding signals and Javascript + // responses from the network. + task_environment_.RunUntilIdle(); + EXPECT_FALSE(run_loop.AnyQuitCalled()); + EXPECT_EQ(0u, num_generate_bid_calls); + + // 2) The worklet script load completes. + AddJavascriptResponse(&url_loader_factory_, interest_group_bidding_url_, + CreateGenerateBidScript(kBidderScriptReturnValue)); + // No callbacks are invoked, as the BidderWorklet is still waiting on the + // trusted bidding signals responses. + task_environment_.RunUntilIdle(); + EXPECT_FALSE(run_loop.AnyQuitCalled()); + EXPECT_EQ(0u, num_generate_bid_calls); + + // 3) The trusted bidding signals are loaded. for (size_t i = 0; i < kNumGenerateBidCalls; ++i) { AddJsonResponse( &url_loader_factory_, GURL(base::StringPrintf( - "https://signals.test/?hostname=top.window.test&keys=%zu,key", i)), - base::StringPrintf(R"({"key":%zu})", i + 1)); + "https://signals.test/?hostname=top.window.test&keys=%zu", i)), + base::StringPrintf(R"({"%zu":%zu})", i, i + 1)); } // The worklets can now generate bids. run_loop.Run(); - EXPECT_EQ(num_generate_bid_calls, kNumGenerateBidCalls); + EXPECT_EQ(kNumGenerateBidCalls, num_generate_bid_calls); } TEST_F(BidderWorkletTest, GenerateBidInterestGroupUserBiddingSignals) {
diff --git a/content/services/auction_worklet/public/mojom/bidder_worklet.mojom b/content/services/auction_worklet/public/mojom/bidder_worklet.mojom index 3ff08d6..98c6747 100644 --- a/content/services/auction_worklet/public/mojom/bidder_worklet.mojom +++ b/content/services/auction_worklet/public/mojom/bidder_worklet.mojom
@@ -137,6 +137,15 @@ BidderWorkletBid? bid, array<string> errors); + // Sends pending bidding signals URL requests, if any. Unlike with + // SellerWorklets, this must be called for BidderWorklets that need to send + // requests for realtime bidding signals URL. The difference is because each + // auction makes all GenerateBid() calls to a single BidderWorklet at once + // one after another, so they know at what point they have made their last + // GenerateBid() invocation, and only one signals request will need to be + // made. + SendPendingSignalsRequests(); + // Calls the worklet's reportWin() method. Waits for the worklet script to // be loaded first, if needed. //
diff --git a/content/services/auction_worklet/public/mojom/seller_worklet.mojom b/content/services/auction_worklet/public/mojom/seller_worklet.mojom index 55750c6..e6db4915 100644 --- a/content/services/auction_worklet/public/mojom/seller_worklet.mojom +++ b/content/services/auction_worklet/public/mojom/seller_worklet.mojom
@@ -34,9 +34,8 @@ // // `bid` The numeric value of the bid offered by the BidWorklet. // - // `shareable_auction_config` Subset of the blink.mojom.AuctionAdConfig that - // excludes values that must be the same for all auctions using this - // worklet. + // `auction_ad_config_non_shared_params` Values in an AuctionConfig that can + // vary between auctions that can share a SellerWorklet. // // `browser_signal_interest_group_owner` The owner of the interest group // that offered the bid. @@ -62,7 +61,8 @@ // `score` is 0. ScoreAd(string ad_metadata_json, double bid, - blink.mojom.ShareableAuctionAdConfig shareable_auction_config, + blink.mojom.AuctionAdConfigNonSharedParams + auction_ad_config_non_shared_params, url.mojom.Origin browser_signal_interest_group_owner, url.mojom.Url browser_signal_render_url, array<url.mojom.Url> browser_signal_ad_component_render_urls, @@ -87,9 +87,8 @@ // between invocations of this method and ScoreAd(). // // Arguments: - // `shareable_auction_config` Subset of the blink.mojom.AuctionAdConfig that - // excludes values that must be the same for all auctions using this - // worklet. + // `auction_ad_config_non_shared_params` Values in an AuctionConfig that can + // vary between auctions that can share a SellerWorklet. // // `browser_signal_interest_group_owner` The owner of the interest group // that offered the winning bid. @@ -112,14 +111,16 @@ // sensitive for the renderers to see. `errors` should not be assumed to be // empty if the other values are populated, nor should it be assumed to be // non-empty if the other values are null. - ReportResult(blink.mojom.ShareableAuctionAdConfig shareable_auction_config, - url.mojom.Origin browser_signal_interest_group_owner, - url.mojom.Url browser_signal_render_url, - double browser_signal_bid, - double browser_signal_desirability) => - (string? signals_for_winner, - url.mojom.Url? report_url, - array<string> error_msgs); + ReportResult( + blink.mojom.AuctionAdConfigNonSharedParams + auction_ad_config_non_shared_params, + url.mojom.Origin browser_signal_interest_group_owner, + url.mojom.Url browser_signal_render_url, + double browser_signal_bid, + double browser_signal_desirability) => + (string? signals_for_winner, + url.mojom.Url? report_url, + array<string> error_msgs); // Establishes a debugger connection to the worklet. ConnectDevToolsAgent(pending_receiver<blink.mojom.DevToolsAgent> agent);
diff --git a/content/services/auction_worklet/seller_worklet.cc b/content/services/auction_worklet/seller_worklet.cc index 412bd800..19972c6 100644 --- a/content/services/auction_worklet/seller_worklet.cc +++ b/content/services/auction_worklet/seller_worklet.cc
@@ -55,12 +55,12 @@ // 'https://www.another-buyer.com': {...}, // ...} // } -bool AppendAuctionConfig( - AuctionV8Helper* const v8_helper, - v8::Local<v8::Context> context, - const GURL& decision_logic_url, - const blink::mojom::ShareableAuctionAdConfig& shareable_auction_config, - std::vector<v8::Local<v8::Value>>* args) { +bool AppendAuctionConfig(AuctionV8Helper* const v8_helper, + v8::Local<v8::Context> context, + const GURL& decision_logic_url, + const blink::mojom::AuctionAdConfigNonSharedParams& + auction_ad_config_non_shared_params, + std::vector<v8::Local<v8::Value>>* args) { v8::Isolate* isolate = v8_helper->isolate(); v8::Local<v8::Object> auction_config_value = v8::Object::New(isolate); gin::Dictionary auction_config_dict(isolate, auction_config_value); @@ -70,14 +70,16 @@ return false; } - if (shareable_auction_config.interest_group_buyers) { - if (shareable_auction_config.interest_group_buyers->is_all_buyers()) { + if (auction_ad_config_non_shared_params.interest_group_buyers) { + if (auction_ad_config_non_shared_params.interest_group_buyers + ->is_all_buyers()) { if (!auction_config_dict.Set("interestGroupBuyers", std::string("*"))) return false; } else { std::vector<v8::Local<v8::Value>> interest_group_buyers; for (const url::Origin& buyer : - shareable_auction_config.interest_group_buyers->get_buyers()) { + auction_ad_config_non_shared_params.interest_group_buyers + ->get_buyers()) { v8::Local<v8::String> v8_buyer; if (!v8_helper->CreateUtf8String(buyer.Serialize()).ToLocal(&v8_buyer)) return false; @@ -87,25 +89,26 @@ } } - if (shareable_auction_config.auction_signals.has_value() && + if (auction_ad_config_non_shared_params.auction_signals.has_value() && !v8_helper->InsertJsonValue( context, "auctionSignals", - shareable_auction_config.auction_signals.value(), + auction_ad_config_non_shared_params.auction_signals.value(), auction_config_value)) { return false; } - if (shareable_auction_config.seller_signals.has_value() && + if (auction_ad_config_non_shared_params.seller_signals.has_value() && !v8_helper->InsertJsonValue( context, "sellerSignals", - shareable_auction_config.seller_signals.value(), + auction_ad_config_non_shared_params.seller_signals.value(), auction_config_value)) { return false; } - if (shareable_auction_config.per_buyer_signals.has_value()) { + if (auction_ad_config_non_shared_params.per_buyer_signals.has_value()) { v8::Local<v8::Object> per_buyer_value = v8::Object::New(isolate); - for (const auto& kv : shareable_auction_config.per_buyer_signals.value()) { + for (const auto& kv : + auction_ad_config_non_shared_params.per_buyer_signals.value()) { if (!v8_helper->InsertJsonValue(context, kv.first.Serialize(), kv.second, per_buyer_value)) { return false; @@ -169,7 +172,8 @@ void SellerWorklet::ScoreAd( const std::string& ad_metadata_json, double bid, - blink::mojom::ShareableAuctionAdConfigPtr shareable_auction_config, + blink::mojom::AuctionAdConfigNonSharedParamsPtr + auction_ad_config_non_shared_params, const url::Origin& browser_signal_interest_group_owner, const GURL& browser_signal_render_url, const std::vector<GURL>& browser_signal_ad_components, @@ -182,7 +186,8 @@ auto score_ad_task = score_ad_tasks_.begin(); score_ad_task->ad_metadata_json = ad_metadata_json; score_ad_task->bid = bid; - score_ad_task->shareable_auction_config = std::move(shareable_auction_config); + score_ad_task->auction_ad_config_non_shared_params = + std::move(auction_ad_config_non_shared_params); score_ad_task->browser_signal_interest_group_owner = browser_signal_interest_group_owner; score_ad_task->browser_signal_render_url = browser_signal_render_url; @@ -214,7 +219,8 @@ } void SellerWorklet::ReportResult( - blink::mojom::ShareableAuctionAdConfigPtr shareable_auction_config, + blink::mojom::AuctionAdConfigNonSharedParamsPtr + auction_ad_config_non_shared_params, const url::Origin& browser_signal_interest_group_owner, const GURL& browser_signal_render_url, double browser_signal_bid, @@ -227,7 +233,7 @@ FROM_HERE, base::BindOnce(&SellerWorklet::V8State::ReportResult, base::Unretained(v8_state_.get()), - std::move(shareable_auction_config), + std::move(auction_ad_config_non_shared_params), browser_signal_interest_group_owner, browser_signal_render_url, browser_signal_bid, browser_signal_desirability, std::move(callback))); @@ -271,7 +277,8 @@ void SellerWorklet::V8State::ScoreAd( const std::string& ad_metadata_json, double bid, - blink::mojom::ShareableAuctionAdConfigPtr shareable_auction_config, + blink::mojom::AuctionAdConfigNonSharedParamsPtr + auction_ad_config_non_shared_params, scoped_refptr<TrustedSignals::Result> trusted_scoring_signals, const url::Origin& browser_signal_interest_group_owner, const GURL& browser_signal_render_url, @@ -297,7 +304,7 @@ args.push_back(gin::ConvertToV8(isolate, bid)); if (!AppendAuctionConfig(v8_helper_.get(), context, decision_logic_url_, - *shareable_auction_config, &args)) { + *auction_ad_config_non_shared_params, &args)) { PostScoreAdCallbackToUserThread(std::move(callback), 0 /* score */, std::vector<std::string>() /* errors */); return; @@ -374,7 +381,8 @@ } void SellerWorklet::V8State::ReportResult( - blink::mojom::ShareableAuctionAdConfigPtr shareable_auction_config, + blink::mojom::AuctionAdConfigNonSharedParamsPtr + auction_ad_config_non_shared_params, const url::Origin& browser_signal_interest_group_owner, const GURL& browser_signal_render_url, double browser_signal_bid, @@ -395,7 +403,7 @@ std::vector<v8::Local<v8::Value>> args; if (!AppendAuctionConfig(v8_helper_.get(), context, decision_logic_url_, - *shareable_auction_config, &args)) { + *auction_ad_config_non_shared_params, &args)) { PostReportResultCallbackToUserThread( std::move(callback), absl::nullopt /* signals_for_winner */, absl::nullopt /* report_url */, @@ -556,7 +564,7 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(user_sequence_checker_); task->trusted_scoring_signals_error_msg = std::move(error_msg); - task->trusted_bidding_signals_result = std::move(result); + task->trusted_scoring_signals_result = std::move(result); // Clean up single-use object, now that it has done its job. task->trusted_scoring_signals_request.reset(); @@ -574,8 +582,8 @@ base::BindOnce( &SellerWorklet::V8State::ScoreAd, base::Unretained(v8_state_.get()), task->ad_metadata_json, task->bid, - std::move(task->shareable_auction_config), - std::move(task->trusted_bidding_signals_result), + std::move(task->auction_ad_config_non_shared_params), + std::move(task->trusted_scoring_signals_result), std::move(task->browser_signal_interest_group_owner), std::move(task->browser_signal_render_url), std::move(task->browser_signal_ad_components),
diff --git a/content/services/auction_worklet/seller_worklet.h b/content/services/auction_worklet/seller_worklet.h index 12f5369..debe447 100644 --- a/content/services/auction_worklet/seller_worklet.h +++ b/content/services/auction_worklet/seller_worklet.h
@@ -73,23 +73,23 @@ int context_group_id_for_testing() const; // mojom::SellerWorklet implementation: - void ScoreAd( - const std::string& ad_metadata_json, - double bid, - blink::mojom::ShareableAuctionAdConfigPtr shareable_auction_config, - const url::Origin& browser_signal_interest_group_owner, - const GURL& browser_signal_render_url, - const std::vector<GURL>& browser_signal_ad_components, - uint32_t browser_signal_bidding_duration_msecs, - ScoreAdCallback callback) override; + void ScoreAd(const std::string& ad_metadata_json, + double bid, + blink::mojom::AuctionAdConfigNonSharedParamsPtr + auction_ad_config_non_shared_params, + const url::Origin& browser_signal_interest_group_owner, + const GURL& browser_signal_render_url, + const std::vector<GURL>& browser_signal_ad_components, + uint32_t browser_signal_bidding_duration_msecs, + ScoreAdCallback callback) override; void SendPendingSignalsRequests() override; - void ReportResult( - blink::mojom::ShareableAuctionAdConfigPtr shareable_auction_config, - const url::Origin& browser_signal_interest_group_owner, - const GURL& browser_signal_render_url, - double browser_signal_bid, - double browser_signal_desirability, - ReportResultCallback callback) override; + void ReportResult(blink::mojom::AuctionAdConfigNonSharedParamsPtr + auction_ad_config_non_shared_params, + const url::Origin& browser_signal_interest_group_owner, + const GURL& browser_signal_render_url, + double browser_signal_bid, + double browser_signal_desirability, + ReportResultCallback callback) override; void ConnectDevToolsAgent( mojo::PendingReceiver<blink::mojom::DevToolsAgent> agent) override; @@ -105,7 +105,8 @@ // safe to access after that happens. std::string ad_metadata_json; double bid; - blink::mojom::ShareableAuctionAdConfigPtr shareable_auction_config; + blink::mojom::AuctionAdConfigNonSharedParamsPtr + auction_ad_config_non_shared_params; url::Origin browser_signal_interest_group_owner; GURL browser_signal_render_url; // While these are URLs, it's more concenient to store these as strings @@ -118,7 +119,7 @@ std::unique_ptr<TrustedSignalsRequestManager::Request> trusted_scoring_signals_request; - scoped_refptr<TrustedSignals::Result> trusted_bidding_signals_result; + scoped_refptr<TrustedSignals::Result> trusted_scoring_signals_result; // Error message from downloading trusted scoring signals, if any. Prepended // to errors passed to the ScoreAdCallback. @@ -146,24 +147,24 @@ void SetWorkletScript(WorkletLoader::Result worklet_script); - void ScoreAd( - const std::string& ad_metadata_json, - double bid, - blink::mojom::ShareableAuctionAdConfigPtr shareable_auction_config, - scoped_refptr<TrustedSignals::Result> trusted_scoring_signals, - const url::Origin& browser_signal_interest_group_owner, - const GURL& browser_signal_render_url, - const std::vector<std::string>& browser_signal_ad_components, - uint32_t browser_signal_bidding_duration_msecs, - ScoreAdCallbackInternal callback); + void ScoreAd(const std::string& ad_metadata_json, + double bid, + blink::mojom::AuctionAdConfigNonSharedParamsPtr + auction_ad_config_non_shared_params, + scoped_refptr<TrustedSignals::Result> trusted_scoring_signals, + const url::Origin& browser_signal_interest_group_owner, + const GURL& browser_signal_render_url, + const std::vector<std::string>& browser_signal_ad_components, + uint32_t browser_signal_bidding_duration_msecs, + ScoreAdCallbackInternal callback); - void ReportResult( - blink::mojom::ShareableAuctionAdConfigPtr shareable_auction_config, - const url::Origin& browser_signal_interest_group_owner, - const GURL& browser_signal_render_url, - double browser_signal_bid, - double browser_signal_desirability, - ReportResultCallback callback); + void ReportResult(blink::mojom::AuctionAdConfigNonSharedParamsPtr + auction_ad_config_non_shared_params, + const url::Origin& browser_signal_interest_group_owner, + const GURL& browser_signal_render_url, + double browser_signal_bid, + double browser_signal_desirability, + ReportResultCallback callback); void ConnectDevToolsAgent( mojo::PendingReceiver<blink::mojom::DevToolsAgent> agent); @@ -243,7 +244,7 @@ const GURL script_source_url_; - // This is populated only if `this` was created with a non-null + // Populated only if `this` was created with a non-null // `trusted_scoring_signals_url`. std::unique_ptr<TrustedSignalsRequestManager> trusted_signals_request_manager_;
diff --git a/content/services/auction_worklet/seller_worklet_unittest.cc b/content/services/auction_worklet/seller_worklet_unittest.cc index 4e62444..9c710d4 100644 --- a/content/services/auction_worklet/seller_worklet_unittest.cc +++ b/content/services/auction_worklet/seller_worklet_unittest.cc
@@ -115,7 +115,8 @@ bid_ = 1; decision_logic_url_ = GURL("https://url.test/"); trusted_scoring_signals_url_.reset(); - shareable_config_ = blink::mojom::ShareableAuctionAdConfig::New(); + auction_ad_config_non_shared_params_ = + blink::mojom::AuctionAdConfigNonSharedParams::New(); top_window_origin_ = url::Origin::Create(GURL("https://window.test/")); browser_signal_interest_group_owner_ = @@ -183,7 +184,7 @@ const std::vector<std::string>& expected_errors, base::OnceClosure done_closure) { seller_worklet->ScoreAd( - ad_metadata_, bid_, shareable_config_.Clone(), + ad_metadata_, bid_, auction_ad_config_non_shared_params_.Clone(), browser_signal_interest_group_owner_, browser_signal_render_url_, browser_signal_ad_components_, browser_signal_bidding_duration_msecs_, base::BindOnce( @@ -200,7 +201,7 @@ void RunScoreAdOnWorkletExpectingCallbackNeverInvoked( mojom::SellerWorklet* seller_worklet) { seller_worklet->ScoreAd( - ad_metadata_, bid_, shareable_config_.Clone(), + ad_metadata_, bid_, auction_ad_config_non_shared_params_.Clone(), browser_signal_interest_group_owner_, browser_signal_render_url_, browser_signal_ad_components_, browser_signal_bidding_duration_msecs_, base::BindOnce( @@ -273,8 +274,9 @@ const std::vector<std::string>& expected_errors, base::OnceClosure done_closure) { seller_worklet->ReportResult( - shareable_config_.Clone(), browser_signal_interest_group_owner_, - browser_signal_render_url_, bid_, browser_signal_desireability_, + auction_ad_config_non_shared_params_.Clone(), + browser_signal_interest_group_owner_, browser_signal_render_url_, bid_, + browser_signal_desireability_, base::BindOnce( [](const absl::optional<std::string>& expected_signals_for_winner, const absl::optional<GURL>& expected_report_url, @@ -383,7 +385,8 @@ double bid_; GURL decision_logic_url_; absl::optional<GURL> trusted_scoring_signals_url_; - blink::mojom::ShareableAuctionAdConfigPtr shareable_config_; + blink::mojom::AuctionAdConfigNonSharedParamsPtr + auction_ad_config_non_shared_params_; url::Origin top_window_origin_; url::Origin browser_signal_interest_group_owner_; GURL browser_signal_render_url_; @@ -1151,17 +1154,20 @@ // Everything filled in. decision_logic_url_ = GURL("https://example.com/auction.js"); - shareable_config_->interest_group_buyers = + auction_ad_config_non_shared_params_->interest_group_buyers = blink::mojom::InterestGroupBuyers::NewAllBuyers( blink::mojom::AllBuyers::New()); - shareable_config_->auction_signals = R"({"is_auction_signals": true})"; - shareable_config_->seller_signals = R"({"is_seller_signals": true})"; + auction_ad_config_non_shared_params_->auction_signals = + R"({"is_auction_signals": true})"; + auction_ad_config_non_shared_params_->seller_signals = + R"({"is_seller_signals": true})"; base::flat_map<url::Origin, std::string> per_buyer_signals; per_buyer_signals[url::Origin::Create(GURL("https://a.com"))] = R"({"signals_a": "A"})"; per_buyer_signals[url::Origin::Create(GURL("https://b.com"))] = R"({"signals_b": "B"})"; - shareable_config_->per_buyer_signals = std::move(per_buyer_signals); + auction_ad_config_non_shared_params_->per_buyer_signals = + std::move(per_buyer_signals); const char kExpectedJson[] = R"({"seller":"https://example.com",)" @@ -1180,9 +1186,10 @@ std::vector<url::Origin> buyers; buyers.push_back(url::Origin::Create(GURL("https://buyer1.com"))); buyers.push_back(url::Origin::Create(GURL("https://another-buyer.com"))); - shareable_config_ = blink::mojom::ShareableAuctionAdConfig::New(); + auction_ad_config_non_shared_params_ = + blink::mojom::AuctionAdConfigNonSharedParams::New(); decision_logic_url_ = GURL("https://example.com/auction.js"); - shareable_config_->interest_group_buyers = + auction_ad_config_non_shared_params_->interest_group_buyers = blink::mojom::InterestGroupBuyers::NewBuyers(std::move(buyers)); const char kExpectedJson2[] = R"({"seller":"https://example.com",)" @@ -1226,7 +1233,7 @@ for (int j = 0; j < 2; ++j) { base::RunLoop run_loop; seller_worklet->ScoreAd( - ad_metadata_, bid_, shareable_config_.Clone(), + ad_metadata_, bid_, auction_ad_config_non_shared_params_.Clone(), browser_signal_interest_group_owner_, browser_signal_render_url_, browser_signal_ad_components_, browser_signal_bidding_duration_msecs_, base::BindLambdaForTesting( @@ -1242,8 +1249,9 @@ for (int j = 0; j < 2; ++j) { base::RunLoop run_loop; seller_worklet->ReportResult( - shareable_config_.Clone(), browser_signal_interest_group_owner_, - browser_signal_render_url_, bid_, browser_signal_desireability_, + auction_ad_config_non_shared_params_.Clone(), + browser_signal_interest_group_owner_, browser_signal_render_url_, + bid_, browser_signal_desireability_, base::BindLambdaForTesting( [&run_loop](const absl::optional<std::string>& signals_for_winner, const absl::optional<GURL>& report_url, @@ -1265,7 +1273,7 @@ base::WaitableEvent* event_handle = WedgeV8Thread(v8_helper_.get()); seller_worklet->ScoreAd( - ad_metadata_, bid_, shareable_config_.Clone(), + ad_metadata_, bid_, auction_ad_config_non_shared_params_.Clone(), browser_signal_interest_group_owner_, browser_signal_render_url_, browser_signal_ad_components_, browser_signal_bidding_duration_msecs_, base::BindOnce([](double score, const std::vector<std::string>& errors) { @@ -1287,8 +1295,9 @@ base::WaitableEvent* event_handle = WedgeV8Thread(v8_helper_.get()); seller_worklet->ReportResult( - shareable_config_.Clone(), browser_signal_interest_group_owner_, - browser_signal_render_url_, bid_, browser_signal_desireability_, + auction_ad_config_non_shared_params_.Clone(), + browser_signal_interest_group_owner_, browser_signal_render_url_, bid_, + browser_signal_desireability_, base::BindOnce([](const absl::optional<std::string>& signals_for_winner, const absl::optional<GURL>& report_url, const std::vector<std::string>& errors) {
diff --git a/device/bluetooth/public/mojom/BUILD.gn b/device/bluetooth/public/mojom/BUILD.gn index 31d67355..1c8b889 100644 --- a/device/bluetooth/public/mojom/BUILD.gn +++ b/device/bluetooth/public/mojom/BUILD.gn
@@ -6,6 +6,7 @@ mojom("mojom") { sources = [ "uuid.mojom" ] + webui_module_path = "/" cpp_typemaps = [ { @@ -48,6 +49,7 @@ "adapter.mojom", "device.mojom", ] + webui_module_path = "/" public_deps = [ ":mojom" ]
diff --git a/extensions/shell/browser/shell_content_browser_client.cc b/extensions/shell/browser/shell_content_browser_client.cc index 7e607d6a..5ef23f3 100644 --- a/extensions/shell/browser/shell_content_browser_client.cc +++ b/extensions/shell/browser/shell_content_browser_client.cc
@@ -403,8 +403,6 @@ kSwitchNames, base::size(kSwitchNames)); #if BUILDFLAG(ENABLE_NACL) - // NOTE: app_shell does not support non-SFI mode, so it does not pass through - // SFI switches either here or for the zygote process. static const char* const kNaclSwitchNames[] = { ::switches::kEnableNaClDebug, };
diff --git a/gpu/vulkan/vulkan_device_queue.cc b/gpu/vulkan/vulkan_device_queue.cc index 41450a73..ab1d25a 100644 --- a/gpu/vulkan/vulkan_device_queue.cc +++ b/gpu/vulkan/vulkan_device_queue.cc
@@ -391,7 +391,8 @@ VkDevice vk_device, VkQueue vk_queue, uint32_t vk_queue_index, - gfx::ExtensionSet enabled_extensions) { + gfx::ExtensionSet enabled_extensions, + const VkPhysicalDeviceFeatures2& vk_physical_device_features2) { // Currently VulkanDeviceQueue for drdc thread(aka CompositorGpuThread) uses // the same vulkan queue as the gpu main thread. Now since both gpu main and // drdc threads would be accessing/submitting work to the same queue, all the @@ -406,6 +407,7 @@ // access map here. GetVulkanFunctionPointers()->per_queue_lock_map[vk_queue] = std::make_unique<base::Lock>(); + enabled_device_features_2_ = vk_physical_device_features2; return InitCommon(vk_physical_device, vk_device, vk_queue, vk_queue_index, enabled_extensions); }
diff --git a/gpu/vulkan/vulkan_device_queue.h b/gpu/vulkan/vulkan_device_queue.h index 98ddec0..fb19191 100644 --- a/gpu/vulkan/vulkan_device_queue.h +++ b/gpu/vulkan/vulkan_device_queue.h
@@ -65,11 +65,13 @@ // have its own instance of VulkanFenceHelper and VmaAllocator. Also note that // this CompositorGpuThread does not own the |vk_device| and |vk_queue| and // hence will not destroy them. - bool InitializeForCompositorGpuThread(VkPhysicalDevice vk_physical_device, - VkDevice vk_device, - VkQueue vk_queue, - uint32_t vk_queue_index, - gfx::ExtensionSet enabled_extensions); + bool InitializeForCompositorGpuThread( + VkPhysicalDevice vk_physical_device, + VkDevice vk_device, + VkQueue vk_queue, + uint32_t vk_queue_index, + gfx::ExtensionSet enabled_extensions, + const VkPhysicalDeviceFeatures2& vk_physical_device_features2); const gfx::ExtensionSet& enabled_extensions() const { return enabled_extensions_;
diff --git a/infra/config/generated/luci/commit-queue.cfg b/infra/config/generated/luci/commit-queue.cfg index 3a2f69a..92336168 100644 --- a/infra/config/generated/luci/commit-queue.cfg +++ b/infra/config/generated/luci/commit-queue.cfg
@@ -162,6 +162,12 @@ owner_whitelist_group: "project-chromium-robot-committers" } builders { + name: "chrome/try/mac-arm-pgo" + includable_only: true + owner_whitelist_group: "googlers" + owner_whitelist_group: "project-chromium-robot-committers" + } + builders { name: "chrome/try/mac-chrome" includable_only: true owner_whitelist_group: "googlers"
diff --git a/infra/config/subprojects/chromium/try.star b/infra/config/subprojects/chromium/try.star index 791c9d6..d8d2f61 100644 --- a/infra/config/subprojects/chromium/try.star +++ b/infra/config/subprojects/chromium/try.star
@@ -262,6 +262,11 @@ ) chrome_internal_verifier( + builder = "mac-arm-pgo", + branch_selector = branches.STANDARD_MILESTONE, +) + +chrome_internal_verifier( builder = "mac-pgo", branch_selector = branches.STANDARD_MILESTONE, )
diff --git a/ios/chrome/browser/providers/BUILD.gn b/ios/chrome/browser/providers/BUILD.gn index 699bc652..1eadbcca 100644 --- a/ios/chrome/browser/providers/BUILD.gn +++ b/ios/chrome/browser/providers/BUILD.gn
@@ -48,6 +48,7 @@ "//ios/chrome/browser/providers/risk_data:chromium_risk_data", "//ios/chrome/browser/providers/signin:chromium_signin_error", "//ios/chrome/browser/providers/signin:chromium_signin_resources", + "//ios/chrome/browser/providers/signin:chromium_signin_sso", "//ios/chrome/browser/providers/text_zoom:chromium_text_zoom", "//ios/chrome/browser/providers/ui_utils:chromium_ui_utils", "//ios/chrome/browser/providers/url_rewriters:chromium_url_rewriters",
diff --git a/ios/chrome/browser/providers/signin/BUILD.gn b/ios/chrome/browser/providers/signin/BUILD.gn index a5088a2..147595e 100644 --- a/ios/chrome/browser/providers/signin/BUILD.gn +++ b/ios/chrome/browser/providers/signin/BUILD.gn
@@ -21,3 +21,10 @@ ] frameworks = [ "UIKit.framework" ] } + +source_set("chromium_signin_sso") { + configs += [ "//build/config/compiler:enable_arc" ] + sources = [ "chromium_signin_sso.mm" ] + deps = [ "//ios/public/provider/chrome/browser/signin:signin_sso_api" ] + frameworks = [ "Foundation.framework" ] +}
diff --git a/ios/chrome/browser/providers/signin/chromium_signin_sso.mm b/ios/chrome/browser/providers/signin/chromium_signin_sso.mm new file mode 100644 index 0000000..a83c554e --- /dev/null +++ b/ios/chrome/browser/providers/signin/chromium_signin_sso.mm
@@ -0,0 +1,27 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#import "ios/public/provider/chrome/browser/signin/signin_sso_api.h" + +#import <Foundation/Foundation.h> + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +@interface ChromiumSingleSignOnService : NSObject <SingleSignOnService> +@end + +@implementation ChromiumSingleSignOnService +@end + +namespace ios { +namespace provider { + +id<SingleSignOnService> CreateSSOService() { + return [[ChromiumSingleSignOnService alloc] init]; +} + +} // namespace provider +} // namespace ios
diff --git a/ios/chrome/browser/ui/infobars/infobar_egtest.mm b/ios/chrome/browser/ui/infobars/infobar_egtest.mm index 6617b2f..82f42fb 100644 --- a/ios/chrome/browser/ui/infobars/infobar_egtest.mm +++ b/ios/chrome/browser/ui/infobars/infobar_egtest.mm
@@ -33,10 +33,13 @@ visible ? @"Waiting for infobar to show" : @"Waiting for infobar to hide"; id<GREYMatcher> expected_visibility = visible ? grey_notNil() : grey_nil(); - // After |kInfobarBannerDefaultPresentationDurationInSeconds| seconds the + // After |kInfobarBannerLongPresentationDurationInSeconds| seconds the // banner should disappear. Includes |kWaitForUIElementTimeout| for EG // synchronization. - NSTimeInterval delay = kInfobarBannerDefaultPresentationDurationInSeconds + + // TODO(crbug.com/1284475): After the experiment, the delay time should be + // set back to |kInfobarBannerDefaultPresentationDurationInSeconds| + + // |kWaitForUIElementTimeout|to save testing time. + NSTimeInterval delay = kInfobarBannerLongPresentationDurationInSeconds + base::test::ios::kWaitForUIElementTimeout; BOOL bannerShown = WaitUntilConditionOrTimeout(delay, ^{
diff --git a/ios/chrome/browser/ui/toolbar/primary_toolbar_view_controller.mm b/ios/chrome/browser/ui/toolbar/primary_toolbar_view_controller.mm index f9329b2..5b14db6e 100644 --- a/ios/chrome/browser/ui/toolbar/primary_toolbar_view_controller.mm +++ b/ios/chrome/browser/ui/toolbar/primary_toolbar_view_controller.mm
@@ -268,7 +268,6 @@ - (void)expandLocationBar { [self deactivateViewLocationBarConstraints]; [NSLayoutConstraint activateConstraints:self.view.expandedConstraints]; - NSLog(@"rkgibson: Expanding"); [self.view layoutIfNeeded]; } @@ -277,7 +276,6 @@ if (IsSplitToolbarMode(self)) { [NSLayoutConstraint activateConstraints:self.view.contractedNoMarginConstraints]; - NSLog(@"rkgibson: Contracting"); } else { [NSLayoutConstraint activateConstraints:self.view.contractedConstraints]; }
diff --git a/ios/chrome/test/app/sync_test_util.mm b/ios/chrome/test/app/sync_test_util.mm index 0efaedd..d088d8e3 100644 --- a/ios/chrome/test/app/sync_test_util.mm +++ b/ios/chrome/test/app/sync_test_util.mm
@@ -136,7 +136,7 @@ std::unique_ptr<base::DictionaryValue> entities = gSyncFakeServer->GetEntitiesAsDictionaryValue(); - std::string model_type_string = ModelTypeToString(type); + std::string model_type_string = ModelTypeToDebugString(type); base::ListValue* entity_list = NULL; if (!entities->GetList(model_type_string, &entity_list)) { return 0;
diff --git a/ios/chrome/test/earl_grey/chrome_earl_grey_ui.mm b/ios/chrome/test/earl_grey/chrome_earl_grey_ui.mm index 43ca9267..fcdfe15 100644 --- a/ios/chrome/test/earl_grey/chrome_earl_grey_ui.mm +++ b/ios/chrome/test/earl_grey/chrome_earl_grey_ui.mm
@@ -124,9 +124,9 @@ - (void)closeToolsMenu { if ([ChromeEarlGrey isNewOverflowMenuEnabled] && - UIDevice.currentDevice.userInterfaceIdiom == UIUserInterfaceIdiomPhone) { - // With the new overflow menu on iPhone, the half sheet covers the bottom - // half of the screen. Swiping down on the sheet will close the menu. + [ChromeEarlGrey isCompactWidth]) { + // With the new overflow menu on compact devices, the half sheet covers the + // bottom half of the screen. Swiping down on the sheet will close the menu. [[EarlGrey selectElementWithMatcher:chrome_test_util::ToolsMenuView()] performAction:grey_swipeFastInDirection(kGREYDirectionDown)]; } else {
diff --git a/ios/chrome/test/providers/BUILD.gn b/ios/chrome/test/providers/BUILD.gn index 6ec61a3..094b212 100644 --- a/ios/chrome/test/providers/BUILD.gn +++ b/ios/chrome/test/providers/BUILD.gn
@@ -19,7 +19,6 @@ "//ios/chrome/test/providers/password_auto_fill", "//ios/chrome/test/providers/risk_data", "//ios/chrome/test/providers/signin", - "//ios/chrome/test/providers/signin", "//ios/chrome/test/providers/text_zoom", "//ios/chrome/test/providers/ui_utils", "//ios/chrome/test/providers/url_rewriters",
diff --git a/ios/chrome/test/providers/signin/BUILD.gn b/ios/chrome/test/providers/signin/BUILD.gn index 0b64829f..5f3080d 100644 --- a/ios/chrome/test/providers/signin/BUILD.gn +++ b/ios/chrome/test/providers/signin/BUILD.gn
@@ -7,6 +7,7 @@ deps = [ ":signin_error", ":signin_resources", + ":signin_sso", ] } @@ -31,3 +32,11 @@ ] frameworks = [ "UIKit.framework" ] } + +source_set("signin_sso") { + testonly = true + configs += [ "//build/config/compiler:enable_arc" ] + sources = [ "test_signin_sso.mm" ] + deps = [ "//ios/public/provider/chrome/browser/signin:signin_sso_api" ] + frameworks = [ "Foundation.framework" ] +}
diff --git a/ios/chrome/test/providers/signin/test_signin_sso.mm b/ios/chrome/test/providers/signin/test_signin_sso.mm new file mode 100644 index 0000000..29581fb8 --- /dev/null +++ b/ios/chrome/test/providers/signin/test_signin_sso.mm
@@ -0,0 +1,27 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#import "ios/public/provider/chrome/browser/signin/signin_sso_api.h" + +#import <Foundation/Foundation.h> + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +@interface TestSingleSignOnService : NSObject <SingleSignOnService> +@end + +@implementation TestSingleSignOnService +@end + +namespace ios { +namespace provider { + +id<SingleSignOnService> CreateSSOService() { + return [[TestSingleSignOnService alloc] init]; +} + +} // namespace provider +} // namespace ios
diff --git a/ios/components/webui/sync_internals/sync_internals_message_handler.mm b/ios/components/webui/sync_internals/sync_internals_message_handler.mm index 2009f554..fec62e4 100644 --- a/ios/components/webui/sync_internals/sync_internals_message_handler.mm +++ b/ios/components/webui/sync_internals/sync_internals_message_handler.mm
@@ -128,7 +128,7 @@ auto type_list = std::make_unique<base::ListValue>(); syncer::ModelTypeSet protocol_types = syncer::ProtocolTypes(); for (syncer::ModelType type : protocol_types) { - type_list->Append(ModelTypeToString(type)); + type_list->Append(ModelTypeToDebugString(type)); } event_details.Set(syncer::sync_ui_util::kTypes, std::move(type_list)); DispatchEvent(syncer::sync_ui_util::kOnReceivedListOfTypes, event_details); @@ -263,7 +263,7 @@ for (const syncer::TypeEntitiesCount& count : entity_counts) { base::DictionaryValue count_dictionary; count_dictionary.SetStringPath(syncer::sync_ui_util::kModelType, - ModelTypeToString(count.type)); + ModelTypeToDebugString(count.type)); count_dictionary.SetIntPath(syncer::sync_ui_util::kEntities, count.entities); count_dictionary.SetIntPath(syncer::sync_ui_util::kNonTombstoneEntities,
diff --git a/ios/google_internal/frameworks/LSApplicationQuerySchemes.plist.sha1 b/ios/google_internal/frameworks/LSApplicationQuerySchemes.plist.sha1 index b7b1541..0aca43bd 100644 --- a/ios/google_internal/frameworks/LSApplicationQuerySchemes.plist.sha1 +++ b/ios/google_internal/frameworks/LSApplicationQuerySchemes.plist.sha1
@@ -1 +1 @@ -24da1b3ddbd47ddbc716471228fd2e6db577e5b5 \ No newline at end of file +9a2519bd4af4e085afa809c39bf9867aee250f80 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/chrome_internal_dynamic_framework.ios.zip.sha1 b/ios/google_internal/frameworks/chrome_internal_dynamic_framework.ios.zip.sha1 index d8bd273..0e022bf 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 @@ -98e34c9bd8467de54f31b6849216f915e5ce9b71 \ No newline at end of file +8410b3c11e9aadaf98b1c2e621362d77bfeb0f25 \ 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 ce99124..befe5a0 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 @@ -8fc241e4d29caa8900339b2a449628d51b798f53 \ No newline at end of file +24c20df5c36374c0935030b9e0da17953d60e822 \ 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 8017274..ac3dbff 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 @@ -dea257e2babf128def3a05899747f145ea5a6d9d \ No newline at end of file +97ccfd87f3ee5195ef5fe2d4d9021197483767d9 \ 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 036362be..b3e54b36 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 @@ -81268634c9fa5bc11dae81d0f083b495257514df \ No newline at end of file +f6d1af4d3b976c6f577f12c3fcc91a541e091b40 \ 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 231ba121..9a54435e 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 @@ -bdf395fc2079d8834feed85c47610f7efc6bad38 \ No newline at end of file +f1ca50cc49450c321dc7640f52836bb328fc672a \ 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 c541eabd..a608c170 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 @@ -b8c410eec9723c1405d4aab2f5b342da3e0f4e2c \ No newline at end of file +3250c10fa3d6fb3d5491e29d8892ac6a7cbf46b8 \ 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 bff8575..db5d84f 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 @@ -ad335ce00ff3629f7f1fd8938b4406db40757341 \ No newline at end of file +76f2020ed5896d4376405645606c1608eb40b56e \ 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 05151d63..dae20aa 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 @@ -e50673e9c2e2fd52876d012d739fa2192ea1d8a6 \ No newline at end of file +75a457dd3e0ac0df63873cbc5e387eba9f134c01 \ 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 67a3300b..da9017a 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 @@ -199be598097f9edc9edbce67eeb1a34639ba75e4 \ No newline at end of file +2055f5e8a3503363fe2d64ae346c40740f4a60d5 \ 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 9c46015..08232e7 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 @@ -d2745bb41de5904ec74b0099f13ded92a96b3c9c \ No newline at end of file +e7b4eca3283837843e6d8ad928b15d94b4f48173 \ No newline at end of file
diff --git a/ios/public/provider/chrome/browser/BUILD.gn b/ios/public/provider/chrome/browser/BUILD.gn index fea87a9..8237cc06 100644 --- a/ios/public/provider/chrome/browser/BUILD.gn +++ b/ios/public/provider/chrome/browser/BUILD.gn
@@ -36,6 +36,7 @@ "//ios/public/provider/chrome/browser/risk_data:risk_data_api", "//ios/public/provider/chrome/browser/signin:signin_error_api", "//ios/public/provider/chrome/browser/signin:signin_resources_api", + "//ios/public/provider/chrome/browser/signin:signin_sso_api", "//ios/public/provider/chrome/browser/text_zoom:text_zoom_api", "//ios/public/provider/chrome/browser/ui_utils:ui_utils_api", "//ios/public/provider/chrome/browser/url_rewriters:url_rewriters_api",
diff --git a/ios/public/provider/chrome/browser/signin/BUILD.gn b/ios/public/provider/chrome/browser/signin/BUILD.gn index 55d1da92..6b6ddaad 100644 --- a/ios/public/provider/chrome/browser/signin/BUILD.gn +++ b/ios/public/provider/chrome/browser/signin/BUILD.gn
@@ -36,6 +36,13 @@ frameworks = [ "UIKit.framework" ] } +source_set("signin_sso_api") { + configs += [ "//build/config/compiler:enable_arc" ] + sources = [ "signin_sso_api.h" ] + deps = [] + frameworks = [ "Foundation.framework" ] +} + source_set("test_support") { configs += [ "//build/config/compiler:enable_arc" ] testonly = true
diff --git a/ios/public/provider/chrome/browser/signin/signin_sso_api.h b/ios/public/provider/chrome/browser/signin/signin_sso_api.h new file mode 100644 index 0000000..3075462 --- /dev/null +++ b/ios/public/provider/chrome/browser/signin/signin_sso_api.h
@@ -0,0 +1,23 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef IOS_PUBLIC_PROVIDER_CHROME_BROWSER_SIGNIN_SIGNIN_SSO_API_H_ +#define IOS_PUBLIC_PROVIDER_CHROME_BROWSER_SIGNIN_SIGNIN_SSO_API_H_ + +#import <Foundation/Foundation.h> + +// Abstract protocol of the Single-Sign-On Service used by Chrome. +@protocol SingleSignOnService <NSObject> +@end + +namespace ios { +namespace provider { + +// Creates a new instance of SingleSignOnService. +id<SingleSignOnService> CreateSSOService(); + +} // namespace provider +} // namespace ios + +#endif // IOS_PUBLIC_PROVIDER_CHROME_BROWSER_SIGNIN_SIGNIN_SSO_API_H_
diff --git a/jingle/BUILD.gn b/jingle/BUILD.gn index 5aad94f..619847fb 100644 --- a/jingle/BUILD.gn +++ b/jingle/BUILD.gn
@@ -31,16 +31,10 @@ test("jingle_unittests") { sources = [ "glue/fake_ssl_client_socket_unittest.cc", - "glue/logging_unittest.cc", "glue/thread_wrapper_unittest.cc", "run_all_unittests.cc", ] - if (is_android) { - # LibjingleLogTest don't pass on Android (crbug.com/843104). - sources -= [ "glue/logging_unittest.cc" ] - } - deps = [ ":webrtc_glue", "//base",
diff --git a/mojo/core/user_message_impl.cc b/mojo/core/user_message_impl.cc index 927b19f..09cb1be 100644 --- a/mojo/core/user_message_impl.cc +++ b/mojo/core/user_message_impl.cc
@@ -306,8 +306,8 @@ }; void EnsureMemoryDumpProviderExists() { - static base::NoDestructor<MessageMemoryDumpProvider> provider; - ALLOW_UNUSED_LOCAL(provider); + [[maybe_unused]] static base::NoDestructor<MessageMemoryDumpProvider> + provider; } } // namespace
diff --git a/mojo/public/c/system/tests/core_perftest.cc b/mojo/public/c/system/tests/core_perftest.cc index 316884f..eec2a32 100644 --- a/mojo/public/c/system/tests/core_perftest.cc +++ b/mojo/public/c/system/tests/core_perftest.cc
@@ -128,8 +128,8 @@ static void MessagePipe_CreateAndClose(void* closure) { CorePerftest* self = static_cast<CorePerftest*>(closure); - MojoResult result = MojoCreateMessagePipe(nullptr, &self->h0_, &self->h1_); - ALLOW_UNUSED_LOCAL(result); + [[maybe_unused]] MojoResult result = + MojoCreateMessagePipe(nullptr, &self->h0_, &self->h1_); assert(result == MOJO_RESULT_OK); result = MojoClose(self->h0_); assert(result == MOJO_RESULT_OK); @@ -139,10 +139,9 @@ static void MessagePipe_WriteAndRead(void* closure) { CorePerftest* self = static_cast<CorePerftest*>(closure); - MojoResult result = mojo::WriteMessageRaw( + [[maybe_unused]] MojoResult result = mojo::WriteMessageRaw( mojo::MessagePipeHandle(self->h0_), self->buffer_.data(), self->buffer_.size(), nullptr, 0, MOJO_WRITE_MESSAGE_FLAG_NONE); - ALLOW_UNUSED_LOCAL(result); assert(result == MOJO_RESULT_OK); result = mojo::ReadMessageRaw(mojo::MessagePipeHandle(self->h1_), &self->buffer_, @@ -153,8 +152,8 @@ static void MessagePipe_EmptyRead(void* closure) { CorePerftest* self = static_cast<CorePerftest*>(closure); MojoMessageHandle message; - MojoResult result = MojoReadMessage(self->h0_, nullptr, &message); - ALLOW_UNUSED_LOCAL(result); + [[maybe_unused]] MojoResult result = + MojoReadMessage(self->h0_, nullptr, &message); assert(result == MOJO_RESULT_SHOULD_WAIT); } @@ -168,8 +167,8 @@ assert(num_writers > 0); assert(num_readers > 0); - MojoResult result = MojoCreateMessagePipe(nullptr, &h0_, &h1_); - ALLOW_UNUSED_LOCAL(result); + [[maybe_unused]] MojoResult result = + MojoCreateMessagePipe(nullptr, &h0_, &h1_); assert(result == MOJO_RESULT_OK); std::vector<MessagePipeWriterThread*> writers; @@ -248,8 +247,7 @@ static_cast<time_t>(microseconds / 1000000), // Seconds. static_cast<long>(microseconds % 1000000) * 1000L // Nanoseconds. }; - int rv = nanosleep(&req, nullptr); - ALLOW_UNUSED_LOCAL(rv); + [[maybe_unused]] int rv = nanosleep(&req, nullptr); assert(rv == 0); } #endif // !defined(WIN32) @@ -268,8 +266,8 @@ } TEST_F(CorePerftest, MessagePipe_WriteAndRead) { - MojoResult result = MojoCreateMessagePipe(nullptr, &h0_, &h1_); - ALLOW_UNUSED_LOCAL(result); + [[maybe_unused]] MojoResult result = + MojoCreateMessagePipe(nullptr, &h0_, &h1_); assert(result == MOJO_RESULT_OK); buffer_.resize(10); mojo::test::IterateAndReportPerf("MessagePipe_WriteAndRead", "10bytes", @@ -294,8 +292,8 @@ } TEST_F(CorePerftest, MessagePipe_EmptyRead) { - MojoResult result = MojoCreateMessagePipe(nullptr, &h0_, &h1_); - ALLOW_UNUSED_LOCAL(result); + [[maybe_unused]] MojoResult result = + MojoCreateMessagePipe(nullptr, &h0_, &h1_); assert(result == MOJO_RESULT_OK); mojo::test::IterateAndReportPerf("MessagePipe_EmptyRead", nullptr, &CorePerftest::MessagePipe_EmptyRead, this);
diff --git a/mojo/public/cpp/system/handle.h b/mojo/public/cpp/system/handle.h index e743ef3..bcd061c 100644 --- a/mojo/public/cpp/system/handle.h +++ b/mojo/public/cpp/system/handle.h
@@ -9,7 +9,6 @@ #include <limits> #include "base/check_op.h" -#include "base/compiler_specific.h" #include "mojo/public/c/system/functions.h" #include "mojo/public/c/system/types.h" #include "mojo/public/cpp/system/handle_signals_state.h" @@ -175,8 +174,7 @@ void Close() { DCHECK(is_valid()); - MojoResult result = MojoClose(value_); - ALLOW_UNUSED_LOCAL(result); + [[maybe_unused]] MojoResult result = MojoClose(value_); DCHECK_EQ(MOJO_RESULT_OK, result); }
diff --git a/mojo/public/cpp/system/message.h b/mojo/public/cpp/system/message.h index 3cc052f..4d5b0561 100644 --- a/mojo/public/cpp/system/message.h +++ b/mojo/public/cpp/system/message.h
@@ -39,8 +39,7 @@ void Close() { DCHECK(is_valid()); - MojoResult result = MojoDestroyMessage(value_); - ALLOW_UNUSED_LOCAL(result); + [[maybe_unused]] MojoResult result = MojoDestroyMessage(value_); DCHECK_EQ(MOJO_RESULT_OK, result); }
diff --git a/net/BUILD.gn b/net/BUILD.gn index 457b3f81..ddc88aa5 100644 --- a/net/BUILD.gn +++ b/net/BUILD.gn
@@ -1965,6 +1965,7 @@ "data/ssl/certificates/prime256v1-ecdsa-intermediate.pem", "data/ssl/certificates/punycodetest.pem", "data/ssl/certificates/quic-chain.pem", + "data/ssl/certificates/quic-ecdsa-leaf.key", "data/ssl/certificates/quic-leaf-cert.key", "data/ssl/certificates/quic-leaf-cert.key.pkcs8.pem", "data/ssl/certificates/quic-leaf-cert.key.sct",
diff --git a/net/data/ssl/certificates/quic-ecdsa-leaf.key b/net/data/ssl/certificates/quic-ecdsa-leaf.key new file mode 100644 index 0000000..b3e47c7b --- /dev/null +++ b/net/data/ssl/certificates/quic-ecdsa-leaf.key Binary files differ
diff --git a/net/data/ssl/certificates/quic-short-lived.pem b/net/data/ssl/certificates/quic-short-lived.pem index 36422406..ef24357a 100644 --- a/net/data/ssl/certificates/quic-short-lived.pem +++ b/net/data/ssl/certificates/quic-short-lived.pem
@@ -2,79 +2,41 @@ Data: Version: 3 (0x2) Serial Number: - 02:10:43:05:54:18:1c:69:17:b8:d7:dd:1c:87:89:d3:d3:f9:8d:c7 - Signature Algorithm: sha256WithRSAEncryption - Issuer: C = US, CN = Short-lived Certificate + 14:95:0e:b4:a9:33:04:9b:ed:a5:47:b9:c8:0f:12:14:57:d1:66:ff + Signature Algorithm: ecdsa-with-SHA256 + Issuer: CN = Short-lived Certificate Validity Not Before: Jun 5 19:49:12 2020 GMT Not After : Jun 19 19:49:12 2020 GMT - Subject: C = US, CN = Short-lived Certificate + Subject: CN = Short-lived Certificate Subject Public Key Info: - Public Key Algorithm: rsaEncryption - RSA Public-Key: (2048 bit) - Modulus: - 00:b2:56:6f:7e:d4:b4:b6:4e:e3:15:8e:8a:e9:46: - 06:15:63:4c:6d:3a:32:67:c7:14:a4:17:fc:b7:04: - 98:fb:b5:11:ae:93:1c:20:73:15:cd:b3:bc:ee:61: - 82:8e:cb:b8:78:ca:6d:e6:57:73:f3:45:6e:1e:c3: - 27:5d:af:5e:52:6d:12:47:44:72:3d:7d:8a:c1:47: - 50:19:4a:21:a4:08:b4:cc:2e:9c:a2:2a:ce:1b:87: - 82:ae:3a:23:b0:dd:d2:3e:64:fe:ce:a6:35:34:93: - 07:f8:88:6e:c8:be:b2:0b:5f:9c:96:0e:79:1c:a3: - 2b:c9:23:5a:8a:1f:1e:17:e2:a9:d4:3c:49:22:29: - 43:fa:63:55:3c:72:62:4a:d1:72:5a:ae:75:a8:14: - 67:eb:58:88:ce:11:0c:bf:09:67:f2:bb:c8:80:3e: - 4a:f0:35:ad:d2:dc:43:a3:2f:da:c6:3b:1c:6e:76: - 70:31:73:cc:33:5b:4f:36:dc:f3:8f:9f:a6:07:6d: - 61:e0:66:6f:2c:76:bd:85:a3:8b:d0:8a:ce:c4:bc: - 97:e0:ed:e1:29:df:a1:62:b9:ad:d8:0f:1a:f8:ae: - 44:fe:a6:28:95:c4:cc:df:b5:f7:6d:46:ae:ef:9b: - af:73:50:1d:9f:f0:c7:a0:ef:37:4b:13:73:96:24: - 95:0f - Exponent: 65537 (0x10001) + Public Key Algorithm: id-ecPublicKey + Public-Key: (256 bit) + pub: + 04:42:8a:75:3b:89:02:17:c3:97:d9:35:3c:ac:9a: + 46:a4:46:fa:17:cc:5d:0a:4c:6a:a3:88:7c:ff:44: + c5:96:af:6d:3b:17:76:d1:59:54:23:cc:16:05:96: + 29:9e:2c:f4:a7:9b:c4:42:3b:21:4e:ac:bd:8f:57: + 92:2b:fe:8f:85 + ASN1 OID: prime256v1 + NIST CURVE: P-256 X509v3 extensions: - X509v3 Subject Key Identifier: - 9A:4F:94:3E:9D:8E:6D:5A:9B:9B:8B:88:97:B6:D4:FF:10:AE:47:76 - X509v3 Authority Key Identifier: - keyid:9A:4F:94:3E:9D:8E:6D:5A:9B:9B:8B:88:97:B6:D4:FF:10:AE:47:76 - - X509v3 Basic Constraints: critical - CA:TRUE + X509v3 Basic Constraints: + CA:FALSE X509v3 Subject Alternative Name: DNS:example.org - Signature Algorithm: sha256WithRSAEncryption - 7b:10:40:c9:9b:ad:b1:3d:03:c3:b6:f3:d7:3f:75:56:2b:80: - ff:c4:e5:88:3a:b4:0b:c2:4a:cd:ae:0a:b3:d4:1f:d3:ec:ec: - 81:85:0b:96:47:2d:78:d1:9c:45:c3:cd:7c:ba:a0:f8:b0:56: - 83:2f:e9:8a:06:05:fa:06:65:85:fd:60:99:6e:29:5c:b8:22: - 6f:1b:24:63:ce:95:f6:bc:a1:76:69:15:b7:33:b4:e1:c4:e4: - e1:8d:2b:71:5f:af:8d:0e:17:be:ea:b1:b7:75:66:29:8d:4d: - 92:bc:fe:7e:12:b3:46:ab:fb:7f:01:46:77:c1:6a:1b:9b:65: - 79:cb:aa:64:24:1a:ee:99:85:8e:b8:51:33:c7:8d:88:40:ae: - 0b:e2:cf:b1:57:f1:c9:a7:08:d7:8d:3d:da:9c:f4:79:28:a3: - 39:0e:e6:2f:16:71:89:4c:8b:cc:62:6c:13:b2:f0:38:1d:7b: - 04:4b:21:01:c9:52:09:6e:0f:7a:13:a7:62:07:08:7a:0e:90: - a8:fd:13:2b:2c:39:37:3b:0f:fa:36:f7:64:76:d3:b5:9b:7a: - ab:49:b3:52:0f:cf:d2:c6:02:c9:05:30:3f:60:c7:c5:f3:4b: - fa:c3:e6:fd:de:3f:2b:d6:a5:1a:ff:6c:8e:75:d0:c9:ff:f2: - 65:d8:07:d1 + Signature Algorithm: ecdsa-with-SHA256 + 30:45:02:20:73:ca:c3:64:38:04:ad:5e:f7:87:a6:1f:ac:62: + 03:7b:3a:11:5b:51:2a:11:b2:25:e3:24:1e:62:ec:72:39:be: + 02:21:00:f7:df:1b:83:07:a2:fd:d1:1f:c9:92:57:1f:ee:2c: + f2:27:b5:99:91:8f:8b:9d:02:a3:f7:5d:17:9e:d6:19:a6 -----BEGIN CERTIFICATE----- -MIIDVzCCAj+gAwIBAgIUAhBDBVQYHGkXuNfdHIeJ09P5jccwDQYJKoZIhvcNAQEL -BQAwLzELMAkGA1UEBhMCVVMxIDAeBgNVBAMMF1Nob3J0LWxpdmVkIENlcnRpZmlj -YXRlMB4XDTIwMDYwNTE5NDkxMloXDTIwMDYxOTE5NDkxMlowLzELMAkGA1UEBhMC -VVMxIDAeBgNVBAMMF1Nob3J0LWxpdmVkIENlcnRpZmljYXRlMIIBIjANBgkqhkiG -9w0BAQEFAAOCAQ8AMIIBCgKCAQEAslZvftS0tk7jFY6K6UYGFWNMbToyZ8cUpBf8 -twSY+7URrpMcIHMVzbO87mGCjsu4eMpt5ldz80VuHsMnXa9eUm0SR0RyPX2KwUdQ -GUohpAi0zC6coirOG4eCrjojsN3SPmT+zqY1NJMH+IhuyL6yC1+clg55HKMrySNa -ih8eF+Kp1DxJIilD+mNVPHJiStFyWq51qBRn61iIzhEMvwln8rvIgD5K8DWt0txD -oy/axjscbnZwMXPMM1tPNtzzj5+mB21h4GZvLHa9haOL0IrOxLyX4O3hKd+hYrmt -2A8a+K5E/qYolcTM37X3bUau75uvc1Adn/DHoO83SxNzliSVDwIDAQABo2swaTAd -BgNVHQ4EFgQUmk+UPp2ObVqbm4uIl7bU/xCuR3YwHwYDVR0jBBgwFoAUmk+UPp2O -bVqbm4uIl7bU/xCuR3YwDwYDVR0TAQH/BAUwAwEB/zAWBgNVHREEDzANggtleGFt -cGxlLm9yZzANBgkqhkiG9w0BAQsFAAOCAQEAexBAyZutsT0Dw7bz1z91ViuA/8Tl -iDq0C8JKza4Ks9Qf0+zsgYULlkcteNGcRcPNfLqg+LBWgy/pigYF+gZlhf1gmW4p -XLgibxskY86V9ryhdmkVtzO04cTk4Y0rcV+vjQ4Xvuqxt3VmKY1Nkrz+fhKzRqv7 -fwFGd8FqG5tlecuqZCQa7pmFjrhRM8eNiECuC+LPsVfxyacI14092pz0eSijOQ7m -LxZxiUyLzGJsE7LwOB17BEshAclSCW4PehOnYgcIeg6QqP0TKyw5NzsP+jb3ZHbT -tZt6q0mzUg/P0sYCyQUwP2DHxfNL+sPm/d4/K9alGv9sjnXQyf/yZdgH0Q== +MIIBazCCARGgAwIBAgIUFJUOtKkzBJvtpUe5yA8SFFfRZv8wCgYIKoZIzj0EAwIw +IjEgMB4GA1UEAwwXU2hvcnQtbGl2ZWQgQ2VydGlmaWNhdGUwHhcNMjAwNjA1MTk0 +OTEyWhcNMjAwNjE5MTk0OTEyWjAiMSAwHgYDVQQDDBdTaG9ydC1saXZlZCBDZXJ0 +aWZpY2F0ZTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABEKKdTuJAhfDl9k1PKya +RqRG+hfMXQpMaqOIfP9ExZavbTsXdtFZVCPMFgWWKZ4s9KebxEI7IU6svY9Xkiv+ +j4WjJTAjMAkGA1UdEwQCMAAwFgYDVR0RBA8wDYILZXhhbXBsZS5vcmcwCgYIKoZI +zj0EAwIDSAAwRQIgc8rDZDgErV73h6YfrGIDezoRW1EqEbIl4yQeYuxyOb4CIQD3 +3xuDB6L90R/Jklcf7izyJ7WZkY+LnQKj910XntYZpg== -----END CERTIFICATE-----
diff --git a/net/quic/dedicated_web_transport_http3_client.cc b/net/quic/dedicated_web_transport_http3_client.cc index c0aa320..385c01f3 100644 --- a/net/quic/dedicated_web_transport_http3_client.cc +++ b/net/quic/dedicated_web_transport_http3_client.cc
@@ -44,6 +44,25 @@ return hosts; } +// A version of WebTransportFingerprintProofVerifier that enforces +// Chromium-specific policies. +class ChromiumWebTransportFingerprintProofVerifier + : public quic::WebTransportFingerprintProofVerifier { + public: + using WebTransportFingerprintProofVerifier:: + WebTransportFingerprintProofVerifier; + + protected: + bool IsKeyTypeAllowedByPolicy( + const quic::CertificateView& certificate) override { + if (certificate.public_key_type() == quic::PublicKeyType::kRsa) { + return false; + } + return WebTransportFingerprintProofVerifier::IsKeyTypeAllowedByPolicy( + certificate); + } +}; + std::unique_ptr<quic::ProofVerifier> CreateProofVerifier( const NetworkIsolationKey& isolation_key, URLRequestContext* context, @@ -57,8 +76,9 @@ isolation_key); } - auto verifier = std::make_unique<quic::WebTransportFingerprintProofVerifier>( - context->quic_context()->clock(), kCustomCertificateMaxValidityDays); + auto verifier = + std::make_unique<ChromiumWebTransportFingerprintProofVerifier>( + context->quic_context()->clock(), kCustomCertificateMaxValidityDays); for (const quic::CertificateFingerprint& fingerprint : parameters.server_certificate_fingerprints) { bool success = verifier->AddFingerprint(fingerprint);
diff --git a/net/third_party/quiche/BUILD.gn b/net/third_party/quiche/BUILD.gn index 7ce70584..928ed7c 100644 --- a/net/third_party/quiche/BUILD.gn +++ b/net/third_party/quiche/BUILD.gn
@@ -277,6 +277,8 @@ "src/quic/core/crypto/p256_key_exchange.h", "src/quic/core/crypto/proof_source.cc", "src/quic/core/crypto/proof_source.h", + "src/quic/core/crypto/proof_source_x509.cc", + "src/quic/core/crypto/proof_source_x509.h", "src/quic/core/crypto/proof_verifier.h", "src/quic/core/crypto/quic_client_session_cache.cc", "src/quic/core/crypto/quic_client_session_cache.h", @@ -1359,6 +1361,7 @@ "src/quic/core/crypto/null_decrypter_test.cc", "src/quic/core/crypto/null_encrypter_test.cc", "src/quic/core/crypto/p256_key_exchange_test.cc", + "src/quic/core/crypto/proof_source_x509_test.cc", "src/quic/core/crypto/quic_client_session_cache_test.cc", "src/quic/core/crypto/quic_compressed_certs_cache_test.cc", "src/quic/core/crypto/quic_crypto_client_config_test.cc",
diff --git a/pdf/pdfium/pdfium_engine.cc b/pdf/pdfium/pdfium_engine.cc index 59332512..f523fcbe 100644 --- a/pdf/pdfium/pdfium_engine.cc +++ b/pdf/pdfium/pdfium_engine.cc
@@ -89,7 +89,7 @@ #endif using printing::ConvertUnit; -using printing::ConvertUnitDouble; +using printing::ConvertUnitFloat; using printing::kPixelsPerInch; using printing::kPointsPerInch; @@ -2680,10 +2680,10 @@ // Create blank pages with the same size as the first page. gfx::Size page_0_size = GetPageSize(0); - double page_0_width_in_points = - ConvertUnitDouble(page_0_size.width(), kPixelsPerInch, kPointsPerInch); - double page_0_height_in_points = - ConvertUnitDouble(page_0_size.height(), kPixelsPerInch, kPointsPerInch); + float page_0_width_in_points = + ConvertUnitFloat(page_0_size.width(), kPixelsPerInch, kPointsPerInch); + float page_0_height_in_points = + ConvertUnitFloat(page_0_size.height(), kPixelsPerInch, kPointsPerInch); for (size_t i = 1; i < num_pages; ++i) { { @@ -3062,9 +3062,9 @@ return gfx::Size(); int width_in_pixels = static_cast<int>( - ConvertUnitDouble(size_in_points.width, kPointsPerInch, kPixelsPerInch)); + ConvertUnitFloat(size_in_points.width, kPointsPerInch, kPixelsPerInch)); int height_in_pixels = static_cast<int>( - ConvertUnitDouble(size_in_points.height, kPointsPerInch, kPixelsPerInch)); + ConvertUnitFloat(size_in_points.height, kPointsPerInch, kPixelsPerInch)); switch (layout_options.default_page_orientation()) { case PageOrientation::kOriginal:
diff --git a/pdf/pdfium/pdfium_engine_exports.cc b/pdf/pdfium/pdfium_engine_exports.cc index b33ead3..4104698 100644 --- a/pdf/pdfium/pdfium_engine_exports.cc +++ b/pdf/pdfium/pdfium_engine_exports.cc
@@ -28,7 +28,7 @@ #include "ui/gfx/geometry/size_f.h" #include "ui/gfx/geometry/vector2d.h" -using printing::ConvertUnitDouble; +using printing::ConvertUnitFloat; using printing::kPointsPerInch; namespace chrome_pdf { @@ -43,9 +43,9 @@ const int dpi_y = settings.dpi.height(); const int dpi = std::max(dpi_x, dpi_y); int page_width = static_cast<int>( - ConvertUnitDouble(FPDF_GetPageWidthF(page), kPointsPerInch, dpi)); + ConvertUnitFloat(FPDF_GetPageWidthF(page), kPointsPerInch, dpi)); int page_height = static_cast<int>( - ConvertUnitDouble(FPDF_GetPageHeightF(page), kPointsPerInch, dpi)); + ConvertUnitFloat(FPDF_GetPageHeightF(page), kPointsPerInch, dpi)); // Start by assuming that we will draw exactly to the bounds rect // specified.
diff --git a/pdf/pdfium/pdfium_page.cc b/pdf/pdfium/pdfium_page.cc index 6e8e303e8..9472471 100644 --- a/pdf/pdfium/pdfium_page.cc +++ b/pdf/pdfium/pdfium_page.cc
@@ -41,7 +41,7 @@ #include "ui/gfx/geometry/vector2d_f.h" #include "ui/gfx/range/range.h" -using printing::ConvertUnitDouble; +using printing::ConvertUnitFloat; using printing::kPixelsPerInch; using printing::kPointsPerInch; @@ -86,10 +86,10 @@ height = 1; gfx::RectF output_rect( - ConvertUnitDouble(min_x, kPointsPerInch, kPixelsPerInch), - ConvertUnitDouble(min_y, kPointsPerInch, kPixelsPerInch), - ConvertUnitDouble(width, kPointsPerInch, kPixelsPerInch), - ConvertUnitDouble(height, kPointsPerInch, kPixelsPerInch)); + ConvertUnitFloat(min_x, kPointsPerInch, kPixelsPerInch), + ConvertUnitFloat(min_y, kPointsPerInch, kPixelsPerInch), + ConvertUnitFloat(width, kPointsPerInch, kPixelsPerInch), + ConvertUnitFloat(height, kPointsPerInch, kPixelsPerInch)); return output_rect; }
diff --git a/pdf/pdfium/pdfium_print.cc b/pdf/pdfium/pdfium_print.cc index 31e3acf..9f421f6 100644 --- a/pdf/pdfium/pdfium_print.cc +++ b/pdf/pdfium/pdfium_print.cc
@@ -27,7 +27,7 @@ #include "ui/gfx/geometry/size_f.h" using printing::ConvertUnit; -using printing::ConvertUnitDouble; +using printing::ConvertUnitFloat; using printing::kPointsPerInch; namespace chrome_pdf { @@ -395,8 +395,8 @@ FPDF_RenderPageBitmap(bitmap.get(), page_to_print, 0, 0, bitmap_size.width(), bitmap_size.height(), /*rotate=*/0, FPDF_PRINTING); - double ratio_x = ConvertUnitDouble(bitmap_size.width(), dpi, kPointsPerInch); - double ratio_y = ConvertUnitDouble(bitmap_size.height(), dpi, kPointsPerInch); + float ratio_x = ConvertUnitFloat(bitmap_size.width(), dpi, kPointsPerInch); + float ratio_y = ConvertUnitFloat(bitmap_size.height(), dpi, kPointsPerInch); // Add the bitmap to an image object and add the image object to the output // page.
diff --git a/ppapi/native_client/nacl_test_data.gni b/ppapi/native_client/nacl_test_data.gni index d179121..caf0d78 100644 --- a/ppapi/native_client/nacl_test_data.gni +++ b/ppapi/native_client/nacl_test_data.gni
@@ -26,7 +26,6 @@ # sources: source files for a target # generate_nmf: whether to generate a manifest (default true) # pretranslate_pexe: whether to pre-translate pexe to nexe during build -# (default true for Non-SFI, otherwise false) # nonstable_pexe: use non-finalized pexe (default false) # debug_pexe: copy both non-finalized and finalized pexe (default false) # destination_dir: the output directory relative to the $root_build_dir, @@ -52,12 +51,8 @@ nmf_cpu = current_cpu } - if (current_cpu == "pnacl") { - if (defined(invoker.pretranslate_pexe)) { - pretranslate_pexe = invoker.pretranslate_pexe - } else { - pretranslate_pexe = false - } + if (current_cpu == "pnacl" && defined(invoker.pretranslate_pexe)) { + pretranslate_pexe = invoker.pretranslate_pexe } else { pretranslate_pexe = false }
diff --git a/printing/print_settings.cc b/printing/print_settings.cc index a896ef7..4dbf023 100644 --- a/printing/print_settings.cc +++ b/printing/print_settings.cc
@@ -411,16 +411,14 @@ case mojom::MarginType::kCustomMargins: { margins.header = 0; margins.footer = 0; - margins.top = ConvertUnitDouble(requested_custom_margins_in_points_.top, - kPointsPerInch, units_per_inch); - margins.bottom = - ConvertUnitDouble(requested_custom_margins_in_points_.bottom, - kPointsPerInch, units_per_inch); - margins.left = ConvertUnitDouble(requested_custom_margins_in_points_.left, - kPointsPerInch, units_per_inch); - margins.right = - ConvertUnitDouble(requested_custom_margins_in_points_.right, - kPointsPerInch, units_per_inch); + margins.top = ConvertUnit(requested_custom_margins_in_points_.top, + kPointsPerInch, units_per_inch); + margins.bottom = ConvertUnit(requested_custom_margins_in_points_.bottom, + kPointsPerInch, units_per_inch); + margins.left = ConvertUnit(requested_custom_margins_in_points_.left, + kPointsPerInch, units_per_inch); + margins.right = ConvertUnit(requested_custom_margins_in_points_.right, + kPointsPerInch, units_per_inch); break; } default: {
diff --git a/printing/printing_context_chromeos.cc b/printing/printing_context_chromeos.cc index 670df66..305c274 100644 --- a/printing/printing_context_chromeos.cc +++ b/printing/printing_context_chromeos.cc
@@ -70,7 +70,7 @@ // Given an integral `value` expressed in PWG units (1/100 mm), returns // the same value expressed in device units. int PwgUnitsToDeviceUnits(int value, float micrometers_per_device_unit) { - return ConvertUnitDouble(value, micrometers_per_device_unit, 10); + return ConvertUnitFloat(value, micrometers_per_device_unit, 10); } // Given a `media_size`, the specification of the media's `margins`, and
diff --git a/printing/units.cc b/printing/units.cc index 997877e..6ed48862 100644 --- a/printing/units.cc +++ b/printing/units.cc
@@ -9,7 +9,7 @@ namespace printing { -int ConvertUnit(double value, int old_unit, int new_unit) { +int ConvertUnit(float value, int old_unit, int new_unit) { DCHECK_GT(new_unit, 0); DCHECK_GT(old_unit, 0); // With integer arithmetic, to divide a value with correct rounding, you need @@ -22,22 +22,10 @@ } } -double ConvertUnitDouble(double value, double old_unit, double new_unit) { +float ConvertUnitFloat(float value, float old_unit, float new_unit) { DCHECK_GT(new_unit, 0); DCHECK_GT(old_unit, 0); return value * new_unit / old_unit; } -int ConvertPixelsToPoint(int pixels) { - return ConvertUnit(pixels, kPixelsPerInch, kPointsPerInch); -} - -double ConvertPixelsToPointDouble(double pixels) { - return ConvertUnitDouble(pixels, kPixelsPerInch, kPointsPerInch); -} - -double ConvertPointsToPixelDouble(double points) { - return ConvertUnitDouble(points, kPointsPerInch, kPixelsPerInch); -} - } // namespace printing
diff --git a/printing/units.h b/printing/units.h index 7460ded2..d4a0ed7 100644 --- a/printing/units.h +++ b/printing/units.h
@@ -45,22 +45,11 @@ // Converts from one unit system to another using integer arithmetics. COMPONENT_EXPORT(PRINTING_BASE) -int ConvertUnit(double value, int old_unit, int new_unit); +int ConvertUnit(float value, int old_unit, int new_unit); -// Converts from one unit system to another using doubles. +// Converts from one unit system to another using floats. COMPONENT_EXPORT(PRINTING_BASE) -double ConvertUnitDouble(double value, double old_unit, double new_unit); - -// Converts from 1 pixel to 1 point using integers. -COMPONENT_EXPORT(PRINTING_BASE) int ConvertPixelsToPoint(int pixels); - -// Converts from 1 pixel to 1 point using doubles. -COMPONENT_EXPORT(PRINTING_BASE) -double ConvertPixelsToPointDouble(double pixels); - -// Converts from 1 point to 1 pixel using doubles. -COMPONENT_EXPORT(PRINTING_BASE) -double ConvertPointsToPixelDouble(double points); +float ConvertUnitFloat(float value, float old_unit, float new_unit); } // namespace printing
diff --git a/printing/units_unittest.cc b/printing/units_unittest.cc index f43dabd..df4d2177 100644 --- a/printing/units_unittest.cc +++ b/printing/units_unittest.cc
@@ -45,19 +45,19 @@ EXPECT_EQ(0, ConvertUnit(2, 1000000000, 1)); EXPECT_EQ(2000000000, ConvertUnit(2, 1, 1000000000)); - EXPECT_EQ(100, ConvertUnitDouble(100, 100, 100)); - EXPECT_EQ(-100, ConvertUnitDouble(-100, 100, 100)); - EXPECT_EQ(0, ConvertUnitDouble(0, 100, 100)); - EXPECT_DOUBLE_EQ(0.000002, ConvertUnitDouble(2, 1000, 0.001)); - EXPECT_EQ(2000000, ConvertUnitDouble(2, 0.001, 1000)); + EXPECT_EQ(100, ConvertUnitFloat(100, 100, 100)); + EXPECT_EQ(-100, ConvertUnitFloat(-100, 100, 100)); + EXPECT_EQ(0, ConvertUnitFloat(0, 100, 100)); + EXPECT_FLOAT_EQ(0.000002, ConvertUnitFloat(2, 1000, 0.001)); + EXPECT_FLOAT_EQ(2000000, ConvertUnitFloat(2, 0.001, 1000)); - EXPECT_EQ(8.25, ConvertPixelsToPointDouble(11.0)); + EXPECT_EQ(8.25, ConvertUnitFloat(11.0, kPixelsPerInch, kPointsPerInch)); // Round down. - EXPECT_EQ(8, ConvertPixelsToPoint(11)); - EXPECT_EQ(7.5, ConvertPixelsToPointDouble(10.0)); + EXPECT_EQ(8, ConvertUnit(11, kPixelsPerInch, kPointsPerInch)); + EXPECT_EQ(7.5, ConvertUnitFloat(10.0, kPixelsPerInch, kPointsPerInch)); // Round up. - EXPECT_EQ(8, ConvertPixelsToPoint(10)); - EXPECT_EQ(0, ConvertPixelsToPoint(0)); + EXPECT_EQ(8, ConvertUnit(10, kPixelsPerInch, kPointsPerInch)); + EXPECT_EQ(0, ConvertUnit(0, kPixelsPerInch, kPointsPerInch)); } } // namespace printing
diff --git a/remoting/host/basic_desktop_environment.cc b/remoting/host/basic_desktop_environment.cc index aaa3e1c..db502cac 100644 --- a/remoting/host/basic_desktop_environment.cc +++ b/remoting/host/basic_desktop_environment.cc
@@ -15,6 +15,7 @@ #include "remoting/host/base/screen_controls.h" #include "remoting/host/client_session_control.h" #include "remoting/host/desktop_capturer_proxy.h" +#include "remoting/host/desktop_display_info_monitor.h" #include "remoting/host/file_transfer/local_file_operations.h" #include "remoting/host/input_injector.h" #include "remoting/host/keyboard_layout_monitor.h" @@ -148,8 +149,11 @@ BasicDesktopEnvironment::CreateVideoCapturer() { DCHECK(caller_task_runner_->BelongsToCurrentThread()); - std::unique_ptr<DesktopCapturerProxy> result(new DesktopCapturerProxy( - video_capture_task_runner_, ui_task_runner_, client_session_control_)); + auto result = std::make_unique<DesktopCapturerProxy>( + video_capture_task_runner_, ui_task_runner_); + result->set_desktop_display_info_monitor( + std::make_unique<DesktopDisplayInfoMonitor>(ui_task_runner_, + client_session_control_)); result->CreateCapturer(desktop_capture_options()); return std::move(result); }
diff --git a/remoting/host/desktop_capturer_proxy.cc b/remoting/host/desktop_capturer_proxy.cc index f5b8698..687f69d 100644 --- a/remoting/host/desktop_capturer_proxy.cc +++ b/remoting/host/desktop_capturer_proxy.cc
@@ -17,7 +17,7 @@ #include "base/threading/thread_task_runner_handle.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" -#include "remoting/host/client_session_control.h" +#include "remoting/host/desktop_display_info_monitor.h" #include "remoting/proto/control.pb.h" #include "third_party/webrtc/modules/desktop_capture/desktop_capture_options.h" #include "third_party/webrtc/modules/desktop_capture/desktop_capturer.h" @@ -130,11 +130,8 @@ DesktopCapturerProxy::DesktopCapturerProxy( scoped_refptr<base::SingleThreadTaskRunner> capture_task_runner, - scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner, - base::WeakPtr<ClientSessionControl> client_session_control) - : capture_task_runner_(capture_task_runner), - client_session_control_(client_session_control), - desktop_display_info_monitor_(ui_task_runner, client_session_control) { + scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner) + : capture_task_runner_(capture_task_runner) { core_ = std::make_unique<Core>(weak_factory_.GetWeakPtr()); } @@ -142,6 +139,12 @@ capture_task_runner_->DeleteSoon(FROM_HERE, core_.release()); } +void DesktopCapturerProxy::set_desktop_display_info_monitor( + std::unique_ptr<DesktopDisplayInfoMonitor> monitor) { + DCHECK(thread_checker_.CalledOnValidThread()); + desktop_display_info_monitor_ = std::move(monitor); +} + void DesktopCapturerProxy::CreateCapturer( const webrtc::DesktopCaptureOptions& options) { DCHECK(thread_checker_.CalledOnValidThread()); @@ -194,10 +197,14 @@ bool DesktopCapturerProxy::SelectSource(SourceId id_index) { DCHECK(thread_checker_.CalledOnValidThread()); - SourceId id = desktop_display_info_monitor_.SourceIdFromIndex(id_index); - capture_task_runner_->PostTask( - FROM_HERE, - base::BindOnce(&Core::SelectSource, base::Unretained(core_.get()), id)); + if (desktop_display_info_monitor_) { + SourceId id = desktop_display_info_monitor_->SourceIdFromIndex(id_index); + capture_task_runner_->PostTask( + FROM_HERE, + base::BindOnce(&Core::SelectSource, base::Unretained(core_.get()), id)); + } else { + NOTIMPLEMENTED(); + } return false; } @@ -208,8 +215,8 @@ callback_->OnCaptureResult(result, std::move(frame)); - if (client_session_control_) { - desktop_display_info_monitor_.QueryDisplayInfo(); + if (desktop_display_info_monitor_) { + desktop_display_info_monitor_->QueryDisplayInfo(); } }
diff --git a/remoting/host/desktop_capturer_proxy.h b/remoting/host/desktop_capturer_proxy.h index d621432..bbe018e 100644 --- a/remoting/host/desktop_capturer_proxy.h +++ b/remoting/host/desktop_capturer_proxy.h
@@ -11,7 +11,6 @@ #include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" #include "base/threading/thread_checker.h" -#include "remoting/host/desktop_display_info_monitor.h" #include "third_party/webrtc/modules/desktop_capture/desktop_capturer.h" namespace base { @@ -25,24 +24,32 @@ namespace remoting { class ClientSessionControl; +class DesktopDisplayInfoMonitor; // DesktopCapturerProxy is responsible for calling webrtc::DesktopCapturer on // the capturer thread and then returning results to the caller's thread. // GetSourceList() is not implemented by this class, it always returns false. -// This class also loads the list of desktop displays on the UI thread, and -// notifies the ClientSessionControl if the displays have changed. +// This class optionally loads the list of desktop displays on the UI thread +// (after each captured frame), which will notify the ClientSessionControl +// if the displays have changed. class DesktopCapturerProxy : public webrtc::DesktopCapturer { public: explicit DesktopCapturerProxy( scoped_refptr<base::SingleThreadTaskRunner> capture_task_runner, - scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner, - base::WeakPtr<ClientSessionControl> client_session_control); + scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner); DesktopCapturerProxy(const DesktopCapturerProxy&) = delete; DesktopCapturerProxy& operator=(const DesktopCapturerProxy&) = delete; ~DesktopCapturerProxy() override; + // If a monitor is provided, it will be asked to load the display-info after + // each captured frame. This is intended only for the single-video-stream + // case. When multiple video streams are used (each with its own capturer), + // the display-info will not be loaded by this class. + void set_desktop_display_info_monitor( + std::unique_ptr<DesktopDisplayInfoMonitor> monitor); + // CreateCapturer() should be used if the capturer needs to be created on the // capturer thread. Alternatively the capturer can be passed to // set_capturer(). @@ -55,6 +62,12 @@ shared_memory_factory) override; void CaptureFrame() override; bool GetSourceList(SourceList* sources) override; + + // |id| here is currently index-based, so this method requires a + // DesktopDisplayInfoMonitor to convert |id| to a monitor id, otherwise this + // is a no-op. + // TODO(lambroslambrou): Fix callers to provide a monitor id instead of an + // index (so that this method works consistently with the base-class version). bool SelectSource(SourceId id) override; private: @@ -70,13 +83,9 @@ raw_ptr<webrtc::DesktopCapturer::Callback> callback_; - // Used to disconnect the client session. - // Note: This cannot be used on Windows because the ClientSession is not in - // the same process as the DesktopCapturerProxy. - base::WeakPtr<ClientSessionControl> client_session_control_; - - // Monitors and stores info about the desktop displays. - DesktopDisplayInfoMonitor desktop_display_info_monitor_; + // Monitors and stores info about the desktop displays. Only used in the + // single-video-stream case. + std::unique_ptr<DesktopDisplayInfoMonitor> desktop_display_info_monitor_; base::WeakPtrFactory<DesktopCapturerProxy> weak_factory_{this}; };
diff --git a/remoting/host/fake_desktop_environment.cc b/remoting/host/fake_desktop_environment.cc index 1601f36b..8bb75b9 100644 --- a/remoting/host/fake_desktop_environment.cc +++ b/remoting/host/fake_desktop_environment.cc
@@ -88,13 +88,12 @@ std::unique_ptr<webrtc::DesktopCapturer> FakeDesktopEnvironment::CreateVideoCapturer() { - std::unique_ptr<protocol::FakeDesktopCapturer> fake_capturer( - new protocol::FakeDesktopCapturer()); + auto fake_capturer = std::make_unique<protocol::FakeDesktopCapturer>(); if (!frame_generator_.is_null()) fake_capturer->set_frame_generator(frame_generator_); - std::unique_ptr<DesktopCapturerProxy> result( - new DesktopCapturerProxy(capture_thread_, capture_thread_, nullptr)); + auto result = + std::make_unique<DesktopCapturerProxy>(capture_thread_, capture_thread_); result->set_capturer(std::move(fake_capturer)); return std::move(result); }
diff --git a/remoting/protocol/webrtc_video_frame_adapter.cc b/remoting/protocol/webrtc_video_frame_adapter.cc index ab5dce6..08d0a1c 100644 --- a/remoting/protocol/webrtc_video_frame_adapter.cc +++ b/remoting/protocol/webrtc_video_frame_adapter.cc
@@ -36,9 +36,9 @@ rect.left(), rect.top(), rect.width(), rect.height()}); } - rtc::scoped_refptr<WebrtcVideoFrameAdapter> adapter = + rtc::scoped_refptr<WebrtcVideoFrameAdapter> adapter( new rtc::RefCountedObject<WebrtcVideoFrameAdapter>( - std::move(desktop_frame), std::move(frame_stats)); + std::move(desktop_frame), std::move(frame_stats))); // In the empty case, it is important to set the video-frame's update // rectangle explicitly to empty, otherwise an unset value would be
diff --git a/remoting/protocol/webrtc_video_frame_adapter_unittest.cc b/remoting/protocol/webrtc_video_frame_adapter_unittest.cc index bdb62045..b6160602 100644 --- a/remoting/protocol/webrtc_video_frame_adapter_unittest.cc +++ b/remoting/protocol/webrtc_video_frame_adapter_unittest.cc
@@ -44,9 +44,9 @@ TEST(WebrtcVideoFrameAdapter, AdapterHasCorrectSize) { auto desktop_frame = MakeDesktopFrame(100, 200); auto frame_stats = std::make_unique<WebrtcVideoEncoder::FrameStats>(); - rtc::scoped_refptr<WebrtcVideoFrameAdapter> adapter = + rtc::scoped_refptr<WebrtcVideoFrameAdapter> adapter( new rtc::RefCountedObject<WebrtcVideoFrameAdapter>( - std::move(desktop_frame), std::move(frame_stats)); + std::move(desktop_frame), std::move(frame_stats))); EXPECT_EQ(100, adapter->width()); EXPECT_EQ(200, adapter->height());
diff --git a/remoting/protocol/webrtc_video_track_source_unittest.cc b/remoting/protocol/webrtc_video_track_source_unittest.cc index b449be9..5a6d6dae 100644 --- a/remoting/protocol/webrtc_video_track_source_unittest.cc +++ b/remoting/protocol/webrtc_video_track_source_unittest.cc
@@ -54,9 +54,9 @@ EXPECT_CALL(add_sink_callback_, Run(Field(&rtc::VideoSinkWants::max_framerate_fps, 123))); - rtc::scoped_refptr<webrtc::VideoTrackSourceInterface> source = + rtc::scoped_refptr<webrtc::VideoTrackSourceInterface> source( new rtc::RefCountedObject<WebrtcVideoTrackSource>( - add_sink_callback_.Get()); + add_sink_callback_.Get())); rtc::VideoSinkWants wants; wants.max_framerate_fps = 123; source->AddOrUpdateSink(&video_sink_, wants); @@ -68,9 +68,9 @@ auto frame = std::make_unique<BasicDesktopFrame>(DesktopSize(123, 234)); EXPECT_CALL(video_sink_, OnFrame(Property(&VideoFrame::width, 123))); - rtc::scoped_refptr<WebrtcVideoTrackSource> source = + rtc::scoped_refptr<WebrtcVideoTrackSource> source( new rtc::RefCountedObject<WebrtcVideoTrackSource>( - add_sink_callback_.Get()); + add_sink_callback_.Get())); source->AddOrUpdateSink(&video_sink_, rtc::VideoSinkWants()); source->SendCapturedFrame(std::move(frame), nullptr); @@ -85,9 +85,9 @@ EXPECT_CALL(video_sink_, OnFrame(Property(&VideoFrame::id, 2))); } - rtc::scoped_refptr<WebrtcVideoTrackSource> source = + rtc::scoped_refptr<WebrtcVideoTrackSource> source( new rtc::RefCountedObject<WebrtcVideoTrackSource>( - add_sink_callback_.Get()); + add_sink_callback_.Get())); source->AddOrUpdateSink(&video_sink_, rtc::VideoSinkWants()); source->SendCapturedFrame( std::make_unique<BasicDesktopFrame>(DesktopSize(100, 100)), nullptr);
diff --git a/services/network/dhcp_pac_file_fetcher_mojo_unittest.cc b/services/network/dhcp_pac_file_fetcher_mojo_unittest.cc index fae0f65..979ef5f 100644 --- a/services/network/dhcp_pac_file_fetcher_mojo_unittest.cc +++ b/services/network/dhcp_pac_file_fetcher_mojo_unittest.cc
@@ -10,6 +10,8 @@ #include "net/test/gtest_util.h" #include "net/test/test_with_task_environment.h" #include "net/traffic_annotation/network_traffic_annotation_test_helper.h" +#include "net/url_request/url_request_context.h" +#include "net/url_request/url_request_context_builder.h" #include "net/url_request/url_request_test_util.h" #include "services/network/dhcp_pac_file_fetcher_mojo.h" #include "services/network/mock_mojo_dhcp_wpad_url_client.h" @@ -29,9 +31,10 @@ protected: void CreateFetcher(const std::string& pac_url) { - net::TestURLRequestContext context; + auto context_builder = net::CreateTestURLRequestContextBuilder(); + auto context = context_builder->Build(); dhcp_pac_file_fetcher_mojo_ = std::make_unique<DhcpPacFileFetcherMojo>( - &context, + context.get(), network::MockMojoDhcpWpadUrlClient::CreateWithSelfOwnedReceiver( pac_url)); mock_pac_file_fetcher_ = new net::MockPacFileFetcher();
diff --git a/services/network/expect_ct_reporter_unittest.cc b/services/network/expect_ct_reporter_unittest.cc index c1bd23b..2288d0d 100644 --- a/services/network/expect_ct_reporter_unittest.cc +++ b/services/network/expect_ct_reporter_unittest.cc
@@ -28,6 +28,7 @@ #include "net/test/url_request/url_request_failed_job.h" #include "net/traffic_annotation/network_traffic_annotation_test_helper.h" #include "net/url_request/report_sender.h" +#include "net/url_request/url_request_context_builder.h" #include "net/url_request/url_request_filter.h" #include "net/url_request/url_request_test_util.h" #include "services/network/public/cpp/features.h" @@ -324,11 +325,11 @@ ExpectCTReporterWaitTest& operator=(const ExpectCTReporterWaitTest&) = delete; void SetUp() override { - // Initializes URLRequestContext after the thread is set up. - context_ = std::make_unique<net::TestURLRequestContext>( - true /* delay_initialization */); - context_->set_network_delegate(&network_delegate_); - context_->Init(); + auto context_builder = net::CreateTestURLRequestContextBuilder(); + context_builder->set_network_delegate( + std::make_unique<TestExpectCTNetworkDelegate>()); + + context_ = context_builder->Build(); net::URLRequestFailedJob::AddUrlHandler(); } @@ -336,7 +337,12 @@ net::URLRequestFilter::GetInstance()->ClearHandlers(); } - net::TestURLRequestContext* context() { return context_.get(); } + net::URLRequestContext* context() { return context_.get(); } + TestExpectCTNetworkDelegate* network_delegate() { + // This is safe as we provided a TestExpectCTNetworkDelegate in SetUp(). + return static_cast<TestExpectCTNetworkDelegate*>( + context_->network_delegate()); + } protected: void SendReport(ExpectCTReporter* reporter, @@ -345,7 +351,7 @@ base::Time expiration, const net::SSLInfo& ssl_info) { base::RunLoop run_loop; - network_delegate_.set_url_request_destroyed_callback( + network_delegate()->set_url_request_destroyed_callback( run_loop.QuitClosure()); reporter->OnExpectCTFailed( host_port, report_uri, expiration, ssl_info.cert.get(), @@ -355,8 +361,7 @@ } private: - TestExpectCTNetworkDelegate network_delegate_; - std::unique_ptr<net::TestURLRequestContext> context_; + std::unique_ptr<net::URLRequestContext> context_; base::test::TaskEnvironment task_environment_; }; @@ -489,8 +494,9 @@ ASSERT_TRUE(test_server().Start()); TestCertificateReportSender* sender = new TestCertificateReportSender(); - net::TestURLRequestContext context; - ExpectCTReporter reporter(&context, base::NullCallback(), + auto context_builder = net::CreateTestURLRequestContextBuilder(); + auto context = context_builder->Build(); + ExpectCTReporter reporter(context.get(), base::NullCallback(), base::NullCallback()); reporter.report_sender_.reset(sender); EXPECT_TRUE(sender->latest_report_uri().is_empty()); @@ -538,8 +544,9 @@ // Test that no report is sent if the report URI is empty. TEST_F(ExpectCTReporterTest, EmptyReportURI) { TestCertificateReportSender* sender = new TestCertificateReportSender(); - net::TestURLRequestContext context; - ExpectCTReporter reporter(&context, base::NullCallback(), + auto context_builder = net::CreateTestURLRequestContextBuilder(); + auto context = context_builder->Build(); + ExpectCTReporter reporter(context.get(), base::NullCallback(), base::NullCallback()); reporter.report_sender_.reset(sender); EXPECT_TRUE(sender->latest_report_uri().is_empty()); @@ -578,8 +585,9 @@ // Test that a sent report has the right format. TEST_F(ExpectCTReporterTest, SendReport) { TestCertificateReportSender* sender = new TestCertificateReportSender(); - net::TestURLRequestContext context; - ExpectCTReporter reporter(&context, base::NullCallback(), + auto context_builder = net::CreateTestURLRequestContextBuilder(); + auto context = context_builder->Build(); + ExpectCTReporter reporter(context.get(), base::NullCallback(), base::NullCallback()); reporter.report_sender_.reset(sender); EXPECT_TRUE(sender->latest_report_uri().is_empty()); @@ -685,8 +693,9 @@ base::RunLoop run_loop; - net::TestURLRequestContext context; - ExpectCTReporter reporter(&context, run_loop.QuitClosure(), + auto context_builder = net::CreateTestURLRequestContextBuilder(); + auto context = context_builder->Build(); + ExpectCTReporter reporter(context.get(), run_loop.QuitClosure(), base::NullCallback()); net::SSLInfo ssl_info; @@ -738,12 +747,12 @@ TestCertificateReportSender* sender = new TestCertificateReportSender(); - TestExpectCTNetworkDelegate network_delegate; - net::TestURLRequestContext context(true /* delay_initialization*/); - context.set_network_delegate(&network_delegate); - context.Init(); + auto context_builder = net::CreateTestURLRequestContextBuilder(); + auto& network_delegate = *context_builder->set_network_delegate( + std::make_unique<TestExpectCTNetworkDelegate>()); + auto context = context_builder->Build(); - ExpectCTReporter reporter(&context, base::NullCallback(), + ExpectCTReporter reporter(context.get(), base::NullCallback(), base::NullCallback()); reporter.report_sender_.reset(sender); EXPECT_TRUE(sender->latest_report_uri().is_empty()); @@ -792,8 +801,9 @@ ASSERT_TRUE(test_server().Start()); TestCertificateReportSender* sender = new TestCertificateReportSender(); - net::TestURLRequestContext context; - ExpectCTReporter reporter(&context, base::NullCallback(), + auto context_builder = net::CreateTestURLRequestContextBuilder(); + auto context = context_builder->Build(); + ExpectCTReporter reporter(context.get(), base::NullCallback(), base::NullCallback()); reporter.report_sender_.reset(sender); EXPECT_TRUE(sender->latest_report_uri().is_empty()); @@ -823,8 +833,9 @@ // Access-Control-Allow-Origin. TEST_F(ExpectCTReporterTest, BadCorsPreflightResponseOrigin) { TestCertificateReportSender* sender = new TestCertificateReportSender(); - net::TestURLRequestContext context; - ExpectCTReporter reporter(&context, base::NullCallback(), + auto context_builder = net::CreateTestURLRequestContextBuilder(); + auto context = context_builder->Build(); + ExpectCTReporter reporter(context.get(), base::NullCallback(), base::NullCallback()); reporter.report_sender_.reset(sender); EXPECT_TRUE(sender->latest_report_uri().is_empty()); @@ -848,8 +859,9 @@ // Access-Control-Allow-Methods. TEST_F(ExpectCTReporterTest, BadCorsPreflightResponseMethods) { TestCertificateReportSender* sender = new TestCertificateReportSender(); - net::TestURLRequestContext context; - ExpectCTReporter reporter(&context, base::NullCallback(), + auto context_builder = net::CreateTestURLRequestContextBuilder(); + auto context = context_builder->Build(); + ExpectCTReporter reporter(context.get(), base::NullCallback(), base::NullCallback()); reporter.report_sender_.reset(sender); EXPECT_TRUE(sender->latest_report_uri().is_empty()); @@ -873,8 +885,9 @@ // Access-Control-Allow-Headers. TEST_F(ExpectCTReporterTest, BadCorsPreflightResponseHeaders) { TestCertificateReportSender* sender = new TestCertificateReportSender(); - net::TestURLRequestContext context; - ExpectCTReporter reporter(&context, base::NullCallback(), + auto context_builder = net::CreateTestURLRequestContextBuilder(); + auto context = context_builder->Build(); + ExpectCTReporter reporter(context.get(), base::NullCallback(), base::NullCallback()); reporter.report_sender_.reset(sender); EXPECT_TRUE(sender->latest_report_uri().is_empty());
diff --git a/services/network/network_context_unittest.cc b/services/network/network_context_unittest.cc index afc980e..d4c27c7 100644 --- a/services/network/network_context_unittest.cc +++ b/services/network/network_context_unittest.cc
@@ -167,6 +167,7 @@ namespace { +using net::CreateTestURLRequestContextBuilder; using ::testing::Optional; constexpr char kMockHost[] = "mock.host"; @@ -392,6 +393,33 @@ }; #endif // BUILDFLAG(IS_P2P_ENABLED) +class HostResolverFactory final : public net::HostResolver::Factory { + public: + explicit HostResolverFactory(std::unique_ptr<net::HostResolver> resolver) + : resolver_(std::move(resolver)) {} + + std::unique_ptr<net::HostResolver> CreateResolver( + net::HostResolverManager* manager, + base::StringPiece host_mapping_rules, + bool enable_caching) override { + DCHECK(resolver_); + return std::move(resolver_); + } + + // See HostResolver::CreateStandaloneResolver. + std::unique_ptr<net::HostResolver> CreateStandaloneResolver( + net::NetLog* net_log, + const net::HostResolver::ManagerOptions& options, + base::StringPiece host_mapping_rules, + bool enable_caching) override { + NOTREACHED(); + return nullptr; + } + + private: + std::unique_ptr<net::HostResolver> resolver_; +}; + class NetworkContextTest : public testing::Test { public: explicit NetworkContextTest( @@ -1311,14 +1339,12 @@ // Test that host resolution error information is available. TEST_F(NetworkContextTest, HostResolutionFailure) { + auto context_builder = CreateTestURLRequestContextBuilder(); std::unique_ptr<net::MockHostResolver> resolver = std::make_unique<net::MockHostResolver>(); - std::unique_ptr<net::TestURLRequestContext> url_request_context = - std::make_unique<net::TestURLRequestContext>( - true /* delay_initialization */); - url_request_context->set_host_resolver(resolver.get()); resolver->rules()->AddSimulatedTimeoutFailure("*"); - url_request_context->Init(); + context_builder->set_host_resolver(std::move(resolver)); + auto url_request_context = context_builder->Build(); network_context_remote_.reset(); std::unique_ptr<NetworkContext> network_context = @@ -1366,13 +1392,13 @@ ASSERT_TRUE(ip_address.AssignFromIPLiteral("1.2.3.4")); net::NetworkIsolationKey network_isolation_key = net::NetworkIsolationKey::CreateTransient(); - net::MockCachingHostResolver host_resolver; - std::unique_ptr<net::TestURLRequestContext> url_request_context = - std::make_unique<net::TestURLRequestContext>( - true /* delay_initialization */); - url_request_context->set_host_resolver(&host_resolver); + auto context_builder = CreateTestURLRequestContextBuilder(); + context_builder->set_host_resolver( + std::make_unique<net::MockCachingHostResolver>()); + auto url_request_context = context_builder->Build(); + auto& host_resolver = *static_cast<net::MockCachingHostResolver*>( + url_request_context->host_resolver()); host_resolver.rules()->AddRule(kHostname, ip_address.ToString()); - url_request_context->Init(); network_context_remote_.reset(); std::unique_ptr<NetworkContext> network_context = @@ -3315,12 +3341,13 @@ TEST_F(NetworkContextTest, ResolveHost_Sync) { auto resolver = std::make_unique<net::MockHostResolver>(); resolver->rules()->AddRule("sync.test", "1.2.3.4"); + resolver->set_synchronous_mode(true); + network_service_->set_host_resolver_factory_for_testing( + std::make_unique<HostResolverFactory>(std::move(resolver))); + std::unique_ptr<NetworkContext> network_context = CreateContextWithParams(CreateNetworkContextParamsForTesting()); - network_context->url_request_context()->set_host_resolver(resolver.get()); - resolver->set_synchronous_mode(true); - base::RunLoop run_loop; mojo::Remote<mojom::ResolveHostHandle> control_handle; mojom::ResolveHostParametersPtr optional_parameters = @@ -3347,12 +3374,12 @@ TEST_F(NetworkContextTest, ResolveHost_Async) { auto resolver = std::make_unique<net::MockHostResolver>(); resolver->rules()->AddRule("async.test", "1.2.3.4"); + resolver->set_synchronous_mode(false); + network_service_->set_host_resolver_factory_for_testing( + std::make_unique<HostResolverFactory>(std::move(resolver))); std::unique_ptr<NetworkContext> network_context = CreateContextWithParams(CreateNetworkContextParamsForTesting()); - network_context->url_request_context()->set_host_resolver(resolver.get()); - resolver->set_synchronous_mode(false); - base::RunLoop run_loop; mojo::Remote<mojom::ResolveHostHandle> control_handle; mojom::ResolveHostParametersPtr optional_parameters = @@ -3384,12 +3411,12 @@ TEST_F(NetworkContextTest, ResolveHost_Failure_Sync) { auto resolver = std::make_unique<net::MockHostResolver>(); - std::unique_ptr<NetworkContext> network_context = - CreateContextWithParams(CreateNetworkContextParamsForTesting()); - - network_context->url_request_context()->set_host_resolver(resolver.get()); resolver->rules()->AddSimulatedTimeoutFailure("example.com"); resolver->set_synchronous_mode(true); + network_service_->set_host_resolver_factory_for_testing( + std::make_unique<HostResolverFactory>(std::move(resolver))); + std::unique_ptr<NetworkContext> network_context = + CreateContextWithParams(CreateNetworkContextParamsForTesting()); base::RunLoop run_loop; mojo::Remote<mojom::ResolveHostHandle> control_handle; @@ -3415,12 +3442,12 @@ TEST_F(NetworkContextTest, ResolveHost_Failure_Async) { auto resolver = std::make_unique<net::MockHostResolver>(); - std::unique_ptr<NetworkContext> network_context = - CreateContextWithParams(CreateNetworkContextParamsForTesting()); - - network_context->url_request_context()->set_host_resolver(resolver.get()); resolver->rules()->AddSimulatedTimeoutFailure("example.com"); resolver->set_synchronous_mode(false); + network_service_->set_host_resolver_factory_for_testing( + std::make_unique<HostResolverFactory>(std::move(resolver))); + std::unique_ptr<NetworkContext> network_context = + CreateContextWithParams(CreateNetworkContextParamsForTesting()); base::RunLoop run_loop; mojo::Remote<mojom::ResolveHostHandle> control_handle; @@ -3454,13 +3481,14 @@ const url::Origin kOrigin = url::Origin::Create(GURL("https://foo.test/")); const net::NetworkIsolationKey kNetworkIsolationKey(kOrigin, kOrigin); - net::MockHostResolver resolver; - resolver.rules()->AddRule("nik.test", "1.2.3.4"); + auto resolver = std::make_unique<net::MockHostResolver>(); + resolver->rules()->AddRule("nik.test", "1.2.3.4"); + net::MockHostResolver* raw_resolver = resolver.get(); + network_service_->set_host_resolver_factory_for_testing( + std::make_unique<HostResolverFactory>(std::move(resolver))); std::unique_ptr<NetworkContext> network_context = CreateContextWithParams(CreateNetworkContextParamsForTesting()); - network_context->url_request_context()->set_host_resolver(&resolver); - base::RunLoop run_loop; mojo::Remote<mojom::ResolveHostHandle> control_handle; mojom::ResolveHostParametersPtr optional_parameters = @@ -3482,7 +3510,7 @@ EXPECT_EQ(0u, network_context->GetNumOutstandingResolveHostRequestsForTesting()); EXPECT_EQ(kNetworkIsolationKey, - resolver.last_request_network_isolation_key()); + raw_resolver->last_request_network_isolation_key()); } TEST_F(NetworkContextTest, ResolveHost_NoControlHandle) { @@ -4628,14 +4656,12 @@ base::FilePath(FILE_PATH_LITERAL("services/test/data"))); ASSERT_TRUE(test_server.Start()); - std::unique_ptr<net::MockHostResolver> resolver = - std::make_unique<net::MockHostResolver>(); - resolver->rules()->AddRule("example.test", test_server.GetIPLiteralString()); - std::unique_ptr<net::TestURLRequestContext> url_request_context = - std::make_unique<net::TestURLRequestContext>( - true /* delay_initialization */); - url_request_context->set_host_resolver(resolver.get()); - url_request_context->Init(); + auto context_builder = CreateTestURLRequestContextBuilder(); + context_builder->set_host_resolver(std::make_unique<net::MockHostResolver>()); + auto url_request_context = context_builder->Build(); + auto& resolver = *static_cast<net::MockHostResolver*>( + url_request_context->host_resolver()); + resolver.rules()->AddRule("example.test", test_server.GetIPLiteralString()); network_context_remote_.reset(); std::unique_ptr<NetworkContext> network_context = @@ -4670,10 +4696,10 @@ client.RunUntilComplete(); if (disable_secure_dns) { EXPECT_EQ(net::SecureDnsPolicy::kDisable, - resolver->last_secure_dns_policy()); + resolver.last_secure_dns_policy()); } else { EXPECT_EQ(net::SecureDnsPolicy::kAllow, - resolver->last_secure_dns_policy()); + resolver.last_secure_dns_policy()); } } } @@ -4686,18 +4712,18 @@ base::FilePath(FILE_PATH_LITERAL("services/test/data"))); ASSERT_TRUE(test_server.Start()); - net::MockHostResolver resolver; + auto context_builder = CreateTestURLRequestContextBuilder(); + context_builder->set_host_resolver(std::make_unique<net::MockHostResolver>()); + auto url_request_context = context_builder->Build(); + auto& resolver = *static_cast<net::MockHostResolver*>( + url_request_context->host_resolver()); resolver.rules()->AddRule("example.test", test_server.GetIPLiteralString()); - net::TestURLRequestContext url_request_context( - true /* delay_initialization */); - url_request_context.set_host_resolver(&resolver); - url_request_context.Init(); network_context_remote_.reset(); NetworkContext network_context( network_service_.get(), network_context_remote_.BindNewPipeAndPassReceiver(), - &url_request_context, + url_request_context.get(), /*cors_exempt_header_list=*/std::vector<std::string>()); for (bool disable_secure_dns : {false, true}) {
diff --git a/services/network/network_service_proxy_delegate_unittest.cc b/services/network/network_service_proxy_delegate_unittest.cc index 636848c..a2e9d73 100644 --- a/services/network/network_service_proxy_delegate_unittest.cc +++ b/services/network/network_service_proxy_delegate_unittest.cc
@@ -14,6 +14,8 @@ #include "net/base/proxy_server.h" #include "net/base/proxy_string_util.h" #include "net/traffic_annotation/network_traffic_annotation_test_helper.h" +#include "net/url_request/url_request_context.h" +#include "net/url_request/url_request_context_builder.h" #include "net/url_request/url_request_test_util.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -76,8 +78,7 @@ NetworkServiceProxyDelegateTest() {} void SetUp() override { - context_ = std::make_unique<net::TestURLRequestContext>(true); - context_->Init(); + context_ = net::CreateTestURLRequestContextBuilder()->Build(); } protected: @@ -117,7 +118,7 @@ mojo::Remote<mojom::CustomProxyConfigClient> client_; // Owned by the proxy delegate returned by |CreateDelegate|. raw_ptr<TestCustomProxyConnectionObserver> observer_ = nullptr; - std::unique_ptr<net::TestURLRequestContext> context_; + std::unique_ptr<net::URLRequestContext> context_; base::test::TaskEnvironment task_environment_; };
diff --git a/services/network/p2p/socket_tcp_unittest.cc b/services/network/p2p/socket_tcp_unittest.cc index d6b7663..6da2d34 100644 --- a/services/network/p2p/socket_tcp_unittest.cc +++ b/services/network/p2p/socket_tcp_unittest.cc
@@ -26,6 +26,8 @@ #include "net/socket/socket_test_util.h" #include "net/socket/stream_socket.h" #include "net/traffic_annotation/network_traffic_annotation_test_helper.h" +#include "net/url_request/url_request_context.h" +#include "net/url_request/url_request_context_builder.h" #include "net/url_request/url_request_test_util.h" #include "services/network/p2p/socket_test_utils.h" #include "services/network/proxy_resolving_client_socket_factory.h" @@ -502,11 +504,11 @@ socket_client.InitWithNewPipeAndPassReceiver()); EXPECT_CALL(fake_client2, SocketCreated(_, _)).Times(1); - net::TestURLRequestContext context(true); net::MockClientSocketFactory mock_socket_factory; - context.set_client_socket_factory(&mock_socket_factory); - context.Init(); - ProxyResolvingClientSocketFactory factory(&context); + auto context_builder = net::CreateTestURLRequestContextBuilder(); + context_builder->set_client_socket_factory_for_testing(&mock_socket_factory); + auto context = context_builder->Build(); + ProxyResolvingClientSocketFactory factory(context.get()); base::StringPiece ssl_client_hello = jingle_glue::FakeSSLClientSocket::GetSslClientHello(); @@ -557,14 +559,14 @@ socket_client.InitWithNewPipeAndPassReceiver()); EXPECT_CALL(fake_client2, SocketCreated(_, _)).Times(1); - net::TestURLRequestContext context(true); net::MockClientSocketFactory mock_socket_factory; - context.set_client_socket_factory(&mock_socket_factory); - net::MockCachingHostResolver host_resolver; - host_resolver.rules()->AddRule(kHostname, "1.2.3.4"); - context.set_host_resolver(&host_resolver); - context.Init(); - ProxyResolvingClientSocketFactory factory(&context); + auto context_builder = net::CreateTestURLRequestContextBuilder(); + context_builder->set_client_socket_factory_for_testing(&mock_socket_factory); + auto host_resolver = std::make_unique<net::MockCachingHostResolver>(); + host_resolver->rules()->AddRule(kHostname, "1.2.3.4"); + context_builder->set_host_resolver(std::move(host_resolver)); + auto context = context_builder->Build(); + ProxyResolvingClientSocketFactory factory(context.get()); base::StringPiece ssl_client_hello = jingle_glue::FakeSSLClientSocket::GetSslClientHello(); @@ -604,9 +606,9 @@ net::HostResolver::ResolveHostParameters params; params.source = net::HostResolverSource::LOCAL_ONLY; std::unique_ptr<net::HostResolver::ResolveHostRequest> request1 = - context.host_resolver()->CreateRequest(kHostPortPair, - network_isolation_key, - net::NetLogWithSource(), params); + context->host_resolver()->CreateRequest(kHostPortPair, + network_isolation_key, + net::NetLogWithSource(), params); net::TestCompletionCallback callback1; int result = request1->Start(callback1.callback()); EXPECT_EQ(net::OK, callback1.GetResult(result)); @@ -620,8 +622,8 @@ kDestinationOrigin /* frame_origin */)}; for (const auto& other_nik : kOtherNiks) { std::unique_ptr<net::HostResolver::ResolveHostRequest> request2 = - context.host_resolver()->CreateRequest(kHostPortPair, other_nik, - net::NetLogWithSource(), params); + context->host_resolver()->CreateRequest( + kHostPortPair, other_nik, net::NetLogWithSource(), params); net::TestCompletionCallback callback2; result = request2->Start(callback2.callback()); EXPECT_EQ(net::ERR_NAME_NOT_RESOLVED, callback2.GetResult(result)); @@ -652,11 +654,11 @@ socket_client.InitWithNewPipeAndPassReceiver()); EXPECT_CALL(fake_client2, SocketCreated(_, _)).Times(1); - net::TestURLRequestContext context(true); net::MockClientSocketFactory mock_socket_factory; - context.set_client_socket_factory(&mock_socket_factory); - context.Init(); - ProxyResolvingClientSocketFactory factory(&context); + auto context_builder = net::CreateTestURLRequestContextBuilder(); + context_builder->set_client_socket_factory_for_testing(&mock_socket_factory); + auto context = context_builder->Build(); + ProxyResolvingClientSocketFactory factory(context.get()); const net::IoMode io_mode = std::get<0>(GetParam()); const P2PSocketType socket_type = std::get<1>(GetParam()); // OnOpen() calls DoRead(), so populate the mock socket with a pending read.
diff --git a/services/network/proxy_resolving_client_socket_unittest.cc b/services/network/proxy_resolving_client_socket_unittest.cc index 310ca65..73faab5 100644 --- a/services/network/proxy_resolving_client_socket_unittest.cc +++ b/services/network/proxy_resolving_client_socket_unittest.cc
@@ -10,6 +10,7 @@ #include "base/compiler_specific.h" #include "base/run_loop.h" +#include "base/strings/string_piece.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/test/scoped_feature_list.h" @@ -30,6 +31,7 @@ #include "net/spdy/spdy_test_util_common.h" #include "net/test/gtest_util.h" #include "net/traffic_annotation/network_traffic_annotation_test_helper.h" +#include "net/url_request/url_request_context_builder.h" #include "net/url_request/url_request_test_util.h" #include "services/network/proxy_resolving_client_socket_factory.h" #include "testing/gtest/include/gtest/gtest.h" @@ -40,25 +42,11 @@ namespace { -class TestURLRequestContextWithProxy : public net::TestURLRequestContext { - public: - explicit TestURLRequestContextWithProxy( - const std::string& pac_result, - net::ClientSocketFactory* client_socket_factory) - : TestURLRequestContext(true) { - context_storage_.set_proxy_resolution_service( - net::ConfiguredProxyResolutionService::CreateFixedFromPacResult( - pac_result, TRAFFIC_ANNOTATION_FOR_TESTS)); - auto host_resolver = std::make_unique<net::MockCachingHostResolver>( - /*cache_invalidation_num=*/0, - /*default_result=*/net::MockHostResolverBase::RuleResolver:: - GetLocalhostResult()); - context_storage_.set_host_resolver(std::move(host_resolver)); - set_client_socket_factory(client_socket_factory); - Init(); - } - ~TestURLRequestContextWithProxy() override {} -}; +std::unique_ptr<net::ConfiguredProxyResolutionService> +CreateProxyResolutionService(base::StringPiece pac_result) { + return net::ConfiguredProxyResolutionService::CreateFixedFromPacResult( + static_cast<std::string>(pac_result), TRAFFIC_ANNOTATION_FOR_TESTS); +} } // namespace @@ -66,10 +54,7 @@ : public testing::Test, public testing::WithParamInterface<bool> { protected: - ProxyResolvingClientSocketTest() - : context_with_proxy_("PROXY bad:99; PROXY maybe:80; DIRECT", - &mock_client_socket_factory_), - use_tls_(GetParam()) { + ProxyResolvingClientSocketTest() : use_tls_(GetParam()) { feature_list_.InitWithFeatures( // enabled_features {net::features::kPartitionConnectionsByNetworkIsolationKey, @@ -86,9 +71,18 @@ base::RunLoop().RunUntilIdle(); } + std::unique_ptr<net::URLRequestContextBuilder> CreateBuilder( + base::StringPiece pac_result = "PROXY bad:99; PROXY maybe:80; DIRECT") { + auto builder = net::CreateTestURLRequestContextBuilder(); + builder->set_proxy_resolution_service( + CreateProxyResolutionService(pac_result)); + builder->set_client_socket_factory_for_testing( + &mock_client_socket_factory_); + return builder; + } + base::test::TaskEnvironment task_environment_; base::test::ScopedFeatureList feature_list_; - TestURLRequestContextWithProxy context_with_proxy_; net::MockClientSocketFactory mock_client_socket_factory_; const bool use_tls_; }; @@ -107,8 +101,8 @@ kNetworkIsolationKeyOrigin /* top_frame_origin */, kNetworkIsolationKeyOrigin /* frame_origin */); - TestURLRequestContextWithProxy url_request_context( - "DIRECT", &mock_client_socket_factory_); + auto url_request_context = CreateBuilder("DIRECT")->Build(); + const GURL kDestination("https://dest.test/"); net::StaticSocketDataProvider socket_data; mock_client_socket_factory_.AddSocketDataProvider(&socket_data); @@ -116,7 +110,7 @@ mock_client_socket_factory_.AddSSLSocketDataProvider(&ssl_data); ProxyResolvingClientSocketFactory proxy_resolving_socket_factory( - &url_request_context); + url_request_context.get()); std::unique_ptr<ProxyResolvingClientSocket> socket = proxy_resolving_socket_factory.CreateSocket( kDestination, kNetworkIsolationKey, use_tls_); @@ -131,7 +125,7 @@ net::HostResolver::ResolveHostParameters params; params.source = net::HostResolverSource::LOCAL_ONLY; std::unique_ptr<net::HostResolver::ResolveHostRequest> request1 = - url_request_context.host_resolver()->CreateRequest( + url_request_context->host_resolver()->CreateRequest( kDestinationHostPortPair, kNetworkIsolationKey, net::NetLogWithSource(), params); net::TestCompletionCallback callback2; @@ -146,7 +140,7 @@ kDestinationOrigin /* frame_origin */)}; for (const auto& other_nik : kOtherNiks) { std::unique_ptr<net::HostResolver::ResolveHostRequest> request2 = - url_request_context.host_resolver()->CreateRequest( + url_request_context->host_resolver()->CreateRequest( kDestinationHostPortPair, other_nik, net::NetLogWithSource(), params); net::TestCompletionCallback callback3; @@ -171,8 +165,7 @@ return; net::SpdySessionDependencies session_deps; session_deps.proxy_resolution_service = - net::ConfiguredProxyResolutionService::CreateFixedFromPacResult( - "HTTPS proxy.test:80", TRAFFIC_ANNOTATION_FOR_TESTS); + CreateProxyResolutionService("HTTPS proxy.test:80"); std::unique_ptr<net::HttpNetworkSession> http_network_session = net::SpdySessionDependencies::SpdyCreateSession(&session_deps); @@ -302,8 +295,9 @@ mock_client_socket_factory_.AddSSLSocketDataProvider(ssl_data[i].get()); } + auto context = CreateBuilder()->Build(); ProxyResolvingClientSocketFactory proxy_resolving_socket_factory( - &context_with_proxy_); + context.get()); std::vector<std::unique_ptr<ProxyResolvingClientSocket>> sockets; for (int i = 0; i < kNumSockets; ++i) { std::unique_ptr<ProxyResolvingClientSocket> socket = @@ -333,14 +327,9 @@ }; const GURL kDestination("https://example.com:443"); for (auto test : kTestCases) { - std::unique_ptr<net::URLRequestContext> context; - if (test.is_direct) { - context = std::make_unique<TestURLRequestContextWithProxy>( - "DIRECT", &mock_client_socket_factory_); - } else { - context = std::make_unique<TestURLRequestContextWithProxy>( - "PROXY myproxy.com:89", &mock_client_socket_factory_); - } + base::StringPiece pac_result = + test.is_direct ? "DIRECT" : "PROXY myproxy.com:89"; + auto context = CreateBuilder(pac_result)->Build(); net::StaticSocketDataProvider socket_data; socket_data.set_connect_data(net::MockConnect( test.is_error_sync ? net::SYNCHRONOUS : net::ASYNC, net::ERR_FAILED)); @@ -373,15 +362,13 @@ const int kDirectPort = 443; for (bool is_direct : {true, false}) { net::MockClientSocketFactory socket_factory; - std::unique_ptr<net::URLRequestContext> context; + std::string pac_result; if (is_direct) { - context = std::make_unique<TestURLRequestContextWithProxy>( - "DIRECT", &mock_client_socket_factory_); + pac_result = "DIRECT"; } else { - context = std::make_unique<TestURLRequestContextWithProxy>( - base::StringPrintf("PROXY myproxy.com:%d", kProxyPort), - &mock_client_socket_factory_); + pac_result = base::StringPrintf("PROXY myproxy.com:%d", kProxyPort); } + auto context = CreateBuilder(pac_result)->Build(); net::MockRead reads[] = {net::MockRead("HTTP/1.1 200 Success\r\n\r\n")}; net::MockWrite writes[] = { net::MockWrite("CONNECT example.com:443 HTTP/1.1\r\n" @@ -430,8 +417,7 @@ mock_client_socket_factory_.AddSocketDataProvider(&socket_data); mock_client_socket_factory_.AddSSLSocketDataProvider(&ssl_socket); - auto context = std::make_unique<TestURLRequestContextWithProxy>( - "DIRECT", &mock_client_socket_factory_); + auto context = CreateBuilder("DIRECT")->Build(); ProxyResolvingClientSocketFactory proxy_resolving_socket_factory( context.get()); @@ -467,15 +453,13 @@ const int kProxyPort = 8009; const int kDirectPort = 80; for (auto test : kTestCases) { - std::unique_ptr<net::URLRequestContext> context; + std::string pac_result; if (test.is_direct) { - context = std::make_unique<TestURLRequestContextWithProxy>( - "DIRECT", &mock_client_socket_factory_); + pac_result = "DIRECT"; } else { - context = std::make_unique<TestURLRequestContextWithProxy>( - base::StringPrintf("PROXY myproxy.com:%d", kProxyPort), - &mock_client_socket_factory_); + pac_result = base::StringPrintf("PROXY myproxy.com:%d", kProxyPort); } + auto context = CreateBuilder(pac_result)->Build(); std::vector<net::MockWrite> writes; std::vector<net::MockRead> reads; if (!test.is_direct) { @@ -566,8 +550,9 @@ net::SSLSocketDataProvider ssl_socket(net::ASYNC, net::OK); mock_client_socket_factory_.AddSSLSocketDataProvider(&ssl_socket); + auto context = CreateBuilder()->Build(); ProxyResolvingClientSocketFactory proxy_resolving_socket_factory( - &context_with_proxy_); + context.get()); std::unique_ptr<ProxyResolvingClientSocket> socket = proxy_resolving_socket_factory.CreateSocket( kDestination, net::NetworkIsolationKey(), use_tls_); @@ -578,7 +563,7 @@ EXPECT_EQ(net::OK, status); const net::ProxyRetryInfoMap& retry_info = - context_with_proxy_.proxy_resolution_service()->proxy_retry_info(); + context->proxy_resolution_service()->proxy_retry_info(); EXPECT_EQ(1u, retry_info.size()); net::ProxyRetryInfoMap::const_iterator iter = retry_info.find("bad:99"); @@ -603,8 +588,9 @@ net::StaticSocketDataProvider kSocketData1(kConnectReads1, kConnectWrites1); mock_client_socket_factory_.AddSocketDataProvider(&kSocketData1); + auto context = CreateBuilder()->Build(); ProxyResolvingClientSocketFactory proxy_resolving_socket_factory( - &context_with_proxy_); + context.get()); std::unique_ptr<ProxyResolvingClientSocket> socket = proxy_resolving_socket_factory.CreateSocket( kDestination, net::NetworkIsolationKey(), use_tls_); @@ -663,10 +649,10 @@ net::SSLSocketDataProvider ssl_socket(net::ASYNC, net::OK); mock_client_socket_factory_.AddSSLSocketDataProvider(&ssl_socket); + auto context = CreateBuilder()->Build(); + net::HttpAuthCache* auth_cache = - context_with_proxy_.http_transaction_factory() - ->GetSession() - ->http_auth_cache(); + context->http_transaction_factory()->GetSession()->http_auth_cache(); auth_cache->Add(url::SchemeHostPort(GURL("http://bad:99")), net::HttpAuth::AUTH_PROXY, "test_realm", @@ -681,7 +667,7 @@ net::AuthCredentials(u"user2", u"password2"), std::string()); ProxyResolvingClientSocketFactory proxy_resolving_socket_factory( - &context_with_proxy_); + context.get()); std::unique_ptr<ProxyResolvingClientSocket> socket = proxy_resolving_socket_factory.CreateSocket( kDestination, net::NetworkIsolationKey(), use_tls_); @@ -723,10 +709,10 @@ net::SSLSocketDataProvider ssl_socket(net::ASYNC, net::OK); mock_client_socket_factory_.AddSSLSocketDataProvider(&ssl_socket); + auto context = CreateBuilder()->Build(); + net::HttpAuthCache* auth_cache = - context_with_proxy_.http_transaction_factory() - ->GetSession() - ->http_auth_cache(); + context->http_transaction_factory()->GetSession()->http_auth_cache(); // We are adding these credentials at an empty path so that it won't be picked // up by the preemptive authentication step and will only be picked up via @@ -738,7 +724,7 @@ net::AuthCredentials(u"user", u"password"), std::string()); ProxyResolvingClientSocketFactory proxy_resolving_socket_factory( - &context_with_proxy_); + context.get()); std::unique_ptr<ProxyResolvingClientSocket> socket = proxy_resolving_socket_factory.CreateSocket( kDestination, net::NetworkIsolationKey(), use_tls_); @@ -752,15 +738,15 @@ // ProxyResolvingClientSocketFactory uses the latest cache for creating new // sockets. TEST_P(ProxyResolvingClientSocketTest, FactoryUsesLatestHTTPAuthCache) { + auto context = CreateBuilder()->Build(); + ProxyResolvingClientSocketFactory proxy_resolving_socket_factory( - &context_with_proxy_); + context.get()); // After creating |socket_factory|, updates the auth cache with credentials. // New socket connections should pick up this change. net::HttpAuthCache* auth_cache = - context_with_proxy_.http_transaction_factory() - ->GetSession() - ->http_auth_cache(); + context->http_transaction_factory()->GetSession()->http_auth_cache(); // We are adding these credentials at an empty path so that it won't be picked // up by the preemptive authentication step and will only be picked up via @@ -824,10 +810,10 @@ net::SSLSocketDataProvider ssl_socket(net::ASYNC, net::OK); mock_client_socket_factory_.AddSSLSocketDataProvider(&ssl_socket); + auto context = CreateBuilder()->Build(); + net::HttpAuthCache* auth_cache = - context_with_proxy_.http_transaction_factory() - ->GetSession() - ->http_auth_cache(); + context->http_transaction_factory()->GetSession()->http_auth_cache(); auth_cache->Add(url::SchemeHostPort(GURL("http://bad:99")), net::HttpAuth::AUTH_PROXY, "test_realm", @@ -836,7 +822,7 @@ net::AuthCredentials(u"user", u"password"), "/"); ProxyResolvingClientSocketFactory proxy_resolving_socket_factory( - &context_with_proxy_); + context.get()); std::unique_ptr<ProxyResolvingClientSocket> socket = proxy_resolving_socket_factory.CreateSocket( kDestination, net::NetworkIsolationKey(), use_tls_); @@ -864,8 +850,10 @@ net::StaticSocketDataProvider kSocketData(kConnectReads, kConnectWrites); mock_client_socket_factory_.AddSocketDataProvider(&kSocketData); + auto context = CreateBuilder()->Build(); + ProxyResolvingClientSocketFactory proxy_resolving_socket_factory( - &context_with_proxy_); + context.get()); std::unique_ptr<ProxyResolvingClientSocket> socket = proxy_resolving_socket_factory.CreateSocket( kDestination, net::NetworkIsolationKey(), use_tls_); @@ -879,7 +867,7 @@ TEST_P(ProxyResolvingClientSocketTest, URLSanitized) { GURL url("http://username:password@www.example.com:79/?ref#hash#hash"); - auto context = std::make_unique<net::TestURLRequestContext>(true); + auto context_builder = CreateBuilder(); net::ProxyConfig proxy_config; proxy_config.set_pac_url(GURL("http://foopy/proxy.pac")); proxy_config.set_pac_mandatory(true); @@ -888,14 +876,14 @@ std::make_unique<net::MockAsyncProxyResolverFactory>(false); net::MockAsyncProxyResolverFactory* proxy_resolver_factory_raw = proxy_resolver_factory.get(); - net::ConfiguredProxyResolutionService service( - std::make_unique<net::ProxyConfigServiceFixed>( - net::ProxyConfigWithAnnotation(proxy_config, - TRAFFIC_ANNOTATION_FOR_TESTS)), - std::move(proxy_resolver_factory), nullptr, - true /* quick_check_enabled */); - context->set_proxy_resolution_service(&service); - context->Init(); + context_builder->set_proxy_resolution_service( + std::make_unique<net::ConfiguredProxyResolutionService>( + std::make_unique<net::ProxyConfigServiceFixed>( + net::ProxyConfigWithAnnotation(proxy_config, + TRAFFIC_ANNOTATION_FOR_TESTS)), + std::move(proxy_resolver_factory), nullptr, + /*quick_check_enabled=*/true)); + auto context = context_builder->Build(); ProxyResolvingClientSocketFactory proxy_resolving_socket_factory( context.get()); @@ -924,7 +912,7 @@ SocketDestroyedBeforeProxyResolutionCompletes) { GURL url("http://www.example.com:79"); - auto context = std::make_unique<net::TestURLRequestContext>(true); + auto context_builder = CreateBuilder(); net::ProxyConfig proxy_config; proxy_config.set_pac_url(GURL("http://foopy/proxy.pac")); proxy_config.set_pac_mandatory(true); @@ -933,14 +921,14 @@ std::make_unique<net::MockAsyncProxyResolverFactory>(false); net::MockAsyncProxyResolverFactory* proxy_resolver_factory_raw = proxy_resolver_factory.get(); - net::ConfiguredProxyResolutionService service( - std::make_unique<net::ProxyConfigServiceFixed>( - net::ProxyConfigWithAnnotation(proxy_config, - TRAFFIC_ANNOTATION_FOR_TESTS)), - std::move(proxy_resolver_factory), nullptr, - true /* quick_check_enabled */); - context->set_proxy_resolution_service(&service); - context->Init(); + context_builder->set_proxy_resolution_service( + std::make_unique<net::ConfiguredProxyResolutionService>( + std::make_unique<net::ProxyConfigServiceFixed>( + net::ProxyConfigWithAnnotation(proxy_config, + TRAFFIC_ANNOTATION_FOR_TESTS)), + std::move(proxy_resolver_factory), nullptr, + /*quick_check_enabled=*/true)); + auto context = context_builder->Build(); ProxyResolvingClientSocketFactory proxy_resolving_socket_factory( context.get()); @@ -962,20 +950,20 @@ TEST_P(ProxyResolvingClientSocketTest, NoSupportedProxies) { const GURL kDestination("https://example.com:443"); - auto context = std::make_unique<net::TestURLRequestContext>(true); + auto context_builder = CreateBuilder(); net::ProxyConfig proxy_config; // Use an unsupported proxy scheme. proxy_config.proxy_rules().ParseFromString("quic://foopy:8080"); auto proxy_resolver_factory = std::make_unique<net::MockAsyncProxyResolverFactory>(false); - net::ConfiguredProxyResolutionService service( - std::make_unique<net::ProxyConfigServiceFixed>( - net::ProxyConfigWithAnnotation(proxy_config, - TRAFFIC_ANNOTATION_FOR_TESTS)), - std::move(proxy_resolver_factory), nullptr, - true /* quick_check_enabled */); - context->set_proxy_resolution_service(&service); - context->Init(); + context_builder->set_proxy_resolution_service( + std::make_unique<net::ConfiguredProxyResolutionService>( + std::make_unique<net::ProxyConfigServiceFixed>( + net::ProxyConfigWithAnnotation(proxy_config, + TRAFFIC_ANNOTATION_FOR_TESTS)), + std::move(proxy_resolver_factory), nullptr, + /*quick_check_enabled=*/true)); + auto context = context_builder->Build(); ProxyResolvingClientSocketFactory proxy_resolving_socket_factory( context.get()); @@ -992,17 +980,11 @@ : public testing::Test, public testing::WithParamInterface<::testing::tuple<bool, bool, int>> { public: - ReconsiderProxyAfterErrorTest() - : context_with_proxy_( - "HTTPS badproxy:99; HTTPS badfallbackproxy:98; DIRECT", - &mock_client_socket_factory_), - use_tls_(::testing::get<0>(GetParam())) {} - - ~ReconsiderProxyAfterErrorTest() override {} + ReconsiderProxyAfterErrorTest() : use_tls_(::testing::get<0>(GetParam())) {} + ~ReconsiderProxyAfterErrorTest() override = default; base::test::TaskEnvironment task_environment_; net::MockClientSocketFactory mock_client_socket_factory_; - TestURLRequestContextWithProxy context_with_proxy_; const bool use_tls_; }; @@ -1030,11 +1012,15 @@ net::IoMode io_mode = ::testing::get<1>(GetParam()) ? net::SYNCHRONOUS : net::ASYNC; const int mock_error = ::testing::get<2>(GetParam()); + auto context_builder = net::CreateTestURLRequestContextBuilder(); + context_builder->set_proxy_resolution_service(CreateProxyResolutionService( + "HTTPS badproxy:99; HTTPS badfallbackproxy:98; DIRECT")); + context_builder->set_client_socket_factory_for_testing( + &mock_client_socket_factory_); + auto context = context_builder->Build(); // Before starting the test, verify that there are no proxies marked as bad. - ASSERT_TRUE(context_with_proxy_.proxy_resolution_service() - ->proxy_retry_info() - .empty()) + ASSERT_TRUE(context->proxy_resolution_service()->proxy_retry_info().empty()) << mock_error; // Configure the HTTP CONNECT to fail with `mock_error`. @@ -1072,7 +1058,7 @@ const GURL kDestination("https://example.com:443"); ProxyResolvingClientSocketFactory proxy_resolving_socket_factory( - &context_with_proxy_); + context.get()); std::unique_ptr<ProxyResolvingClientSocket> socket = proxy_resolving_socket_factory.CreateSocket( kDestination, net::NetworkIsolationKey(), use_tls_); @@ -1083,7 +1069,7 @@ EXPECT_EQ(net::OK, status); const net::ProxyRetryInfoMap& retry_info = - context_with_proxy_.proxy_resolution_service()->proxy_retry_info(); + context->proxy_resolution_service()->proxy_retry_info(); EXPECT_EQ(2u, retry_info.size()) << mock_error; EXPECT_NE(retry_info.end(), retry_info.find("https://badproxy:99")); EXPECT_NE(retry_info.end(), retry_info.find("https://badfallbackproxy:98"));
diff --git a/services/network/proxy_resolving_socket_mojo_unittest.cc b/services/network/proxy_resolving_socket_mojo_unittest.cc index 7bfdf53..111ccb80 100644 --- a/services/network/proxy_resolving_socket_mojo_unittest.cc +++ b/services/network/proxy_resolving_socket_mojo_unittest.cc
@@ -24,6 +24,7 @@ #include "net/proxy_resolution/configured_proxy_resolution_service.h" #include "net/socket/socket_test_util.h" #include "net/traffic_annotation/network_traffic_annotation_test_helper.h" +#include "net/url_request/url_request_context_builder.h" #include "net/url_request/url_request_test_util.h" #include "services/network/mojo_socket_test_util.h" #include "services/network/proxy_resolving_socket_factory_mojo.h" @@ -33,28 +34,6 @@ namespace network { -namespace { - -// A net::TestURLRequestContext implementation that configures the proxy to be -// a PAC string. -class TestURLRequestContextWithProxy : public net::TestURLRequestContext { - public: - explicit TestURLRequestContextWithProxy(const std::string& pac_result) - : TestURLRequestContext(true) { - context_storage_.set_proxy_resolution_service( - net::ConfiguredProxyResolutionService::CreateFixedFromPacResult( - pac_result, TRAFFIC_ANNOTATION_FOR_TESTS)); - auto host_resolver = std::make_unique<net::MockHostResolver>( - /*default_result=*/net::MockHostResolverBase::RuleResolver:: - GetLocalhostResult()); - context_storage_.set_host_resolver(std::move(host_resolver)); - } - - ~TestURLRequestContextWithProxy() override {} -}; - -} // namespace - class ProxyResolvingSocketTestBase { public: ProxyResolvingSocketTestBase(bool use_tls) @@ -70,24 +49,26 @@ void Init(const std::string& pac_result) { // Init() can be called multiple times in a test. Reset the members for each - // invocation. |context_with_proxy_| must outlive |factory_impl_|, which - // uses the URLRequestContet. + // invocation. `context_` must outlive `factory_impl_`, which uses the + // URLRequestContext. factory_receiver_ = nullptr; factory_impl_ = nullptr; factory_remote_.reset(); - context_with_proxy_ = nullptr; + context_ = nullptr; mock_client_socket_factory_ = std::make_unique<net::MockClientSocketFactory>(); mock_client_socket_factory_->set_enable_read_if_ready(true); - context_with_proxy_ = - std::make_unique<TestURLRequestContextWithProxy>(pac_result); - context_with_proxy_->set_client_socket_factory( + auto context_builder = net::CreateTestURLRequestContextBuilder(); + context_builder->set_proxy_resolution_service( + net::ConfiguredProxyResolutionService::CreateFixedFromPacResult( + pac_result, TRAFFIC_ANNOTATION_FOR_TESTS)); + context_builder->set_client_socket_factory_for_testing( mock_client_socket_factory_.get()); - context_with_proxy_->Init(); + context_ = context_builder->Build(); - factory_impl_ = std::make_unique<ProxyResolvingSocketFactoryMojo>( - context_with_proxy_.get()); + factory_impl_ = + std::make_unique<ProxyResolvingSocketFactoryMojo>(context_.get()); factory_receiver_ = std::make_unique<mojo::Receiver<mojom::ProxyResolvingSocketFactory>>( factory_impl_.get(), factory_remote_.BindNewPipeAndPassReceiver()); @@ -165,7 +146,7 @@ bool fake_tls_handshake_; base::test::TaskEnvironment task_environment_; std::unique_ptr<net::MockClientSocketFactory> mock_client_socket_factory_; - std::unique_ptr<TestURLRequestContextWithProxy> context_with_proxy_; + std::unique_ptr<net::URLRequestContext> context_; mojo::Remote<mojom::ProxyResolvingSocketFactory> factory_remote_; std::unique_ptr<mojo::Receiver<mojom::ProxyResolvingSocketFactory>> factory_receiver_;
diff --git a/services/network/public/cpp/corb/corb_impl_unittest.cc b/services/network/public/cpp/corb/corb_impl_unittest.cc index b06100af..b7b4bfe 100644 --- a/services/network/public/cpp/corb/corb_impl_unittest.cc +++ b/services/network/public/cpp/corb/corb_impl_unittest.cc
@@ -19,6 +19,7 @@ #include "net/http/http_util.h" #include "net/traffic_annotation/network_traffic_annotation_test_helper.h" #include "net/url_request/url_request_context.h" +#include "net/url_request/url_request_context_builder.h" #include "net/url_request/url_request_test_util.h" #include "services/network/public/cpp/corb/corb_impl.h" #include "services/network/public/mojom/url_response_head.mojom.h" @@ -1857,7 +1858,8 @@ class ResponseAnalyzerTest : public testing::Test, public testing::WithParamInterface<TestScenario> { public: - ResponseAnalyzerTest() = default; + ResponseAnalyzerTest() + : context_(net::CreateTestURLRequestContextBuilder()->Build()) {} ResponseAnalyzerTest(const ResponseAnalyzerTest&) = delete; ResponseAnalyzerTest& operator=(const ResponseAnalyzerTest&) = delete; @@ -1893,9 +1895,9 @@ std::unique_ptr<ResponseAnalyzer> analyzer) { TestScenario scenario = GetParam(); // Initialize |request| from the parameters. - std::unique_ptr<net::URLRequest> request = - context_.CreateRequest(GURL(scenario.target_url), net::DEFAULT_PRIORITY, - &delegate_, TRAFFIC_ANNOTATION_FOR_TESTS); + std::unique_ptr<net::URLRequest> request = context_->CreateRequest( + GURL(scenario.target_url), net::DEFAULT_PRIORITY, &delegate_, + TRAFFIC_ANNOTATION_FOR_TESTS); request->set_initiator( url::Origin::Create(GURL(scenario.initiator_origin))); @@ -2001,7 +2003,7 @@ protected: base::test::TaskEnvironment task_environment_; - net::TestURLRequestContext context_; + std::unique_ptr<net::URLRequestContext> context_; net::TestDelegate delegate_; }; // namespace network
diff --git a/services/network/public/cpp/server/http_server_unittest.cc b/services/network/public/cpp/server/http_server_unittest.cc index 8cca7451..3e1182b 100644 --- a/services/network/public/cpp/server/http_server_unittest.cc +++ b/services/network/public/cpp/server/http_server_unittest.cc
@@ -30,6 +30,8 @@ #include "net/log/net_log_source.h" #include "net/test/gtest_util.h" #include "net/traffic_annotation/network_traffic_annotation_test_helper.h" +#include "net/url_request/url_request_context.h" +#include "net/url_request/url_request_context_builder.h" #include "net/url_request/url_request_test_util.h" #include "net/websockets/websocket_frame.h" #include "services/network/public/cpp/server/http_connection.h" @@ -44,7 +46,10 @@ class TestHttpClient { public: - TestHttpClient() : factory_(nullptr, &url_request_context_) {} + TestHttpClient() + : url_request_context_( + net::CreateTestURLRequestContextBuilder()->Build()), + factory_(nullptr, url_request_context_.get()) {} int ConnectAndWait(const net::IPEndPoint& address) { net::AddressList addresses(address); @@ -145,7 +150,7 @@ return body_size >= headers->GetContentLength(); } - net::TestURLRequestContext url_request_context_; + std::unique_ptr<net::URLRequestContext> url_request_context_; network::SocketFactory factory_; scoped_refptr<net::IOBufferWithSize> read_buffer_; scoped_refptr<net::DrainableIOBuffer> write_buffer_; @@ -168,7 +173,9 @@ : task_environment_(base::test::TaskEnvironment::MainThreadType::IO), quit_after_request_count_(0), quit_on_close_connection_(-1), - factory_(nullptr, &url_request_context_) {} + url_request_context_( + net::CreateTestURLRequestContextBuilder()->Build()), + factory_(nullptr, url_request_context_.get()) {} void SetUp() override { int net_error = net::ERR_FAILED; @@ -301,7 +308,7 @@ std::unique_ptr<base::RunLoop> quit_on_create_loop_; int quit_on_close_connection_; - net::TestURLRequestContext url_request_context_; + std::unique_ptr<net::URLRequestContext> url_request_context_; SocketFactory factory_; mojo::PendingRemote<mojom::TCPServerSocket> server_socket_; };
diff --git a/services/network/resource_scheduler/resource_scheduler_unittest.cc b/services/network/resource_scheduler/resource_scheduler_unittest.cc index c355ace..0a608a3f 100644 --- a/services/network/resource_scheduler/resource_scheduler_unittest.cc +++ b/services/network/resource_scheduler/resource_scheduler_unittest.cc
@@ -35,6 +35,8 @@ #include "net/test/embedded_test_server/embedded_test_server.h" #include "net/traffic_annotation/network_traffic_annotation_test_helper.h" #include "net/url_request/url_request.h" +#include "net/url_request/url_request_context.h" +#include "net/url_request/url_request_context_builder.h" #include "net/url_request/url_request_test_util.h" #include "services/network/public/cpp/features.h" #include "services/network/public/mojom/network_context.mojom.h" @@ -177,9 +179,9 @@ net::features::kPartitionHttpServerPropertiesByNetworkIsolationKey); // This has to be done after initializing the feature list, since the value // of the feature is cached. - context_ = std::make_unique<net::TestURLRequestContext>(true); - context_->set_network_quality_estimator(&network_quality_estimator_); - context_->Init(); + auto context_builder = net::CreateTestURLRequestContextBuilder(); + context_builder->set_network_quality_estimator(&network_quality_estimator_); + context_ = context_builder->Build(); InitializeScheduler(); } @@ -552,7 +554,7 @@ base::test::TaskEnvironment task_environment_; std::unique_ptr<ResourceScheduler> scheduler_; net::TestNetworkQualityEstimator network_quality_estimator_; - std::unique_ptr<net::TestURLRequestContext> context_; + std::unique_ptr<net::URLRequestContext> context_; ResourceSchedulerParamsManager resource_scheduler_params_manager_; base::SimpleTestTickClock tick_clock_; };
diff --git a/services/network/sec_header_helpers_unittest.cc b/services/network/sec_header_helpers_unittest.cc index 8c6db5a..ae0798a 100644 --- a/services/network/sec_header_helpers_unittest.cc +++ b/services/network/sec_header_helpers_unittest.cc
@@ -8,6 +8,7 @@ #include "net/traffic_annotation/network_traffic_annotation_test_helper.h" #include "net/url_request/url_request.h" #include "net/url_request/url_request_context.h" +#include "net/url_request/url_request_context_builder.h" #include "net/url_request/url_request_test_util.h" #include "services/network/public/cpp/cors/origin_access_list.h" #include "services/network/public/mojom/cors_origin_pattern.mojom.h" @@ -41,10 +42,11 @@ public: SecHeaderHelpersTest() : task_environment_(base::test::TaskEnvironment::MainThreadType::IO), - url_request_(context_.CreateRequest(GURL(kSecureSite), - net::DEFAULT_PRIORITY, - /*delegate=*/nullptr, - TRAFFIC_ANNOTATION_FOR_TESTS)) { + context_(net::CreateTestURLRequestContextBuilder()->Build()), + url_request_(context_->CreateRequest(GURL(kSecureSite), + net::DEFAULT_PRIORITY, + /*delegate=*/nullptr, + TRAFFIC_ANNOTATION_FOR_TESTS)) { url_request_->set_initiator( url::Origin::Create(GURL(kPrivilegedInitiator))); } @@ -53,7 +55,7 @@ private: base::test::TaskEnvironment task_environment_; - net::TestURLRequestContext context_; + std::unique_ptr<net::URLRequestContext> context_; std::unique_ptr<net::URLRequest> url_request_; };
diff --git a/services/network/tcp_bound_socket_unittest.cc b/services/network/tcp_bound_socket_unittest.cc index 6f66e1d1..b7abecbd 100644 --- a/services/network/tcp_bound_socket_unittest.cc +++ b/services/network/tcp_bound_socket_unittest.cc
@@ -27,6 +27,8 @@ #include "net/test/embedded_test_server/http_request.h" #include "net/test/embedded_test_server/http_response.h" #include "net/traffic_annotation/network_traffic_annotation_test_helper.h" +#include "net/url_request/url_request_context.h" +#include "net/url_request/url_request_context_builder.h" #include "net/url_request/url_request_test_util.h" #include "services/network/mojo_socket_test_util.h" #include "services/network/public/mojom/tcp_socket.mojom.h" @@ -41,7 +43,9 @@ public: TCPBoundSocketTest() : task_environment_(base::test::TaskEnvironment::MainThreadType::IO), - factory_(nullptr /* net_log */, &url_request_context_) {} + url_request_context_( + net::CreateTestURLRequestContextBuilder()->Build()), + factory_(/*net_log=*/nullptr, url_request_context_.get()) {} TCPBoundSocketTest(const TCPBoundSocketTest&) = delete; TCPBoundSocketTest& operator=(const TCPBoundSocketTest&) = delete; @@ -198,7 +202,7 @@ private: base::test::TaskEnvironment task_environment_; - net::TestURLRequestContext url_request_context_; + std::unique_ptr<net::URLRequestContext> url_request_context_; SocketFactory factory_; };
diff --git a/services/network/tcp_socket_unittest.cc b/services/network/tcp_socket_unittest.cc index a713410d..1a88603d 100644 --- a/services/network/tcp_socket_unittest.cc +++ b/services/network/tcp_socket_unittest.cc
@@ -29,6 +29,8 @@ #include "net/socket/server_socket.h" #include "net/socket/socket_test_util.h" #include "net/traffic_annotation/network_traffic_annotation_test_helper.h" +#include "net/url_request/url_request_context.h" +#include "net/url_request/url_request_context_builder.h" #include "net/url_request/url_request_test_util.h" #include "services/network/mojo_socket_test_util.h" #include "services/network/public/mojom/network_service.mojom.h" @@ -149,7 +151,9 @@ TestServer() : TestServer(net::IPEndPoint(net::IPAddress::IPv6Localhost(), 0)) {} explicit TestServer(const net::IPEndPoint& server_addr) - : factory_(nullptr, &url_request_context_), + : url_request_context_( + net::CreateTestURLRequestContextBuilder()->Build()), + factory_(nullptr, url_request_context_.get()), readable_handle_watcher_(FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::AUTOMATIC), server_addr_(server_addr) {} @@ -252,7 +256,7 @@ } } - net::TestURLRequestContext url_request_context_; + std::unique_ptr<net::URLRequestContext> url_request_context_; SocketFactory factory_; mojo::Remote<mojom::TCPServerSocket> server_socket_; std::vector<mojo::Remote<mojom::TCPConnectedSocket>> connected_sockets_; @@ -270,8 +274,7 @@ class TCPSocketTest : public testing::Test { public: TCPSocketTest() - : task_environment_(base::test::TaskEnvironment::MainThreadType::IO), - url_request_context_(true) {} + : task_environment_(base::test::TaskEnvironment::MainThreadType::IO) {} TCPSocketTest(const TCPSocketTest&) = delete; TCPSocketTest& operator=(const TCPSocketTest&) = delete; @@ -279,10 +282,12 @@ ~TCPSocketTest() override {} void Init(net::ClientSocketFactory* mock_client_socket_factory) { - url_request_context_.set_client_socket_factory(mock_client_socket_factory); - url_request_context_.Init(); + auto context_builder = net::CreateTestURLRequestContextBuilder(); + context_builder->set_client_socket_factory_for_testing( + mock_client_socket_factory); + url_request_context_ = context_builder->Build(); factory_ = std::make_unique<SocketFactory>(nullptr /*net_log*/, - &url_request_context_); + url_request_context_.get()); } void SetUp() override { Init(nullptr); } @@ -361,7 +366,7 @@ private: base::test::TaskEnvironment task_environment_; - net::TestURLRequestContext url_request_context_; + std::unique_ptr<net::URLRequestContext> url_request_context_; std::unique_ptr<SocketFactory> factory_; TestSocketObserver test_observer_; mojo::UniqueReceiverSet<mojom::TCPServerSocket> tcp_server_socket_receiver_;
diff --git a/services/network/test/test_shared_url_loader_factory.cc b/services/network/test/test_shared_url_loader_factory.cc index 88144d3..89edf6d 100644 --- a/services/network/test/test_shared_url_loader_factory.cc +++ b/services/network/test/test_shared_url_loader_factory.cc
@@ -5,6 +5,8 @@ #include "services/network/test/test_shared_url_loader_factory.h" #include "base/notreached.h" +#include "net/url_request/url_request_context.h" +#include "net/url_request/url_request_context_builder.h" #include "net/url_request/url_request_test_util.h" #include "services/network/network_context.h" #include "services/network/public/cpp/cross_thread_pending_shared_url_loader_factory.h" @@ -14,7 +16,8 @@ TestSharedURLLoaderFactory::TestSharedURLLoaderFactory( NetworkService* network_service, bool is_trusted) { - url_request_context_ = std::make_unique<net::TestURLRequestContext>(); + auto context_builder = net::CreateTestURLRequestContextBuilder(); + url_request_context_ = context_builder->Build(); mojo::Remote<mojom::NetworkContext> network_context; network_context_ = std::make_unique<NetworkContext>( network_service, network_context.BindNewPipeAndPassReceiver(),
diff --git a/services/network/test/test_shared_url_loader_factory.h b/services/network/test/test_shared_url_loader_factory.h index 062c520..b1255292 100644 --- a/services/network/test/test_shared_url_loader_factory.h +++ b/services/network/test/test_shared_url_loader_factory.h
@@ -11,7 +11,7 @@ #include "services/network/public/cpp/shared_url_loader_factory.h" namespace net { -class TestURLRequestContext; +class URLRequestContext; } namespace network { @@ -56,7 +56,7 @@ // Tracks the number of times |CreateLoaderAndStart()| has been called. int num_created_loaders_ = 0; - std::unique_ptr<net::TestURLRequestContext> url_request_context_; + std::unique_ptr<net::URLRequestContext> url_request_context_; std::unique_ptr<NetworkContext> network_context_; mojo::Remote<mojom::URLLoaderFactory> url_loader_factory_; };
diff --git a/services/network/tls_client_socket_unittest.cc b/services/network/tls_client_socket_unittest.cc index edbd69f..f1262d8 100644 --- a/services/network/tls_client_socket_unittest.cc +++ b/services/network/tls_client_socket_unittest.cc
@@ -27,6 +27,8 @@ #include "net/test/embedded_test_server/http_request.h" #include "net/test/embedded_test_server/http_response.h" #include "net/traffic_annotation/network_traffic_annotation_test_helper.h" +#include "net/url_request/url_request_context.h" +#include "net/url_request/url_request_context_builder.h" #include "net/url_request/url_request_test_util.h" #include "services/network/mojo_socket_test_util.h" #include "services/network/proxy_resolving_socket_factory_mojo.h" @@ -53,8 +55,7 @@ explicit TLSClientSocketTestBase(Mode mode) : mode_(mode), - task_environment_(base::test::TaskEnvironment::MainThreadType::IO), - url_request_context_(true) {} + task_environment_(base::test::TaskEnvironment::MainThreadType::IO) {} TLSClientSocketTestBase(const TLSClientSocketTestBase&) = delete; TLSClientSocketTestBase& operator=(const TLSClientSocketTestBase&) = delete; @@ -78,24 +79,23 @@ // Initializes the test fixture. If |use_mock_sockets|, mock client socket // factory will be used. void Init(bool use_mock_sockets, bool configure_proxy) { + auto context_builder = net::CreateTestURLRequestContextBuilder(); if (use_mock_sockets) { mock_client_socket_factory_.set_enable_read_if_ready(true); - url_request_context_.set_client_socket_factory( + context_builder->set_client_socket_factory_for_testing( &mock_client_socket_factory_); } if (configure_proxy) { - proxy_resolution_service_ = + context_builder->set_proxy_resolution_service( net::ConfiguredProxyResolutionService::CreateFixed( - "http://proxy:8080", TRAFFIC_ANNOTATION_FOR_TESTS); - url_request_context_.set_proxy_resolution_service( - proxy_resolution_service_.get()); + "http://proxy:8080", TRAFFIC_ANNOTATION_FOR_TESTS)); } - url_request_context_.Init(); - factory_ = std::make_unique<SocketFactory>(nullptr /*net_log*/, - &url_request_context_); + url_request_context_ = context_builder->Build(); + factory_ = std::make_unique<SocketFactory>(/*net_log=*/nullptr, + url_request_context_.get()); proxy_resolving_factory_ = std::make_unique<ProxyResolvingSocketFactoryMojo>( - &url_request_context_); + url_request_context_.get()); } // Reads |num_bytes| from |handle| or reads until an error occurs. Returns the @@ -305,9 +305,8 @@ // SSLInfo obtained from UpgradeToTLS. absl::optional<net::SSLInfo> ssl_info_; - std::unique_ptr<net::ProxyResolutionService> proxy_resolution_service_; - net::TestURLRequestContext url_request_context_; net::MockClientSocketFactory mock_client_socket_factory_; + std::unique_ptr<net::URLRequestContext> url_request_context_; std::unique_ptr<SocketFactory> factory_; std::unique_ptr<ProxyResolvingSocketFactoryMojo> proxy_resolving_factory_; TestSocketObserver pre_tls_observer_;
diff --git a/services/network/trust_tokens/test/trust_token_test_util.cc b/services/network/trust_tokens/test/trust_token_test_util.cc index cff86a00..ede6716 100644 --- a/services/network/trust_tokens/test/trust_token_test_util.cc +++ b/services/network/trust_tokens/test/trust_token_test_util.cc
@@ -9,20 +9,24 @@ #include "base/test/bind.h" #include "base/test/task_environment.h" #include "base/values.h" +#include "net/url_request/url_request_context.h" +#include "net/url_request/url_request_context_builder.h" namespace network { TestURLRequestMaker::TestURLRequestMaker() { - context_.set_net_log(net::NetLog::Get()); + auto context_builder = net::CreateTestURLRequestContextBuilder(); + context_builder->set_net_log(net::NetLog::Get()); + context_ = context_builder->Build(); } TestURLRequestMaker::~TestURLRequestMaker() = default; std::unique_ptr<net::URLRequest> TestURLRequestMaker::MakeURLRequest( base::StringPiece spec) { - return context_.CreateRequest(GURL(spec), - net::RequestPriority::DEFAULT_PRIORITY, - &delegate_, TRAFFIC_ANNOTATION_FOR_TESTS); + return context_->CreateRequest(GURL(spec), + net::RequestPriority::DEFAULT_PRIORITY, + &delegate_, TRAFFIC_ANNOTATION_FOR_TESTS); } TrustTokenRequestHelperTest::TrustTokenRequestHelperTest(
diff --git a/services/network/trust_tokens/test/trust_token_test_util.h b/services/network/trust_tokens/test/trust_token_test_util.h index cb696c4..2153a65 100644 --- a/services/network/trust_tokens/test/trust_token_test_util.h +++ b/services/network/trust_tokens/test/trust_token_test_util.h
@@ -22,6 +22,7 @@ namespace net { class URLRequest; +class URLRequestContext; } // namespace net namespace network { @@ -41,7 +42,7 @@ protected: net::TestDelegate delegate_; - net::TestURLRequestContext context_; + std::unique_ptr<net::URLRequestContext> context_; }; // TrustTokenRequestHelperTest is a fixture common to tests for Trust Tokens
diff --git a/services/network/trust_tokens/trust_token_key_commitment_controller_unittest.cc b/services/network/trust_tokens/trust_token_key_commitment_controller_unittest.cc index 4d69758..209abbd 100644 --- a/services/network/trust_tokens/trust_token_key_commitment_controller_unittest.cc +++ b/services/network/trust_tokens/trust_token_key_commitment_controller_unittest.cc
@@ -15,6 +15,8 @@ #include "net/http/http_request_headers.h" #include "net/traffic_annotation/network_traffic_annotation_test_helper.h" #include "net/url_request/url_request.h" +#include "net/url_request/url_request_context.h" +#include "net/url_request/url_request_context_builder.h" #include "net/url_request/url_request_test_util.h" #include "services/network/public/cpp/url_loader_completion_status.h" #include "services/network/public/mojom/trust_tokens.mojom-forward.h" @@ -104,19 +106,20 @@ class TrustTokenKeyCommitmentControllerTest : public ::testing::Test { public: TrustTokenKeyCommitmentControllerTest() - : issuer_request_(MakeURLRequest("https://issuer.com/")) {} + : context_(net::CreateTestURLRequestContextBuilder()->Build()), + issuer_request_(MakeURLRequest("https://issuer.com/")) {} ~TrustTokenKeyCommitmentControllerTest() override = default; protected: std::unique_ptr<net::URLRequest> MakeURLRequest(std::string spec) { - return context_.CreateRequest(GURL(spec), - net::RequestPriority::DEFAULT_PRIORITY, - &delegate_, TRAFFIC_ANNOTATION_FOR_TESTS); + return context_->CreateRequest(GURL(spec), + net::RequestPriority::DEFAULT_PRIORITY, + &delegate_, TRAFFIC_ANNOTATION_FOR_TESTS); } const net::URLRequest& IssuerURLRequest() { return *issuer_request_; } base::test::TaskEnvironment env_; net::TestDelegate delegate_; - net::TestURLRequestContext context_; + std::unique_ptr<net::URLRequestContext> context_; std::unique_ptr<net::URLRequest> issuer_request_; };
diff --git a/services/network/udp_socket_unittest.cc b/services/network/udp_socket_unittest.cc index c9b28d53..32b2a2ff 100644 --- a/services/network/udp_socket_unittest.cc +++ b/services/network/udp_socket_unittest.cc
@@ -22,6 +22,8 @@ #include "net/socket/udp_socket.h" #include "net/traffic_annotation/network_traffic_annotation.h" #include "net/traffic_annotation/network_traffic_annotation_test_helper.h" +#include "net/url_request/url_request_context.h" +#include "net/url_request/url_request_context_builder.h" #include "net/url_request/url_request_test_util.h" #include "services/network/public/mojom/udp_socket.mojom.h" #include "services/network/socket_factory.h" @@ -192,7 +194,9 @@ public: UDPSocketTest() : task_environment_(base::test::TaskEnvironment::MainThreadType::IO), - factory_(nullptr /*netlog*/, &url_request_context_) {} + url_request_context_( + net::CreateTestURLRequestContextBuilder()->Build()), + factory_(nullptr /*netlog*/, url_request_context_.get()) {} UDPSocketTest(const UDPSocketTest&) = delete; UDPSocketTest& operator=(const UDPSocketTest&) = delete; @@ -213,7 +217,7 @@ private: base::test::TaskEnvironment task_environment_; - net::TestURLRequestContext url_request_context_; + std::unique_ptr<net::URLRequestContext> url_request_context_; SocketFactory factory_; };
diff --git a/services/network/web_transport_unittest.cc b/services/network/web_transport_unittest.cc index a521642..7d07726 100644 --- a/services/network/web_transport_unittest.cc +++ b/services/network/web_transport_unittest.cc
@@ -14,11 +14,13 @@ #include "base/test/bind.h" #include "base/test/task_environment.h" #include "net/cert/mock_cert_verifier.h" +#include "net/cert/pem.h" #include "net/dns/mock_host_resolver.h" #include "net/log/test_net_log.h" #include "net/quic/crypto/proof_source_chromium.h" #include "net/quic/quic_context.h" #include "net/test/test_data_directory.h" +#include "net/third_party/quiche/src/quic/core/crypto/proof_source_x509.h" #include "net/third_party/quiche/src/quic/test_tools/crypto_test_utils.h" #include "net/third_party/quiche/src/quic/test_tools/quic_test_backend.h" #include "net/tools/quic/quic_simple_server.h" @@ -660,11 +662,35 @@ static std::unique_ptr<quic::ProofSource> CreateProofSource() { auto proof_source = std::make_unique<net::ProofSourceChromium>(); base::FilePath certs_dir = net::GetTestCertsDirectory(); - EXPECT_TRUE(proof_source->Initialize( - certs_dir.AppendASCII("quic-short-lived.pem"), - certs_dir.AppendASCII("quic-leaf-cert.key"), - certs_dir.AppendASCII("quic-leaf-cert.key.sct"))); - return proof_source; + base::FilePath cert_path = certs_dir.AppendASCII("quic-short-lived.pem"); + base::FilePath key_path = certs_dir.AppendASCII("quic-ecdsa-leaf.key"); + + std::string cert_pem, key_raw; + if (!base::ReadFileToString(cert_path, &cert_pem)) { + ADD_FAILURE() << "Failed to load the certificate from " << cert_path; + return nullptr; + } + if (!base::ReadFileToString(key_path, &key_raw)) { + ADD_FAILURE() << "Failed to load the private key from " << key_path; + return nullptr; + } + + net::PEMTokenizer pem_tokenizer(cert_pem, {"CERTIFICATE"}); + if (!pem_tokenizer.GetNext()) { + ADD_FAILURE() << "No certificates found in " << cert_path; + return nullptr; + } + auto chain = quic::QuicReferenceCountedPointer<quic::ProofSource::Chain>( + new quic::ProofSource::Chain( + std::vector<std::string>{pem_tokenizer.data()})); + std::unique_ptr<quic::CertificatePrivateKey> key = + quic::CertificatePrivateKey::LoadFromDer(key_raw); + if (!key) { + ADD_FAILURE() << "Failed to parse the key file " << key_path; + return nullptr; + } + + return quic::ProofSourceX509::Create(std::move(chain), std::move(*key)); } }; @@ -677,8 +703,8 @@ auto fingerprint = mojom::WebTransportCertificateFingerprint::New( "sha-256", - "ED:3D:D7:C3:67:10:94:68:D1:DC:D1:26:5C:B2:74:D7:1C:" - "A2:63:3E:94:94:C0:84:39:D6:64:FA:08:B9:77:37"); + "6E:8E:7B:43:2A:30:B2:A8:5F:59:56:85:64:C2:48:E9:35:" + "CB:63:B0:7A:E9:F5:CA:3C:35:6F:CB:CC:E8:8D:1B"); std::vector<mojom::WebTransportCertificateFingerprintPtr> fingerprints; fingerprints.push_back(std::move(fingerprint));
diff --git a/testing/buildbot/chromium.angle.json b/testing/buildbot/chromium.angle.json index 14a87e20..8db99d5 100644 --- a/testing/buildbot/chromium.angle.json +++ b/testing/buildbot/chromium.angle.json
@@ -1485,7 +1485,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -1512,7 +1512,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -1556,7 +1556,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -1596,7 +1596,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -1637,7 +1637,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -1677,7 +1677,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -1717,7 +1717,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -1757,7 +1757,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ],
diff --git a/testing/buildbot/chromium.clang.json b/testing/buildbot/chromium.clang.json index eca3fe0..153c4830 100644 --- a/testing/buildbot/chromium.clang.json +++ b/testing/buildbot/chromium.clang.json
@@ -9489,9 +9489,6 @@ "test_id_prefix": "ninja://ipc:ipc_tests/" }, { - "args": [ - "--test-launcher-filter-file=../../testing/buildbot/filters/fuchsia.jingle_unittests.filter" - ], "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -11099,9 +11096,6 @@ "test_id_prefix": "ninja://ipc:ipc_tests/" }, { - "args": [ - "--test-launcher-filter-file=../../testing/buildbot/filters/fuchsia.jingle_unittests.filter" - ], "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py"
diff --git a/testing/buildbot/chromium.dawn.json b/testing/buildbot/chromium.dawn.json index 442be649..54cb731 100644 --- a/testing/buildbot/chromium.dawn.json +++ b/testing/buildbot/chromium.dawn.json
@@ -1041,7 +1041,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -1070,7 +1070,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -1099,7 +1099,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -1128,7 +1128,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -1156,7 +1156,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -1182,7 +1182,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -1215,7 +1215,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -1248,7 +1248,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -1283,7 +1283,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -1885,7 +1885,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -1914,7 +1914,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -1943,7 +1943,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -1972,7 +1972,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -2000,7 +2000,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -2026,7 +2026,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -2059,7 +2059,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -2092,7 +2092,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -2127,7 +2127,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ],
diff --git a/testing/buildbot/chromium.fyi.json b/testing/buildbot/chromium.fyi.json index 9cadf1d..fbadc2c 100644 --- a/testing/buildbot/chromium.fyi.json +++ b/testing/buildbot/chromium.fyi.json
@@ -18922,7 +18922,6 @@ }, { "args": [ - "--test-launcher-filter-file=../../testing/buildbot/filters/fuchsia.jingle_unittests.filter", "--ram-size-mb=16384", "--code-coverage", "--code-coverage-dir=${ISOLATED_OUTDIR}" @@ -20111,9 +20110,6 @@ "test_id_prefix": "ninja://ipc:ipc_tests/" }, { - "args": [ - "--test-launcher-filter-file=../../testing/buildbot/filters/fuchsia.jingle_unittests.filter" - ], "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -21351,7 +21347,6 @@ }, { "args": [ - "--test-launcher-filter-file=../../testing/buildbot/filters/fuchsia.jingle_unittests.filter", "--device=aemu" ], "merge": { @@ -22741,9 +22736,6 @@ "test_id_prefix": "ninja://ipc:ipc_tests/" }, { - "args": [ - "--test-launcher-filter-file=../../testing/buildbot/filters/fuchsia.jingle_unittests.filter" - ], "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -24034,9 +24026,6 @@ "test_id_prefix": "ninja://ipc:ipc_tests/" }, { - "args": [ - "--test-launcher-filter-file=../../testing/buildbot/filters/fuchsia.jingle_unittests.filter" - ], "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -83798,6 +83787,36 @@ "test_id_prefix": "ninja://tools/grit:grit_python_unittests/" }, { + "args": [ + "--flag-specific=highdpi", + "--num-retries=3" + ], + "isolate_name": "blink_web_tests", + "isolate_profile_data": true, + "merge": { + "args": [ + "--verbose" + ], + "script": "//third_party/blink/tools/merge_web_test_results.py" + }, + "name": "high_dpi_blink_web_tests", + "resultdb": { + "enable": true + }, + "results_handler": "layout tests", + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", + "shards": 12 + }, + "test_id_prefix": "ninja://:blink_web_tests/" + }, + { "isolate_name": "mojo_python_unittests", "isolate_profile_data": true, "merge": {
diff --git a/testing/buildbot/chromium.gpu.fyi.json b/testing/buildbot/chromium.gpu.fyi.json index 9a3b1468e73..78338df 100644 --- a/testing/buildbot/chromium.gpu.fyi.json +++ b/testing/buildbot/chromium.gpu.fyi.json
@@ -16849,7 +16849,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -16880,7 +16880,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -16909,7 +16909,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -16938,7 +16938,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -16964,7 +16964,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -16990,7 +16990,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -17013,7 +17013,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -17040,7 +17040,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -17063,7 +17063,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -17104,7 +17104,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -17143,7 +17143,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -17181,7 +17181,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -17219,7 +17219,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -17257,7 +17257,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -17299,7 +17299,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -17346,7 +17346,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -17393,7 +17393,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -17431,7 +17431,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -17469,7 +17469,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -17516,7 +17516,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -17563,7 +17563,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -17602,7 +17602,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -17641,7 +17641,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -17679,7 +17679,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -17720,7 +17720,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -17762,7 +17762,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -17803,7 +17803,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -17844,7 +17844,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -17884,7 +17884,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -17915,7 +17915,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -17945,7 +17945,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -17974,7 +17974,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -18000,7 +18000,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -18026,7 +18026,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -18049,7 +18049,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -18076,7 +18076,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -18099,7 +18099,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -18139,7 +18139,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -18177,7 +18177,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -18215,7 +18215,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -18253,7 +18253,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -18291,7 +18291,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -18333,7 +18333,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -18380,7 +18380,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -18427,7 +18427,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -18474,7 +18474,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -18521,7 +18521,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -18560,7 +18560,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -18599,7 +18599,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -18637,7 +18637,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -18676,7 +18676,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -18716,7 +18716,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -19328,7 +19328,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -19359,7 +19359,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -19388,7 +19388,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -19417,7 +19417,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -19443,7 +19443,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -19469,7 +19469,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -19492,7 +19492,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -19519,7 +19519,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -19542,7 +19542,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -19582,7 +19582,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -19620,7 +19620,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -19658,7 +19658,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -19696,7 +19696,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -19734,7 +19734,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -19776,7 +19776,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -19823,7 +19823,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -19870,7 +19870,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -19908,7 +19908,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -19946,7 +19946,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -19993,7 +19993,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -20040,7 +20040,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -20069,7 +20069,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -20107,7 +20107,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -20146,7 +20146,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -20184,7 +20184,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -20224,7 +20224,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -20265,7 +20265,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -20306,7 +20306,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -20346,7 +20346,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -20386,7 +20386,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -20426,7 +20426,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -20465,7 +20465,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -24545,7 +24545,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -24568,7 +24568,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -24595,7 +24595,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -24618,7 +24618,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -24658,7 +24658,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -24696,7 +24696,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -24734,7 +24734,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -24772,7 +24772,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -24814,7 +24814,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -24861,7 +24861,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -24899,7 +24899,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -24946,7 +24946,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -24985,7 +24985,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -25023,7 +25023,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -25057,7 +25057,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -25097,7 +25097,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -25137,7 +25137,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -25177,7 +25177,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -25217,7 +25217,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ],
diff --git a/testing/buildbot/chromium.gpu.json b/testing/buildbot/chromium.gpu.json index 45f5b33..3c2a79cc 100644 --- a/testing/buildbot/chromium.gpu.json +++ b/testing/buildbot/chromium.gpu.json
@@ -2546,7 +2546,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -2576,7 +2576,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -2603,7 +2603,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -2643,7 +2643,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -2681,7 +2681,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -2719,7 +2719,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -2757,7 +2757,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -2799,7 +2799,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -2846,7 +2846,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -2893,7 +2893,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -2932,7 +2932,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -2970,7 +2970,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -3009,7 +3009,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -3040,7 +3040,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -3071,7 +3071,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -3100,7 +3100,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -3127,7 +3127,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -3167,7 +3167,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -3205,7 +3205,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -3243,7 +3243,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -3281,7 +3281,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -3323,7 +3323,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -3370,7 +3370,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -3417,7 +3417,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -3447,7 +3447,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -3485,7 +3485,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -3523,7 +3523,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ], @@ -3562,7 +3562,7 @@ "display_attached": "1", "gpu": "1002:6821", "hidpi": "1", - "os": "Mac-11.4", + "os": "Mac-11.4|Mac-12.1", "pool": "chromium.tests.gpu" } ],
diff --git a/testing/buildbot/chromium.linux.json b/testing/buildbot/chromium.linux.json index c79f873..7e2ae66 100644 --- a/testing/buildbot/chromium.linux.json +++ b/testing/buildbot/chromium.linux.json
@@ -2466,9 +2466,6 @@ "test_id_prefix": "ninja://ipc:ipc_tests/" }, { - "args": [ - "--test-launcher-filter-file=../../testing/buildbot/filters/fuchsia.jingle_unittests.filter" - ], "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -3719,9 +3716,6 @@ "test_id_prefix": "ninja://ipc:ipc_tests/" }, { - "args": [ - "--test-launcher-filter-file=../../testing/buildbot/filters/fuchsia.jingle_unittests.filter" - ], "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -6274,6 +6268,37 @@ "test_id_prefix": "ninja://tools/grit:grit_python_unittests/" }, { + "args": [ + "--flag-specific=highdpi", + "--num-retries=3" + ], + "experiment_percentage": 100, + "isolate_name": "blink_web_tests", + "isolate_profile_data": true, + "merge": { + "args": [ + "--verbose" + ], + "script": "//third_party/blink/tools/merge_web_test_results.py" + }, + "name": "high_dpi_blink_web_tests", + "resultdb": { + "enable": true + }, + "results_handler": "layout tests", + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", + "shards": 12 + }, + "test_id_prefix": "ninja://:blink_web_tests/" + }, + { "isolate_name": "mojo_python_unittests", "isolate_profile_data": true, "merge": { @@ -12034,6 +12059,35 @@ "test_id_prefix": "ninja://tools/grit:grit_python_unittests/" }, { + "args": [ + "--flag-specific=highdpi", + "--num-retries=3" + ], + "isolate_name": "blink_web_tests", + "merge": { + "args": [ + "--verbose" + ], + "script": "//third_party/blink/tools/merge_web_test_results.py" + }, + "name": "high_dpi_blink_web_tests", + "resultdb": { + "enable": true + }, + "results_handler": "layout tests", + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", + "shards": 12 + }, + "test_id_prefix": "ninja://:blink_web_tests/" + }, + { "isolate_name": "mojo_python_unittests", "merge": { "args": [], @@ -13993,6 +14047,35 @@ "test_id_prefix": "ninja://tools/grit:grit_python_unittests/" }, { + "args": [ + "--flag-specific=highdpi", + "--num-retries=3" + ], + "isolate_name": "blink_web_tests", + "merge": { + "args": [ + "--verbose" + ], + "script": "//third_party/blink/tools/merge_web_test_results.py" + }, + "name": "high_dpi_blink_web_tests", + "resultdb": { + "enable": true + }, + "results_handler": "layout tests", + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-14.04" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", + "shards": 12 + }, + "test_id_prefix": "ninja://:blink_web_tests/" + }, + { "isolate_name": "mojo_python_unittests", "merge": { "args": [], @@ -15940,6 +16023,35 @@ "test_id_prefix": "ninja://tools/grit:grit_python_unittests/" }, { + "args": [ + "--flag-specific=highdpi", + "--num-retries=3" + ], + "isolate_name": "blink_web_tests", + "merge": { + "args": [ + "--verbose" + ], + "script": "//third_party/blink/tools/merge_web_test_results.py" + }, + "name": "high_dpi_blink_web_tests", + "resultdb": { + "enable": true + }, + "results_handler": "layout tests", + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-16.04" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", + "shards": 12 + }, + "test_id_prefix": "ninja://:blink_web_tests/" + }, + { "isolate_name": "mojo_python_unittests", "merge": { "args": [],
diff --git a/testing/buildbot/filters/BUILD.gn b/testing/buildbot/filters/BUILD.gn index 035c7c6..895f0d2a 100644 --- a/testing/buildbot/filters/BUILD.gn +++ b/testing/buildbot/filters/BUILD.gn
@@ -188,7 +188,6 @@ "//testing/buildbot/filters/fuchsia.debug.snapshot_unittests.filter", "//testing/buildbot/filters/fuchsia.debug.views_unittests.filter", "//testing/buildbot/filters/fuchsia.headless_browsertests.filter", - "//testing/buildbot/filters/fuchsia.jingle_unittests.filter", "//testing/buildbot/filters/fuchsia.net_perftests.filter", "//testing/buildbot/filters/fuchsia.services_unittests.filter", "//testing/buildbot/filters/fuchsia.storage_unittests.filter",
diff --git a/testing/buildbot/filters/fuchsia.jingle_unittests.filter b/testing/buildbot/filters/fuchsia.jingle_unittests.filter deleted file mode 100644 index 0368d91..0000000 --- a/testing/buildbot/filters/fuchsia.jingle_unittests.filter +++ /dev/null
@@ -1,2 +0,0 @@ -# https://crbug.com/1241660 --LibjingleLogTest.*
diff --git a/testing/buildbot/mixins.pyl b/testing/buildbot/mixins.pyl index a59909d..24fa19aa 100644 --- a/testing/buildbot/mixins.pyl +++ b/testing/buildbot/mixins.pyl
@@ -781,7 +781,7 @@ 'cpu': 'x86-64', 'gpu': '1002:6821', 'hidpi': '1', - 'os': 'Mac-11.4', + 'os': 'Mac-11.4|Mac-12.1', 'pool': 'chromium.tests.gpu', 'display_attached': '1', },
diff --git a/testing/buildbot/test_suite_exceptions.pyl b/testing/buildbot/test_suite_exceptions.pyl index 145db610..81be100 100644 --- a/testing/buildbot/test_suite_exceptions.pyl +++ b/testing/buildbot/test_suite_exceptions.pyl
@@ -1792,6 +1792,13 @@ }, }, }, + 'high_dpi_blink_web_tests': { + 'modifications': { + 'Linux Tests': { + 'experiment_percentage': 100, + }, + }, + }, 'info_collection_tests': { 'remove_from': [ 'Android V8 FYI Release (Nexus 5X)',
diff --git a/testing/buildbot/test_suites.pyl b/testing/buildbot/test_suites.pyl index 250d2d4..68aa86b4 100644 --- a/testing/buildbot/test_suites.pyl +++ b/testing/buildbot/test_suites.pyl
@@ -1270,8 +1270,6 @@ 'swarming': { 'shards': 12, }, - # Experimental until tests are rebaselined. - # 'experiment_percentage': 100, }, }, @@ -1700,11 +1698,7 @@ ], }, 'ipc_tests': {}, - 'jingle_unittests': { - 'args': [ - '--test-launcher-filter-file=../../testing/buildbot/filters/fuchsia.jingle_unittests.filter', - ], - }, + 'jingle_unittests': {}, 'latency_unittests': {}, 'media_unittests': {}, 'midi_unittests': {}, @@ -6145,6 +6139,7 @@ 'mojo_python_unittests_isolated_scripts', 'telemetry_perf_unittests_isolated_scripts', 'vulkan_swiftshader_isolated_scripts', + 'chromium_web_tests_high_dpi_isolated_scripts', ], 'chromium_mac_gtests': [
diff --git a/testing/variations/fieldtrial_testing_config.json b/testing/variations/fieldtrial_testing_config.json index 73f9719..4560dcc 100644 --- a/testing/variations/fieldtrial_testing_config.json +++ b/testing/variations/fieldtrial_testing_config.json
@@ -951,6 +951,21 @@ ] } ], + "AsyncFontAccess": [ + { + "platforms": [ + "windows" + ], + "experiments": [ + { + "name": "AsyncFontAccess", + "enable_features": [ + "AsyncFontAccess" + ] + } + ] + } + ], "AudioServiceSandboxLinux": [ { "platforms": [ @@ -4422,6 +4437,21 @@ ] } ], + "IOSNewOverflowMenu": [ + { + "platforms": [ + "ios" + ], + "experiments": [ + { + "name": "Enabled", + "enable_features": [ + "NewOverflowMenu" + ] + } + ] + } + ], "IOSRestoreSessionFromCache": [ { "platforms": [ @@ -4932,7 +4962,11 @@ ], "experiments": [ { - "name": "Enable_14s_20220104", + "name": "Enable_14s_20220118", + "params": { + "DefaultPresentationMessagesDurationFeatureParam": "14", + "LongPresentationMessagesDurationFeatureParam": "14" + }, "enable_features": [ "EnableLongMessageDuration" ] @@ -5533,8 +5567,7 @@ "OmniboxPreserveLongerShortcutsText", "OmniboxRemoveSuggestionsFromClipboard", "OmniboxRichAutocompletion", - "OmniboxUIExperimentMaxAutocompleteMatches", - "SearchSuggestChips" + "OmniboxUIExperimentMaxAutocompleteMatches" ], "disable_features": [ "OmniboxShortBookmarkSuggestionsByTotalInputLength" @@ -6205,6 +6238,9 @@ "experiments": [ { "name": "Enabled", + "params": { + "use_basic_close_label": "true" + }, "enable_features": [ "PasswordChange" ] @@ -7197,24 +7233,6 @@ ] } ], - "SearchRankerQueryBasedMixedTypes": [ - { - "platforms": [ - "chromeos" - ], - "experiments": [ - { - "name": "Enabled", - "params": { - "use_aggregated_model": "true" - }, - "enable_features": [ - "EnableQueryBasedMixedTypesRanker" - ] - } - ] - } - ], "SendAllUserInteractionLatencies": [ { "platforms": [
diff --git a/third_party/blink/public/BUILD.gn b/third_party/blink/public/BUILD.gn index 2b3f9f6..68d9510 100644 --- a/third_party/blink/public/BUILD.gn +++ b/third_party/blink/public/BUILD.gn
@@ -198,7 +198,6 @@ "platform/web_dedicated_worker_host_factory_client.h", "platform/web_distillability.h", "platform/web_document_subresource_filter.h", - "platform/web_double_size.h", "platform/web_drag_data.h", "platform/web_effective_connection_type.h", "platform/web_encrypted_media_client.h",
diff --git a/third_party/blink/public/mojom/BUILD.gn b/third_party/blink/public/mojom/BUILD.gn index a340467a6..5c7b09ef 100644 --- a/third_party/blink/public/mojom/BUILD.gn +++ b/third_party/blink/public/mojom/BUILD.gn
@@ -189,7 +189,7 @@ "speech/speech_synthesis.mojom", "storage_access/storage_access_automation.mojom", "storage_key/storage_key.mojom", - "subapps/sub_apps_provider.mojom", + "subapps/sub_apps_service.mojom", "timing/performance_mark_or_measure.mojom", "timing/resource_timing.mojom", "timing/worker_timing_container.mojom",
diff --git a/third_party/blink/public/mojom/interest_group/interest_group_types.mojom b/third_party/blink/public/mojom/interest_group/interest_group_types.mojom index e76fce09..8fd8410 100644 --- a/third_party/blink/public/mojom/interest_group/interest_group_types.mojom +++ b/third_party/blink/public/mojom/interest_group/interest_group_types.mojom
@@ -60,10 +60,11 @@ AllBuyers all_buyers; }; -// Subset of AuctionAdConfig that can be handled by the same loaded -// SellerWorklet when the other parameters (seller, script and signals URLs, -// and top window origin) are all exactly the same. -struct ShareableAuctionAdConfig { +// Subset of AuctionAdConfig that is not shared by all auctions that are +// using the same SellerWorklet object (so it's "not shared" between +// AuctionConfigs that share the same SellerWorklet). Other AuctionAdConfig +// parameters all must be the same for two auctions to share a Sellerworklet. +struct AuctionAdConfigNonSharedParams { // Owners of interest groups allowed to participate in the auction. blink.mojom.InterestGroupBuyers? interest_group_buyers; @@ -104,5 +105,5 @@ url.mojom.Url? trusted_scoring_signals_url; // Other parameters are grouped in a struct that is passed to SellerWorklets. - ShareableAuctionAdConfig shareable_auction_ad_config; + AuctionAdConfigNonSharedParams auction_ad_config_non_shared_params; };
diff --git a/third_party/blink/public/mojom/subapps/sub_apps_provider.mojom b/third_party/blink/public/mojom/subapps/sub_apps_service.mojom similarity index 82% rename from third_party/blink/public/mojom/subapps/sub_apps_provider.mojom rename to third_party/blink/public/mojom/subapps/sub_apps_service.mojom index 385ead6..e8f9ce3 100644 --- a/third_party/blink/public/mojom/subapps/sub_apps_provider.mojom +++ b/third_party/blink/public/mojom/subapps/sub_apps_service.mojom
@@ -4,7 +4,7 @@ module blink.mojom; -enum SubAppsProviderResult { +enum SubAppsServiceResult { kSuccess, kFailure, }; @@ -17,10 +17,10 @@ // NOTE: This Mojo interface is per-frame, there is one logical instance per // frame, and it's main-frame only. It is only valid for already-installed apps, // and has an origin associated with it. -interface SubAppsProvider { +interface SubAppsService { // Installs a sub-app of an already-installed app corresponding to this - // instance of SubAppsProvider. `install_path` is the absolute path which will + // instance of SubAppsService. `install_path` is the absolute path which will // be attached to the origin of the already-installed app (effectively // limiting the API to same-origin apps). - Add(string install_path) => (SubAppsProviderResult result); + Add(string install_path) => (SubAppsServiceResult result); };
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 89ee227b..336aa37 100644 --- a/third_party/blink/public/mojom/web_feature/web_feature.mojom +++ b/third_party/blink/public/mojom/web_feature/web_feature.mojom
@@ -3430,6 +3430,7 @@ kWebAppManifestHandleLinks = 4109, kHTMLParamElementURLParameterInUsePdf = 4110, kHTMLParamElementURLParameterInUseNonPdf = 4111, + kWebTransportServerCertificateHashes = 4112, // 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/public/platform/web_double_size.h b/third_party/blink/public/platform/web_double_size.h deleted file mode 100644 index 6a75155..0000000 --- a/third_party/blink/public/platform/web_double_size.h +++ /dev/null
@@ -1,76 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef THIRD_PARTY_BLINK_PUBLIC_PLATFORM_WEB_DOUBLE_SIZE_H_ -#define THIRD_PARTY_BLINK_PUBLIC_PLATFORM_WEB_DOUBLE_SIZE_H_ - -#include "third_party/blink/public/platform/web_common.h" - -#if INSIDE_BLINK -#include "third_party/blink/renderer/platform/geometry/double_size.h" // nogncheck -#else -#include "ui/gfx/geometry/size_f.h" -#include "ui/gfx/geometry/vector2d_f.h" -#endif - -namespace blink { - -class WebDoubleSize { - public: - bool IsEmpty() const { return width_ <= 0 || height_ <= 0; } - - WebDoubleSize() : width_(0), height_(0) {} - - WebDoubleSize(double width, double height) : width_(width), height_(height) {} - -#if INSIDE_BLINK - WebDoubleSize(const DoubleSize& size) - : width_(size.Width()), height_(size.Height()) {} - - WebDoubleSize& operator=(const DoubleSize& size) { - width_ = size.Width(); - height_ = size.Height(); - return *this; - } - - operator DoubleSize() const { return DoubleSize(width_, height_); } -#else - WebDoubleSize(const gfx::SizeF& size) - : width_(size.width()), height_(size.height()) {} - - WebDoubleSize(const gfx::Vector2dF& vector) - : width_(vector.x()), height_(vector.y()) {} - - WebDoubleSize& operator=(const gfx::SizeF& size) { - width_ = size.width(); - height_ = size.height(); - return *this; - } - - WebDoubleSize& operator=(const gfx::Vector2dF& vector) { - width_ = vector.x(); - height_ = vector.y(); - return *this; - } -#endif - - double Width() const { return width_; } - double Height() const { return height_; } - - private: - double width_; - double height_; -}; - -inline bool operator==(const WebDoubleSize& a, const WebDoubleSize& b) { - return a.Width() == b.Width() && a.Height() == b.Height(); -} - -inline bool operator!=(const WebDoubleSize& a, const WebDoubleSize& b) { - return !(a == b); -} - -} // namespace blink - -#endif // THIRD_PARTY_BLINK_PUBLIC_PLATFORM_WEB_DOUBLE_SIZE_H_
diff --git a/third_party/blink/public/web/web_print_page_description.h b/third_party/blink/public/web/web_print_page_description.h index 5b8b0c50..72061e4 100644 --- a/third_party/blink/public/web/web_print_page_description.h +++ b/third_party/blink/public/web/web_print_page_description.h
@@ -6,13 +6,13 @@ #define THIRD_PARTY_BLINK_PUBLIC_WEB_WEB_PRINT_PAGE_DESCRIPTION_H_ #include "third_party/blink/public/common/css/page_orientation.h" -#include "third_party/blink/public/platform/web_double_size.h" +#include "ui/gfx/geometry/size_f.h" namespace blink { // Description of a specific page when printing. All sizes are in pixels. struct WebPrintPageDescription { - WebDoubleSize size; + gfx::SizeF size; int margin_top = 0; int margin_right = 0; int margin_bottom = 0;
diff --git a/third_party/blink/renderer/build/scripts/templates/internal_settings_generated.h.tmpl b/third_party/blink/renderer/build/scripts/templates/internal_settings_generated.h.tmpl index 90e41fb..b010c776 100644 --- a/third_party/blink/renderer/build/scripts/templates/internal_settings_generated.h.tmpl +++ b/third_party/blink/renderer/build/scripts/templates/internal_settings_generated.h.tmpl
@@ -8,7 +8,8 @@ #include "base/memory/scoped_refptr.h" #include "third_party/blink/renderer/platform/bindings/script_wrappable.h" -#include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" #include "third_party/blink/renderer/platform/wtf/ref_counted.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
diff --git a/third_party/blink/renderer/core/animation/animation_test.cc b/third_party/blink/renderer/core/animation/animation_test.cc index c0ebe02..03d15a9 100644 --- a/third_party/blink/renderer/core/animation/animation_test.cc +++ b/third_party/blink/renderer/core/animation/animation_test.cc
@@ -2299,7 +2299,7 @@ CompositorAnimations::kTimelineSourceHasInvalidCompositingState); } -#if defined(OS_MAC) && defined(ARCH_CPU_ARM64) +#if BUILDFLAG(IS_MAC) && defined(ARCH_CPU_ARM64) // https://crbug.com/1222646 #define MAYBE_ContentVisibleDisplayLockTest \ DISABLED_ContentVisibleDisplayLockTest
diff --git a/third_party/blink/renderer/core/clipboard/clipboard_utilities.h b/third_party/blink/renderer/core/clipboard/clipboard_utilities.h index 0268306..c4adbe0f 100644 --- a/third_party/blink/renderer/core/clipboard/clipboard_utilities.h +++ b/third_party/blink/renderer/core/clipboard/clipboard_utilities.h
@@ -40,7 +40,7 @@ namespace blink { -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) CORE_EXPORT void ReplaceNewlinesWithWindowsStyleNewlines(String&); #endif CORE_EXPORT void ReplaceNBSPWithSpace(String&);
diff --git a/third_party/blink/renderer/core/clipboard/data_transfer.cc b/third_party/blink/renderer/core/clipboard/data_transfer.cc index 1c0d9f2..ed0b10b 100644 --- a/third_party/blink/renderer/core/clipboard/data_transfer.cc +++ b/third_party/blink/renderer/core/clipboard/data_transfer.cc
@@ -521,7 +521,7 @@ } String str = selection.SelectedTextForClipboard(); -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) ReplaceNewlinesWithWindowsStyleNewlines(str); #endif ReplaceNBSPWithSpace(str);
diff --git a/third_party/blink/renderer/core/clipboard/system_clipboard.cc b/third_party/blink/renderer/core/clipboard/system_clipboard.cc index 8b3f0a5..db71d2a3 100644 --- a/third_party/blink/renderer/core/clipboard/system_clipboard.cc +++ b/third_party/blink/renderer/core/clipboard/system_clipboard.cc
@@ -119,7 +119,7 @@ // TODO(https://crbug.com/106449): add support for smart replace, which is // currently under-specified. String text = plain_text; -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) ReplaceNewlinesWithWindowsStyleNewlines(text); #endif if (clipboard_.is_bound()) @@ -212,7 +212,7 @@ } if (url.IsValid() && !url.IsEmpty()) { -#if !defined(OS_MAC) +#if !BUILDFLAG(IS_MAC) // See http://crbug.com/838808: Not writing text/plain on Mac for // consistency between platforms, and to help fix errors in applications // which prefer text/plain content over image content for compatibility with @@ -287,7 +287,7 @@ } void SystemClipboard::CopyToFindPboard(const String& text) { -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) if (clipboard_.is_bound()) clipboard_->WriteStringToFindPboard(text); #endif
diff --git a/third_party/blink/renderer/core/css/css_font_family_webkit_prefix_test.cc b/third_party/blink/renderer/core/css/css_font_family_webkit_prefix_test.cc index 438d7e8..7dd1574 100644 --- a/third_party/blink/renderer/core/css/css_font_family_webkit_prefix_test.cc +++ b/third_party/blink/renderer/core/css/css_font_family_webkit_prefix_test.cc
@@ -11,7 +11,7 @@ #include "third_party/blink/renderer/platform/font_family_names.h" #include "third_party/blink/renderer/platform/testing/unit_test_helpers.h" -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) #include "third_party/blink/public/web/win/web_font_rendering.h" #endif @@ -49,7 +49,7 @@ void SetUp() override { SimTest::SetUp(); m_standard_font = GetGenericGenericFontFamilySettings().Standard(); -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) // An extra step is required to ensure that the system font is configured. // TODO(crbug.com/969622): Remove this. blink::WebFontRendering::SetMenuFontMetrics( @@ -129,7 +129,7 @@ // Counter should be triggered on macOS, even if -apple-system is placed // before or -system-ui is place after. LoadPageWithFontFamilyValue("-apple-system, BlinkMacSystemFont, system-ui"); -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) ASSERT_TRUE(GetDocument().IsUseCounted(WebFeature::kBlinkMacSystemFont)); #else ASSERT_FALSE(GetDocument().IsUseCounted(WebFeature::kBlinkMacSystemFont));
diff --git a/third_party/blink/renderer/core/css/css_math_expression_node.cc b/third_party/blink/renderer/core/css/css_math_expression_node.cc index 47b6d6e..20a8fb3 100644 --- a/third_party/blink/renderer/core/css/css_math_expression_node.cc +++ b/third_party/blink/renderer/core/css/css_math_expression_node.cc
@@ -241,7 +241,7 @@ scoped_refptr<const CalculationExpressionNode> CSSMathExpressionNumericLiteral::ToCalculationExpression( const CSSToLengthConversionData& conversion_data) const { - return base::MakeRefCounted<CalculationExpressionLeafNode>( + return base::MakeRefCounted<CalculationExpressionPixelsAndPercentNode>( *ToPixelsAndPercent(conversion_data)); } @@ -565,31 +565,42 @@ const CSSToLengthConversionData& conversion_data) const { switch (operator_) { case CSSMathOperator::kAdd: - return CalculationExpressionAdditiveNode::CreateSimplified( - left_side_->ToCalculationExpression(conversion_data), - right_side_->ToCalculationExpression(conversion_data), - CalculationExpressionAdditiveNode::Type::kAdd); + return CalculationExpressionOperatorNode::CreateSimplified( + CalculationExpressionOperatorNode::Children( + {left_side_->ToCalculationExpression(conversion_data), + right_side_->ToCalculationExpression(conversion_data)}), + CalculationOperator::kAdd); case CSSMathOperator::kSubtract: - return CalculationExpressionAdditiveNode::CreateSimplified( - left_side_->ToCalculationExpression(conversion_data), - right_side_->ToCalculationExpression(conversion_data), - CalculationExpressionAdditiveNode::Type::kSubtract); + return CalculationExpressionOperatorNode::CreateSimplified( + CalculationExpressionOperatorNode::Children( + {left_side_->ToCalculationExpression(conversion_data), + right_side_->ToCalculationExpression(conversion_data)}), + CalculationOperator::kSubtract); case CSSMathOperator::kMultiply: DCHECK_NE((left_side_->Category() == kCalcNumber), (right_side_->Category() == kCalcNumber)); if (left_side_->Category() == kCalcNumber) { - return CalculationExpressionMultiplicationNode::CreateSimplified( - right_side_->ToCalculationExpression(conversion_data), - left_side_->DoubleValue()); + return CalculationExpressionOperatorNode::CreateSimplified( + CalculationExpressionOperatorNode::Children( + {right_side_->ToCalculationExpression(conversion_data), + base::MakeRefCounted<CalculationExpressionNumberNode>( + left_side_->DoubleValue())}), + CalculationOperator::kMultiply); } - return CalculationExpressionMultiplicationNode::CreateSimplified( - left_side_->ToCalculationExpression(conversion_data), - right_side_->DoubleValue()); + return CalculationExpressionOperatorNode::CreateSimplified( + CalculationExpressionOperatorNode::Children( + {left_side_->ToCalculationExpression(conversion_data), + base::MakeRefCounted<CalculationExpressionNumberNode>( + right_side_->DoubleValue())}), + CalculationOperator::kMultiply); case CSSMathOperator::kDivide: DCHECK_EQ(right_side_->Category(), kCalcNumber); - return CalculationExpressionMultiplicationNode::CreateSimplified( - left_side_->ToCalculationExpression(conversion_data), - 1.0 / right_side_->DoubleValue()); + return CalculationExpressionOperatorNode::CreateSimplified( + CalculationExpressionOperatorNode::Children( + {left_side_->ToCalculationExpression(conversion_data), + base::MakeRefCounted<CalculationExpressionNumberNode>( + 1.0 / right_side_->DoubleValue())}), + CalculationOperator::kMultiply); default: NOTREACHED(); return nullptr; @@ -963,11 +974,11 @@ operands.ReserveCapacity(operands_.size()); for (const auto& operand : operands_) operands.push_back(operand->ToCalculationExpression(data)); - auto expression_type = operator_ == CSSMathOperator::kMin - ? CalculationExpressionComparisonNode::Type::kMin - : CalculationExpressionComparisonNode::Type::kMax; - return CalculationExpressionComparisonNode::CreateSimplified( - std::move(operands), expression_type); + auto expression_operator = operator_ == CSSMathOperator::kMin + ? CalculationOperator::kMin + : CalculationOperator::kMax; + return CalculationExpressionOperatorNode::CreateSimplified( + std::move(operands), expression_operator); } bool CSSMathExpressionVariadicOperation::AccumulateLengthArray(CSSLengthArray&, @@ -1332,39 +1343,58 @@ // static CSSMathExpressionNode* CSSMathExpressionNode::Create( const CalculationExpressionNode& node) { - if (node.IsLeaf()) { - const auto& leaf = To<CalculationExpressionLeafNode>(node); - return Create(leaf.GetPixelsAndPercent()); + if (node.IsPixelsAndPercent()) { + const auto& pixels_and_percent = + To<CalculationExpressionPixelsAndPercentNode>(node); + return Create(pixels_and_percent.GetPixelsAndPercent()); } - if (node.IsMultiplication()) { - const auto& multiplication = - To<CalculationExpressionMultiplicationNode>(node); - double factor = multiplication.GetFactor(); - return CSSMathExpressionBinaryOperation::Create( - Create(multiplication.GetChild()), - CSSMathExpressionNumericLiteral::Create(CSSNumericLiteralValue::Create( - factor, CSSPrimitiveValue::UnitType::kNumber)), - CSSMathOperator::kMultiply); - } + DCHECK(node.IsOperator()); - if (node.IsAdditive()) { - const auto& add_or_subtract = To<CalculationExpressionAdditiveNode>(node); - auto* lhs = Create(add_or_subtract.GetLeftSide()); - auto* rhs = Create(add_or_subtract.GetRightSide()); - CSSMathOperator op = add_or_subtract.IsAdd() ? CSSMathOperator::kAdd - : CSSMathOperator::kSubtract; - return CSSMathExpressionBinaryOperation::Create(lhs, rhs, op); + const auto& operation = To<CalculationExpressionOperatorNode>(node); + const auto& children = operation.GetChildren(); + const auto calc_op = operation.GetOperator(); + switch (calc_op) { + case CalculationOperator::kMultiply: { + DCHECK_EQ(children.size(), 2u); + auto& pixels_and_percent_node = + children[0]->IsNumber() ? children[1] : children[0]; + auto& number_node = children[0]->IsNumber() ? children[0] : children[1]; + const auto& number = To<CalculationExpressionNumberNode>(*number_node); + double number_value = number.Value(); + return CSSMathExpressionBinaryOperation::Create( + Create(*pixels_and_percent_node), + CSSMathExpressionNumericLiteral::Create( + CSSNumericLiteralValue::Create( + number_value, CSSPrimitiveValue::UnitType::kNumber)), + CSSMathOperator::kMultiply); + } + case CalculationOperator::kAdd: + case CalculationOperator::kSubtract: { + DCHECK_EQ(children.size(), 2u); + auto* lhs = Create(*children[0]); + auto* rhs = Create(*children[1]); + CSSMathOperator op = (calc_op == CalculationOperator::kAdd) + ? CSSMathOperator::kAdd + : CSSMathOperator::kSubtract; + return CSSMathExpressionBinaryOperation::Create(lhs, rhs, op); + } + case CalculationOperator::kMin: + case CalculationOperator::kMax: { + DCHECK(children.size()); + CSSMathExpressionVariadicOperation::Operands operands; + for (const auto& child : children) + operands.push_back(Create(*child)); + CSSMathOperator op = (calc_op == CalculationOperator::kMin) + ? CSSMathOperator::kMin + : CSSMathOperator::kMax; + return CSSMathExpressionVariadicOperation::Create(std::move(operands), + op); + } + default: + NOTREACHED(); + return nullptr; } - - DCHECK(node.IsComparison()); - const auto& comparison = To<CalculationExpressionComparisonNode>(node); - CSSMathExpressionVariadicOperation::Operands operands; - for (const auto& operand : comparison.GetOperands()) - operands.push_back(Create(*operand)); - CSSMathOperator op = - comparison.IsMin() ? CSSMathOperator::kMin : CSSMathOperator::kMax; - return CSSMathExpressionVariadicOperation::Create(std::move(operands), op); } // static
diff --git a/third_party/blink/renderer/core/css/css_math_expression_node_test.cc b/third_party/blink/renderer/core/css/css_math_expression_node_test.cc index ad78da4..3cfc3c2 100644 --- a/third_party/blink/renderer/core/css/css_math_expression_node_test.cc +++ b/third_party/blink/renderer/core/css/css_math_expression_node_test.cc
@@ -56,11 +56,11 @@ float expected_percent) { scoped_refptr<const CalculationExpressionNode> value = expression->ToCalculationExpression(conversion_data); - EXPECT_TRUE(value->IsLeaf()); + EXPECT_TRUE(value->IsPixelsAndPercent()); EXPECT_EQ(expected_pixels, - To<CalculationExpressionLeafNode>(*value).Pixels()); + To<CalculationExpressionPixelsAndPercentNode>(*value).Pixels()); EXPECT_EQ(expected_percent, - To<CalculationExpressionLeafNode>(*value).Percent()); + To<CalculationExpressionPixelsAndPercentNode>(*value).Percent()); absl::optional<PixelsAndPercent> pixels_and_percent = expression->ToPixelsAndPercent(conversion_data);
diff --git a/third_party/blink/renderer/core/css/css_numeric_literal_value.cc b/third_party/blink/renderer/core/css/css_numeric_literal_value.cc index 16eaaaf..f8aca66 100644 --- a/third_party/blink/renderer/core/css/css_numeric_literal_value.cc +++ b/third_party/blink/renderer/core/css/css_numeric_literal_value.cc
@@ -153,11 +153,11 @@ } static String FormatNumber(double number, const char* suffix) { -#if defined(OS_WIN) && _MSC_VER < 1900 +#if BUILDFLAG(IS_WIN) && _MSC_VER < 1900 unsigned oldFormat = _set_output_format(_TWO_DIGIT_EXPONENT); #endif String result = String::Format("%.6g%s", number, suffix); -#if defined(OS_WIN) && _MSC_VER < 1900 +#if BUILDFLAG(IS_WIN) && _MSC_VER < 1900 _set_output_format(oldFormat); #endif return result;
diff --git a/third_party/blink/renderer/core/css/local_font_face_source.cc b/third_party/blink/renderer/core/css/local_font_face_source.cc index e8f1fca..329cbfc 100644 --- a/third_party/blink/renderer/core/css/local_font_face_source.cc +++ b/third_party/blink/renderer/core/css/local_font_face_source.cc
@@ -102,7 +102,7 @@ // Fonts sends, compare crbug.com/765980. So for now, we continue to // pass font_description to avoid breaking Google Fonts. FontDescription unstyled_description(font_description); -#if !defined(OS_ANDROID) +#if !BUILDFLAG(IS_ANDROID) unstyled_description.SetStretch(NormalWidthValue()); unstyled_description.SetStyle(NormalSlopeValue()); unstyled_description.SetWeight(NormalWeightValue());
diff --git a/third_party/blink/renderer/core/css/parser/css_parser_fast_paths.cc b/third_party/blink/renderer/core/css/parser/css_parser_fast_paths.cc index 5801748b..5dbf9ba3 100644 --- a/third_party/blink/renderer/core/css/parser/css_parser_fast_paths.cc +++ b/third_party/blink/renderer/core/css/parser/css_parser_fast_paths.cc
@@ -903,7 +903,7 @@ return value_id == CSSValueID::kNowrap || value_id == CSSValueID::kWrap || value_id == CSSValueID::kWrapReverse; case CSSPropertyID::kHyphens: -#if BUILDFLAG(USE_MINIKIN_HYPHENATION) || defined(OS_MAC) +#if BUILDFLAG(USE_MINIKIN_HYPHENATION) || BUILDFLAG(IS_MAC) return value_id == CSSValueID::kAuto || value_id == CSSValueID::kNone || value_id == CSSValueID::kManual; #else
diff --git a/third_party/blink/renderer/core/css/parser/css_proto_converter.cc b/third_party/blink/renderer/core/css/parser/css_proto_converter.cc index 556b3fb1..d19768e7 100644 --- a/third_party/blink/renderer/core/css/parser/css_proto_converter.cc +++ b/third_party/blink/renderer/core/css/parser/css_proto_converter.cc
@@ -14,7 +14,7 @@ // TODO(bikineev): "IN" comes as a macro from <windows.h>. It conflicts with // Length::IN from the generated proto file. Change the name in css.proto rather // than hacking with directives here. -#if defined(OS_WIN) && defined(IN) +#if BUILDFLAG(IS_WIN) && defined(IN) #undef IN #endif
diff --git a/third_party/blink/renderer/core/css/resolver/style_builder_converter.cc b/third_party/blink/renderer/core/css/resolver/style_builder_converter.cc index 0eb212d2..dff0d94 100644 --- a/third_party/blink/renderer/core/css/resolver/style_builder_converter.cc +++ b/third_party/blink/renderer/core/css/resolver/style_builder_converter.cc
@@ -242,7 +242,7 @@ FontFamily* curr_family = nullptr; -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) bool has_seen_system_ui = false; #endif @@ -266,7 +266,7 @@ // TODO(crbug.com/1065468): Get rid of GenericFamilyType. bool is_generic = generic_family != FontDescription::kNoFamily || IsA<CSSIdentifierValue>(*family); -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) // TODO(https://crbug.com/554590): Remove this counter when it's no longer // necessary. if (!has_seen_system_ui) {
diff --git a/third_party/blink/renderer/core/dom/document.cc b/third_party/blink/renderer/core/dom/document.cc index b856574..6cbde2e 100644 --- a/third_party/blink/renderer/core/dom/document.cc +++ b/third_party/blink/renderer/core/dom/document.cc
@@ -2589,33 +2589,28 @@ WebPrintPageDescription* description) { scoped_refptr<const ComputedStyle> style = StyleForPage(page_index); - double width = description->size.Width(); - double height = description->size.Height(); switch (style->GetPageSizeType()) { case PageSizeType::kAuto: break; case PageSizeType::kLandscape: - if (width < height) - std::swap(width, height); + if (description->size.width() < description->size.height()) + description->size.Transpose(); break; case PageSizeType::kPortrait: - if (width > height) - std::swap(width, height); + if (description->size.width() > description->size.height()) + description->size.Transpose(); break; - case PageSizeType::kFixed: { - gfx::SizeF size = style->PageSize(); - width = size.width(); - height = size.height(); + case PageSizeType::kFixed: + description->size = style->PageSize(); break; - } default: NOTREACHED(); } - description->size = WebDoubleSize(width, height); // The percentage is calculated with respect to the width even for margin top // and bottom. // http://www.w3.org/TR/CSS2/box.html#margin-properties + float width = description->size.width(); if (!style->MarginTop().IsAuto()) description->margin_top = IntValueForLength(style->MarginTop(), width); if (!style->MarginRight().IsAuto())
diff --git a/third_party/blink/renderer/core/dom/document_test.cc b/third_party/blink/renderer/core/dom/document_test.cc index afc1b68..f253dc2 100644 --- a/third_party/blink/renderer/core/dom/document_test.cc +++ b/third_party/blink/renderer/core/dom/document_test.cc
@@ -888,7 +888,7 @@ } // Android does not support non-overlay top-level scrollbars. -#if !defined(OS_ANDROID) +#if !BUILDFLAG(IS_ANDROID) TEST_F(DocumentTest, ElementFromPointOnScrollbar) { GetDocument().SetCompatibilityMode(Document::kQuirksMode); // This test requires that scrollbars take up space. @@ -915,7 +915,7 @@ // A hit test above the horizontal scrollbar should hit the body element. EXPECT_EQ(GetDocument().ElementFromPoint(1, 580), GetDocument().body()); } -#endif // defined(OS_ANDROID) +#endif // !BUILDFLAG(IS_ANDROID) TEST_F(DocumentTest, ElementFromPointWithPageZoom) { GetDocument().SetCompatibilityMode(Document::kQuirksMode); @@ -1085,7 +1085,7 @@ EXPECT_EQ(50, description.margin_right); EXPECT_EQ(50, description.margin_bottom); EXPECT_EQ(50, description.margin_left); - EXPECT_EQ(WebDoubleSize(400, 960), description.size); + EXPECT_EQ(gfx::SizeF(400, 960), description.size); } TEST(Document, HandlesDisconnectDuringHasTrustToken) {
diff --git a/third_party/blink/renderer/core/dom/events/event_dispatcher.cc b/third_party/blink/renderer/core/dom/events/event_dispatcher.cc index 7901b9c..f7ce838a 100644 --- a/third_party/blink/renderer/core/dom/events/event_dispatcher.cc +++ b/third_party/blink/renderer/core/dom/events/event_dispatcher.cc
@@ -377,13 +377,13 @@ } } } else { -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) // If a keypress event is prevented, the cursor position may be out of // sync as RenderWidgetHostViewCocoa::insertText assumes that the text // has been accepted. See https://crbug.com/1204523 for details. if (event_->type() == event_type_names::kKeypress && view_) view_->GetFrame().GetEditor().SyncSelection(SyncCondition::kForced); -#endif // defined(OS_MAC) +#endif // BUILDFLAG(IS_MAC) } auto* keyboard_event = DynamicTo<KeyboardEvent>(event_);
diff --git a/third_party/blink/renderer/core/editing/commands/apply_style_command_test.cc b/third_party/blink/renderer/core/editing/commands/apply_style_command_test.cc index b8af0efa..d1ad7f6 100644 --- a/third_party/blink/renderer/core/editing/commands/apply_style_command_test.cc +++ b/third_party/blink/renderer/core/editing/commands/apply_style_command_test.cc
@@ -199,7 +199,7 @@ InputEvent::InputType::kFormatItalic) ->Apply(); -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) EXPECT_EQ("|a<select multiple><option></option></select>b", GetSelectionTextFromBody()); #else
diff --git a/third_party/blink/renderer/core/editing/commands/move_commands_test.cc b/third_party/blink/renderer/core/editing/commands/move_commands_test.cc index 385124e..5215d8b 100644 --- a/third_party/blink/renderer/core/editing/commands/move_commands_test.cc +++ b/third_party/blink/renderer/core/editing/commands/move_commands_test.cc
@@ -57,13 +57,13 @@ VerifyCaretBrowsingPositionAndFocusUpdate( "<div>a|b</div><div><a href=\"foo\">cd</a></div>", "body", MoveCommands::ExecuteMoveDown, -#if !defined(OS_MAC) +#if !BUILDFLAG(IS_MAC) "<div>ab</div><div><a href=\"foo\">c|d</a></div>", "a"); -#else // defined(OS_MAC) - // MoveDown navigates visually, placing caret at different position for - // macOS. +#else + // MoveDown navigates visually, placing caret at different position for + // macOS. "<div>ab</div><div><a href=\"foo\">|cd</a></div>", "a"); -#endif // !defined(OS_MAC) +#endif } TEST_F(MoveCommandsTest, CaretBrowsingPositionAndFocusUpdate_MoveForward) { @@ -185,13 +185,13 @@ VerifyCaretBrowsingPositionAndFocusUpdate( "<div><a href=\"foo\">ab</a></div><div>c|d</div>", "body", MoveCommands::ExecuteMoveUp, -#if !defined(OS_MAC) +#if !BUILDFLAG(IS_MAC) "<div><a href=\"foo\">a|b</a></div><div>cd</div>", "a"); -#else // defined(OS_MAC) +#else // MoveUp navigates visually, placing caret at different position for // macOS. "<div><a href=\"foo\">|ab</a></div><div>cd</div>", "a"); -#endif // !defined(OS_MAC) +#endif } TEST_F(MoveCommandsTest, CaretBrowsingPositionAndFocusUpdate_MoveWordBackward) {
diff --git a/third_party/blink/renderer/core/editing/commands/smart_replace_icu.cc b/third_party/blink/renderer/core/editing/commands/smart_replace_icu.cc index 5fb4b14e..26e6098f 100644 --- a/third_party/blink/renderer/core/editing/commands/smart_replace_icu.cc +++ b/third_party/blink/renderer/core/editing/commands/smart_replace_icu.cc
@@ -31,7 +31,7 @@ #include "build/build_config.h" -#if !defined(OS_MAC) +#if !BUILDFLAG(IS_MAC) #include <unicode/uset.h> #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" @@ -112,4 +112,4 @@ } } -#endif // !defined(OS_MAC) +#endif // !BUILDFLAG(IS_MAC)
diff --git a/third_party/blink/renderer/core/editing/editing_behavior.cc b/third_party/blink/renderer/core/editing/editing_behavior.cc index 14d10a4..6b7a35b 100644 --- a/third_party/blink/renderer/core/editing/editing_behavior.cc +++ b/third_party/blink/renderer/core/editing/editing_behavior.cc
@@ -44,7 +44,7 @@ const unsigned kAltKey = WebInputEvent::kAltKey; const unsigned kShiftKey = WebInputEvent::kShiftKey; const unsigned kMetaKey = WebInputEvent::kMetaKey; -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) // Aliases for the generic key defintions to make kbd shortcuts definitions more // readable on OS X. const unsigned kOptionKey = kAltKey; @@ -87,7 +87,7 @@ const KeyboardCodeKeyDownEntry kKeyboardCodeKeyDownEntries[] = { {VKEY_LEFT, 0, "MoveLeft"}, {VKEY_LEFT, kShiftKey, "MoveLeftAndModifySelection"}, -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) {VKEY_LEFT, kOptionKey, "MoveWordLeft"}, {VKEY_LEFT, kOptionKey | kShiftKey, "MoveWordLeftAndModifySelection"}, #else @@ -96,7 +96,7 @@ #endif {VKEY_RIGHT, 0, "MoveRight"}, {VKEY_RIGHT, kShiftKey, "MoveRightAndModifySelection"}, -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) {VKEY_RIGHT, kOptionKey, "MoveWordRight"}, {VKEY_RIGHT, kOptionKey | kShiftKey, "MoveWordRightAndModifySelection"}, #else @@ -109,7 +109,7 @@ {VKEY_DOWN, 0, "MoveDown"}, {VKEY_DOWN, kShiftKey, "MoveDownAndModifySelection"}, {VKEY_NEXT, kShiftKey, "MovePageDownAndModifySelection"}, -#if !defined(OS_MAC) +#if !BUILDFLAG(IS_MAC) {VKEY_UP, kCtrlKey, "MoveParagraphBackward"}, {VKEY_UP, kCtrlKey | kShiftKey, "MoveParagraphBackwardAndModifySelection"}, {VKEY_DOWN, kCtrlKey, "MoveParagraphForward"}, @@ -119,32 +119,32 @@ #endif {VKEY_HOME, 0, "MoveToBeginningOfLine"}, {VKEY_HOME, kShiftKey, "MoveToBeginningOfLineAndModifySelection"}, -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) {VKEY_PRIOR, kOptionKey, "MovePageUp"}, {VKEY_NEXT, kOptionKey, "MovePageDown"}, #endif -#if !defined(OS_MAC) +#if !BUILDFLAG(IS_MAC) {VKEY_HOME, kCtrlKey, "MoveToBeginningOfDocument"}, {VKEY_HOME, kCtrlKey | kShiftKey, "MoveToBeginningOfDocumentAndModifySelection"}, #endif {VKEY_END, 0, "MoveToEndOfLine"}, {VKEY_END, kShiftKey, "MoveToEndOfLineAndModifySelection"}, -#if !defined(OS_MAC) +#if !BUILDFLAG(IS_MAC) {VKEY_END, kCtrlKey, "MoveToEndOfDocument"}, {VKEY_END, kCtrlKey | kShiftKey, "MoveToEndOfDocumentAndModifySelection"}, #endif {VKEY_BACK, 0, "DeleteBackward"}, {VKEY_BACK, kShiftKey, "DeleteBackward"}, {VKEY_DELETE, 0, "DeleteForward"}, -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) {VKEY_BACK, kOptionKey, "DeleteWordBackward"}, {VKEY_DELETE, kOptionKey, "DeleteWordForward"}, #else {VKEY_BACK, kCtrlKey, "DeleteWordBackward"}, {VKEY_DELETE, kCtrlKey, "DeleteWordForward"}, #endif -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) {'B', kCommandKey, "ToggleBold"}, {'I', kCommandKey, "ToggleItalic"}, #else @@ -164,7 +164,7 @@ {VKEY_INSERT, kCtrlKey, "Copy"}, {VKEY_INSERT, kShiftKey, "Paste"}, {VKEY_DELETE, kShiftKey, "Cut"}, -#if !defined(OS_MAC) +#if !BUILDFLAG(IS_MAC) // On OS X, we pipe these back to the browser, so that it can do menu item // blinking. {'C', kCtrlKey, "Copy"}, @@ -176,7 +176,7 @@ {'Z', kCtrlKey | kShiftKey, "Redo"}, {'Y', kCtrlKey, "Redo"}, #endif -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) {VKEY_BACK, kAltKey, "Undo"}, {VKEY_BACK, kAltKey | kShiftKey, "Redo"}, #endif @@ -280,19 +280,19 @@ // unexpected behaviour if (ch < ' ') return false; -#if defined(OS_LINUX) || defined(OS_CHROMEOS) +#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) // According to XKB map no keyboard combinations with ctrl key are mapped to // printable characters, however we need the filter as the DomKey/text could // contain printable characters. if (event.ctrlKey()) return false; -#elif !defined(OS_WIN) +#elif !BUILDFLAG(IS_WIN) // Don't insert ASCII character if ctrl w/o alt or meta is on. // On Mac, we should ignore events when meta is on (Command-<x>). if (ch < 0x80) { if (event.ctrlKey() && !event.altKey()) return false; -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) if (event.metaKey()) return false; #endif
diff --git a/third_party/blink/renderer/core/editing/finder/find_buffer_test.cc b/third_party/blink/renderer/core/editing/finder/find_buffer_test.cc index bf3b075e..9e86f68 100644 --- a/third_party/blink/renderer/core/editing/finder/find_buffer_test.cc +++ b/third_party/blink/renderer/core/editing/finder/find_buffer_test.cc
@@ -662,20 +662,20 @@ SetBodyContent("<select multiple><option>find me</option></select>"); { FindBuffer buffer(WholeDocumentRange()); -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) EXPECT_EQ(0u, buffer.FindMatches("find", 0).CountForTesting()); #else EXPECT_EQ(1u, buffer.FindMatches("find", 0).CountForTesting()); -#endif // defined(OS_ANDROID) +#endif // BUILDFLAG(IS_ANDROID) } SetBodyContent("<select size=2><option>find me</option></select>"); { FindBuffer buffer(WholeDocumentRange()); -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) EXPECT_EQ(0u, buffer.FindMatches("find", 0).CountForTesting()); #else EXPECT_EQ(1u, buffer.FindMatches("find", 0).CountForTesting()); -#endif // defined(OS_ANDROID) +#endif // BUILDFLAG(IS_ANDROID) } SetBodyContent("<select size=1><option>find me</option></select>"); {
diff --git a/third_party/blink/renderer/core/editing/frame_caret_test.cc b/third_party/blink/renderer/core/editing/frame_caret_test.cc index ca02f820..1916a9efc 100644 --- a/third_party/blink/renderer/core/editing/frame_caret_test.cc +++ b/third_party/blink/renderer/core/editing/frame_caret_test.cc
@@ -35,7 +35,7 @@ ScopedWebTestMode web_test_mode_{false}; }; -#if defined(OS_MAC) && defined(ARCH_CPU_ARM64) +#if BUILDFLAG(IS_MAC) && defined(ARCH_CPU_ARM64) // https://crbug.com/1222649 #define MAYBE_BlinkAfterTyping DISABLED_BlinkAfterTyping #else
diff --git a/third_party/blink/renderer/core/editing/keyboard_test.cc b/third_party/blink/renderer/core/editing/keyboard_test.cc index 83c8fb4..3b3b73a 100644 --- a/third_party/blink/renderer/core/editing/keyboard_test.cc +++ b/third_party/blink/renderer/core/editing/keyboard_test.cc
@@ -74,7 +74,7 @@ // OSModifier is the platform's standard modifier key: control on most // platforms, but meta (command) on Mac. const char* InterpretOSModifierKeyPress(char key_code) { -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) WebInputEvent::Modifiers os_modifier = WebInputEvent::kMetaKey; #else WebInputEvent::Modifiers os_modifier = WebInputEvent::kControlKey; @@ -116,37 +116,37 @@ } TEST_F(KeyboardTest, TestOSModifierZ) { -#if !defined(OS_MAC) +#if !BUILDFLAG(IS_MAC) EXPECT_STREQ("Undo", InterpretOSModifierKeyPress('Z')); #endif } TEST_F(KeyboardTest, TestOSModifierY) { -#if !defined(OS_MAC) +#if !BUILDFLAG(IS_MAC) EXPECT_STREQ("Redo", InterpretOSModifierKeyPress('Y')); #endif } TEST_F(KeyboardTest, TestOSModifierA) { -#if !defined(OS_MAC) +#if !BUILDFLAG(IS_MAC) EXPECT_STREQ("SelectAll", InterpretOSModifierKeyPress('A')); #endif } TEST_F(KeyboardTest, TestOSModifierX) { -#if !defined(OS_MAC) +#if !BUILDFLAG(IS_MAC) EXPECT_STREQ("Cut", InterpretOSModifierKeyPress('X')); #endif } TEST_F(KeyboardTest, TestOSModifierC) { -#if !defined(OS_MAC) +#if !BUILDFLAG(IS_MAC) EXPECT_STREQ("Copy", InterpretOSModifierKeyPress('C')); #endif } TEST_F(KeyboardTest, TestOSModifierV) { -#if !defined(OS_MAC) +#if !BUILDFLAG(IS_MAC) EXPECT_STREQ("Paste", InterpretOSModifierKeyPress('V')); #endif }
diff --git a/third_party/blink/renderer/core/editing/suggestion/text_suggestion_controller_test.cc b/third_party/blink/renderer/core/editing/suggestion/text_suggestion_controller_test.cc index 4bf1879ce..615e3b7f 100644 --- a/third_party/blink/renderer/core/editing/suggestion/text_suggestion_controller_test.cc +++ b/third_party/blink/renderer/core/editing/suggestion/text_suggestion_controller_test.cc
@@ -84,7 +84,7 @@ } // Flaky on Android: http://crbug.com/1104700 -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) #define MAYBE_ApplyTextSuggestion DISABLED_ApplyTextSuggestion #else #define MAYBE_ApplyTextSuggestion ApplyTextSuggestion
diff --git a/third_party/blink/renderer/core/events/keyboard_event.cc b/third_party/blink/renderer/core/events/keyboard_event.cc index d54d932..cfc48b2 100644 --- a/third_party/blink/renderer/core/events/keyboard_event.cc +++ b/third_party/blink/renderer/core/events/keyboard_event.cc
@@ -133,7 +133,7 @@ else key_code_ = char_code_; -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) // FIXME: Check to see if this applies to other OS. // If the key event belongs to IME composition then propagate to JS. if (key.native_key_code == 0xE5) // VKEY_PROCESSKEY
diff --git a/third_party/blink/renderer/core/events/ui_event_with_key_state.cc b/third_party/blink/renderer/core/events/ui_event_with_key_state.cc index a558308..9f467fb 100644 --- a/third_party/blink/renderer/core/events/ui_event_with_key_state.cc +++ b/third_party/blink/renderer/core/events/ui_event_with_key_state.cc
@@ -76,7 +76,7 @@ bool shift_key, bool alt_key, bool meta_key) { -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) const bool new_tab_modifier_set = meta_key; #else const bool new_tab_modifier_set = ctrl_key; @@ -121,7 +121,7 @@ {"Meta", WebInputEvent::kMetaKey}, {"AltGraph", WebInputEvent::kAltGrKey}, {"Accel", -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) WebInputEvent::kMetaKey #else WebInputEvent::kControlKey
diff --git a/third_party/blink/renderer/core/execution_context/execution_context.cc b/third_party/blink/renderer/core/execution_context/execution_context.cc index 74814e7..738ea70 100644 --- a/third_party/blink/renderer/core/execution_context/execution_context.cc +++ b/third_party/blink/renderer/core/execution_context/execution_context.cc
@@ -231,7 +231,7 @@ if (SecurityPolicy::IsSharedArrayBufferAlwaysAllowedForOrigin(origin)) return true; -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) return false; #else // On desktop, enable transfer for the reverse Origin Trial, or if the
diff --git a/third_party/blink/renderer/core/execution_context/navigator_base.cc b/third_party/blink/renderer/core/execution_context/navigator_base.cc index f6e9b96a..0961d0f 100644 --- a/third_party/blink/renderer/core/execution_context/navigator_base.cc +++ b/third_party/blink/renderer/core/execution_context/navigator_base.cc
@@ -10,7 +10,7 @@ #include "third_party/blink/renderer/core/execution_context/execution_context.h" #include "third_party/blink/renderer/platform/wtf/text/string_builder.h" -#if !defined(OS_MAC) && !defined(OS_WIN) +#if !BUILDFLAG(IS_MAC) && !BUILDFLAG(IS_WIN) #include <sys/utsname.h> #include "third_party/blink/renderer/platform/wtf/thread_specific.h" #include "third_party/blink/renderer/platform/wtf/threading.h" @@ -40,11 +40,11 @@ // matching the frozen string per https://github.com/WICG/ua-client-hints. // See content::frozen_user_agent_strings. if (RuntimeEnabledFeatures::UserAgentReductionEnabled(execution_context)) { -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) return "Linux armv81"; -#elif defined(OS_MAC) +#elif BUILDFLAG(IS_MAC) return "MacIntel"; -#elif defined(OS_WIN) +#elif BUILDFLAG(IS_WIN) return "Win32"; #else return "Linux x86_64";
diff --git a/third_party/blink/renderer/core/exported/web_disallow_transition_scope_test.cc b/third_party/blink/renderer/core/exported/web_disallow_transition_scope_test.cc index 323686c..5bf102b9 100644 --- a/third_party/blink/renderer/core/exported/web_disallow_transition_scope_test.cc +++ b/third_party/blink/renderer/core/exported/web_disallow_transition_scope_test.cc
@@ -30,7 +30,7 @@ return web_view_helper_.LocalMainFrame()->GetDocument(); } -#if !defined(OS_ANDROID) +#if !BUILDFLAG(IS_ANDROID) // TODO(crbug.com/1067036): the death test fails on Android. TEST_F(WebDisallowTransitionScopeTest, TestDisallowTransition) { // Make the death test thread-safe. For more info, see:
diff --git a/third_party/blink/renderer/core/exported/web_media_player_impl_unittest.cc b/third_party/blink/renderer/core/exported/web_media_player_impl_unittest.cc index a9b1585..5817b440 100644 --- a/third_party/blink/renderer/core/exported/web_media_player_impl_unittest.cc +++ b/third_party/blink/renderer/core/exported/web_media_player_impl_unittest.cc
@@ -382,7 +382,7 @@ auto factory_selector = std::make_unique<media::RendererFactorySelector>(); renderer_factory_selector_ = factory_selector.get(); decoder_factory_ = std::make_unique<media::DefaultDecoderFactory>(nullptr); -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) factory_selector->AddBaseFactory( media::RendererType::kDefault, std::make_unique<media::DefaultRendererFactory>( @@ -1754,7 +1754,7 @@ media::BUFFERING_CHANGE_REASON_UNKNOWN); } -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) TEST_F(WebMediaPlayerImplTest, FallbackToMediaFoundationRenderer) { InitializeWebMediaPlayerImpl(); // To avoid PreloadMetadataLazyLoad. @@ -1799,7 +1799,7 @@ Load(kEncryptedVideoOnlyTestFile); run_loop.Run(); } -#endif // defined(OS_WIN) +#endif // BUILDFLAG(IS_WIN) TEST_F(WebMediaPlayerImplTest, VideoConfigChange) { InitializeWebMediaPlayerImpl(); @@ -2329,7 +2329,7 @@ } bool IsAndroid() { -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) return true; #else return false;
diff --git a/third_party/blink/renderer/core/exported/web_plugin_container_impl.cc b/third_party/blink/renderer/core/exported/web_plugin_container_impl.cc index 978c2dcd..0e3fb914 100644 --- a/third_party/blink/renderer/core/exported/web_plugin_container_impl.cc +++ b/third_party/blink/renderer/core/exported/web_plugin_container_impl.cc
@@ -111,7 +111,7 @@ namespace { -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) const WebInputEvent::Modifiers kEditingModifier = WebInputEvent::kMetaKey; #else const WebInputEvent::Modifiers kEditingModifier = WebInputEvent::kControlKey;
diff --git a/third_party/blink/renderer/core/exported/web_plugin_container_test.cc b/third_party/blink/renderer/core/exported/web_plugin_container_test.cc index 86dbca25..d036668 100644 --- a/third_party/blink/renderer/core/exported/web_plugin_container_test.cc +++ b/third_party/blink/renderer/core/exported/web_plugin_container_test.cc
@@ -114,7 +114,7 @@ namespace { -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) const WebInputEvent::Modifiers kEditingModifier = WebInputEvent::kMetaKey; #else const WebInputEvent::Modifiers kEditingModifier = WebInputEvent::kControlKey;
diff --git a/third_party/blink/renderer/core/exported/web_view_impl.cc b/third_party/blink/renderer/core/exported/web_view_impl.cc index 37f973b..87e3d73 100644 --- a/third_party/blink/renderer/core/exported/web_view_impl.cc +++ b/third_party/blink/renderer/core/exported/web_view_impl.cc
@@ -178,17 +178,17 @@ #include "ui/base/ui_base_features.h" #include "ui/gfx/geometry/skia_conversions.h" -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) #include "components/viz/common/features.h" #endif -#if !defined(OS_MAC) +#if !BUILDFLAG(IS_MAC) #include "skia/ext/legacy_display_globals.h" #include "third_party/blink/public/platform/web_font_render_style.h" #include "ui/gfx/font_render_params.h" #endif -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) #include "third_party/blink/public/web/win/web_font_rendering.h" #endif @@ -369,7 +369,7 @@ } WebMediaPlayer::SurfaceLayerMode GetVideoSurfaceLayerMode() { -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) if (!::features::UseSurfaceLayerForVideo()) return blink::WebMediaPlayer::SurfaceLayerMode::kNever; #endif @@ -396,12 +396,12 @@ return ui::mojom::blink::WindowOpenDisposition::IGNORE_ACTION; } -#if !defined(OS_MAC) && !defined(OS_WIN) +#if !BUILDFLAG(IS_MAC) && !BUILDFLAG(IS_WIN) SkFontHinting RendererPreferencesToSkiaHinting( const blink::RendererPreferences& prefs) { // TODO(crbug.com/1052397): Revisit once build flag switch of lacros-chrome is // complete. -#if defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS) +#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS) if (!prefs.should_antialias_text) { // When anti-aliasing is off, GTK maps all non-zero hinting settings to // 'Normal' hinting so we do the same. Otherwise, folks who have 'Slight' @@ -434,7 +434,7 @@ return SkFontHinting::kNormal; } } -#endif // OS_MAC +#endif // !BUILDFLAG(IS_MAC) && !BUILDFLAG(IS_WIN) } // namespace @@ -933,7 +933,7 @@ StartPageScaleAnimation(scroll, false, scale, kFindInPageAnimationDuration); } -#if !defined(OS_MAC) +#if !BUILDFLAG(IS_MAC) // Mac has no way to open a context menu based on a keyboard event. WebInputEventResult WebViewImpl::SendContextMenuEvent() { // The contextMenuController() holds onto the last context menu that was @@ -1612,7 +1612,7 @@ prefs.dont_send_key_events_to_javascript); settings->SetWebAppScope(WebString::FromASCII(prefs.web_app_scope.spec())); -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) settings->SetAllowCustomScrollbarInMainFrame(false); settings->SetAccessibilityFontScaleFactor(prefs.font_scale_factor); settings->SetDeviceScaleAdjustment(prefs.device_scale_adjustment); @@ -1659,7 +1659,7 @@ prefs.scroll_top_left_interop_enabled); RuntimeEnabledFeatures::SetAcceleratedSmallCanvasesEnabled( !prefs.disable_accelerated_small_canvases); -#endif // defined(OS_ANDROID) +#endif // BUILDFLAG(IS_ANDROID) settings->SetForceDarkModeEnabled(prefs.force_dark_mode_enabled); settings->SetAccessibilityAlwaysShowFocus(prefs.always_show_focus); @@ -1794,12 +1794,12 @@ settings->SetTouchDragEndContextMenu(prefs.touch_dragend_context_menu); settings->SetWebXRImmersiveArAllowed(prefs.webxr_immersive_ar_allowed); -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) web_view_impl->SetMaximumLegibleScale( prefs.default_maximum_page_scale_factor); #endif -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) RuntimeEnabledFeatures::SetMiddleClickAutoscrollEnabled(true); #endif @@ -3136,11 +3136,11 @@ } void WebViewImpl::UpdateFontRenderingFromRendererPrefs() { -#if !defined(OS_MAC) +#if !BUILDFLAG(IS_MAC) skia::LegacyDisplayGlobals::SetCachedPixelGeometry( gfx::FontRenderParams::SubpixelRenderingToSkiaPixelGeometry( renderer_preferences_.subpixel_rendering)); -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) // Cache the system font metrics in blink. WebFontRendering::SetMenuFontMetrics( WebString::FromUTF16(renderer_preferences_.menu_font_family_name), @@ -3170,15 +3170,16 @@ renderer_preferences_.use_subpixel_positioning); // TODO(crbug.com/1052397): Revisit once build flag switch of lacros-chrome is // complete. -#if (defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)) && !defined(OS_ANDROID) +#if (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)) && \ + !BUILDFLAG(IS_ANDROID) if (!renderer_preferences_.system_font_family_name.empty()) { WebFontRenderStyle::SetSystemFontFamily(blink::WebString::FromUTF8( renderer_preferences_.system_font_family_name)); } -#endif // (defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)) && - // !defined(OS_ANDROID) -#endif // defined(OS_WIN) -#endif // !defined(OS_MAC) +#endif // (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)) && + // !BUILDFLAG(IS_ANDROID) +#endif // BUILDFLAG(IS_WIN) +#endif // !BUILDFLAG(IS_MAC) } void WebViewImpl::ActivatePrerenderedPage(
diff --git a/third_party/blink/renderer/core/exported/web_view_test.cc b/third_party/blink/renderer/core/exported/web_view_test.cc index 6e131a26..5432869 100644 --- a/third_party/blink/renderer/core/exported/web_view_test.cc +++ b/third_party/blink/renderer/core/exported/web_view_test.cc
@@ -898,7 +898,7 @@ EXPECT_EQ(expected_height, client.GetTestData().Height()); // Android disables main frame scrollbars. -#if !defined(OS_ANDROID) +#if !BUILDFLAG(IS_ANDROID) EXPECT_EQ(expected_horizontal_state, client.GetTestData().GetHorizontalScrollbarState()); EXPECT_EQ(expected_vertical_state, @@ -3171,7 +3171,7 @@ EXPECT_TRUE(frame->GetFrame()->Selection().IsHandleVisible()); } -#if !defined(OS_MAC) +#if !BUILDFLAG(IS_MAC) TEST_F(WebViewTest, TouchDoesntSelectEmptyTextarea) { RegisterMockedHttpURLLoad("longpress_textarea.html");
diff --git a/third_party/blink/renderer/core/frame/browser_controls_test.cc b/third_party/blink/renderer/core/frame/browser_controls_test.cc index 58b4cb0..5ba353c 100644 --- a/third_party/blink/renderer/core/frame/browser_controls_test.cc +++ b/third_party/blink/renderer/core/frame/browser_controls_test.cc
@@ -205,7 +205,7 @@ // Disable these tests on Mac OSX until further investigation. // Local build on Mac is OK but the bot fails. This is not an issue as // Browser Controls are currently only used on Android. -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) #define MAYBE(test) DISABLED_##test #else #define MAYBE(test) test
diff --git a/third_party/blink/renderer/core/frame/frame_overlay.h b/third_party/blink/renderer/core/frame/frame_overlay.h index 78447e1..0e708b0 100644 --- a/third_party/blink/renderer/core/frame/frame_overlay.h +++ b/third_party/blink/renderer/core/frame/frame_overlay.h
@@ -33,6 +33,8 @@ #include "base/time/time.h" #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/platform/graphics/paint/display_item_client.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" namespace blink {
diff --git a/third_party/blink/renderer/core/frame/frame_test_helpers.cc b/third_party/blink/renderer/core/frame/frame_test_helpers.cc index 0bc9012..1646bf2 100644 --- a/third_party/blink/renderer/core/frame/frame_test_helpers.cc +++ b/third_party/blink/renderer/core/frame/frame_test_helpers.cc
@@ -151,7 +151,7 @@ // test makes progress. settings.single_thread_proxy_scheduler = false; settings.use_layer_lists = true; -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) settings.enable_elastic_overscroll = true; #endif return settings;
diff --git a/third_party/blink/renderer/core/frame/local_frame.cc b/third_party/blink/renderer/core/frame/local_frame.cc index 56c9b35..bb3841b 100644 --- a/third_party/blink/renderer/core/frame/local_frame.cc +++ b/third_party/blink/renderer/core/frame/local_frame.cc
@@ -37,6 +37,7 @@ #include "base/metrics/histogram_functions.h" #include "base/unguessable_token.h" #include "base/values.h" +#include "build/build_config.h" #include "mojo/public/cpp/bindings/self_owned_receiver.h" #include "mojo/public/cpp/system/message_pipe.h" #include "services/data_decoder/public/mojom/resource_snapshot_for_web_bundle.mojom-blink.h" @@ -206,7 +207,7 @@ #include "ui/gfx/geometry/rect_f.h" #include "ui/gfx/geometry/transform.h" -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) #include "third_party/blink/renderer/core/editing/ephemeral_range.h" #include "third_party/blink/renderer/core/editing/substring_util.h" #include "third_party/blink/renderer/platform/fonts/mac/attributed_string_type_converter.h" @@ -2668,7 +2669,7 @@ : mojom::blink::FocusType::kForward); } -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) void LocalFrame::GetCharacterIndexAtPoint(const gfx::Point& point) { HitTestLocation location(View()->ViewportToFrame(gfx::Point(point))); HitTestResult result = GetEventHandler().HitTestResultAtLocation( @@ -3045,7 +3046,7 @@ return false; } -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) void LocalFrame::ResetTextInputHostForTesting() { mojo_handler_->ResetTextInputHostForTesting(); }
diff --git a/third_party/blink/renderer/core/frame/local_frame.h b/third_party/blink/renderer/core/frame/local_frame.h index dbb0f87e0..eb52802 100644 --- a/third_party/blink/renderer/core/frame/local_frame.h +++ b/third_party/blink/renderer/core/frame/local_frame.h
@@ -643,7 +643,7 @@ void ClosePageForTesting(); void SetInitialFocus(bool reverse); -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) void GetCharacterIndexAtPoint(const gfx::Point& point); #endif void UpdateWindowControlsOverlay(const gfx::Rect& bounding_rect_in_dips); @@ -714,7 +714,7 @@ // to FrameFirstPaint. void OnFirstPaint(bool text_painted, bool image_painted); -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) void ResetTextInputHostForTesting(); void RebindTextInputHostForTesting(); #endif
diff --git a/third_party/blink/renderer/core/frame/local_frame_mojo_handler.cc b/third_party/blink/renderer/core/frame/local_frame_mojo_handler.cc index 7e90af56..e00351a 100644 --- a/third_party/blink/renderer/core/frame/local_frame_mojo_handler.cc +++ b/third_party/blink/renderer/core/frame/local_frame_mojo_handler.cc
@@ -4,6 +4,7 @@ #include "third_party/blink/renderer/core/frame/local_frame_mojo_handler.h" +#include "build/build_config.h" #include "components/power_scheduler/power_mode.h" #include "components/power_scheduler/power_mode_arbiter.h" #include "mojo/public/cpp/bindings/self_owned_receiver.h" @@ -59,7 +60,7 @@ #include "third_party/blink/renderer/platform/mhtml/serialized_resource.h" #include "third_party/blink/renderer/platform/widget/frame_widget.h" -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) #include "third_party/blink/renderer/core/editing/substring_util.h" #include "third_party/blink/renderer/platform/fonts/mac/attributed_string_type_converter.h" #include "ui/base/mojom/attributed_string.mojom-blink.h" @@ -72,7 +73,7 @@ constexpr char kInvalidWorldID[] = "JavaScriptExecuteRequestInIsolatedWorld gets an invalid world id."; -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) uint32_t GetCurrentCursorPositionInFrame(LocalFrame* local_frame) { blink::WebRange range = WebLocalFrameImpl::FromFrame(local_frame)->SelectionRange(); @@ -323,7 +324,7 @@ frame.GetRemoteNavigationAssociatedInterfaces()->GetInterface( back_forward_cache_controller_host_remote_.BindNewEndpointAndPassReceiver( frame.GetTaskRunner(TaskType::kInternalDefault))); -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) // It should be bound before accessing TextInputHost which is the interface to // respond to GetCharacterIndexAtPoint. frame.GetBrowserInterfaceBroker().GetInterface( @@ -351,7 +352,7 @@ void LocalFrameMojoHandler::Trace(Visitor* visitor) const { visitor->Trace(frame_); visitor->Trace(back_forward_cache_controller_host_remote_); -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) visitor->Trace(text_input_host_); #endif visitor->Trace(reporting_service_); @@ -388,7 +389,7 @@ return *back_forward_cache_controller_host_remote_.get(); } -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) mojom::blink::TextInputHost& LocalFrameMojoHandler::TextInputHost() { DCHECK(text_input_host_.is_bound()); return *text_input_host_.get(); @@ -946,7 +947,7 @@ power_scheduler::PowerModeVoter::kScriptExecutionTimeout); } -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) void LocalFrameMojoHandler::GetCharacterIndexAtPoint(const gfx::Point& point) { frame_->GetCharacterIndexAtPoint(point); } @@ -1058,7 +1059,7 @@ frame_->Client()->BindDevToolsAgent(std::move(host), std::move(receiver)); } -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) void LocalFrameMojoHandler::ExtractSmartClipData( const gfx::Rect& rect, ExtractSmartClipDataCallback callback) { @@ -1070,7 +1071,7 @@ clip_html.IsNull() ? g_empty_string : clip_html, clip_rect); } -#endif // defined(OS_ANDROID) +#endif // BUILDFLAG(IS_ANDROID) void LocalFrameMojoHandler::HandleRendererDebugURL(const KURL& url) { DCHECK(IsRendererDebugURL(url));
diff --git a/third_party/blink/renderer/core/frame/local_frame_mojo_handler.h b/third_party/blink/renderer/core/frame/local_frame_mojo_handler.h index b92f80e..ece7b148 100644 --- a/third_party/blink/renderer/core/frame/local_frame_mojo_handler.h +++ b/third_party/blink/renderer/core/frame/local_frame_mojo_handler.h
@@ -19,7 +19,7 @@ #include "third_party/blink/renderer/platform/mojo/heap_mojo_receiver.h" #include "third_party/blink/renderer/platform/mojo/heap_mojo_remote.h" -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) #include "third_party/blink/public/mojom/input/text_input_host.mojom-blink.h" #endif @@ -64,7 +64,7 @@ mojom::blink::BackForwardCacheControllerHost& BackForwardCacheControllerHostRemote(); -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) mojom::blink::TextInputHost& TextInputHost(); void ResetTextInputHostForTesting(); void RebindTextInputHostForTesting(); @@ -161,7 +161,7 @@ bool wants_result, int32_t world_id, JavaScriptExecuteRequestInIsolatedWorldCallback callback) final; -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) void GetCharacterIndexAtPoint(const gfx::Point& point) final; void GetFirstRectForRange(const gfx::Range& range) final; void GetStringForRange(const gfx::Range& range, @@ -184,7 +184,7 @@ mojo::PendingAssociatedRemote<mojom::blink::DevToolsAgentHost> host, mojo::PendingAssociatedReceiver<mojom::blink::DevToolsAgent> receiver) final; -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) void ExtractSmartClipData(const gfx::Rect& rect, ExtractSmartClipDataCallback callback) final; #endif @@ -237,7 +237,7 @@ HeapMojoAssociatedRemote<mojom::blink::BackForwardCacheControllerHost> back_forward_cache_controller_host_remote_{nullptr}; -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) HeapMojoRemote<mojom::blink::TextInputHost> text_input_host_{nullptr}; #endif
diff --git a/third_party/blink/renderer/core/frame/local_frame_test.cc b/third_party/blink/renderer/core/frame/local_frame_test.cc index 78eda5f..6d788ecd 100644 --- a/third_party/blink/renderer/core/frame/local_frame_test.cc +++ b/third_party/blink/renderer/core/frame/local_frame_test.cc
@@ -14,7 +14,7 @@ #include "third_party/blink/renderer/platform/loader/fetch/fetch_parameters.h" #include "third_party/blink/renderer/platform/network/network_state_notifier.h" #include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h" -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) #include "mojo/public/cpp/bindings/receiver.h" #include "third_party/blink/public/mojom/input/text_input_host.mojom-blink.h" #include "third_party/blink/renderer/core/frame/frame_test_helpers.h" @@ -33,7 +33,7 @@ settings.SetLazyLoadEnabled(true); } -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) void RegisterMockedHttpURLLoad(const std::string& base_url, const std::string& file_name) { url_test_helpers::RegisterMockedURLLoadFromBase( @@ -238,7 +238,7 @@ TestGreenDiv(*page_holder); } -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) TEST_F(LocalFrameTest, CharacterIndexAtPointWithPinchZoom) { RegisterMockedHttpURLLoad("http://internal.test/", "sometext.html");
diff --git a/third_party/blink/renderer/core/frame/mhtml_archive_test.cc b/third_party/blink/renderer/core/frame/mhtml_archive_test.cc index ad98278..6788797 100644 --- a/third_party/blink/renderer/core/frame/mhtml_archive_test.cc +++ b/third_party/blink/renderer/core/frame/mhtml_archive_test.cc
@@ -364,7 +364,7 @@ CheckLoadResult(ToKURL("http://www.example.com"), data.get(), MHTMLLoadResult::kSuccess); -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) CheckLoadResult(ToKURL("content://foo"), data.get(), MHTMLLoadResult::kSuccess); #else
diff --git a/third_party/blink/renderer/core/frame/navigator_id.cc b/third_party/blink/renderer/core/frame/navigator_id.cc index 9c534d6..50a1727 100644 --- a/third_party/blink/renderer/core/frame/navigator_id.cc +++ b/third_party/blink/renderer/core/frame/navigator_id.cc
@@ -36,7 +36,7 @@ #include "third_party/blink/public/common/features.h" #include "third_party/blink/renderer/platform/wtf/text/string_builder.h" -#if !defined(OS_MAC) && !defined(OS_WIN) +#if !BUILDFLAG(IS_MAC) && !BUILDFLAG(IS_WIN) #include <sys/utsname.h> #include "third_party/blink/renderer/platform/wtf/thread_specific.h" #include "third_party/blink/renderer/platform/wtf/threading.h" @@ -59,10 +59,10 @@ } String NavigatorID::platform() const { -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) // Match Safari and Mozilla on Mac x86. return "MacIntel"; -#elif defined(OS_WIN) +#elif BUILDFLAG(IS_WIN) // Match Safari and Mozilla on Windows. return "Win32"; #else // Unix-like systems
diff --git a/third_party/blink/renderer/core/frame/settings.cc b/third_party/blink/renderer/core/frame/settings.cc index f49095b..f56f10b 100644 --- a/third_party/blink/renderer/core/frame/settings.cc +++ b/third_party/blink/renderer/core/frame/settings.cc
@@ -85,13 +85,13 @@ // 99) MacEditingBehavior is used a fallback. static mojom::blink::EditingBehavior EditingBehaviorTypeForPlatform() { return -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) mojom::blink::EditingBehavior::kEditingMacBehavior -#elif defined(OS_WIN) +#elif BUILDFLAG(IS_WIN) mojom::blink::EditingBehavior::kEditingWindowsBehavior -#elif defined(OS_ANDROID) +#elif BUILDFLAG(IS_ANDROID) mojom::blink::EditingBehavior::kEditingAndroidBehavior -#elif defined(OS_CHROMEOS) +#elif BUILDFLAG(IS_CHROMEOS) mojom::blink::EditingBehavior::kEditingChromeOSBehavior #else // Rest of the UNIX-like systems mojom::blink::EditingBehavior::kEditingUnixBehavior @@ -99,7 +99,7 @@ ; } -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) static const bool kDefaultSelectTrailingWhitespaceEnabled = true; #else static const bool kDefaultSelectTrailingWhitespaceEnabled = false;
diff --git a/third_party/blink/renderer/core/frame/visual_viewport.cc b/third_party/blink/renderer/core/frame/visual_viewport.cc index db985bd36..4d63c50a 100644 --- a/third_party/blink/renderer/core/frame/visual_viewport.cc +++ b/third_party/blink/renderer/core/frame/visual_viewport.cc
@@ -295,7 +295,7 @@ } } -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) if (Platform::Current()->IsElasticOverscrollEnabled() && base::GetFieldTrialParamValueByFeature( ::features::kElasticOverscroll, ::features::kElasticOverscrollType) ==
diff --git a/third_party/blink/renderer/core/frame/web_frame_test.cc b/third_party/blink/renderer/core/frame/web_frame_test.cc index 9517ed9..8791659 100644 --- a/third_party/blink/renderer/core/frame/web_frame_test.cc +++ b/third_party/blink/renderer/core/frame/web_frame_test.cc
@@ -3419,7 +3419,7 @@ } // Android doesn't have scrollbars on the main LocalFrameView -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) TEST_F(WebFrameTest, DISABLED_updateOverlayScrollbarLayers) #else TEST_F(WebFrameTest, updateOverlayScrollbarLayers) @@ -6310,7 +6310,7 @@ EXPECT_EQ(64, ComputeOffset(layout_object, 1000, 1000)); } -#if !defined(OS_MAC) && !defined(OS_LINUX) && !defined(OS_CHROMEOS) +#if !BUILDFLAG(IS_MAC) && !BUILDFLAG(IS_LINUX) && !BUILDFLAG(IS_CHROMEOS) TEST_F(WebFrameTest, SelectRangeStaysHorizontallyAlignedWhenMoved) { RegisterMockedHttpURLLoad("move_caret.html"); @@ -6689,8 +6689,8 @@ TEST_F(CompositedSelectionBoundsTest, SVGTextWithFragments) { RunTest("composited_selection_bounds_svg_text_with_fragments.html"); } -#if defined(OS_WIN) || defined(OS_LINUX) || defined(OS_CHROMEOS) -#if !defined(OS_ANDROID) +#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) +#if !BUILDFLAG(IS_ANDROID) TEST_F(CompositedSelectionBoundsTest, Input) { web_view_helper_.GetWebView()->GetSettings()->SetDefaultFontSize(16); RunTest("composited_selection_bounds_input.html"); @@ -9084,7 +9084,7 @@ } // Crashes on Android: http://crbug.com/403804 -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) TEST_F(WebFrameTest, DISABLED_PrintingBasic) #else TEST_F(WebFrameTest, PrintingBasic) @@ -13192,7 +13192,7 @@ RunPendingTasks(); // Verify that the right WidgetHost has been notified. -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS) EXPECT_EQ(0u, widget_host.VirtualKeyboardRequestCount()); #else EXPECT_LT(0u, widget_host.VirtualKeyboardRequestCount());
diff --git a/third_party/blink/renderer/core/frame/web_frame_widget_impl.cc b/third_party/blink/renderer/core/frame/web_frame_widget_impl.cc index 25e256a..9ffbdb8 100644 --- a/third_party/blink/renderer/core/frame/web_frame_widget_impl.cc +++ b/third_party/blink/renderer/core/frame/web_frame_widget_impl.cc
@@ -130,7 +130,7 @@ #include "ui/base/dragdrop/mojom/drag_drop_types.mojom-blink.h" #include "ui/gfx/geometry/point_conversions.h" -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) #include "third_party/blink/renderer/core/editing/substring_util.h" #include "third_party/blink/renderer/platform/fonts/mac/attributed_string_type_converter.h" #include "ui/base/mojom/attributed_string.mojom-blink.h" @@ -519,7 +519,7 @@ is_throttled, subtree_throttled, display_locked, /*recurse=*/true); } -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) void WebFrameWidgetImpl::GetStringAtPoint(const gfx::Point& point_in_local_root, GetStringAtPointCallback callback) { gfx::Point baseline_point; @@ -691,9 +691,9 @@ return result; } -#if !defined(OS_MAC) +#if !BUILDFLAG(IS_MAC) const WebInputEvent::Type kContextMenuKeyTriggeringEventType = -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) WebInputEvent::Type::kKeyUp; #else WebInputEvent::Type::kRawKeyDown; @@ -713,7 +713,7 @@ View()->SendContextMenuEvent(); return WebInputEventResult::kHandledSystem; } -#endif // !defined(OS_MAC) +#endif // !BUILDFLAG(IS_MAC) return WebInputEventResult::kNotHandled; } @@ -768,7 +768,7 @@ // Dispatch the contextmenu event regardless of if the click was swallowed. if (!GetPage()->GetSettings().GetShowContextMenuOnMouseUp()) { -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) if (event.button == WebMouseEvent::Button::kRight || (event.button == WebMouseEvent::Button::kLeft && event.GetModifiers() & WebMouseEvent::kControlKey)) @@ -3181,7 +3181,7 @@ const gfx::Vector2dF& accumulated_overscroll, const gfx::PointF& position, const gfx::Vector2dF& velocity) { -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) // On OSX the user can disable the elastic overscroll effect. If that's the // case, don't forward the overscroll notification. if (!widget_base_->LayerTreeHost()->GetSettings().enable_elastic_overscroll) @@ -3327,7 +3327,7 @@ } void WebFrameWidgetImpl::DidHandleGestureEvent(const WebGestureEvent& event) { -#if defined(OS_ANDROID) || defined(USE_AURA) +#if BUILDFLAG(IS_ANDROID) || defined(USE_AURA) if (event.GetType() == WebInputEvent::Type::kGestureTap) { widget_base_->ShowVirtualKeyboard(); } else if (event.GetType() == WebInputEvent::Type::kGestureLongPress) { @@ -3679,7 +3679,7 @@ widget_base_->DIPsToRoundedBlinkSpace(point_in_dips)); } -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) void WebFrameWidgetImpl::SelectAroundCaret( mojom::blink::SelectionGranularity granularity, bool should_show_handle,
diff --git a/third_party/blink/renderer/core/frame/web_frame_widget_impl.h b/third_party/blink/renderer/core/frame/web_frame_widget_impl.h index ad009f10..6efc0aa 100644 --- a/third_party/blink/renderer/core/frame/web_frame_widget_impl.h +++ b/third_party/blink/renderer/core/frame/web_frame_widget_impl.h
@@ -733,7 +733,7 @@ // Sets the inert bit on an out-of-process iframe, causing it to ignore // input. void SetIsInertForSubFrame(bool inert) override; -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) void GetStringAtPoint(const gfx::Point& point_in_local_root, GetStringAtPointCallback callback) override; #endif @@ -778,7 +778,7 @@ void ScrollFocusedEditableNodeIntoRect( const gfx::Rect& rect_in_dips) override; void MoveCaret(const gfx::Point& point_in_dips) override; -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) void SelectAroundCaret(mojom::blink::SelectionGranularity granularity, bool should_show_handle, bool should_show_context_menu,
diff --git a/third_party/blink/renderer/core/frame/web_frame_widget_test.cc b/third_party/blink/renderer/core/frame/web_frame_widget_test.cc index 8b49326..f0a2637e 100644 --- a/third_party/blink/renderer/core/frame/web_frame_widget_test.cc +++ b/third_party/blink/renderer/core/frame/web_frame_widget_test.cc
@@ -132,7 +132,7 @@ EXPECT_EQ(gfx::PointF(150.27, 150.25), point); } -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) TEST_F(WebFrameWidgetSimTest, ForceSendMetadataOnInput) { const cc::LayerTreeHost* layer_tree_host = WebView().MainFrameViewWidget()->LayerTreeHostForTesting(); @@ -145,7 +145,7 @@ EXPECT_TRUE( layer_tree_host->pending_commit_state()->force_send_metadata_request); } -#endif // defined(OS_ANDROID) +#endif // BUILDFLAG(IS_ANDROID) // A test that forces a RemoteMainFrame to be created. class WebFrameWidgetImplRemoteFrameSimTest : public SimTest {
diff --git a/third_party/blink/renderer/core/frame/web_local_frame_impl.cc b/third_party/blink/renderer/core/frame/web_local_frame_impl.cc index d4535bba..6945280 100644 --- a/third_party/blink/renderer/core/frame/web_local_frame_impl.cc +++ b/third_party/blink/renderer/core/frame/web_local_frame_impl.cc
@@ -109,7 +109,6 @@ #include "third_party/blink/public/mojom/portal/portal.mojom-blink.h" #include "third_party/blink/public/platform/interface_registry.h" #include "third_party/blink/public/platform/task_type.h" -#include "third_party/blink/public/platform/web_double_size.h" #include "third_party/blink/public/platform/web_isolated_world_info.h" #include "third_party/blink/public/platform/web_security_origin.h" #include "third_party/blink/public/platform/web_url_error.h" @@ -265,7 +264,7 @@ #include "third_party/blink/renderer/platform/wtf/casting.h" #include "third_party/blink/renderer/platform/wtf/hash_map.h" -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) #include "third_party/blink/public/web/win/web_font_family_names.h" #include "third_party/blink/renderer/core/layout/layout_font_accessor_win.h" #endif @@ -386,7 +385,7 @@ current_height += page_size_in_pixels.width() + 1; } -#if defined(OS_WIN) || defined(OS_MAC) +#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) // Account for the disabling of scaling in spoolPage. In the context of // SpoolAllPagesWithBoundariesForTesting the scale HAS NOT been // pre-applied. @@ -414,7 +413,7 @@ float scale = printed_page_width_ / page_rect.width(); AffineTransform transform; -#if defined(OS_POSIX) && !defined(OS_MAC) +#if BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_MAC) transform.Scale(scale); #endif transform.Translate(static_cast<float>(-page_rect.x()), @@ -672,7 +671,7 @@ return GetFrame()->LastActivationWasRestricted(); } -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) WebFontFamilyNames WebLocalFrameImpl::GetWebFontFamilyNames() const { FontFamilyNames font_family_names; GetFontsUsedByFrame(*GetFrame(), font_family_names); @@ -1370,7 +1369,7 @@ String text = GetFrame()->Selection().SelectedText( TextIteratorBehavior::EmitsObjectReplacementCharacterBehavior()); -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) ReplaceNewlinesWithWindowsStyleNewlines(text); #endif ReplaceNBSPWithSpace(text); @@ -2650,7 +2649,7 @@ params.selection_rect = LocalRootFrameWidget()->BlinkSpaceToEnclosedDIPs(data.selection_rect); -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) // The Samsung Email app relies on the context menu being shown after the // javascript onselectionchanged is triggered. // See crbug.com/729488
diff --git a/third_party/blink/renderer/core/frame/web_local_frame_impl.h b/third_party/blink/renderer/core/frame/web_local_frame_impl.h index 7a7b9ba..2264b68 100644 --- a/third_party/blink/renderer/core/frame/web_local_frame_impl.h +++ b/third_party/blink/renderer/core/frame/web_local_frame_impl.h
@@ -329,7 +329,7 @@ bool HasTransientUserActivation() override; bool ConsumeTransientUserActivation(UserActivationUpdateSource) override; bool LastActivationWasRestricted() const override; -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) WebFontFamilyNames GetWebFontFamilyNames() const override; #endif void SetTargetToCurrentHistoryItem(const WebString& target) override;
diff --git a/third_party/blink/renderer/core/html/canvas/canvas_async_blob_creator.cc b/third_party/blink/renderer/core/html/canvas/canvas_async_blob_creator.cc index 01bc6b9..8f1edab 100644 --- a/third_party/blink/renderer/core/html/canvas/canvas_async_blob_creator.cc +++ b/third_party/blink/renderer/core/html/canvas/canvas_async_blob_creator.cc
@@ -43,8 +43,8 @@ base::Microseconds(100); /* The value is based on user statistics on Nov 2017. */ -#if (defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_MAC) || \ - defined(OS_WIN)) +#if (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_MAC) || \ + BUILDFLAG(IS_WIN)) const double kIdleTaskStartTimeoutDelayMs = 1000.0; #else const double kIdleTaskStartTimeoutDelayMs = 4000.0; // For ChromeOS, Mobile @@ -53,7 +53,7 @@ /* The value is based on user statistics on May 2018. */ // We should be more lenient on completion timeout delay to ensure that the // switch from idle to main thread only happens to a minority of toBlob calls -#if !defined(OS_ANDROID) +#if !BUILDFLAG(IS_ANDROID) // Png image encoding on 4k by 4k canvas on Mac HDD takes 5.7+ seconds // We see that 99% users require less than 5 seconds. const double kIdleTaskCompleteTimeoutDelayMs = 5700.0;
diff --git a/third_party/blink/renderer/core/html/custom/custom_element_reaction.h b/third_party/blink/renderer/core/html/custom/custom_element_reaction.h index fb7af93f..08d2bef7 100644 --- a/third_party/blink/renderer/core/html/custom/custom_element_reaction.h +++ b/third_party/blink/renderer/core/html/custom/custom_element_reaction.h
@@ -6,7 +6,8 @@ #define THIRD_PARTY_BLINK_RENDERER_CORE_HTML_CUSTOM_CUSTOM_ELEMENT_REACTION_H_ #include "third_party/blink/renderer/core/core_export.h" -#include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" namespace blink {
diff --git a/third_party/blink/renderer/core/html/forms/chooser_resource_loader.cc b/third_party/blink/renderer/core/html/forms/chooser_resource_loader.cc index f2813d4..0ccd10f 100644 --- a/third_party/blink/renderer/core/html/forms/chooser_resource_loader.cc +++ b/third_party/blink/renderer/core/html/forms/chooser_resource_loader.cc
@@ -12,7 +12,7 @@ namespace blink { Vector<char> ChooserResourceLoader::GetSuggestionPickerStyleSheet() { -#if !defined(OS_ANDROID) +#if !BUILDFLAG(IS_ANDROID) return UncompressResourceAsBinary(IDR_SUGGESTION_PICKER_CSS); #else NOTREACHED(); @@ -21,7 +21,7 @@ } Vector<char> ChooserResourceLoader::GetSuggestionPickerJS() { -#if !defined(OS_ANDROID) +#if !BUILDFLAG(IS_ANDROID) return UncompressResourceAsBinary(IDR_SUGGESTION_PICKER_JS); #else NOTREACHED(); @@ -30,7 +30,7 @@ } Vector<char> ChooserResourceLoader::GetPickerCommonStyleSheet() { -#if !defined(OS_ANDROID) +#if !BUILDFLAG(IS_ANDROID) return UncompressResourceAsBinary(IDR_PICKER_COMMON_CSS); #else NOTREACHED(); @@ -39,7 +39,7 @@ } Vector<char> ChooserResourceLoader::GetPickerCommonJS() { -#if !defined(OS_ANDROID) +#if !BUILDFLAG(IS_ANDROID) return UncompressResourceAsBinary(IDR_PICKER_COMMON_JS); #else NOTREACHED(); @@ -48,7 +48,7 @@ } Vector<char> ChooserResourceLoader::GetCalendarPickerStyleSheet() { -#if !defined(OS_ANDROID) +#if !BUILDFLAG(IS_ANDROID) return UncompressResourceAsBinary(IDR_CALENDAR_PICKER_CSS); #else NOTREACHED(); @@ -57,7 +57,7 @@ } Vector<char> ChooserResourceLoader::GetCalendarPickerJS() { -#if !defined(OS_ANDROID) +#if !BUILDFLAG(IS_ANDROID) return UncompressResourceAsBinary(IDR_CALENDAR_PICKER_JS); #else NOTREACHED(); @@ -66,7 +66,7 @@ } Vector<char> ChooserResourceLoader::GetMonthPickerJS() { -#if !defined(OS_ANDROID) +#if !BUILDFLAG(IS_ANDROID) return UncompressResourceAsBinary(IDR_MONTH_PICKER_JS); #else NOTREACHED(); @@ -75,7 +75,7 @@ } Vector<char> ChooserResourceLoader::GetTimePickerStyleSheet() { -#if !defined(OS_ANDROID) +#if !BUILDFLAG(IS_ANDROID) return UncompressResourceAsBinary(IDR_TIME_PICKER_CSS); #else NOTREACHED(); @@ -84,7 +84,7 @@ } Vector<char> ChooserResourceLoader::GetTimePickerJS() { -#if !defined(OS_ANDROID) +#if !BUILDFLAG(IS_ANDROID) return UncompressResourceAsBinary(IDR_TIME_PICKER_JS); #else NOTREACHED(); @@ -93,7 +93,7 @@ } Vector<char> ChooserResourceLoader::GetDateTimeLocalPickerJS() { -#if !defined(OS_ANDROID) +#if !BUILDFLAG(IS_ANDROID) return UncompressResourceAsBinary(IDR_DATETIMELOCAL_PICKER_JS); #else NOTREACHED(); @@ -102,7 +102,7 @@ } Vector<char> ChooserResourceLoader::GetColorSuggestionPickerStyleSheet() { -#if !defined(OS_ANDROID) +#if !BUILDFLAG(IS_ANDROID) return UncompressResourceAsBinary(IDR_COLOR_SUGGESTION_PICKER_CSS); #else NOTREACHED(); @@ -111,7 +111,7 @@ } Vector<char> ChooserResourceLoader::GetColorSuggestionPickerJS() { -#if !defined(OS_ANDROID) +#if !BUILDFLAG(IS_ANDROID) return UncompressResourceAsBinary(IDR_COLOR_SUGGESTION_PICKER_JS); #else NOTREACHED(); @@ -120,7 +120,7 @@ } Vector<char> ChooserResourceLoader::GetColorPickerStyleSheet() { -#if !defined(OS_ANDROID) +#if !BUILDFLAG(IS_ANDROID) return UncompressResourceAsBinary(IDR_COLOR_PICKER_CSS); #else NOTREACHED(); @@ -129,7 +129,7 @@ } Vector<char> ChooserResourceLoader::GetColorPickerJS() { -#if !defined(OS_ANDROID) +#if !BUILDFLAG(IS_ANDROID) return UncompressResourceAsBinary(IDR_COLOR_PICKER_JS); #else NOTREACHED(); @@ -138,7 +138,7 @@ } Vector<char> ChooserResourceLoader::GetColorPickerCommonJS() { -#if !defined(OS_ANDROID) +#if !BUILDFLAG(IS_ANDROID) return UncompressResourceAsBinary(IDR_COLOR_PICKER_COMMON_JS); #else NOTREACHED(); @@ -147,7 +147,7 @@ } Vector<char> ChooserResourceLoader::GetListPickerStyleSheet() { -#if !defined(OS_ANDROID) +#if !BUILDFLAG(IS_ANDROID) return UncompressResourceAsBinary(IDR_LIST_PICKER_CSS); #else NOTREACHED(); @@ -156,7 +156,7 @@ } Vector<char> ChooserResourceLoader::GetListPickerJS() { -#if !defined(OS_ANDROID) +#if !BUILDFLAG(IS_ANDROID) return UncompressResourceAsBinary(IDR_LIST_PICKER_JS); #else NOTREACHED();
diff --git a/third_party/blink/renderer/core/html/forms/color_chooser_popup_ui_controller.cc b/third_party/blink/renderer/core/html/forms/color_chooser_popup_ui_controller.cc index e91b44bb..18643d09 100644 --- a/third_party/blink/renderer/core/html/forms/color_chooser_popup_ui_controller.cc +++ b/third_party/blink/renderer/core/html/forms/color_chooser_popup_ui_controller.cc
@@ -111,13 +111,13 @@ AddProperty("zoomFactor", ScaledZoomFactor(), data); AddProperty("shouldShowColorSuggestionPicker", false, data); AddProperty("isEyeDropperEnabled", ::features::IsEyeDropperEnabled(), data); -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) AddProperty("isBorderTransparent", true, data); #endif // We don't create PagePopups on Android, so these strings are excluded // from blink_strings.grd on Android to save binary size. We have to // exclude them here as well to avoid an Android build break. -#if !defined(OS_ANDROID) +#if !BUILDFLAG(IS_ANDROID) AddLocalizedProperty("axColorWellLabel", IDS_AX_COLOR_WELL, data); AddLocalizedProperty("axColorWellRoleDescription", IDS_AX_COLOR_WELL_ROLEDESCRIPTION, data); @@ -176,7 +176,7 @@ AddProperty("zoomFactor", ScaledZoomFactor(), data); AddProperty("shouldShowColorSuggestionPicker", true, data); AddProperty("isEyeDropperEnabled", ::features::IsEyeDropperEnabled(), data); -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) AddProperty("isBorderTransparent", true, data); #endif PagePopupClient::AddString("};\n", data);
diff --git a/third_party/blink/renderer/core/html/forms/color_chooser_ui_controller.cc b/third_party/blink/renderer/core/html/forms/color_chooser_ui_controller.cc index e779fe1..543dd199 100644 --- a/third_party/blink/renderer/core/html/forms/color_chooser_ui_controller.cc +++ b/third_party/blink/renderer/core/html/forms/color_chooser_ui_controller.cc
@@ -53,7 +53,7 @@ } void ColorChooserUIController::OpenUI() { -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) OpenColorChooser(); #else NOTREACHED() << "ColorChooserUIController should only be used on Android"; @@ -79,7 +79,7 @@ client_->DidChooseColor(color); } -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) void ColorChooserUIController::OpenColorChooser() { DCHECK(!chooser_); frame_->GetBrowserInterfaceBroker().GetInterface(
diff --git a/third_party/blink/renderer/core/html/forms/color_chooser_ui_controller.h b/third_party/blink/renderer/core/html/forms/color_chooser_ui_controller.h index c1b34bb3..0dc76847 100644 --- a/third_party/blink/renderer/core/html/forms/color_chooser_ui_controller.h +++ b/third_party/blink/renderer/core/html/forms/color_chooser_ui_controller.h
@@ -63,7 +63,7 @@ void DidChooseColor(uint32_t color) final; protected: -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) void OpenColorChooser(); #endif mojo::Remote<mojom::blink::ColorChooser> chooser_;
diff --git a/third_party/blink/renderer/core/html/forms/date_time_chooser_impl.cc b/third_party/blink/renderer/core/html/forms/date_time_chooser_impl.cc index 87e8ac3..93d448fc 100644 --- a/third_party/blink/renderer/core/html/forms/date_time_chooser_impl.cc +++ b/third_party/blink/renderer/core/html/forms/date_time_chooser_impl.cc
@@ -177,7 +177,7 @@ AddProperty("ampmLabels", locale_->TimeAMPMLabels(), data); AddProperty("isLocaleRTL", locale_->IsRTL(), data); AddProperty("isRTL", parameters_->is_anchor_element_rtl, data); -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) AddProperty("isBorderTransparent", true, data); #endif AddProperty("mode", parameters_->type.GetString(), data);
diff --git a/third_party/blink/renderer/core/html/forms/date_time_chooser_impl.h b/third_party/blink/renderer/core/html/forms/date_time_chooser_impl.h index 698916d..c95e32a 100644 --- a/third_party/blink/renderer/core/html/forms/date_time_chooser_impl.h +++ b/third_party/blink/renderer/core/html/forms/date_time_chooser_impl.h
@@ -35,6 +35,8 @@ #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/core/html/forms/date_time_chooser.h" #include "third_party/blink/renderer/core/page/page_popup_client.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" namespace blink {
diff --git a/third_party/blink/renderer/core/html/forms/external_popup_menu.cc b/third_party/blink/renderer/core/html/forms/external_popup_menu.cc index e49235b..0a77381 100644 --- a/third_party/blink/renderer/core/html/forms/external_popup_menu.cc +++ b/third_party/blink/renderer/core/html/forms/external_popup_menu.cc
@@ -151,7 +151,7 @@ void ExternalPopupMenu::Show(PopupMenu::ShowEventType) { if (!ShowInternal()) return; -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) const WebInputEvent* current_event = CurrentInputEvent::Get(); if (current_event && current_event->GetType() == WebInputEvent::Type::kMouseDown) {
diff --git a/third_party/blink/renderer/core/html/forms/input_type_view.h b/third_party/blink/renderer/core/html/forms/input_type_view.h index 43099194..6195c15 100644 --- a/third_party/blink/renderer/core/html/forms/input_type_view.h +++ b/third_party/blink/renderer/core/html/forms/input_type_view.h
@@ -37,7 +37,8 @@ #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/core/dom/events/event_dispatcher.h" #include "third_party/blink/renderer/core/dom/events/simulated_click_options.h" -#include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" #include "third_party/blink/renderer/platform/text/text_direction.h" #include "third_party/blink/renderer/platform/wtf/allocator/allocator.h" #include "third_party/blink/renderer/platform/wtf/forward.h"
diff --git a/third_party/blink/renderer/core/html/forms/internal_popup_menu.cc b/third_party/blink/renderer/core/html/forms/internal_popup_menu.cc index c9849ff..ede9cec 100644 --- a/third_party/blink/renderer/core/html/forms/internal_popup_menu.cc +++ b/third_party/blink/renderer/core/html/forms/internal_popup_menu.cc
@@ -159,7 +159,7 @@ is_in_group_(false), buffer_(buffer) { DCHECK(buffer_); -#if defined(OS_LINUX) || defined(OS_CHROMEOS) +#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) // On other platforms, the <option> background color is the same as the // <select> background color. On Linux, that makes the <option> // background color very dark, so by default, try to use a lighter
diff --git a/third_party/blink/renderer/core/html/forms/internal_popup_menu_test.cc b/third_party/blink/renderer/core/html/forms/internal_popup_menu_test.cc index 924d163..f77c31c7 100644 --- a/third_party/blink/renderer/core/html/forms/internal_popup_menu_test.cc +++ b/third_party/blink/renderer/core/html/forms/internal_popup_menu_test.cc
@@ -20,7 +20,7 @@ // InternalPopupMenuTest is not used on Android, and its Platform implementation // does not provide the resources (as in GetDataResource) needed by // InternalPopupMenu::WriteDocument. -#if !defined(OS_ANDROID) +#if !BUILDFLAG(IS_ANDROID) TEST(InternalPopupMenuTest, ShowSelectDisplayNone) { auto dummy_page_holder_ = @@ -48,6 +48,6 @@ menu->Show(PopupMenu::kOther); } -#endif // defined(OS_ANDROID) +#endif // !BUILDFLAG(IS_ANDROID) } // namespace blink
diff --git a/third_party/blink/renderer/core/html/forms/select_type.cc b/third_party/blink/renderer/core/html/forms/select_type.cc index 6261192..e87e314 100644 --- a/third_party/blink/renderer/core/html/forms/select_type.cc +++ b/third_party/blink/renderer/core/html/forms/select_type.cc
@@ -730,7 +730,7 @@ // Convert to coords relative to the list box if needed. if (HTMLOptionElement* option = EventTargetOption(*mouse_event)) { if (!option->IsDisabledFormControl()) { -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) const bool meta_or_ctrl = mouse_event->metaKey(); #else const bool meta_or_ctrl = mouse_event->ctrlKey(); @@ -866,7 +866,7 @@ } bool is_control_key = false; -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) is_control_key = keyboard_event->metaKey(); #else is_control_key = keyboard_event->ctrlKey();
diff --git a/third_party/blink/renderer/core/html/image_document_test.cc b/third_party/blink/renderer/core/html/image_document_test.cc index b5f1b3a..5606346 100644 --- a/third_party/blink/renderer/core/html/image_document_test.cc +++ b/third_party/blink/renderer/core/html/image_document_test.cc
@@ -244,7 +244,7 @@ blink::test::RunPendingTasks(); } -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) #define MAYBE(test) DISABLED_##test #else #define MAYBE(test) test
diff --git a/third_party/blink/renderer/core/html/link_resource.h b/third_party/blink/renderer/core/html/link_resource.h index e5978df..bbad4499 100644 --- a/third_party/blink/renderer/core/html/link_resource.h +++ b/third_party/blink/renderer/core/html/link_resource.h
@@ -32,7 +32,8 @@ #define THIRD_PARTY_BLINK_RENDERER_CORE_HTML_LINK_RESOURCE_H_ #include "third_party/blink/renderer/core/core_export.h" -#include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" #include "third_party/blink/renderer/platform/wtf/text/text_encoding.h" namespace blink {
diff --git a/third_party/blink/renderer/core/html/link_web_bundle.h b/third_party/blink/renderer/core/html/link_web_bundle.h index afa6b44..a954108 100644 --- a/third_party/blink/renderer/core/html/link_web_bundle.h +++ b/third_party/blink/renderer/core/html/link_web_bundle.h
@@ -9,6 +9,8 @@ #include "services/network/public/mojom/url_loader_factory.mojom-blink.h" #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/core/html/link_resource.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" #include "third_party/blink/renderer/platform/loader/fetch/subresource_web_bundle.h" #include "third_party/blink/renderer/platform/weborigin/kurl.h"
diff --git a/third_party/blink/renderer/core/html/media/media_controls.h b/third_party/blink/renderer/core/html/media/media_controls.h index 955dcbe..899a156d 100644 --- a/third_party/blink/renderer/core/html/media/media_controls.h +++ b/third_party/blink/renderer/core/html/media/media_controls.h
@@ -6,8 +6,8 @@ #define THIRD_PARTY_BLINK_RENDERER_CORE_HTML_MEDIA_MEDIA_CONTROLS_H_ #include "third_party/blink/renderer/core/core_export.h" -#include "third_party/blink/renderer/platform/heap/handle.h" -#include "third_party/blink/renderer/platform/heap/visitor.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" namespace blink {
diff --git a/third_party/blink/renderer/core/html/parser/html_parser_metrics_test.cc b/third_party/blink/renderer/core/html/parser/html_parser_metrics_test.cc index 20ac9995..cc0baf9 100644 --- a/third_party/blink/renderer/core/html/parser/html_parser_metrics_test.cc +++ b/third_party/blink/renderer/core/html/parser/html_parser_metrics_test.cc
@@ -119,7 +119,7 @@ EXPECT_GT(parsing_time_total_buckets[0].min, 0); } -#if defined(OS_MAC) && defined(ARCH_CPU_ARM64) +#if BUILDFLAG(IS_MAC) && defined(ARCH_CPU_ARM64) // https://crbug.com/1222653 #define MAYBE_HistogramReportsTwoChunks DISABLED_HistogramReportsTwoChunks #else @@ -205,7 +205,7 @@ EXPECT_GT(yield_time_average_buckets[0].min, 0); } -#if defined(OS_MAC) && defined(ARCH_CPU_ARM64) +#if BUILDFLAG(IS_MAC) && defined(ARCH_CPU_ARM64) // https://crbug.com/1222653 #define MAYBE_ReportSingleChunk DISABLED_ReportSingleChunk #else
diff --git a/third_party/blink/renderer/core/html/parser/html_parser_scheduler.h b/third_party/blink/renderer/core/html/parser/html_parser_scheduler.h index 2b99994f..7244963 100644 --- a/third_party/blink/renderer/core/html/parser/html_parser_scheduler.h +++ b/third_party/blink/renderer/core/html/parser/html_parser_scheduler.h
@@ -30,6 +30,8 @@ #include "base/task/single_thread_task_runner.h" #include "base/timer/elapsed_timer.h" #include "third_party/blink/renderer/core/html/parser/nesting_level_incrementer.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" #include "third_party/blink/renderer/platform/scheduler/public/post_cancellable_task.h" #include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
diff --git a/third_party/blink/renderer/core/html/parser/html_srcset_parser_test.cc b/third_party/blink/renderer/core/html/parser/html_srcset_parser_test.cc index eb2cf141f..9094f8e 100644 --- a/third_party/blink/renderer/core/html/parser/html_srcset_parser_test.cc +++ b/third_party/blink/renderer/core/html/parser/html_srcset_parser_test.cc
@@ -179,7 +179,7 @@ } } -#if defined(OS_ANDROID) && defined(ADDRESS_SANITIZER) +#if BUILDFLAG(IS_ANDROID) && defined(ADDRESS_SANITIZER) // https://crbug.com/1189511 #define MAYBE_SaveDataEnabledBasic DISABLED_SaveDataEnabledBasic #else
diff --git a/third_party/blink/renderer/core/html/track/automatic_track_selection.h b/third_party/blink/renderer/core/html/track/automatic_track_selection.h index 5d02a62..3004d8e0 100644 --- a/third_party/blink/renderer/core/html/track/automatic_track_selection.h +++ b/third_party/blink/renderer/core/html/track/automatic_track_selection.h
@@ -6,8 +6,8 @@ #define THIRD_PARTY_BLINK_RENDERER_CORE_HTML_TRACK_AUTOMATIC_TRACK_SELECTION_H_ #include "third_party/blink/renderer/core/html/track/text_track_kind_user_preference.h" -#include "third_party/blink/renderer/platform/heap/handle.h" #include "third_party/blink/renderer/platform/wtf/allocator/allocator.h" +#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h" namespace blink {
diff --git a/third_party/blink/renderer/core/imagebitmap/image_bitmap_test.cc b/third_party/blink/renderer/core/imagebitmap/image_bitmap_test.cc index 24c0997e..80ca735 100644 --- a/third_party/blink/renderer/core/imagebitmap/image_bitmap_test.cc +++ b/third_party/blink/renderer/core/imagebitmap/image_bitmap_test.cc
@@ -315,7 +315,7 @@ // This test is failing on asan-clang-phone because memory allocation is // declined. See <http://crbug.com/782286>. // See <http://crbug.com/1090252>, test is flaky in fuchsia. -#if defined(OS_ANDROID) || defined(OS_FUCHSIA) +#if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_FUCHSIA) #define MAYBE_CreateImageBitmapFromTooBigImageDataDoesNotCrash \ DISABLED_CreateImageBitmapFromTooBigImageDataDoesNotCrash #else
diff --git a/third_party/blink/renderer/core/input/event_handler_test.cc b/third_party/blink/renderer/core/input/event_handler_test.cc index 6e4fdad3..6d3f7b62 100644 --- a/third_party/blink/renderer/core/input/event_handler_test.cc +++ b/third_party/blink/renderer/core/input/event_handler_test.cc
@@ -1164,7 +1164,7 @@ } // macOS doesn't have keyboard-triggered tooltips. -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) #define MAYBE_FocusSetFromTabUpdatesTooltip \ DISABLED_FocusSetFromTabUpdatesTooltip #else @@ -1202,7 +1202,7 @@ } // macOS doesn't have keyboard-triggered tooltips. -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) #define MAYBE_FocusSetFromAccessKeyUpdatesTooltip \ DISABLED_FocusSetFromAccessKeyUpdatesTooltip #else @@ -1231,7 +1231,7 @@ } // macOS doesn't have keyboard-triggered tooltips. -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) #define MAYBE_FocusSetFromMouseDoesntUpdateTooltip \ DISABLED_FocusSetFromMouseDoesntUpdateTooltip #else @@ -1265,7 +1265,7 @@ } // macOS doesn't have keyboard-triggered tooltips. -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) #define MAYBE_FocusSetFromScriptDoesntUpdateTooltip \ DISABLED_FocusSetFromScriptDoesntUpdateTooltip #else @@ -1291,7 +1291,7 @@ } // macOS doesn't have keyboard-triggered tooltips. -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) #define MAYBE_FocusSetScriptInitiatedFromKeypressUpdatesTooltip \ DISABLED_FocusSetScriptInitiatedFromKeypressUpdatesTooltip #else @@ -1359,7 +1359,7 @@ } // macOS doesn't have keyboard-triggered tooltips. -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) #define MAYBE_FocusSetFromScriptClearsKeyboardTriggeredTooltip \ DISABLED_FocusSetFromScriptClearsKeyboardTriggeredTooltip #else @@ -1684,7 +1684,7 @@ } // https://crbug.com/976557 tracks the fix for re-enabling this test on Mac. -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) #define MAYBE_GestureTapWithScrollSnaps DISABLED_GestureTapWithScrollSnaps #else #define MAYBE_GestureTapWithScrollSnaps GestureTapWithScrollSnaps
diff --git a/third_party/blink/renderer/core/input/keyboard_event_manager.cc b/third_party/blink/renderer/core/input/keyboard_event_manager.cc index 89b82c7..68bc8dc 100644 --- a/third_party/blink/renderer/core/input/keyboard_event_manager.cc +++ b/third_party/blink/renderer/core/input/keyboard_event_manager.cc
@@ -37,9 +37,9 @@ #include "third_party/blink/renderer/platform/windows_keyboard_codes.h" #include "ui/events/keycodes/dom/keycode_converter.h" -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) #include <windows.h> -#elif defined(OS_MAC) +#elif BUILDFLAG(IS_MAC) #import <Carbon/Carbon.h> #endif @@ -324,7 +324,7 @@ if (!node) return WebInputEventResult::kNotHandled; -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) // According to NSEvents.h, OpenStep reserves the range 0xF700-0xF8FF for // function keys. However, some actual private use characters happen to be // in this range, e.g. the Apple logo (Option+Shift+K). 0xF7FF is an @@ -479,7 +479,7 @@ return; } -#if !defined(OS_MAC) +#if !BUILDFLAG(IS_MAC) // Option-Tab is a shortcut based on a system-wide preference on Mac but // should be ignored on all other platforms. if (event->altKey()) { @@ -586,7 +586,7 @@ bool KeyboardEventManager::CurrentCapsLockState() { switch (g_override_caps_lock_state) { case OverrideCapsLockState::kDefault: -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) return GetCurrentKeyModifiers() & alphaLock; #else // Caps lock state use is limited to Mac password input @@ -602,7 +602,7 @@ } WebInputEvent::Modifiers KeyboardEventManager::GetCurrentModifierState() { -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) unsigned modifiers = 0; UInt32 current_modifiers = GetCurrentKeyModifiers(); if (current_modifiers & ::shiftKey)
diff --git a/third_party/blink/renderer/core/input/keyboard_event_manager.h b/third_party/blink/renderer/core/input/keyboard_event_manager.h index aef768c..0587b5e 100644 --- a/third_party/blink/renderer/core/input/keyboard_event_manager.h +++ b/third_party/blink/renderer/core/input/keyboard_event_manager.h
@@ -9,8 +9,8 @@ #include "third_party/blink/public/common/input/web_input_event.h" #include "third_party/blink/public/platform/web_input_event_result.h" #include "third_party/blink/renderer/core/core_export.h" -#include "third_party/blink/renderer/platform/heap/handle.h" -#include "third_party/blink/renderer/platform/heap/visitor.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" #include "third_party/blink/renderer/platform/wtf/allocator/allocator.h" namespace blink { @@ -28,7 +28,7 @@ public: static const int kAccessKeyModifiers = // TODO(crbug.com/618397): Add a settings to control this behavior. -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) WebInputEvent::kControlKey | WebInputEvent::kAltKey; #else WebInputEvent::kAltKey;
diff --git a/third_party/blink/renderer/core/input/mouse_event_manager.cc b/third_party/blink/renderer/core/input/mouse_event_manager.cc index c88d112..c7da1c8b 100644 --- a/third_party/blink/renderer/core/input/mouse_event_manager.cc +++ b/third_party/blink/renderer/core/input/mouse_event_manager.cc
@@ -130,7 +130,7 @@ } // TODO(crbug.com/653490): Read these values from the OS. -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) const int kDragThresholdX = 3; const int kDragThresholdY = 3; constexpr base::TimeDelta kTextDragDelay = base::Seconds(0.15); @@ -348,7 +348,7 @@ // We only prevent click event when the click may cause contextmenu to popup. // However, we always send auxclick. bool context_menu_event = false; -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) // FIXME: The Mac port achieves the same behavior by checking whether the // context menu is currently open in WebPage::mouseEvent(). Consider merging // the implementations. @@ -826,7 +826,7 @@ // We disable the drag and drop actions on pen input on windows. bool should_handle_drag = true; -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) should_handle_drag = !is_pen; #endif
diff --git a/third_party/blink/renderer/core/inspector/dom_editor.h b/third_party/blink/renderer/core/inspector/dom_editor.h index c1dabaf..99e2ffb 100644 --- a/third_party/blink/renderer/core/inspector/dom_editor.h +++ b/third_party/blink/renderer/core/inspector/dom_editor.h
@@ -32,7 +32,8 @@ #define THIRD_PARTY_BLINK_RENDERER_CORE_INSPECTOR_DOM_EDITOR_H_ #include "third_party/blink/renderer/core/inspector/protocol/forward.h" -#include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" namespace blink {
diff --git a/third_party/blink/renderer/core/inspector/inspected_frames.h b/third_party/blink/renderer/core/inspector/inspected_frames.h index 71c2e61..b6541df 100644 --- a/third_party/blink/renderer/core/inspector/inspected_frames.h +++ b/third_party/blink/renderer/core/inspector/inspected_frames.h
@@ -6,7 +6,8 @@ #define THIRD_PARTY_BLINK_RENDERER_CORE_INSPECTOR_INSPECTED_FRAMES_H_ #include "third_party/blink/renderer/core/core_export.h" -#include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" #include "third_party/blink/renderer/platform/wtf/forward.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
diff --git a/third_party/blink/renderer/core/inspector/inspector_media_context_impl.h b/third_party/blink/renderer/core/inspector/inspector_media_context_impl.h index 6fe4613..2cc8107b 100644 --- a/third_party/blink/renderer/core/inspector/inspector_media_context_impl.h +++ b/third_party/blink/renderer/core/inspector/inspector_media_context_impl.h
@@ -14,7 +14,7 @@ namespace blink { -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) // Players are cached per tab. constexpr int kMaxCachedPlayerEvents = 128; #else
diff --git a/third_party/blink/renderer/core/inspector/inspector_memory_agent.cc b/third_party/blink/renderer/core/inspector/inspector_memory_agent.cc index 04e97ce..e50731fd 100644 --- a/third_party/blink/renderer/core/inspector/inspector_memory_agent.cc +++ b/third_party/blink/renderer/core/inspector/inspector_memory_agent.cc
@@ -186,7 +186,7 @@ Vector<String> InspectorMemoryAgent::Symbolize( const WebVector<void*>& addresses) { -#if defined(OS_LINUX) || defined(OS_CHROMEOS) +#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) // TODO(alph): Move symbolization to the client. Vector<void*> addresses_to_symbolize; for (size_t i = 0; i < addresses.size(); i++) {
diff --git a/third_party/blink/renderer/core/inspector/inspector_network_agent.cc b/third_party/blink/renderer/core/inspector/inspector_network_agent.cc index 6760c97..c48a704 100644 --- a/third_party/blink/renderer/core/inspector/inspector_network_agent.cc +++ b/third_party/blink/renderer/core/inspector/inspector_network_agent.cc
@@ -114,7 +114,7 @@ namespace { -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) constexpr int kDefaultTotalBufferSize = 10 * 1000 * 1000; // 10 MB constexpr int kDefaultResourceBufferSize = 5 * 1000 * 1000; // 5 MB #else
diff --git a/third_party/blink/renderer/core/inspector/inspector_overlay_agent.cc b/third_party/blink/renderer/core/inspector/inspector_overlay_agent.cc index c09bc8a..8c22319 100644 --- a/third_party/blink/renderer/core/inspector/inspector_overlay_agent.cc +++ b/third_party/blink/renderer/core/inspector/inspector_overlay_agent.cc
@@ -1239,11 +1239,11 @@ V8AtomicString(isolate, "InspectorOverlayHost"), overlay_host_obj) .ToChecked(); -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) EvaluateInOverlay("setPlatform", "windows"); -#elif defined(OS_MAC) +#elif BUILDFLAG(IS_MAC) EvaluateInOverlay("setPlatform", "mac"); -#elif defined(OS_POSIX) +#elif BUILDFLAG(IS_POSIX) EvaluateInOverlay("setPlatform", "linux"); #else EvaluateInOverlay("setPlatform", "other");
diff --git a/third_party/blink/renderer/core/inspector/inspector_page_agent.cc b/third_party/blink/renderer/core/inspector/inspector_page_agent.cc index d7b26eeb..aea7f92 100644 --- a/third_party/blink/renderer/core/inspector/inspector_page_agent.cc +++ b/third_party/blink/renderer/core/inspector/inspector_page_agent.cc
@@ -1076,7 +1076,7 @@ void InspectorPageAgent::DidResizeMainFrame() { if (!inspected_frames_->Root()->IsMainFrame()) return; -#if !defined(OS_ANDROID) +#if !BUILDFLAG(IS_ANDROID) PageLayoutInvalidated(true); #endif GetFrontend()->frameResized();
diff --git a/third_party/blink/renderer/core/inspector/inspector_performance_agent.cc b/third_party/blink/renderer/core/inspector/inspector_performance_agent.cc index 4621b31..b393f15 100644 --- a/third_party/blink/renderer/core/inspector/inspector_performance_agent.cc +++ b/third_party/blink/renderer/core/inspector/inspector_performance_agent.cc
@@ -41,7 +41,7 @@ std::unique_ptr<base::ProcessMetrics> GetCurrentProcessMetrics() { base::ProcessHandle handle = base::Process::Current().Handle(); -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) // Port provider can be null if querying the current process. return base::ProcessMetrics::CreateProcessMetrics(handle, nullptr); #else
diff --git a/third_party/blink/renderer/core/intersection_observer/intersection_observer_entry.h b/third_party/blink/renderer/core/intersection_observer/intersection_observer_entry.h index e48cb64..e20327b 100644 --- a/third_party/blink/renderer/core/intersection_observer/intersection_observer_entry.h +++ b/third_party/blink/renderer/core/intersection_observer/intersection_observer_entry.h
@@ -8,7 +8,8 @@ #include "third_party/blink/renderer/core/dom/dom_high_res_time_stamp.h" #include "third_party/blink/renderer/core/intersection_observer/intersection_geometry.h" #include "third_party/blink/renderer/platform/bindings/script_wrappable.h" -#include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" #include "ui/gfx/geometry/rect.h" namespace blink {
diff --git a/third_party/blink/renderer/core/layout/counter_node.h b/third_party/blink/renderer/core/layout/counter_node.h index 0921378d..69132fc 100644 --- a/third_party/blink/renderer/core/layout/counter_node.h +++ b/third_party/blink/renderer/core/layout/counter_node.h
@@ -23,7 +23,8 @@ #define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_COUNTER_NODE_H_ #include "base/dcheck_is_on.h" -#include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" #include "third_party/blink/renderer/platform/wtf/allocator/allocator.h" #include "third_party/blink/renderer/platform/wtf/forward.h" #include "third_party/blink/renderer/platform/wtf/ref_counted.h"
diff --git a/third_party/blink/renderer/core/layout/hit_test_request.h b/third_party/blink/renderer/core/layout/hit_test_request.h index 95ee04a..be56667 100644 --- a/third_party/blink/renderer/core/layout/hit_test_request.h +++ b/third_party/blink/renderer/core/layout/hit_test_request.h
@@ -23,7 +23,8 @@ #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_HIT_TEST_REQUEST_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_HIT_TEST_REQUEST_H_ -#include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" #include "third_party/blink/renderer/platform/wtf/allocator/allocator.h" namespace blink {
diff --git a/third_party/blink/renderer/core/layout/layout_block_flow_line.cc b/third_party/blink/renderer/core/layout/layout_block_flow_line.cc index e0d23d7..e75fa66 100644 --- a/third_party/blink/renderer/core/layout/layout_block_flow_line.cc +++ b/third_party/blink/renderer/core/layout/layout_block_flow_line.cc
@@ -558,7 +558,7 @@ bool kerning_is_enabled = font.GetFontDescription().GetTypesettingFeatures() & kKerning; -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) // FIXME: Having any font feature settings enabled can lead to selection gaps // on Chromium-mac. https://bugs.webkit.org/show_bug.cgi?id=113418 bool can_use_cached_word_measurements =
diff --git a/third_party/blink/renderer/core/layout/layout_object_child_list.h b/third_party/blink/renderer/core/layout/layout_object_child_list.h index df58b9a..2f740d8 100644 --- a/third_party/blink/renderer/core/layout/layout_object_child_list.h +++ b/third_party/blink/renderer/core/layout/layout_object_child_list.h
@@ -26,7 +26,8 @@ #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_LAYOUT_OBJECT_CHILD_LIST_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_LAYOUT_OBJECT_CHILD_LIST_H_ -#include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" #include "third_party/blink/renderer/platform/wtf/forward.h" namespace blink {
diff --git a/third_party/blink/renderer/core/layout/layout_state.h b/third_party/blink/renderer/core/layout/layout_state.h index 0c894cb..61a0b4f 100644 --- a/third_party/blink/renderer/core/layout/layout_state.h +++ b/third_party/blink/renderer/core/layout/layout_state.h
@@ -27,7 +27,8 @@ #define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_LAYOUT_STATE_H_ #include "third_party/blink/renderer/platform/geometry/layout_rect.h" -#include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" #include "third_party/blink/renderer/platform/wtf/allocator/allocator.h" #include "third_party/blink/renderer/platform/wtf/hash_map.h" #include "third_party/blink/renderer/platform/wtf/text/atomic_string.h"
diff --git a/third_party/blink/renderer/core/layout/layout_table_cell_test.cc b/third_party/blink/renderer/core/layout/layout_table_cell_test.cc index 49ca8a8..ba95226 100644 --- a/third_party/blink/renderer/core/layout/layout_table_cell_test.cc +++ b/third_party/blink/renderer/core/layout/layout_table_cell_test.cc
@@ -65,7 +65,7 @@ } // Death tests don't work properly on Android. -#if defined(GTEST_HAS_DEATH_TEST) && !defined(OS_ANDROID) +#if defined(GTEST_HAS_DEATH_TEST) && !BUILDFLAG(IS_ANDROID) TEST_F(LayoutTableCellDeathTest, CrashIfColumnOverflowOnSetting) { ASSERT_DEATH(cell_->SetAbsoluteColumnIndex(kMaxColumnIndex + 1), "");
diff --git a/third_party/blink/renderer/core/layout/layout_table_row_test.cc b/third_party/blink/renderer/core/layout/layout_table_row_test.cc index fde971c..e2ddc5a 100644 --- a/third_party/blink/renderer/core/layout/layout_table_row_test.cc +++ b/third_party/blink/renderer/core/layout/layout_table_row_test.cc
@@ -56,7 +56,7 @@ } // Death tests don't work properly on Android. -#if defined(GTEST_HAS_DEATH_TEST) && !defined(OS_ANDROID) +#if defined(GTEST_HAS_DEATH_TEST) && !BUILDFLAG(IS_ANDROID) TEST_F(LayoutTableRowDeathTest, CrashIfRowOverflowOnSetting) { ASSERT_DEATH(row_->SetRowIndex(kMaxRowIndex + 1), "");
diff --git a/third_party/blink/renderer/core/layout/layout_text_test.cc b/third_party/blink/renderer/core/layout/layout_text_test.cc index 73152089e..c047961 100644 --- a/third_party/blink/renderer/core/layout/layout_text_test.cc +++ b/third_party/blink/renderer/core/layout/layout_text_test.cc
@@ -221,7 +221,7 @@ GetBasicText()->ContainsOnlyWhitespaceOrNbsp()); } -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) TEST_F(LayoutTextTest, PrewarmFamily) { base::test::ScopedFeatureList features(kAsyncFontAccess); test::ScopedTestFontPrewarmer prewarmer;
diff --git a/third_party/blink/renderer/core/layout/layout_theme.cc b/third_party/blink/renderer/core/layout/layout_theme.cc index 770c4aa..8355bf3 100644 --- a/third_party/blink/renderer/core/layout/layout_theme.cc +++ b/third_party/blink/renderer/core/layout/layout_theme.cc
@@ -103,7 +103,7 @@ type == input_type_names::kDatetimeLocal || type == input_type_names::kMonth || type == input_type_names::kTime || type == input_type_names::kWeek) { -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) return kMenulistPart; #else return kTextFieldPart; @@ -303,7 +303,7 @@ Color LayoutTheme::ActiveSelectionBackgroundColor( mojom::blink::ColorScheme color_scheme) const { Color color = PlatformActiveSelectionBackgroundColor(color_scheme); -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) // BlendWithWhite() darkens Mac system colors too much. // Apply .8 (204/255) alpha instead, same as Safari. if (color_scheme == mojom::blink::ColorScheme::kDark)
diff --git a/third_party/blink/renderer/core/layout/layout_theme_test.cc b/third_party/blink/renderer/core/layout/layout_theme_test.cc index b540de3..bff8cf9 100644 --- a/third_party/blink/renderer/core/layout/layout_theme_test.cc +++ b/third_party/blink/renderer/core/layout/layout_theme_test.cc
@@ -76,7 +76,7 @@ // The expectations in the tests below are relying on LayoutThemeDefault. // LayoutThemeMac doesn't inherit from that class. -#if !defined(OS_MAC) +#if !BUILDFLAG(IS_MAC) TEST_F(LayoutThemeTest, SystemColorWithColorScheme) { SetHtmlInnerHTML(R"HTML( <style> @@ -133,6 +133,6 @@ LayoutTheme::GetTheme().ActiveSelectionForegroundColor( mojom::blink::ColorScheme::kLight)); } -#endif // !defined(OS_MAC) +#endif // !BUILDFLAG(IS_MAC) } // namespace blink
diff --git a/third_party/blink/renderer/core/layout/layout_view.cc b/third_party/blink/renderer/core/layout/layout_view.cc index d894de2e..936503c 100644 --- a/third_party/blink/renderer/core/layout/layout_view.cc +++ b/third_party/blink/renderer/core/layout/layout_view.cc
@@ -63,7 +63,7 @@ #include "ui/display/screen_info.h" #include "ui/gfx/geometry/quad_f.h" -#if defined(OS_LINUX) || defined(OS_CHROMEOS) +#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) #include "third_party/blink/renderer/platform/fonts/font_cache.h" #endif @@ -357,7 +357,7 @@ DCHECK(!layout_state_); LayoutState root_layout_state(*this); -#if defined(OS_LINUX) || defined(OS_CHROMEOS) +#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) // The font code in FontPlatformData does not have a direct connection to the // document, the frame or anything from which we could retrieve the device // scale factor. After using zoom for DSF, the GraphicsContext does only ever
diff --git a/third_party/blink/renderer/core/layout/line/line_box_list.h b/third_party/blink/renderer/core/layout/line/line_box_list.h index a65d74dc..f2877b32 100644 --- a/third_party/blink/renderer/core/layout/line/line_box_list.h +++ b/third_party/blink/renderer/core/layout/line/line_box_list.h
@@ -32,7 +32,8 @@ #include "base/dcheck_is_on.h" #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/core/layout/api/hit_test_action.h" -#include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" #include "third_party/blink/renderer/platform/wtf/allocator/allocator.h" namespace blink {
diff --git a/third_party/blink/renderer/core/layout/ng/inline/inline_containing_block_utils.h b/third_party/blink/renderer/core/layout/ng/inline/inline_containing_block_utils.h index 9682f8c..bd0627c 100644 --- a/third_party/blink/renderer/core/layout/ng/inline/inline_containing_block_utils.h +++ b/third_party/blink/renderer/core/layout/ng/inline/inline_containing_block_utils.h
@@ -7,7 +7,7 @@ #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/blink/renderer/core/layout/geometry/physical_rect.h" -#include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/heap/member.h" #include "third_party/blink/renderer/platform/wtf/hash_map.h" namespace blink {
diff --git a/third_party/blink/renderer/core/layout/ng/inline/layout_ng_text_test.cc b/third_party/blink/renderer/core/layout/ng/inline/layout_ng_text_test.cc index 3b8c663b..a7fe404 100644 --- a/third_party/blink/renderer/core/layout/ng/inline/layout_ng_text_test.cc +++ b/third_party/blink/renderer/core/layout/ng/inline/layout_ng_text_test.cc
@@ -39,7 +39,7 @@ if (const auto* shape_result = item.TextShapeResult()) { stream << ", ShapeResult=" << shape_result->StartIndex() << "+" << shape_result->NumCharacters(); -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) if (shape_result->NumCharacters() != shape_result->NumGlyphs()) stream << " #glyphs=" << shape_result->NumGlyphs(); #else
diff --git a/third_party/blink/renderer/core/layout/ng/inline/ng_inline_node.cc b/third_party/blink/renderer/core/layout/ng/inline/ng_inline_node.cc index 9e8e217..d7fc08c 100644 --- a/third_party/blink/renderer/core/layout/ng/inline/ng_inline_node.cc +++ b/third_party/blink/renderer/core/layout/ng/inline/ng_inline_node.cc
@@ -523,7 +523,7 @@ DCHECK(data); CollectInlines(data, previous_data); SegmentText(data); -#if defined(OS_CHROMEOS) || defined(OS_ANDROID) +#if BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID) ShapeText(data, previous_data ? &previous_data->text_content : nullptr); ShapeTextForFirstLineIfNeeded(data); #else @@ -941,7 +941,7 @@ // Relocates |ShapeResult| in |previous_data| after |offset|+|length| editor.Run(); node.SegmentText(data); -#if defined(OS_CHROMEOS) || defined(OS_ANDROID) +#if BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID) node.ShapeText(data, &previous_data->text_content, &previous_data->items); node.ShapeTextForFirstLineIfNeeded(data); #else
diff --git a/third_party/blink/renderer/core/layout/ng/list/ng_unpositioned_list_marker.h b/third_party/blink/renderer/core/layout/ng/list/ng_unpositioned_list_marker.h index 60ee8e5..2dee411 100644 --- a/third_party/blink/renderer/core/layout/ng/list/ng_unpositioned_list_marker.h +++ b/third_party/blink/renderer/core/layout/ng/list/ng_unpositioned_list_marker.h
@@ -11,7 +11,8 @@ #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/core/layout/ng/geometry/ng_box_strut.h" #include "third_party/blink/renderer/platform/fonts/font_baseline.h" -#include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" #include "third_party/blink/renderer/platform/wtf/allocator/allocator.h" namespace blink {
diff --git a/third_party/blink/renderer/core/layout/order_iterator.h b/third_party/blink/renderer/core/layout/order_iterator.h index 3dab631..efd8103 100644 --- a/third_party/blink/renderer/core/layout/order_iterator.h +++ b/third_party/blink/renderer/core/layout/order_iterator.h
@@ -31,7 +31,7 @@ #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_ORDER_ITERATOR_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_ORDER_ITERATOR_H_ -#include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/heap/member.h" #include "third_party/blink/renderer/platform/wtf/allocator/allocator.h" #include <set>
diff --git a/third_party/blink/renderer/core/layout/scroll_anchor.h b/third_party/blink/renderer/core/layout/scroll_anchor.h index 357c47e1..5ab18f1 100644 --- a/third_party/blink/renderer/core/layout/scroll_anchor.h +++ b/third_party/blink/renderer/core/layout/scroll_anchor.h
@@ -7,7 +7,8 @@ #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/platform/geometry/layout_point.h" -#include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" namespace gfx {
diff --git a/third_party/blink/renderer/core/layout/scroll_anchor_test.cc b/third_party/blink/renderer/core/layout/scroll_anchor_test.cc index 68a9000..26bca79 100644 --- a/third_party/blink/renderer/core/layout/scroll_anchor_test.cc +++ b/third_party/blink/renderer/core/layout/scroll_anchor_test.cc
@@ -1005,7 +1005,7 @@ GetDocument().getElementById("hidden")->setAttribute(html_names::kStyleAttr, "display:block"); GetDocument().UpdateStyleAndLayout(DocumentUpdateReason::kTest); -#if !defined(OS_MAC) +#if !BUILDFLAG(IS_MAC) EXPECT_EQ(gfx::Vector2d(0, 200), LayoutViewport() ->GetScrollAnimator()
diff --git a/third_party/blink/renderer/core/layout/scrollbars_test.cc b/third_party/blink/renderer/core/layout/scrollbars_test.cc index 314e788..0c14885 100644 --- a/third_party/blink/renderer/core/layout/scrollbars_test.cc +++ b/third_party/blink/renderer/core/layout/scrollbars_test.cc
@@ -1470,7 +1470,7 @@ // a huge fadeout delay. // Disable on Android since VirtualTime not work for Android. // http://crbug.com/633321 -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) TEST_P(ScrollbarsTestWithVirtualTimer, DISABLED_TestNonCompositedOverlayScrollbarsFade) { #else @@ -1580,7 +1580,7 @@ // Make sure native scrollbar can change by Emulator. // Disable on Android since Android always enable OverlayScrollbar. -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) TEST_P(ScrollbarAppearanceTest, DISABLED_NativeScrollbarChangeToMobileByEmulator) { #else @@ -1673,7 +1673,7 @@ EXPECT_FALSE(div_scrollable->VerticalScrollbar()->GetTheme().IsMockTheme()); } -#if !defined(OS_MAC) +#if !BUILDFLAG(IS_MAC) // Ensure that the minimum length for a scrollbar thumb comes from the // WebThemeEngine. Note, Mac scrollbars differ from all other platforms so this // test doesn't apply there. https://crbug.com/682209. @@ -2764,7 +2764,7 @@ // press on scrollbar button should keep scrolling after content loaded. // Disable on Android since VirtualTime not work for Android. // http://crbug.com/633321 -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) TEST_P(ScrollbarsTestWithVirtualTimer, DISABLED_PressScrollbarButtonOnInfiniteScrolling) { #else @@ -2935,7 +2935,7 @@ ScrollbarColorSchemeTest, testing::Values(false)); -#if defined(OS_ANDROID) || defined(OS_MAC) +#if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_MAC) // Not able to paint non-overlay scrollbars through ThemeEngine on Android or // Mac. #define MAYBE_ThemeEnginePaint DISABLED_ThemeEnginePaint
diff --git a/third_party/blink/renderer/core/layout/view_fragmentation_context.h b/third_party/blink/renderer/core/layout/view_fragmentation_context.h index d8f89a7..2ee8212 100644 --- a/third_party/blink/renderer/core/layout/view_fragmentation_context.h +++ b/third_party/blink/renderer/core/layout/view_fragmentation_context.h
@@ -6,6 +6,8 @@ #define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_VIEW_FRAGMENTATION_CONTEXT_H_ #include "third_party/blink/renderer/core/layout/fragmentation_context.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" namespace blink {
diff --git a/third_party/blink/renderer/core/loader/document_load_timing.h b/third_party/blink/renderer/core/loader/document_load_timing.h index 3a834a5d..dc384589 100644 --- a/third_party/blink/renderer/core/loader/document_load_timing.h +++ b/third_party/blink/renderer/core/loader/document_load_timing.h
@@ -28,7 +28,8 @@ #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/blink/renderer/core/core_export.h" -#include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" #include "third_party/blink/renderer/platform/instrumentation/tracing/traced_value.h" #include "third_party/perfetto/include/perfetto/tracing/traced_value_forward.h"
diff --git a/third_party/blink/renderer/core/loader/frame_fetch_context_test.cc b/third_party/blink/renderer/core/loader/frame_fetch_context_test.cc index 5042d865..40bfbab 100644 --- a/third_party/blink/renderer/core/loader/frame_fetch_context_test.cc +++ b/third_party/blink/renderer/core/loader/frame_fetch_context_test.cc
@@ -621,7 +621,7 @@ // Without a permissions policy header, the client hints should be sent only // to the first party origins. Device-memory is a legacy hint that's sent on // Android regardless of Permissions Policy delegation. -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) ExpectHeader("https://www.someother-example.com/1.gif", "Device-Memory", true, "4"); #else @@ -1086,7 +1086,7 @@ "4"); // Device-memory is a legacy hint that's sent on Android regardless of // Permissions Policy delegation. -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) ExpectHeader("https://www.someother-example.com/1.gif", "Device-Memory", true, "4"); #else @@ -1103,7 +1103,7 @@ ExpectHeader("https://www.example.net/1.gif", "ect", false, ""); // DPR is a legacy hint that's sent on Android regardless of Permissions // Policy delegation. -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) ExpectHeader("https://www.example.net/1.gif", "DPR", true, "1"); #else ExpectHeader("https://www.example.net/1.gif", "DPR", false, "");
diff --git a/third_party/blink/renderer/core/loader/history_item.h b/third_party/blink/renderer/core/loader/history_item.h index 05a0024..cc98704 100644 --- a/third_party/blink/renderer/core/loader/history_item.h +++ b/third_party/blink/renderer/core/loader/history_item.h
@@ -33,7 +33,8 @@ #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/core/loader/frame_loader_types.h" #include "third_party/blink/renderer/core/scroll/scroll_types.h" -#include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" #include "third_party/blink/renderer/platform/weborigin/referrer.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
diff --git a/third_party/blink/renderer/core/loader/navigation_policy.cc b/third_party/blink/renderer/core/loader/navigation_policy.cc index d171707..8ead3f4 100644 --- a/third_party/blink/renderer/core/loader/navigation_policy.cc +++ b/third_party/blink/renderer/core/loader/navigation_policy.cc
@@ -52,7 +52,7 @@ bool shift, bool alt, bool meta) { -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) const bool new_tab_modifier = (button == 1) || meta; #else const bool new_tab_modifier = (button == 1) || ctrl;
diff --git a/third_party/blink/renderer/core/loader/navigation_policy_test.cc b/third_party/blink/renderer/core/loader/navigation_policy_test.cc index ae2235ac..6a58caa 100644 --- a/third_party/blink/renderer/core/loader/navigation_policy_test.cc +++ b/third_party/blink/renderer/core/loader/navigation_policy_test.cc
@@ -126,7 +126,7 @@ } TEST_F(NavigationPolicyTest, ControlOrMetaLeftClick) { -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) int modifiers = WebInputEvent::kMetaKey; #else int modifiers = WebInputEvent::kControlKey; @@ -138,7 +138,7 @@ } TEST_F(NavigationPolicyTest, ControlOrMetaLeftClickPopup) { -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) int modifiers = WebInputEvent::kMetaKey; #else int modifiers = WebInputEvent::kControlKey; @@ -150,7 +150,7 @@ } TEST_F(NavigationPolicyTest, ControlOrMetaAndShiftLeftClick) { -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) int modifiers = WebInputEvent::kMetaKey; #else int modifiers = WebInputEvent::kControlKey; @@ -163,7 +163,7 @@ } TEST_F(NavigationPolicyTest, ControlOrMetaAndShiftLeftClickPopup) { -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) int modifiers = WebInputEvent::kMetaKey; #else int modifiers = WebInputEvent::kControlKey; @@ -324,7 +324,7 @@ } TEST_F(NavigationPolicyTest, EventControlOrMetaLeftClick) { -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) int modifiers = WebInputEvent::kMetaKey; #else int modifiers = WebInputEvent::kControlKey; @@ -335,7 +335,7 @@ } TEST_F(NavigationPolicyTest, EventControlOrMetaLeftClickWithUserEvent) { -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) int modifiers = WebInputEvent::kMetaKey; #else int modifiers = WebInputEvent::kControlKey; @@ -347,7 +347,7 @@ TEST_F(NavigationPolicyTest, EventControlOrMetaLeftClickWithDifferentUserEvent) { -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) int modifiers = WebInputEvent::kMetaKey; #else int modifiers = WebInputEvent::kControlKey; @@ -358,7 +358,7 @@ } TEST_F(NavigationPolicyTest, EventShiftControlOrMetaLeftClick) { -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) int modifiers = WebInputEvent::kMetaKey | WebInputEvent::kShiftKey; #else int modifiers = WebInputEvent::kControlKey | WebInputEvent::kShiftKey;
diff --git a/third_party/blink/renderer/core/loader/progress_tracker.h b/third_party/blink/renderer/core/loader/progress_tracker.h index a051999c..35c82bc 100644 --- a/third_party/blink/renderer/core/loader/progress_tracker.h +++ b/third_party/blink/renderer/core/loader/progress_tracker.h
@@ -28,7 +28,8 @@ #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/core/loader/frame_loader_types.h" -#include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" #include "third_party/blink/renderer/platform/loader/fetch/resource_load_priority.h" #include "third_party/blink/renderer/platform/wtf/allocator/allocator.h" #include "third_party/blink/renderer/platform/wtf/forward.h"
diff --git a/third_party/blink/renderer/core/loader/resource/multipart_image_resource_parser.h b/third_party/blink/renderer/core/loader/resource/multipart_image_resource_parser.h index 9b3f7bb..59d6cfa 100644 --- a/third_party/blink/renderer/core/loader/resource/multipart_image_resource_parser.h +++ b/third_party/blink/renderer/core/loader/resource/multipart_image_resource_parser.h
@@ -42,7 +42,8 @@ #define THIRD_PARTY_BLINK_RENDERER_CORE_LOADER_RESOURCE_MULTIPART_IMAGE_RESOURCE_PARSER_H_ #include "third_party/blink/renderer/core/core_export.h" -#include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" #include "third_party/blink/renderer/platform/loader/fetch/resource_response.h" #include "third_party/blink/renderer/platform/wtf/vector.h"
diff --git a/third_party/blink/renderer/core/loader/subresource_filter.h b/third_party/blink/renderer/core/loader/subresource_filter.h index dfb0bfd..d0de292 100644 --- a/third_party/blink/renderer/core/loader/subresource_filter.h +++ b/third_party/blink/renderer/core/loader/subresource_filter.h
@@ -12,7 +12,8 @@ #include "third_party/blink/public/platform/web_document_subresource_filter.h" #include "third_party/blink/public/platform/web_url_request.h" #include "third_party/blink/renderer/core/core_export.h" -#include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" #include "third_party/blink/renderer/platform/weborigin/kurl.h" #include "third_party/blink/renderer/platform/weborigin/reporting_disposition.h"
diff --git a/third_party/blink/renderer/core/loader/web_associated_url_loader_impl_test.cc b/third_party/blink/renderer/core/loader/web_associated_url_loader_impl_test.cc index 9525e55..abcc5dc 100644 --- a/third_party/blink/renderer/core/loader/web_associated_url_loader_impl_test.cc +++ b/third_party/blink/renderer/core/loader/web_associated_url_loader_impl_test.cc
@@ -457,7 +457,7 @@ } // This test is flaky on Windows and Android. See <http://crbug.com/471645>. -#if defined(OS_WIN) || defined(OS_ANDROID) +#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_ANDROID) #define MAYBE_UntrustedCheckHeaders DISABLED_UntrustedCheckHeaders #else #define MAYBE_UntrustedCheckHeaders UntrustedCheckHeaders
diff --git a/third_party/blink/renderer/core/loader/worker_resource_timing_notifier_impl.h b/third_party/blink/renderer/core/loader/worker_resource_timing_notifier_impl.h index 72c14cf..08befb0 100644 --- a/third_party/blink/renderer/core/loader/worker_resource_timing_notifier_impl.h +++ b/third_party/blink/renderer/core/loader/worker_resource_timing_notifier_impl.h
@@ -10,7 +10,8 @@ #include "third_party/blink/public/mojom/timing/resource_timing.mojom-blink.h" #include "third_party/blink/public/mojom/timing/worker_timing_container.mojom-blink.h" #include "third_party/blink/renderer/core/core_export.h" -#include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" #include "third_party/blink/renderer/platform/heap/persistent.h" #include "third_party/blink/renderer/platform/loader/fetch/worker_resource_timing_notifier.h"
diff --git a/third_party/blink/renderer/core/messaging/message_channel.h b/third_party/blink/renderer/core/messaging/message_channel.h index f3dd013..212f21e6 100644 --- a/third_party/blink/renderer/core/messaging/message_channel.h +++ b/third_party/blink/renderer/core/messaging/message_channel.h
@@ -29,7 +29,8 @@ #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/platform/bindings/script_wrappable.h" -#include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" namespace blink {
diff --git a/third_party/blink/renderer/core/page/autoscroll_controller.h b/third_party/blink/renderer/core/page/autoscroll_controller.h index 1a0dd16..756ed767 100644 --- a/third_party/blink/renderer/core/page/autoscroll_controller.h +++ b/third_party/blink/renderer/core/page/autoscroll_controller.h
@@ -30,7 +30,8 @@ #include "base/time/time.h" #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/core/layout/geometry/physical_offset.h" -#include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" #include "ui/gfx/geometry/point_f.h" #include "ui/gfx/geometry/size_f.h"
diff --git a/third_party/blink/renderer/core/page/chrome_client_impl.cc b/third_party/blink/renderer/core/page/chrome_client_impl.cc index 984732c..c442ddf 100644 --- a/third_party/blink/renderer/core/page/chrome_client_impl.cc +++ b/third_party/blink/renderer/core/page/chrome_client_impl.cc
@@ -668,7 +668,7 @@ controller = MakeGarbageCollected<ColorChooserPopupUIController>( frame, this, chooser_client); } else { -#if !defined(OS_ANDROID) +#if !BUILDFLAG(IS_ANDROID) NOTREACHED() << "Page popups should be enabled on all but Android"; #endif controller = @@ -770,7 +770,7 @@ if (cursor_overridden_) return; -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) DCHECK(web_view_); // On Mac the mousemove event propagates to both the popup and main window. // If a popup is open we don't want the main window to change the cursor.
diff --git a/third_party/blink/renderer/core/page/context_menu_controller_test.cc b/third_party/blink/renderer/core/page/context_menu_controller_test.cc index 94980640c..4a1da40 100644 --- a/third_party/blink/renderer/core/page/context_menu_controller_test.cc +++ b/third_party/blink/renderer/core/page/context_menu_controller_test.cc
@@ -644,7 +644,7 @@ EXPECT_EQ(context_menu_data.selected_text, "Sample Input Text"); } -#if !defined(OS_MAC) +#if !BUILDFLAG(IS_MAC) // Mac has no way to open a context menu based on a keyboard event. TEST_P(ContextMenuControllerTest, ValidateNonLocatedContextMenuOnLargeImageElement) {
diff --git a/third_party/blink/renderer/core/page/drag_controller.cc b/third_party/blink/renderer/core/page/drag_controller.cc index da03bc3c..005e7900 100644 --- a/third_party/blink/renderer/core/page/drag_controller.cc +++ b/third_party/blink/renderer/core/page/drag_controller.cc
@@ -95,7 +95,7 @@ #include "ui/gfx/geometry/size.h" #include "ui/gfx/geometry/vector2d_conversions.h" -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) #include <windows.h> #endif @@ -1054,7 +1054,7 @@ } static const gfx::Size MaxDragImageSize(float device_scale_factor) { -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) // Match Safari's drag image size. static const gfx::Size kMaxDragImageSize(400, 400); #else @@ -1368,7 +1368,7 @@ bool DragController::IsCopyKeyDown(DragData* drag_data) { int modifiers = drag_data->GetModifiers(); -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) return modifiers & WebInputEvent::kAltKey; #else return modifiers & WebInputEvent::kControlKey;
diff --git a/third_party/blink/renderer/core/page/frame_tree.h b/third_party/blink/renderer/core/page/frame_tree.h index b3cb867..1e9ac60 100644 --- a/third_party/blink/renderer/core/page/frame_tree.h +++ b/third_party/blink/renderer/core/page/frame_tree.h
@@ -22,7 +22,8 @@ #include "base/dcheck_is_on.h" #include "third_party/blink/renderer/core/core_export.h" -#include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" #include "third_party/blink/renderer/platform/wtf/text/atomic_string.h" namespace blink {
diff --git a/third_party/blink/renderer/core/page/link_highlight.h b/third_party/blink/renderer/core/page/link_highlight.h index f568809a..1eb31471 100644 --- a/third_party/blink/renderer/core/page/link_highlight.h +++ b/third_party/blink/renderer/core/page/link_highlight.h
@@ -9,7 +9,8 @@ #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/platform/graphics/compositor_element_id.h" -#include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" namespace cc { class AnimationHost;
diff --git a/third_party/blink/renderer/core/page/page_visibility_observer.h b/third_party/blink/renderer/core/page/page_visibility_observer.h index 5c8b5912ea..f6432cd77 100644 --- a/third_party/blink/renderer/core/page/page_visibility_observer.h +++ b/third_party/blink/renderer/core/page/page_visibility_observer.h
@@ -28,7 +28,8 @@ #define THIRD_PARTY_BLINK_RENDERER_CORE_PAGE_PAGE_VISIBILITY_OBSERVER_H_ #include "third_party/blink/renderer/core/core_export.h" -#include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" namespace blink {
diff --git a/third_party/blink/renderer/core/page/print_context.cc b/third_party/blink/renderer/core/page/print_context.cc index ef27c9b4..4e97a002 100644 --- a/third_party/blink/renderer/core/page/print_context.cc +++ b/third_party/blink/renderer/core/page/print_context.cc
@@ -297,15 +297,15 @@ int margin_bottom, int margin_left) { WebPrintPageDescription description; - description.size = WebDoubleSize(width, height); + description.size.SetSize(width, height); description.margin_top = margin_top; description.margin_right = margin_right; description.margin_bottom = margin_bottom; description.margin_left = margin_left; frame->GetDocument()->GetPageDescription(page_number, &description); - return "(" + String::Number(floor(description.size.Width())) + ", " + - String::Number(floor(description.size.Height())) + ") " + + return "(" + String::Number(floor(description.size.width())) + ", " + + String::Number(floor(description.size.height())) + ") " + String::Number(description.margin_top) + ' ' + String::Number(description.margin_right) + ' ' + String::Number(description.margin_bottom) + ' ' +
diff --git a/third_party/blink/renderer/core/page/scrolling/element_fragment_anchor.h b/third_party/blink/renderer/core/page/scrolling/element_fragment_anchor.h index 214bd8b..c9f402e 100644 --- a/third_party/blink/renderer/core/page/scrolling/element_fragment_anchor.h +++ b/third_party/blink/renderer/core/page/scrolling/element_fragment_anchor.h
@@ -9,7 +9,8 @@ #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/core/page/scrolling/fragment_anchor.h" #include "third_party/blink/renderer/core/scroll/scroll_types.h" -#include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" namespace blink {
diff --git a/third_party/blink/renderer/core/page/scrolling/fragment_anchor.h b/third_party/blink/renderer/core/page/scrolling/fragment_anchor.h index 49ef021..6923114 100644 --- a/third_party/blink/renderer/core/page/scrolling/fragment_anchor.h +++ b/third_party/blink/renderer/core/page/scrolling/fragment_anchor.h
@@ -7,7 +7,8 @@ #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/core/scroll/scroll_types.h" -#include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" namespace blink { class Element;
diff --git a/third_party/blink/renderer/core/page/scrolling/overscroll_controller.h b/third_party/blink/renderer/core/page/scrolling/overscroll_controller.h index d7cca64..c39da914 100644 --- a/third_party/blink/renderer/core/page/scrolling/overscroll_controller.h +++ b/third_party/blink/renderer/core/page/scrolling/overscroll_controller.h
@@ -6,7 +6,8 @@ #define THIRD_PARTY_BLINK_RENDERER_CORE_PAGE_SCROLLING_OVERSCROLL_CONTROLLER_H_ #include "cc/input/overscroll_behavior.h" -#include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" #include "ui/gfx/geometry/vector2d_f.h" namespace gfx {
diff --git a/third_party/blink/renderer/core/page/scrolling/scrolling_test.cc b/third_party/blink/renderer/core/page/scrolling/scrolling_test.cc index 5cebb6d6..67dfd8de 100644 --- a/third_party/blink/renderer/core/page/scrolling/scrolling_test.cc +++ b/third_party/blink/renderer/core/page/scrolling/scrolling_test.cc
@@ -1541,7 +1541,7 @@ // an empty document by javascript. } -#if defined(OS_MAC) || defined(OS_ANDROID) +#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_ANDROID) TEST_P(ScrollingTest, DISABLED_setupScrollbarLayerShouldSetScrollLayerOpaque) #else TEST_P(ScrollingTest, setupScrollbarLayerShouldSetScrollLayerOpaque)
diff --git a/third_party/blink/renderer/core/page/validation_message_overlay_delegate_test.cc b/third_party/blink/renderer/core/page/validation_message_overlay_delegate_test.cc index 446a72e..8df3931 100644 --- a/third_party/blink/renderer/core/page/validation_message_overlay_delegate_test.cc +++ b/third_party/blink/renderer/core/page/validation_message_overlay_delegate_test.cc
@@ -16,7 +16,7 @@ #include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h" #include "third_party/blink/renderer/platform/web_test_support.h" -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) #include "base/strings/utf_string_conversions.h" #include "third_party/blink/public/web/win/web_font_rendering.h" #endif @@ -25,7 +25,7 @@ class ValidationMessageOverlayDelegateTest : public PaintTestConfigurations, public RenderingTest { -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) public: void SetUp() override { RenderingTest::SetUp();
diff --git a/third_party/blink/renderer/core/paint/document_marker_painter.cc b/third_party/blink/renderer/core/paint/document_marker_painter.cc index cbec247..83403bd 100644 --- a/third_party/blink/renderer/core/paint/document_marker_painter.cc +++ b/third_party/blink/renderer/core/paint/document_marker_painter.cc
@@ -23,7 +23,7 @@ namespace { -#if !defined(OS_MAC) +#if !BUILDFLAG(IS_MAC) static const float kMarkerWidth = 4; static const float kMarkerHeight = 2; @@ -63,7 +63,7 @@ return recorder.finishRecordingAsPicture(); } -#else // defined(OS_MAC) +#else // !BUILDFLAG(IS_MAC) static const float kMarkerWidth = 4; static const float kMarkerHeight = 3; @@ -86,7 +86,7 @@ return recorder.finishRecordingAsPicture(); } -#endif // defined(OS_MAC) +#endif // !BUILDFLAG(IS_MAC) void DrawDocumentMarker(GraphicsContext& context, const gfx::PointF& pt, @@ -97,7 +97,7 @@ SkScalar origin_x = WebCoreFloatToSkScalar(pt.x()); SkScalar origin_y = WebCoreFloatToSkScalar(pt.y()); -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) // Make sure to draw only complete dots, and finish inside the marked text. float spacing = kMarkerSpacing * zoom; width -= fmodf(width + spacing, kMarkerWidth * zoom) - spacing;
diff --git a/third_party/blink/renderer/core/paint/first_meaningful_paint_detector.h b/third_party/blink/renderer/core/paint/first_meaningful_paint_detector.h index 2e0e7cb0..43198cf 100644 --- a/third_party/blink/renderer/core/paint/first_meaningful_paint_detector.h +++ b/third_party/blink/renderer/core/paint/first_meaningful_paint_detector.h
@@ -8,7 +8,8 @@ #include "base/time/time.h" #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/core/paint/paint_event.h" -#include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" namespace base { class TickClock;
diff --git a/third_party/blink/renderer/core/paint/outline_painter.cc b/third_party/blink/renderer/core/paint/outline_painter.cc index 8888468..c8b336c 100644 --- a/third_party/blink/renderer/core/paint/outline_painter.cc +++ b/third_party/blink/renderer/core/paint/outline_painter.cc
@@ -828,7 +828,7 @@ const ComputedStyle& style, const FloatRoundedRect::Radii& corner_radii) { Color inner_color = style.VisitedDependentColor(GetCSSPropertyOutlineColor()); -#if !defined(OS_MAC) +#if !BUILDFLAG(IS_MAC) if (style.DarkColorScheme()) inner_color = Color::kWhite; #endif
diff --git a/third_party/blink/renderer/core/paint/paint_layer.cc b/third_party/blink/renderer/core/paint/paint_layer.cc index 7006764e..b4b4c3f84 100644 --- a/third_party/blink/renderer/core/paint/paint_layer.cc +++ b/third_party/blink/renderer/core/paint/paint_layer.cc
@@ -108,7 +108,7 @@ namespace { -#if defined(OS_LINUX) || defined(OS_CHROMEOS) +#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) struct SameSizeAsPaintLayer : GarbageCollected<PaintLayer>, DisplayItemClient { // The bit fields may fit into the machine word of DisplayItemClient which // has only 8-bit data. @@ -1190,11 +1190,23 @@ DirtyStackingContextZOrderLists(); } -void PaintLayer::AppendSingleFragmentIgnoringPaginationForHitTesting( +void PaintLayer::AppendSingleFragmentForHitTesting( PaintLayerFragments& fragments, + const PaintLayerFragment* container_fragment, ShouldRespectOverflowClipType respect_overflow_clip) const { PaintLayerFragment fragment; - fragment.fragment_data = &GetLayoutObject().FirstFragment(); + if (container_fragment) { + fragment = *container_fragment; + } else { + fragment.fragment_data = &GetLayoutObject().FirstFragment(); + if (GetLayoutObject().CanTraversePhysicalFragments()) { + // Make sure that we actually traverse the fragment tree, by providing a + // physical fragment. Otherwise we'd fall back to LayoutObject traversal. + if (const auto* layout_box = GetLayoutBox()) + fragment.physical_fragment = layout_box->GetPhysicalFragment(0); + } + } + ClipRectsContext clip_rects_context(this, fragment.fragment_data, kExcludeOverlayScrollbarSizeForHitTesting, respect_overflow_clip); @@ -1202,12 +1214,6 @@ .CalculateRects(clip_rects_context, fragment.fragment_data, fragment.layer_bounds, fragment.background_rect, fragment.foreground_rect); - if (GetLayoutObject().CanTraversePhysicalFragments()) { - // Make sure that we actually traverse the fragment tree, by providing a - // physical fragment. Otherwise we'd fall back to LayoutObject traversal. - if (const auto* layout_box = GetLayoutBox()) - fragment.physical_fragment = layout_box->GetPhysicalFragment(0); - } fragments.push_back(fragment); } @@ -1544,13 +1550,15 @@ // test their fragments that are descendants of |container_fragment|. PaintLayer* PaintLayer::HitTestLayer( const PaintLayer& transform_container, - const FragmentData* container_fragment, + const PaintLayerFragment* container_fragment, HitTestResult& result, const HitTestRecursionData& recursion_data, bool applied_transform, HitTestingTransformState* container_transform_state, double* z_offset, bool check_resizer_only) { + const FragmentData* container_fragment_data = + container_fragment ? container_fragment->fragment_data : nullptr; const auto& container_layout_object = transform_container.GetLayoutObject(); DCHECK(container_layout_object.CanContainFixedPositionObjects()); DCHECK(container_layout_object.CanContainAbsolutePositionObjects()); @@ -1647,13 +1655,13 @@ DCHECK(!Preserves3D()); // We need transform state for the first time, or to offset the container // state, so create it here. - const FragmentData* container_fragment_for_transform_state = - container_fragment; const FragmentData* local_fragment_for_transform_state = &layout_object.FirstFragment(); - if (container_fragment) { + const FragmentData* container_fragment_for_transform_state; + if (container_fragment_data) { + container_fragment_for_transform_state = container_fragment_data; const auto& container_transform = - container_fragment->LocalBorderBoxProperties().Transform(); + container_fragment_data->LocalBorderBoxProperties().Transform(); while (local_fragment_for_transform_state) { // Find the first local fragment that is a descendant of // container_fragment. @@ -1715,11 +1723,11 @@ if (recursion_data.intersects_location) { if (applied_transform) { DCHECK_EQ(&transform_container, this); - AppendSingleFragmentIgnoringPaginationForHitTesting(layer_fragments, - clip_behavior); + AppendSingleFragmentForHitTesting(layer_fragments, container_fragment, + clip_behavior); } else { CollectFragments(layer_fragments, &transform_container, clip_behavior, - container_fragment); + container_fragment_data); } // See if the hit test pos is inside the resizer of current layer. This @@ -1895,18 +1903,20 @@ PaintLayer* PaintLayer::HitTestTransformedLayerInFragments( const PaintLayer& transform_container, - const FragmentData* container_fragment, + const PaintLayerFragment* container_fragment, HitTestResult& result, const HitTestRecursionData& recursion_data, HitTestingTransformState* container_transform_state, double* z_offset, bool check_resizer_only, ShouldRespectOverflowClipType clip_behavior) { + const FragmentData* container_fragment_data = + container_fragment ? container_fragment->fragment_data : nullptr; PaintLayerFragments fragments; ClearCollectionScope<PaintLayerFragments> scope(&fragments); CollectFragments(fragments, &transform_container, clip_behavior, - container_fragment); + container_fragment_data); for (const auto& fragment : fragments) { // Apply any clips established by layers in between us and the root layer. @@ -1914,8 +1924,8 @@ continue; PaintLayer* hit_layer = HitTestLayerByApplyingTransform( - transform_container, container_fragment, *fragment.fragment_data, - result, recursion_data, container_transform_state, z_offset, + transform_container, container_fragment, fragment, result, + recursion_data, container_transform_state, z_offset, check_resizer_only); if (hit_layer) return hit_layer; @@ -1926,8 +1936,8 @@ PaintLayer* PaintLayer::HitTestLayerByApplyingTransform( const PaintLayer& transform_container, - const FragmentData* container_fragment, - const FragmentData& local_fragment, + const PaintLayerFragment* container_fragment, + const PaintLayerFragment& local_fragment, HitTestResult& result, const HitTestRecursionData& recursion_data, HitTestingTransformState* root_transform_state, @@ -1938,9 +1948,9 @@ HitTestingTransformState new_transform_state = CreateLocalTransformState( transform_container, container_fragment - ? *container_fragment + ? *container_fragment->fragment_data : transform_container.GetLayoutObject().FirstFragment(), - local_fragment, recursion_data, root_transform_state); + *local_fragment.fragment_data, recursion_data, root_transform_state); // If the transform can't be inverted, then don't hit test this layer at all. if (!new_transform_state.AccumulatedTransform().IsInvertible()) @@ -2037,7 +2047,7 @@ PaintLayer* PaintLayer::HitTestChildren( PaintLayerIteration children_to_visit, const PaintLayer& transform_container, - const FragmentData* container_fragment, + const PaintLayerFragment* container_fragment, HitTestResult& result, const HitTestRecursionData& recursion_data, HitTestingTransformState* container_transform_state,
diff --git a/third_party/blink/renderer/core/paint/paint_layer.h b/third_party/blink/renderer/core/paint/paint_layer.h index 29a7a4f..8ba80ac 100644 --- a/third_party/blink/renderer/core/paint/paint_layer.h +++ b/third_party/blink/renderer/core/paint/paint_layer.h
@@ -683,8 +683,9 @@ void UpdateHasSelfPaintingLayerDescendant() const; - void AppendSingleFragmentIgnoringPaginationForHitTesting( + void AppendSingleFragmentForHitTesting( PaintLayerFragments&, + const PaintLayerFragment* container_fragment, ShouldRespectOverflowClipType) const; void CollectFragments(PaintLayerFragments&, @@ -704,7 +705,7 @@ }; PaintLayer* HitTestLayer(const PaintLayer& transform_container, - const FragmentData* container_fragment, + const PaintLayerFragment* container_fragment, HitTestResult&, const HitTestRecursionData& recursion_data, bool applied_transform = false, @@ -713,8 +714,8 @@ bool check_resizer_only = false); PaintLayer* HitTestLayerByApplyingTransform( const PaintLayer& transform_container, - const FragmentData* container_fragment, - const FragmentData& local_fragment, + const PaintLayerFragment* container_fragment, + const PaintLayerFragment& local_fragment, HitTestResult&, const HitTestRecursionData& recursion_data, HitTestingTransformState*, @@ -724,7 +725,7 @@ PaintLayer* HitTestChildren( PaintLayerIteration, const PaintLayer& transform_container, - const FragmentData* container_fragment, + const PaintLayerFragment* container_fragment, HitTestResult&, const HitTestRecursionData& recursion_data, HitTestingTransformState* container_transform_state, @@ -752,7 +753,7 @@ bool& inside_clip_rect) const; PaintLayer* HitTestTransformedLayerInFragments( const PaintLayer& transform_container, - const FragmentData* container_fragment, + const PaintLayerFragment* container_fragment, HitTestResult&, const HitTestRecursionData&, HitTestingTransformState*,
diff --git a/third_party/blink/renderer/core/paint/paint_layer_scrollable_area_test.cc b/third_party/blink/renderer/core/paint/paint_layer_scrollable_area_test.cc index 2104057..8e25b5cc 100644 --- a/third_party/blink/renderer/core/paint/paint_layer_scrollable_area_test.cc +++ b/third_party/blink/renderer/core/paint/paint_layer_scrollable_area_test.cc
@@ -360,7 +360,7 @@ element->setAttribute("class", "composited"); UpdateAllLifecyclePhasesForTest(); EXPECT_TRUE(IsComposited(element->GetLayoutObject())); -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) // <select> implementation is different and not scrollable on Android. EXPECT_FALSE(UsesCompositedScrolling(element->GetLayoutObject())); #else
diff --git a/third_party/blink/renderer/core/paint/text_decoration_info.cc b/third_party/blink/renderer/core/paint/text_decoration_info.cc index 2925ede..7960a9a5 100644 --- a/third_party/blink/renderer/core/paint/text_decoration_info.cc +++ b/third_party/blink/renderer/core/paint/text_decoration_info.cc
@@ -146,7 +146,7 @@ if (EnumHasFlags(decoration.Lines(), TextDecorationLine::kSpellingError) || EnumHasFlags(decoration.Lines(), TextDecorationLine::kGrammarError)) { // Spelling and grammar error thickness doesn't depend on the font size. -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) applied_decorations_thickness_.push_back(2.f); #else applied_decorations_thickness_.push_back(1.f); @@ -216,7 +216,7 @@ ETextDecorationStyle TextDecorationInfo::DecorationStyle() const { if (IsSpellingOrGrammarError()) { -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) return ETextDecorationStyle::kDotted; #else return ETextDecorationStyle::kWavy;
diff --git a/third_party/blink/renderer/core/paint/theme_painter.cc b/third_party/blink/renderer/core/paint/theme_painter.cc index 2a24472..03dea8f0 100644 --- a/third_party/blink/renderer/core/paint/theme_painter.cc +++ b/third_party/blink/renderer/core/paint/theme_painter.cc
@@ -51,7 +51,7 @@ namespace { bool IsMultipleFieldsTemporalInput(const AtomicString& type) { -#if !defined(OS_ANDROID) +#if !BUILDFLAG(IS_ANDROID) return type == input_type_names::kDate || type == input_type_names::kDatetimeLocal || type == input_type_names::kMonth || type == input_type_names::kTime ||
diff --git a/third_party/blink/renderer/core/scheduler_integration_tests/virtual_time_test.cc b/third_party/blink/renderer/core/scheduler_integration_tests/virtual_time_test.cc index 37dc3b69..960d6f8e 100644 --- a/third_party/blink/renderer/core/scheduler_integration_tests/virtual_time_test.cc +++ b/third_party/blink/renderer/core/scheduler_integration_tests/virtual_time_test.cc
@@ -79,7 +79,7 @@ }; // http://crbug.com/633321 -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) #define MAYBE_SetInterval DISABLED_SetInterval #else #define MAYBE_SetInterval SetInterval @@ -107,7 +107,7 @@ } // http://crbug.com/633321 -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) #define MAYBE_AllowVirtualTimeToAdvance DISABLED_AllowVirtualTimeToAdvance #else #define MAYBE_AllowVirtualTimeToAdvance AllowVirtualTimeToAdvance @@ -136,7 +136,7 @@ } // http://crbug.com/633321 -#if defined(OS_ANDROID) +#if BUILDFLAG(IS_ANDROID) #define MAYBE_VirtualTimeNotAllowedToAdvanceWhileResourcesLoading \ DISABLED_VirtualTimeNotAllowedToAdvanceWhileResourcesLoading #else
diff --git a/third_party/blink/renderer/core/script/dynamic_module_resolver.h b/third_party/blink/renderer/core/script/dynamic_module_resolver.h index 0a1c646d..fdd5faa1 100644 --- a/third_party/blink/renderer/core/script/dynamic_module_resolver.h +++ b/third_party/blink/renderer/core/script/dynamic_module_resolver.h
@@ -6,8 +6,8 @@ #define THIRD_PARTY_BLINK_RENDERER_CORE_SCRIPT_DYNAMIC_MODULE_RESOLVER_H_ #include "third_party/blink/renderer/core/core_export.h" -#include "third_party/blink/renderer/platform/heap/handle.h" -#include "third_party/blink/renderer/platform/heap/visitor.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" #include "third_party/blink/renderer/platform/weborigin/kurl.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
diff --git a/third_party/blink/renderer/core/scroll/scroll_animator.cc b/third_party/blink/renderer/core/scroll/scroll_animator.cc index dc8730fb..a4793f52 100644 --- a/third_party/blink/renderer/core/scroll/scroll_animator.cc +++ b/third_party/blink/renderer/core/scroll/scroll_animator.cc
@@ -34,6 +34,7 @@ #include "base/callback_helpers.h" #include "base/memory/scoped_refptr.h" +#include "build/build_config.h" #include "cc/animation/scroll_offset_animation_curve.h" #include "cc/layers/picture_layer.h" #include "third_party/blink/public/platform/platform.h" @@ -107,7 +108,7 @@ // scroll, the callback is invoked immediately without being stored. DCHECK(HasRunningAnimation() || on_finish_.is_null()); -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) have_scrolled_since_page_load_ = true; #endif @@ -392,7 +393,7 @@ ScrollAnimatorCompositorCoordinator::CancelAnimation(); if (on_finish_) std::move(on_finish_).Run(); -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) have_scrolled_since_page_load_ = false; #endif }
diff --git a/third_party/blink/renderer/core/scroll/scroll_animator.h b/third_party/blink/renderer/core/scroll/scroll_animator.h index 6828f9bc..b9db11c 100644 --- a/third_party/blink/renderer/core/scroll/scroll_animator.h +++ b/third_party/blink/renderer/core/scroll/scroll_animator.h
@@ -130,7 +130,7 @@ void Trace(Visitor*) const override; -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) bool HaveScrolledSincePageLoad() { return have_scrolled_since_page_load_; } #endif @@ -166,7 +166,7 @@ // if it is still useful. // TODO(crbug.com/1122682): This is necessary for fade-in/out animations // on Mac scrollbars. Remove this when MacScrollbarAnimatorImpl is removed. -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) bool have_scrolled_since_page_load_; #endif };
diff --git a/third_party/blink/renderer/core/scroll/scrollable_area.cc b/third_party/blink/renderer/core/scroll/scrollable_area.cc index d9bd9fe..2b35b34 100644 --- a/third_party/blink/renderer/core/scroll/scrollable_area.cc +++ b/third_party/blink/renderer/core/scroll/scrollable_area.cc
@@ -133,7 +133,7 @@ } MacScrollbarAnimator* ScrollableArea::GetMacScrollbarAnimator() const { -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) if (!mac_scrollbar_animator_) { mac_scrollbar_animator_ = MacScrollbarAnimator::Create(const_cast<ScrollableArea*>(this));
diff --git a/third_party/blink/renderer/core/scroll/scrollbar_theme.cc b/third_party/blink/renderer/core/scroll/scrollbar_theme.cc index 59e9d7b..a1316d9 100644 --- a/third_party/blink/renderer/core/scroll/scrollbar_theme.cc +++ b/third_party/blink/renderer/core/scroll/scrollbar_theme.cc
@@ -40,7 +40,7 @@ #include "third_party/blink/renderer/platform/graphics/paint/drawing_recorder.h" #include "third_party/blink/renderer/platform/graphics/paint/paint_controller.h" -#if !defined(OS_MAC) +#if !BUILDFLAG(IS_MAC) #include "third_party/blink/public/platform/web_theme_engine.h" #endif @@ -117,7 +117,7 @@ DrawingRecorder recorder(context, display_item_client, DisplayItem::kScrollCorner, corner_rect); -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) context.FillRect(corner_rect, Color::kWhite, AutoDarkMode::Disabled()); #else Platform::Current()->ThemeEngine()->Paint( @@ -130,7 +130,7 @@ const Scrollbar& scrollbar, const gfx::Rect& rect) { // Android paints tickmarks in the browser at FindResultBar.java. -#if !defined(OS_ANDROID) +#if !BUILDFLAG(IS_ANDROID) if (scrollbar.Orientation() != kVerticalScrollbar) return;
diff --git a/third_party/blink/renderer/core/scroll/scrollbar_theme_aura.cc b/third_party/blink/renderer/core/scroll/scrollbar_theme_aura.cc index 8e37d3e..fe3ddc6 100644 --- a/third_party/blink/renderer/core/scroll/scrollbar_theme_aura.cc +++ b/third_party/blink/renderer/core/scroll/scrollbar_theme_aura.cc
@@ -151,7 +151,7 @@ // is true for at least GTK and QT apps). // TODO(crbug.com/1052397): Revisit once build flag switch of lacros-chrome is // complete. -#if defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS) +#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS) return false; #else return true; @@ -326,7 +326,7 @@ const WebMouseEvent& event) { // TODO(crbug.com/1052397): Revisit once build flag switch of lacros-chrome is // complete. -#if defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS) +#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS) if (event.button == WebPointerProperties::Button::kMiddle) return true; #endif
diff --git a/third_party/blink/renderer/core/style/content_data.h b/third_party/blink/renderer/core/style/content_data.h index d2954aa..d83825d12 100644 --- a/third_party/blink/renderer/core/style/content_data.h +++ b/third_party/blink/renderer/core/style/content_data.h
@@ -29,6 +29,7 @@ #include "third_party/blink/renderer/core/style/computed_style_constants.h" #include "third_party/blink/renderer/core/style/style_image.h" #include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" #include "third_party/blink/renderer/platform/wtf/casting.h" #include "third_party/blink/renderer/platform/wtf/text/atomic_string.h"
diff --git a/third_party/blink/renderer/core/style/list_style_type_data.h b/third_party/blink/renderer/core/style/list_style_type_data.h index a17722c0..730156e9 100644 --- a/third_party/blink/renderer/core/style/list_style_type_data.h +++ b/third_party/blink/renderer/core/style/list_style_type_data.h
@@ -6,7 +6,8 @@ #define THIRD_PARTY_BLINK_RENDERER_CORE_STYLE_LIST_STYLE_TYPE_DATA_H_ #include "third_party/blink/renderer/core/style/computed_style_constants.h" -#include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" #include "third_party/blink/renderer/platform/wtf/text/atomic_string.h" namespace blink {
diff --git a/third_party/blink/renderer/core/style/style_crossfade_image.h b/third_party/blink/renderer/core/style/style_crossfade_image.h index 09c2f14c..2e5bc04 100644 --- a/third_party/blink/renderer/core/style/style_crossfade_image.h +++ b/third_party/blink/renderer/core/style/style_crossfade_image.h
@@ -6,6 +6,8 @@ #define THIRD_PARTY_BLINK_RENDERER_CORE_STYLE_STYLE_CROSSFADE_IMAGE_H_ #include "third_party/blink/renderer/core/style/style_image.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" #include "third_party/blink/renderer/platform/wtf/casting.h" namespace blink {
diff --git a/third_party/blink/renderer/core/style/style_fetched_image.h b/third_party/blink/renderer/core/style/style_fetched_image.h index 6046e50..6016fc5 100644 --- a/third_party/blink/renderer/core/style/style_fetched_image.h +++ b/third_party/blink/renderer/core/style/style_fetched_image.h
@@ -26,6 +26,8 @@ #include "third_party/blink/renderer/core/loader/resource/image_resource_observer.h" #include "third_party/blink/renderer/core/style/style_image.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" #include "third_party/blink/renderer/platform/heap/prefinalizer.h" #include "third_party/blink/renderer/platform/weborigin/kurl.h" #include "third_party/blink/renderer/platform/wtf/casting.h"
diff --git a/third_party/blink/renderer/core/style/style_fetched_image_set.h b/third_party/blink/renderer/core/style/style_fetched_image_set.h index b985476..a0a1015 100644 --- a/third_party/blink/renderer/core/style/style_fetched_image_set.h +++ b/third_party/blink/renderer/core/style/style_fetched_image_set.h
@@ -29,6 +29,8 @@ #include "third_party/blink/renderer/core/loader/resource/image_resource_observer.h" #include "third_party/blink/renderer/core/style/style_image.h" #include "third_party/blink/renderer/platform/geometry/layout_size.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" #include "third_party/blink/renderer/platform/heap/prefinalizer.h" #include "third_party/blink/renderer/platform/weborigin/kurl.h" #include "third_party/blink/renderer/platform/wtf/casting.h"
diff --git a/third_party/blink/renderer/core/style/style_generated_image.h b/third_party/blink/renderer/core/style/style_generated_image.h index 2689992..d0724b4 100644 --- a/third_party/blink/renderer/core/style/style_generated_image.h +++ b/third_party/blink/renderer/core/style/style_generated_image.h
@@ -26,6 +26,8 @@ #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/core/style/style_image.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" #include "third_party/blink/renderer/platform/wtf/casting.h" namespace blink {
diff --git a/third_party/blink/renderer/core/style/style_pending_image.h b/third_party/blink/renderer/core/style/style_pending_image.h index fe38a188..452bfb08 100644 --- a/third_party/blink/renderer/core/style/style_pending_image.h +++ b/third_party/blink/renderer/core/style/style_pending_image.h
@@ -28,6 +28,8 @@ #include "third_party/blink/renderer/core/style/style_image.h" #include "third_party/blink/renderer/platform/graphics/image.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" #include "third_party/blink/renderer/platform/wtf/casting.h" namespace blink {
diff --git a/third_party/blink/renderer/core/svg/properties/svg_listable_property.h b/third_party/blink/renderer/core/svg/properties/svg_listable_property.h index 0fff8bd..e3ae456 100644 --- a/third_party/blink/renderer/core/svg/properties/svg_listable_property.h +++ b/third_party/blink/renderer/core/svg/properties/svg_listable_property.h
@@ -32,6 +32,7 @@ #define THIRD_PARTY_BLINK_RENDERER_CORE_SVG_PROPERTIES_SVG_LISTABLE_PROPERTY_H_ #include "third_party/blink/renderer/core/svg/properties/svg_property.h" +#include "third_party/blink/renderer/platform/heap/member.h" namespace blink {
diff --git a/third_party/blink/renderer/core/svg/properties/svg_property_tear_off.h b/third_party/blink/renderer/core/svg/properties/svg_property_tear_off.h index 09f94cd2c..39145205 100644 --- a/third_party/blink/renderer/core/svg/properties/svg_property_tear_off.h +++ b/third_party/blink/renderer/core/svg/properties/svg_property_tear_off.h
@@ -33,7 +33,8 @@ #include "third_party/blink/renderer/core/svg/properties/svg_property.h" #include "third_party/blink/renderer/platform/bindings/script_wrappable.h" -#include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" namespace blink {
diff --git a/third_party/blink/renderer/core/svg/svg_fit_to_view_box.h b/third_party/blink/renderer/core/svg/svg_fit_to_view_box.h index cdf68dc..43bc564 100644 --- a/third_party/blink/renderer/core/svg/svg_fit_to_view_box.h +++ b/third_party/blink/renderer/core/svg/svg_fit_to_view_box.h
@@ -22,7 +22,8 @@ #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_SVG_SVG_FIT_TO_VIEW_BOX_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_SVG_SVG_FIT_TO_VIEW_BOX_H_ -#include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" namespace gfx { class RectF;
diff --git a/third_party/blink/renderer/core/svg/svg_matrix_tear_off.h b/third_party/blink/renderer/core/svg/svg_matrix_tear_off.h index 6a154dfb..074d9cf7 100644 --- a/third_party/blink/renderer/core/svg/svg_matrix_tear_off.h +++ b/third_party/blink/renderer/core/svg/svg_matrix_tear_off.h
@@ -33,7 +33,8 @@ #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/platform/bindings/script_wrappable.h" -#include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" #include "third_party/blink/renderer/platform/transforms/affine_transform.h" namespace blink {
diff --git a/third_party/blink/renderer/core/svg/svg_resource_document_content.h b/third_party/blink/renderer/core/svg/svg_resource_document_content.h index 15da254..f14f8de 100644 --- a/third_party/blink/renderer/core/svg/svg_resource_document_content.h +++ b/third_party/blink/renderer/core/svg/svg_resource_document_content.h
@@ -24,7 +24,8 @@ #define THIRD_PARTY_BLINK_RENDERER_CORE_SVG_SVG_RESOURCE_DOCUMENT_CONTENT_H_ #include "third_party/blink/renderer/core/core_export.h" -#include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" namespace blink {
diff --git a/third_party/blink/renderer/core/svg/svg_tests.h b/third_party/blink/renderer/core/svg/svg_tests.h index cae06188..5f49b9f 100644 --- a/third_party/blink/renderer/core/svg/svg_tests.h +++ b/third_party/blink/renderer/core/svg/svg_tests.h
@@ -22,7 +22,8 @@ #define THIRD_PARTY_BLINK_RENDERER_CORE_SVG_SVG_TESTS_H_ #include "third_party/blink/renderer/core/core_export.h" -#include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" namespace blink {
diff --git a/third_party/blink/renderer/core/svg/svg_uri_reference.h b/third_party/blink/renderer/core/svg/svg_uri_reference.h index b2fedbd..c09da3f3 100644 --- a/third_party/blink/renderer/core/svg/svg_uri_reference.h +++ b/third_party/blink/renderer/core/svg/svg_uri_reference.h
@@ -23,7 +23,8 @@ #include "base/callback.h" #include "third_party/blink/renderer/core/core_export.h" -#include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" #include "third_party/blink/renderer/platform/weborigin/kurl.h" namespace blink {
diff --git a/third_party/blink/renderer/core/svg/svg_view_spec.h b/third_party/blink/renderer/core/svg/svg_view_spec.h index 65eb928..2e3f383 100644 --- a/third_party/blink/renderer/core/svg/svg_view_spec.h +++ b/third_party/blink/renderer/core/svg/svg_view_spec.h
@@ -21,7 +21,8 @@ #define THIRD_PARTY_BLINK_RENDERER_CORE_SVG_SVG_VIEW_SPEC_H_ #include "third_party/blink/renderer/core/svg/svg_zoom_and_pan.h" -#include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" namespace blink {
diff --git a/third_party/blink/renderer/core/testing/mock_clipboard_host.cc b/third_party/blink/renderer/core/testing/mock_clipboard_host.cc index b0f8a20e..0f0b30a 100644 --- a/third_party/blink/renderer/core/testing/mock_clipboard_host.cc +++ b/third_party/blink/renderer/core/testing/mock_clipboard_host.cc
@@ -202,7 +202,7 @@ unsanitized_custom_data_map_.Set(format, data_copy); } -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) void MockClipboardHost::WriteStringToFindPboard(const String& text) {} #endif
diff --git a/third_party/blink/renderer/core/testing/mock_clipboard_host.h b/third_party/blink/renderer/core/testing/mock_clipboard_host.h index 97e1f01..73d3fac 100644 --- a/third_party/blink/renderer/core/testing/mock_clipboard_host.h +++ b/third_party/blink/renderer/core/testing/mock_clipboard_host.h
@@ -64,7 +64,7 @@ ReadUnsanitizedCustomFormatCallback callback) override; void WriteUnsanitizedCustomFormat(const String& format, mojo_base::BigBuffer data) override; -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) void WriteStringToFindPboard(const String& text) override; #endif
diff --git a/third_party/blink/renderer/core/testing/scoped_mock_overlay_scrollbars.h b/third_party/blink/renderer/core/testing/scoped_mock_overlay_scrollbars.h index a4dab3e..a43c6b77 100644 --- a/third_party/blink/renderer/core/testing/scoped_mock_overlay_scrollbars.h +++ b/third_party/blink/renderer/core/testing/scoped_mock_overlay_scrollbars.h
@@ -68,7 +68,7 @@ // platform independent. if (use_mock_overlay_scrollbars_) return true; -#if defined(OS_ANDROID) || defined(OS_CHROMEOS) +#if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_CHROMEOS) // Non-overlay scrollbar is not supported on Android and ChromeOS. return false; #else
diff --git a/third_party/blink/renderer/core/testing/static_selection.h b/third_party/blink/renderer/core/testing/static_selection.h index 9aeb123..f30b326 100644 --- a/third_party/blink/renderer/core/testing/static_selection.h +++ b/third_party/blink/renderer/core/testing/static_selection.h
@@ -7,7 +7,8 @@ #include "third_party/blink/renderer/core/editing/forward.h" #include "third_party/blink/renderer/platform/bindings/script_wrappable.h" -#include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" namespace blink {
diff --git a/third_party/blink/renderer/core/testing/wait_for_event.h b/third_party/blink/renderer/core/testing/wait_for_event.h index 40f0e65..150671903 100644 --- a/third_party/blink/renderer/core/testing/wait_for_event.h +++ b/third_party/blink/renderer/core/testing/wait_for_event.h
@@ -7,6 +7,8 @@ #include "base/run_loop.h" #include "third_party/blink/renderer/core/dom/events/native_event_listener.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/heap/member.h" namespace blink {
diff --git a/third_party/blink/renderer/core/timing/profiler_group.cc b/third_party/blink/renderer/core/timing/profiler_group.cc index 6638ee3..3f16cebe 100644 --- a/third_party/blink/renderer/core/timing/profiler_group.cc +++ b/third_party/blink/renderer/core/timing/profiler_group.cc
@@ -30,7 +30,7 @@ namespace { -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) // On Windows, assume we have the coarsest possible timer. static constexpr int kBaseSampleIntervalMs = base::Time::kMinLowResolutionThresholdMs; @@ -38,7 +38,7 @@ // Default to a 10ms base sampling interval on other platforms. // TODO(acomminos): Reevaluate based on empirical overhead. static constexpr int kBaseSampleIntervalMs = 10; -#endif // defined(OS_WIN) +#endif // BUILDFLAG(IS_WIN) } // namespace @@ -258,11 +258,11 @@ cpu_profiler_ = v8::CpuProfiler::New(isolate_, v8::kStandardNaming, v8::kEagerLogging); -#if defined(OS_WIN) +#if BUILDFLAG(IS_WIN) // Avoid busy-waiting on Windows, clamping us to the system clock interrupt // interval in the worst case. cpu_profiler_->SetUsePreciseSampling(false); -#endif // defined(OS_WIN) +#endif // BUILDFLAG(IS_WIN) cpu_profiler_->SetSamplingInterval(kBaseSampleIntervalMs * base::Time::kMicrosecondsPerMillisecond); }
diff --git a/third_party/blink/renderer/modules/ad_auction/navigator_auction.cc b/third_party/blink/renderer/modules/ad_auction/navigator_auction.cc index 06dc8dbf..1ff9ffe 100644 --- a/third_party/blink/renderer/modules/ad_auction/navigator_auction.cc +++ b/third_party/blink/renderer/modules/ad_auction/navigator_auction.cc
@@ -548,7 +548,7 @@ mojom::blink::AuctionAdConfig& output) { if (!input.hasInterestGroupBuyers()) return true; - output.shareable_auction_ad_config->interest_group_buyers = + output.auction_ad_config_non_shared_params->interest_group_buyers = mojom::blink::InterestGroupBuyers::New(); switch (input.interestGroupBuyers()->GetContentType()) { case V8UnionUSVStringOrUSVStringSequence::ContentType::kUSVString: { @@ -561,8 +561,8 @@ "strings.")); return false; } - output.shareable_auction_ad_config->interest_group_buyers->set_all_buyers( - mojom::blink::AllBuyers::New()); + output.auction_ad_config_non_shared_params->interest_group_buyers + ->set_all_buyers(mojom::blink::AllBuyers::New()); break; } case V8UnionUSVStringOrUSVStringSequence::ContentType::kUSVStringSequence: { @@ -578,8 +578,8 @@ } buyers.push_back(buyer); } - output.shareable_auction_ad_config->interest_group_buyers->set_buyers( - std::move(buyers)); + output.auction_ad_config_non_shared_params->interest_group_buyers + ->set_buyers(std::move(buyers)); break; } } @@ -594,7 +594,7 @@ if (!input.hasAuctionSignals()) return true; if (!Jsonify(script_state, input.auctionSignals().V8Value(), - output.shareable_auction_ad_config->auction_signals)) { + output.auction_ad_config_non_shared_params->auction_signals)) { exception_state.ThrowTypeError( ErrorInvalidAuctionConfigJson(input, "auctionSignals")); return false; @@ -609,7 +609,7 @@ if (!input.hasSellerSignals()) return true; if (!Jsonify(script_state, input.sellerSignals().V8Value(), - output.shareable_auction_ad_config->seller_signals)) { + output.auction_ad_config_non_shared_params->seller_signals)) { exception_state.ThrowTypeError( ErrorInvalidAuctionConfigJson(input, "sellerSignals")); return false; @@ -624,7 +624,7 @@ mojom::blink::AuctionAdConfig& output) { if (!input.hasPerBuyerSignals()) return true; - output.shareable_auction_ad_config->per_buyer_signals.emplace(); + output.auction_ad_config_non_shared_params->per_buyer_signals.emplace(); for (const auto& per_buyer_signal : input.perBuyerSignals()) { scoped_refptr<const SecurityOrigin> buyer = ParseOrigin(per_buyer_signal.first); @@ -641,7 +641,7 @@ ErrorInvalidAuctionConfigJson(input, "perBuyerSignals")); return false; } - output.shareable_auction_ad_config->per_buyer_signals->insert( + output.auction_ad_config_non_shared_params->per_buyer_signals->insert( buyer, std::move(buyer_signals_str)); } @@ -870,8 +870,8 @@ ExceptionState& exception_state) { const ExecutionContext* context = ExecutionContext::From(script_state); auto mojo_config = mojom::blink::AuctionAdConfig::New(); - mojo_config->shareable_auction_ad_config = - mojom::blink::ShareableAuctionAdConfig::New(); + mojo_config->auction_ad_config_non_shared_params = + mojom::blink::AuctionAdConfigNonSharedParams::New(); if (!CopySellerFromIdlToMojo(exception_state, *config, *mojo_config) || !CopyDecisionLogicUrlFromIdlToMojo(*context, exception_state, *config, *mojo_config) ||
diff --git a/third_party/blink/renderer/modules/bluetooth/bluetooth_error.h b/third_party/blink/renderer/modules/bluetooth/bluetooth_error.h index 42418c0..6ce7c87 100644 --- a/third_party/blink/renderer/modules/bluetooth/bluetooth_error.h +++ b/third_party/blink/renderer/modules/bluetooth/bluetooth_error.h
@@ -8,6 +8,7 @@ #include "third_party/blink/public/mojom/bluetooth/web_bluetooth.mojom-blink-forward.h" #include "third_party/blink/renderer/platform/heap/handle.h" #include "third_party/blink/renderer/platform/wtf/allocator/allocator.h" +#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" namespace blink {
diff --git a/third_party/blink/renderer/modules/peerconnection/mock_peer_connection_dependency_factory.cc b/third_party/blink/renderer/modules/peerconnection/mock_peer_connection_dependency_factory.cc index 36bfcbd..e724ccd 100644 --- a/third_party/blink/renderer/modules/peerconnection/mock_peer_connection_dependency_factory.cc +++ b/third_party/blink/renderer/modules/peerconnection/mock_peer_connection_dependency_factory.cc
@@ -53,13 +53,13 @@ MockMediaStream::MockMediaStream(const std::string& id) : id_(id) {} bool MockMediaStream::AddTrack(AudioTrackInterface* track) { - audio_track_vector_.push_back(track); + audio_track_vector_.emplace_back(track); NotifyObservers(); return true; } bool MockMediaStream::AddTrack(VideoTrackInterface* track) { - video_track_vector_.push_back(track); + video_track_vector_.emplace_back(track); NotifyObservers(); return true; }
diff --git a/third_party/blink/renderer/modules/peerconnection/mock_peer_connection_impl.cc b/third_party/blink/renderer/modules/peerconnection/mock_peer_connection_impl.cc index 420bc60..3a4c036 100644 --- a/third_party/blink/renderer/modules/peerconnection/mock_peer_connection_impl.cc +++ b/third_party/blink/renderer/modules/peerconnection/mock_peer_connection_impl.cc
@@ -63,7 +63,9 @@ } return nullptr; } - void AddStream(MediaStreamInterface* stream) { streams_.push_back(stream); } + void AddStream(MediaStreamInterface* stream) { + streams_.emplace_back(stream); + } void RemoveStream(MediaStreamInterface* stream) { auto it = streams_.begin(); for (; it != streams_.end(); ++it) { @@ -167,7 +169,8 @@ rtc::scoped_refptr<webrtc::DtmfSenderInterface> FakeRtpSender::GetDtmfSender() const { - return new rtc::RefCountedObject<MockDtmfSender>(); + return rtc::scoped_refptr<webrtc::DtmfSenderInterface>( + new rtc::RefCountedObject<MockDtmfSender>()); } FakeRtpReceiver::FakeRtpReceiver( @@ -376,13 +379,14 @@ local_stream_ids_.push_back(stream_id); } } - auto* sender = new rtc::RefCountedObject<FakeRtpSender>(track, stream_ids); + rtc::scoped_refptr<FakeRtpSender> sender( + new rtc::RefCountedObject<FakeRtpSender>(track, stream_ids)); senders_.push_back(sender); return rtc::scoped_refptr<webrtc::RtpSenderInterface>(sender); } bool MockPeerConnectionImpl::RemoveTrack(webrtc::RtpSenderInterface* s) { - rtc::scoped_refptr<FakeRtpSender> sender = static_cast<FakeRtpSender*>(s); + rtc::scoped_refptr<FakeRtpSender> sender(static_cast<FakeRtpSender*>(s)); auto it = std::find(senders_.begin(), senders_.end(), sender); if (it == senders_.end()) return false; @@ -411,11 +415,11 @@ std::vector<rtc::scoped_refptr<webrtc::RtpReceiverInterface>> receivers; for (size_t i = 0; i < remote_streams_->count(); ++i) { for (const auto& audio_track : remote_streams_->at(i)->GetAudioTracks()) { - receivers.push_back( + receivers.emplace_back( new rtc::RefCountedObject<FakeRtpReceiver>(audio_track)); } for (const auto& video_track : remote_streams_->at(i)->GetVideoTracks()) { - receivers.push_back( + receivers.emplace_back( new rtc::RefCountedObject<FakeRtpReceiver>(video_track)); } } @@ -426,7 +430,8 @@ MockPeerConnectionImpl::CreateDataChannel( const std::string& label, const webrtc::DataChannelInit* config) { - return new rtc::RefCountedObject<blink::MockDataChannel>(label, config); + return rtc::scoped_refptr<webrtc::DataChannelInterface>( + new rtc::RefCountedObject<blink::MockDataChannel>(label, config)); } bool MockPeerConnectionImpl::GetStats(webrtc::StatsObserver* observer,
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_handler.cc b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_handler.cc index 8a5be0a..fa7125b 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_handler.cc +++ b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_handler.cc
@@ -18,6 +18,7 @@ #include "base/bind.h" #include "base/location.h" #include "base/logging.h" +#include "base/memory/scoped_refptr.h" #include "base/metrics/histogram_functions.h" #include "base/metrics/histogram_macros.h" #include "base/threading/thread_checker.h" @@ -1745,8 +1746,9 @@ RunSynchronousRepeatingClosureOnSignalingThread( base::BindRepeating( &RTCPeerConnectionHandler::AddTransceiverWithTrackOnSignalingThread, - base::Unretained(this), base::RetainedRef(track_ref->webrtc_track()), - std::cref(init), base::Unretained(&transceiver_state_surfacer), + base::Unretained(this), + base::RetainedRef(track_ref->webrtc_track().get()), std::cref(init), + base::Unretained(&transceiver_state_surfacer), base::Unretained(&error_or_transceiver)), "AddTransceiverWithTrackOnSignalingThread"); if (!error_or_transceiver.ok()) { @@ -1771,13 +1773,14 @@ } void RTCPeerConnectionHandler::AddTransceiverWithTrackOnSignalingThread( - rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> webrtc_track, + webrtc::MediaStreamTrackInterface* webrtc_track, webrtc::RtpTransceiverInit init, blink::TransceiverStateSurfacer* transceiver_state_surfacer, webrtc::RTCErrorOr<rtc::scoped_refptr<webrtc::RtpTransceiverInterface>>* error_or_transceiver) { - *error_or_transceiver = - native_peer_connection_->AddTransceiver(webrtc_track, init); + *error_or_transceiver = native_peer_connection_->AddTransceiver( + rtc::scoped_refptr<webrtc::MediaStreamTrackInterface>(webrtc_track), + init); std::vector<rtc::scoped_refptr<webrtc::RtpTransceiverInterface>> transceivers; if (error_or_transceiver->ok()) transceivers.push_back(error_or_transceiver->value()); @@ -1868,11 +1871,12 @@ webrtc::RTCErrorOr<rtc::scoped_refptr<webrtc::RtpSenderInterface>> error_or_sender; RunSynchronousRepeatingClosureOnSignalingThread( - base::BindRepeating( - &RTCPeerConnectionHandler::AddTrackOnSignalingThread, - base::Unretained(this), base::RetainedRef(track_ref->webrtc_track()), - std::move(stream_ids), base::Unretained(&transceiver_state_surfacer), - base::Unretained(&error_or_sender)), + base::BindRepeating(&RTCPeerConnectionHandler::AddTrackOnSignalingThread, + base::Unretained(this), + base::RetainedRef(track_ref->webrtc_track().get()), + std::move(stream_ids), + base::Unretained(&transceiver_state_surfacer), + base::Unretained(&error_or_sender)), "AddTrackOnSignalingThread"); DCHECK(transceiver_state_surfacer.is_initialized()); if (!error_or_sender.ok()) { @@ -1928,17 +1932,19 @@ } void RTCPeerConnectionHandler::AddTrackOnSignalingThread( - rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track, + webrtc::MediaStreamTrackInterface* track, std::vector<std::string> stream_ids, blink::TransceiverStateSurfacer* transceiver_state_surfacer, webrtc::RTCErrorOr<rtc::scoped_refptr<webrtc::RtpSenderInterface>>* error_or_sender) { - *error_or_sender = native_peer_connection_->AddTrack(track, stream_ids); + *error_or_sender = native_peer_connection_->AddTrack( + rtc::scoped_refptr<webrtc::MediaStreamTrackInterface>(track), stream_ids); std::vector<rtc::scoped_refptr<webrtc::RtpTransceiverInterface>> transceivers; if (error_or_sender->ok()) { auto sender = error_or_sender->value(); if (configuration_.sdp_semantics == webrtc::SdpSemantics::kPlanB) { - transceivers = {new blink::SurfaceSenderStateOnly(sender)}; + transceivers = {rtc::scoped_refptr<webrtc::RtpTransceiverInterface>( + new blink::SurfaceSenderStateOnly(sender))}; } else { DCHECK_EQ(configuration_.sdp_semantics, webrtc::SdpSemantics::kUnifiedPlan); @@ -2065,7 +2071,7 @@ } void RTCPeerConnectionHandler::RemoveTrackUnifiedPlanOnSignalingThread( - rtc::scoped_refptr<webrtc::RtpSenderInterface> sender, + webrtc::RtpSenderInterface* sender, blink::TransceiverStateSurfacer* transceiver_state_surfacer, CancellableBooleanOperationResult* result) { bool is_successful = native_peer_connection_->RemoveTrack(sender);
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_handler.h b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_handler.h index 4f5ab5e..d11b2d62 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_handler.h +++ b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_handler.h
@@ -394,7 +394,7 @@ const FirstSessionDescription& remote); void AddTransceiverWithTrackOnSignalingThread( - rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> webrtc_track, + webrtc::MediaStreamTrackInterface* webrtc_track, webrtc::RtpTransceiverInit init, blink::TransceiverStateSurfacer* transceiver_state_surfacer, webrtc::RTCErrorOr<rtc::scoped_refptr<webrtc::RtpTransceiverInterface>>* @@ -406,7 +406,7 @@ webrtc::RTCErrorOr<rtc::scoped_refptr<webrtc::RtpTransceiverInterface>>* error_or_transceiver); void AddTrackOnSignalingThread( - rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track, + webrtc::MediaStreamTrackInterface* track, std::vector<std::string> stream_ids, blink::TransceiverStateSurfacer* transceiver_state_surfacer, webrtc::RTCErrorOr<rtc::scoped_refptr<webrtc::RtpSenderInterface>>* @@ -415,7 +415,7 @@ webrtc::RTCErrorOr<std::unique_ptr<RTCRtpTransceiverPlatform>> RemoveTrackUnifiedPlan(blink::RTCRtpSenderPlatform* web_sender); void RemoveTrackUnifiedPlanOnSignalingThread( - rtc::scoped_refptr<webrtc::RtpSenderInterface> sender, + webrtc::RtpSenderInterface* sender, blink::TransceiverStateSurfacer* transceiver_state_surfacer, CancellableBooleanOperationResult* result); Vector<std::unique_ptr<RTCRtpTransceiverPlatform>> CreateOfferInternal(
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_rtp_receiver_impl.cc b/third_party/blink/renderer/modules/peerconnection/rtc_rtp_receiver_impl.cc index 70bdf03..12deae23 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_rtp_receiver_impl.cc +++ b/third_party/blink/renderer/modules/peerconnection/rtc_rtp_receiver_impl.cc
@@ -230,7 +230,8 @@ RTCStatsReportCallback callback, const Vector<webrtc::NonStandardGroupId>& exposed_group_ids) { native_peer_connection_->GetStats( - webrtc_receiver_.get(), + rtc::scoped_refptr<webrtc::RtpReceiverInterface>( + webrtc_receiver_.get()), CreateRTCStatsCollectorCallback(main_task_runner_, std::move(callback), exposed_group_ids)); }
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_rtp_receiver_impl_test.cc b/third_party/blink/renderer/modules/peerconnection/rtc_rtp_receiver_impl_test.cc index 82a3774b..24bd6f6a 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_rtp_receiver_impl_test.cc +++ b/third_party/blink/renderer/modules/peerconnection/rtc_rtp_receiver_impl_test.cc
@@ -120,7 +120,8 @@ receiver_ = CreateReceiver(webrtc_track); EXPECT_FALSE(!receiver_->Track()); EXPECT_EQ(receiver_->Track()->Id().Utf8(), webrtc_track->id()); - EXPECT_EQ(receiver_->state().track_ref()->webrtc_track(), webrtc_track); + EXPECT_EQ(receiver_->state().track_ref()->webrtc_track().get(), + webrtc_track.get()); EXPECT_FALSE(receiver_->GetEncodedAudioStreamTransformer()); EXPECT_FALSE(receiver_->GetEncodedVideoStreamTransformer()); } @@ -130,17 +131,20 @@ blink::MockWebRtcAudioTrack::Create("webrtc_track"); receiver_ = CreateReceiver(webrtc_track); auto copy = std::make_unique<RTCRtpReceiverImpl>(*receiver_); - EXPECT_EQ(receiver_->state().track_ref()->webrtc_track(), webrtc_track); + EXPECT_EQ(receiver_->state().track_ref()->webrtc_track().get(), + webrtc_track.get()); const auto& webrtc_receiver = receiver_->state().webrtc_receiver(); auto web_track_unique_id = receiver_->Track()->UniqueId(); // Copy is identical to original. EXPECT_EQ(copy->state().webrtc_receiver(), webrtc_receiver); - EXPECT_EQ(copy->state().track_ref()->webrtc_track(), webrtc_track); + EXPECT_EQ(copy->state().track_ref()->webrtc_track().get(), + webrtc_track.get()); EXPECT_EQ(copy->Track()->UniqueId(), web_track_unique_id); // Copy keeps the internal state alive. receiver_.reset(); EXPECT_EQ(copy->state().webrtc_receiver(), webrtc_receiver); - EXPECT_EQ(copy->state().track_ref()->webrtc_track(), webrtc_track); + EXPECT_EQ(copy->state().track_ref()->webrtc_track().get(), + webrtc_track.get()); EXPECT_EQ(copy->Track()->UniqueId(), web_track_unique_id); }
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_rtp_sender_impl.cc b/third_party/blink/renderer/modules/peerconnection/rtc_rtp_sender_impl.cc index 6b42cde..bc1b614 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_rtp_sender_impl.cc +++ b/third_party/blink/renderer/modules/peerconnection/rtc_rtp_sender_impl.cc
@@ -384,7 +384,7 @@ RTCStatsReportCallbackInternal callback, const Vector<webrtc::NonStandardGroupId>& exposed_group_ids) { native_peer_connection_->GetStats( - webrtc_sender_.get(), + rtc::scoped_refptr<webrtc::RtpSenderInterface>(webrtc_sender_.get()), CreateRTCStatsCollectorCallback( main_task_runner_, ConvertToBaseOnceCallback(std::move(callback)), exposed_group_ids));
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_rtp_transceiver_impl_test.cc b/third_party/blink/renderer/modules/peerconnection/rtc_rtp_transceiver_impl_test.cc index 21d1276..ed8ad15 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_rtp_transceiver_impl_test.cc +++ b/third_party/blink/renderer/modules/peerconnection/rtc_rtp_transceiver_impl_test.cc
@@ -69,8 +69,8 @@ std::unique_ptr<blink::WebRtcMediaStreamTrackAdapterMap::AdapterRef> CreateRemoteTrackAndAdapter(const std::string& id) { - rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> webrtc_track = - blink::MockWebRtcAudioTrack::Create(id).get(); + rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> webrtc_track( + blink::MockWebRtcAudioTrack::Create(id).get()); std::unique_ptr<blink::WebRtcMediaStreamTrackAdapterMap::AdapterRef> track_ref; base::RunLoop run_loop; @@ -89,8 +89,9 @@ rtc::scoped_refptr<blink::FakeRtpSender> CreateWebRtcSender( rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track, const std::string& stream_id) { - return new rtc::RefCountedObject<blink::FakeRtpSender>( - std::move(track), std::vector<std::string>({stream_id})); + return rtc::scoped_refptr<blink::FakeRtpSender>( + new rtc::RefCountedObject<blink::FakeRtpSender>( + std::move(track), std::vector<std::string>({stream_id}))); } rtc::scoped_refptr<blink::FakeRtpReceiver> CreateWebRtcReceiver( @@ -98,10 +99,11 @@ const std::string& stream_id) { rtc::scoped_refptr<webrtc::MediaStreamInterface> remote_stream( new rtc::RefCountedObject<blink::MockMediaStream>(stream_id)); - return new rtc::RefCountedObject<blink::FakeRtpReceiver>( - track.get(), - std::vector<rtc::scoped_refptr<webrtc::MediaStreamInterface>>( - {remote_stream})); + return rtc::scoped_refptr<blink::FakeRtpReceiver>( + new rtc::RefCountedObject<blink::FakeRtpReceiver>( + track, + std::vector<rtc::scoped_refptr<webrtc::MediaStreamInterface>>( + {remote_stream}))); } rtc::scoped_refptr<blink::FakeRtpTransceiver> CreateWebRtcTransceiver( @@ -113,13 +115,14 @@ absl::optional<webrtc::RtpTransceiverDirection> current_direction) { DCHECK(!sender->track() || sender->track()->kind() == receiver->track()->kind()); - return new rtc::RefCountedObject<blink::FakeRtpTransceiver>( - receiver->track()->kind() == - webrtc::MediaStreamTrackInterface::kAudioKind - ? cricket::MEDIA_TYPE_AUDIO - : cricket::MEDIA_TYPE_VIDEO, - std::move(sender), std::move(receiver), std::move(mid), stopped, - direction, std::move(current_direction)); + return rtc::scoped_refptr<blink::FakeRtpTransceiver>( + new rtc::RefCountedObject<blink::FakeRtpTransceiver>( + receiver->track()->kind() == + webrtc::MediaStreamTrackInterface::kAudioKind + ? cricket::MEDIA_TYPE_AUDIO + : cricket::MEDIA_TYPE_VIDEO, + std::move(sender), std::move(receiver), std::move(mid), stopped, + direction, std::move(current_direction))); } RtpTransceiverState CreateTransceiverState(
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_sctp_transport.cc b/third_party/blink/renderer/modules/peerconnection/rtc_sctp_transport.cc index 1ae33178..accc42b 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_sctp_transport.cc +++ b/third_party/blink/renderer/modules/peerconnection/rtc_sctp_transport.cc
@@ -52,8 +52,10 @@ DCHECK(worker_thread); LocalFrame* frame = To<LocalDOMWindow>(context)->GetFrame(); DCHECK(frame); - return SctpTransportProxy::Create(*frame, main_thread, worker_thread, - native_transport, delegate); + return SctpTransportProxy::Create( + *frame, main_thread, worker_thread, + rtc::scoped_refptr<webrtc::SctpTransportInterface>(native_transport), + delegate); } } // namespace
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_sctp_transport_test.cc b/third_party/blink/renderer/modules/peerconnection/rtc_sctp_transport_test.cc index d75aebb3..56207c41 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_sctp_transport_test.cc +++ b/third_party/blink/renderer/modules/peerconnection/rtc_sctp_transport_test.cc
@@ -56,8 +56,8 @@ V8TestingScope scope; ExecutionContext* context = scope.GetExecutionContext(); - rtc::scoped_refptr<webrtc::SctpTransportInterface> mock_native_transport = - new rtc::RefCountedObject<NiceMock<MockSctpTransport>>(); + rtc::scoped_refptr<webrtc::SctpTransportInterface> mock_native_transport( + new rtc::RefCountedObject<NiceMock<MockSctpTransport>>()); RTCSctpTransport* transport = MakeGarbageCollected<RTCSctpTransport>( context, mock_native_transport, main_thread_, worker_thread_); WeakPersistent<RTCSctpTransport> garbage_collection_observer = transport;
diff --git a/third_party/blink/renderer/modules/peerconnection/thermal_resource.cc b/third_party/blink/renderer/modules/peerconnection/thermal_resource.cc index 4c5584a..624e895f 100644 --- a/third_party/blink/renderer/modules/peerconnection/thermal_resource.cc +++ b/third_party/blink/renderer/modules/peerconnection/thermal_resource.cc
@@ -73,12 +73,14 @@ case mojom::blink::DeviceThermalState::kNominal: case mojom::blink::DeviceThermalState::kFair: listener_->OnResourceUsageStateMeasured( - this, webrtc::ResourceUsageState::kUnderuse); + rtc::scoped_refptr<Resource>(this), + webrtc::ResourceUsageState::kUnderuse); break; case mojom::blink::DeviceThermalState::kSerious: case mojom::blink::DeviceThermalState::kCritical: listener_->OnResourceUsageStateMeasured( - this, webrtc::ResourceUsageState::kOveruse); + rtc::scoped_refptr<Resource>(this), + webrtc::ResourceUsageState::kOveruse); break; } // Repeat the reporting every 10 seconds until a new measurement is made or
diff --git a/third_party/blink/renderer/modules/peerconnection/transceiver_state_surfacer_test.cc b/third_party/blink/renderer/modules/peerconnection/transceiver_state_surfacer_test.cc index f5705b2..dbd721de 100644 --- a/third_party/blink/renderer/modules/peerconnection/transceiver_state_surfacer_test.cc +++ b/third_party/blink/renderer/modules/peerconnection/transceiver_state_surfacer_test.cc
@@ -84,7 +84,7 @@ const std::string& remote_track_id, const std::string& remote_stream_id, rtc::scoped_refptr<webrtc::DtlsTransportInterface> transport) { - rtc::scoped_refptr<blink::FakeRtpTransceiver> transceiver = + rtc::scoped_refptr<blink::FakeRtpTransceiver> transceiver( new rtc::RefCountedObject<blink::FakeRtpTransceiver>( local_track->kind() == webrtc::MediaStreamTrackInterface::kAudioKind ? cricket::MEDIA_TYPE_AUDIO @@ -92,7 +92,7 @@ CreateWebRtcSender(local_track, local_stream_id), CreateWebRtcReceiver(remote_track_id, remote_stream_id), absl::nullopt, false, webrtc::RtpTransceiverDirection::kSendRecv, - absl::nullopt); + absl::nullopt)); if (transport.get()) { transceiver->SetTransport(transport); } @@ -102,21 +102,23 @@ rtc::scoped_refptr<blink::FakeRtpSender> CreateWebRtcSender( rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track, const std::string& stream_id) { - return new rtc::RefCountedObject<blink::FakeRtpSender>( - std::move(track), std::vector<std::string>({stream_id})); + return rtc::scoped_refptr<blink::FakeRtpSender>( + new rtc::RefCountedObject<blink::FakeRtpSender>( + std::move(track), std::vector<std::string>({stream_id}))); } rtc::scoped_refptr<blink::FakeRtpReceiver> CreateWebRtcReceiver( const std::string& track_id, const std::string& stream_id) { - rtc::scoped_refptr<webrtc::AudioTrackInterface> remote_track = - blink::MockWebRtcAudioTrack::Create(track_id).get(); + rtc::scoped_refptr<webrtc::AudioTrackInterface> remote_track( + blink::MockWebRtcAudioTrack::Create(track_id).get()); rtc::scoped_refptr<webrtc::MediaStreamInterface> remote_stream( new rtc::RefCountedObject<blink::MockMediaStream>(stream_id)); - return new rtc::RefCountedObject<blink::FakeRtpReceiver>( - remote_track.get(), - std::vector<rtc::scoped_refptr<webrtc::MediaStreamInterface>>( - {remote_stream})); + return rtc::scoped_refptr<blink::FakeRtpReceiver>( + new rtc::RefCountedObject<blink::FakeRtpReceiver>( + remote_track, + std::vector<rtc::scoped_refptr<webrtc::MediaStreamInterface>>( + {remote_stream}))); } // Initializes the surfacer on the signaling thread and signals the waitable @@ -311,7 +313,9 @@ auto local_track_adapter = CreateLocalTrackAndAdapter("local_track"); auto webrtc_transceiver = CreateWebRtcTransceiver( local_track_adapter->webrtc_track(), "local_stream", "remote_track", - "remote_stream", new rtc::RefCountedObject<blink::FakeDtlsTransport>()); + "remote_stream", + rtc::scoped_refptr<webrtc::DtlsTransportInterface>( + new rtc::RefCountedObject<blink::FakeDtlsTransport>())); auto run_loop = AsyncInitializeSurfacerWithCallback( {webrtc_transceiver}, base::BindOnce( @@ -325,7 +329,8 @@ auto webrtc_sender = CreateWebRtcSender(local_track_adapter->webrtc_track(), "local_stream"); auto waitable_event = AsyncInitializeSurfacerWithWaitableEvent( - {new SurfaceSenderStateOnly(webrtc_sender)}); + {rtc::scoped_refptr<webrtc::RtpTransceiverInterface>( + new SurfaceSenderStateOnly(webrtc_sender))}); waitable_event->Wait(); auto transceiver_states = surfacer_->ObtainStates(); EXPECT_EQ(1u, transceiver_states.size()); @@ -346,7 +351,8 @@ auto local_track_adapter = CreateLocalTrackAndAdapter("local_track"); auto webrtc_receiver = CreateWebRtcReceiver("remote_track", "remote_stream"); auto waitable_event = AsyncInitializeSurfacerWithWaitableEvent( - {new SurfaceReceiverStateOnly(webrtc_receiver)}); + {rtc::scoped_refptr<webrtc::RtpTransceiverInterface>( + new SurfaceReceiverStateOnly(webrtc_receiver))}); waitable_event->Wait(); auto transceiver_states = surfacer_->ObtainStates(); EXPECT_EQ(1u, transceiver_states.size()); @@ -368,8 +374,8 @@ auto webrtc_transceiver = CreateWebRtcTransceiver( local_track_adapter->webrtc_track(), "local_stream", "remote_track", "remote_stream", nullptr); - rtc::scoped_refptr<MockSctpTransport> mock_sctp_transport = - new rtc::RefCountedObject<MockSctpTransport>(); + rtc::scoped_refptr<MockSctpTransport> mock_sctp_transport( + new rtc::RefCountedObject<MockSctpTransport>()); webrtc::SctpTransportInformation sctp_transport_info( webrtc::SctpTransportState::kNew); EXPECT_CALL(
diff --git a/third_party/blink/renderer/modules/peerconnection/webrtc_media_stream_track_adapter.cc b/third_party/blink/renderer/modules/peerconnection/webrtc_media_stream_track_adapter.cc index 1f7c0ff..aa1d0b6 100644 --- a/third_party/blink/renderer/modules/peerconnection/webrtc_media_stream_track_adapter.cc +++ b/third_party/blink/renderer/modules/peerconnection/webrtc_media_stream_track_adapter.cc
@@ -146,12 +146,13 @@ return component_.Get(); } -webrtc::MediaStreamTrackInterface* +rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> WebRtcMediaStreamTrackAdapter::webrtc_track() { DCHECK(main_thread_->BelongsToCurrentThread()); DCHECK(webrtc_track_); EnsureTrackIsInitialized(); - return webrtc_track_.get(); + return rtc::scoped_refptr<webrtc::MediaStreamTrackInterface>( + webrtc_track_.get()); } bool WebRtcMediaStreamTrackAdapter::IsEqual(MediaStreamComponent* component) {
diff --git a/third_party/blink/renderer/modules/peerconnection/webrtc_media_stream_track_adapter.h b/third_party/blink/renderer/modules/peerconnection/webrtc_media_stream_track_adapter.h index 1ab4dd8..b8672b7 100644 --- a/third_party/blink/renderer/modules/peerconnection/webrtc_media_stream_track_adapter.h +++ b/third_party/blink/renderer/modules/peerconnection/webrtc_media_stream_track_adapter.h
@@ -65,7 +65,7 @@ // TODO(hbos): Allow these methods to be called on any thread and make them // const. https://crbug.com/756436 MediaStreamComponent* track(); - webrtc::MediaStreamTrackInterface* webrtc_track(); + rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> webrtc_track(); bool IsEqual(MediaStreamComponent* component); // For testing.
diff --git a/third_party/blink/renderer/modules/peerconnection/webrtc_media_stream_track_adapter_map.h b/third_party/blink/renderer/modules/peerconnection/webrtc_media_stream_track_adapter_map.h index e3e8d8c..be93229 100644 --- a/third_party/blink/renderer/modules/peerconnection/webrtc_media_stream_track_adapter_map.h +++ b/third_party/blink/renderer/modules/peerconnection/webrtc_media_stream_track_adapter_map.h
@@ -44,7 +44,7 @@ bool is_initialized() const { return adapter_->is_initialized(); } void InitializeOnMainThread(); MediaStreamComponent* track() const { return adapter_->track(); } - webrtc::MediaStreamTrackInterface* webrtc_track() const { + rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> webrtc_track() const { return adapter_->webrtc_track(); }
diff --git a/third_party/blink/renderer/modules/peerconnection/webrtc_set_description_observer.cc b/third_party/blink/renderer/modules/peerconnection/webrtc_set_description_observer.cc index 998192404..29a8425b 100644 --- a/third_party/blink/renderer/modules/peerconnection/webrtc_set_description_observer.cc +++ b/third_party/blink/renderer/modules/peerconnection/webrtc_set_description_observer.cc
@@ -80,7 +80,8 @@ if (pc_->signaling_state() != webrtc::PeerConnectionInterface::kClosed) { if (surface_receivers_only_) { for (const auto& receiver : pc_->GetReceivers()) { - transceivers.push_back(new blink::SurfaceReceiverStateOnly(receiver)); + transceivers.emplace_back( + new blink::SurfaceReceiverStateOnly(receiver)); } } else { transceivers = pc_->GetTransceivers();
diff --git a/third_party/blink/renderer/modules/peerconnection/webrtc_set_description_observer_test.cc b/third_party/blink/renderer/modules/peerconnection/webrtc_set_description_observer_test.cc index e053b53..d3d57db 100644 --- a/third_party/blink/renderer/modules/peerconnection/webrtc_set_description_observer_test.cc +++ b/third_party/blink/renderer/modules/peerconnection/webrtc_set_description_observer_test.cc
@@ -259,11 +259,11 @@ auto* component = CreateLocalTrack("local_track"); auto local_track_adapter = track_adapter_map_->GetOrCreateLocalTrackAdapter(component); - scoped_refptr<webrtc::MediaStreamTrackInterface> local_track = + rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> local_track = local_track_adapter->webrtc_track(); rtc::scoped_refptr<blink::FakeRtpSender> sender( new rtc::RefCountedObject<blink::FakeRtpSender>( - local_track.get(), std::vector<std::string>({"local_stream"}))); + local_track, std::vector<std::string>({"local_stream"}))); // A requirement of WebRtcSet[Local/Remote]DescriptionObserverHandler is // that local tracks have existing track adapters when the callback is // invoked. In practice this would be ensured by RTCPeerConnectionHandler. @@ -272,13 +272,13 @@ scoped_refptr<blink::MockWebRtcAudioTrack> remote_track = blink::MockWebRtcAudioTrack::Create("remote_track"); - scoped_refptr<webrtc::MediaStreamInterface> remote_stream( + rtc::scoped_refptr<webrtc::MediaStreamInterface> remote_stream( new rtc::RefCountedObject<blink::MockMediaStream>("remote_stream")); rtc::scoped_refptr<blink::FakeRtpReceiver> receiver( new rtc::RefCountedObject<blink::FakeRtpReceiver>( - remote_track.get(), + rtc::scoped_refptr<blink::MockWebRtcAudioTrack>(remote_track.get()), std::vector<rtc::scoped_refptr<webrtc::MediaStreamInterface>>( - {remote_stream.get()}))); + {remote_stream}))); rtc::scoped_refptr<webrtc::RtpTransceiverInterface> transceiver( new rtc::RefCountedObject<blink::FakeRtpTransceiver>( cricket::MEDIA_TYPE_AUDIO, sender, receiver, absl::nullopt, false, @@ -331,13 +331,14 @@ scoped_refptr<blink::MockWebRtcAudioTrack> remote_track = blink::MockWebRtcAudioTrack::Create("remote_track"); - scoped_refptr<webrtc::MediaStreamInterface> remote_stream( + rtc::scoped_refptr<webrtc::MediaStreamInterface> remote_stream( new rtc::RefCountedObject<blink::MockMediaStream>("remote_stream")); rtc::scoped_refptr<webrtc::RtpReceiverInterface> receiver( new rtc::RefCountedObject<blink::FakeRtpReceiver>( - remote_track.get(), + rtc::scoped_refptr<webrtc::MediaStreamTrackInterface>( + remote_track.get()), std::vector<rtc::scoped_refptr<webrtc::MediaStreamInterface>>( - {remote_stream.get()}))); + {remote_stream}))); receivers_.push_back(receiver); EXPECT_CALL(*pc_, GetReceivers()).WillRepeatedly(Return(receivers_)); }
diff --git a/third_party/blink/renderer/modules/subapps/sub_apps.cc b/third_party/blink/renderer/modules/subapps/sub_apps.cc index 7eddcb7..a51e699 100644 --- a/third_party/blink/renderer/modules/subapps/sub_apps.cc +++ b/third_party/blink/renderer/modules/subapps/sub_apps.cc
@@ -24,11 +24,11 @@ namespace { -// We get called back from the SubAppsProvider mojo service (inside the browser +// We get called back from the SubAppsService mojo service (inside the browser // process), pass on the result to the calling context. void OnAddSubApp(ScriptPromiseResolver* resolver, - mojom::blink::SubAppsProviderResult result) { - if (result == mojom::blink::SubAppsProviderResult::kSuccess) { + mojom::blink::SubAppsServiceResult result) { + if (result == mojom::blink::SubAppsServiceResult::kSuccess) { resolver->Resolve(); } else { resolver->Reject(MakeGarbageCollected<DOMException>( @@ -58,14 +58,14 @@ Supplement<Navigator>::Trace(visitor); } -mojo::Remote<mojom::blink::SubAppsProvider>& SubApps::GetProvider() { - if (!provider_.is_bound()) { +mojo::Remote<mojom::blink::SubAppsService>& SubApps::GetService() { + if (!service_.is_bound()) { GetSupplementable() ->GetExecutionContext() ->GetBrowserInterfaceBroker() - .GetInterface(provider_.BindNewPipeAndPassReceiver()); + .GetInterface(service_.BindNewPipeAndPassReceiver()); } - return provider_; + return service_; } ScriptPromise SubApps::add(ScriptState* script_state, @@ -99,8 +99,8 @@ } auto* resolver = MakeGarbageCollected<ScriptPromiseResolver>(script_state); - GetProvider()->Add(completed_url.GetPath(), - WTF::Bind(&OnAddSubApp, WrapPersistent(resolver))); + GetService()->Add(completed_url.GetPath(), + WTF::Bind(&OnAddSubApp, WrapPersistent(resolver))); return resolver->Promise(); }
diff --git a/third_party/blink/renderer/modules/subapps/sub_apps.h b/third_party/blink/renderer/modules/subapps/sub_apps.h index 4c21247..0fdefbc6 100644 --- a/third_party/blink/renderer/modules/subapps/sub_apps.h +++ b/third_party/blink/renderer/modules/subapps/sub_apps.h
@@ -6,7 +6,7 @@ #define THIRD_PARTY_BLINK_RENDERER_MODULES_SUBAPPS_SUB_APPS_H_ #include "mojo/public/cpp/bindings/remote.h" -#include "third_party/blink/public/mojom/subapps/sub_apps_provider.mojom-blink.h" +#include "third_party/blink/public/mojom/subapps/sub_apps_service.mojom-blink.h" #include "third_party/blink/renderer/platform/bindings/script_wrappable.h" #include "third_party/blink/renderer/platform/supplementable.h" #include "third_party/blink/renderer/platform/wtf/forward.h" @@ -36,9 +36,9 @@ ScriptPromise add(ScriptState*, const String& install_url, ExceptionState&); private: - mojo::Remote<mojom::blink::SubAppsProvider>& GetProvider(); + mojo::Remote<mojom::blink::SubAppsService>& GetService(); - mojo::Remote<mojom::blink::SubAppsProvider> provider_; + mojo::Remote<mojom::blink::SubAppsService> service_; }; } // namespace blink
diff --git a/third_party/blink/renderer/modules/webtransport/web_transport.cc b/third_party/blink/renderer/modules/webtransport/web_transport.cc index 994b559..3c6920a 100644 --- a/third_party/blink/renderer/modules/webtransport/web_transport.cc +++ b/third_party/blink/renderer/modules/webtransport/web_transport.cc
@@ -1165,6 +1165,10 @@ hash->algorithm(), value_builder.ToString())); } } + if (!fingerprints.IsEmpty()) { + execution_context->CountUse( + WebFeature::kWebTransportServerCertificateHashes); + } if (auto* scheduler = execution_context->GetScheduler()) { feature_handle_for_scheduler_ = scheduler->RegisterFeature(
diff --git a/third_party/blink/renderer/platform/geometry/calculation_expression_node.cc b/third_party/blink/renderer/platform/geometry/calculation_expression_node.cc index 178741f..6cca7a7 100644 --- a/third_party/blink/renderer/platform/geometry/calculation_expression_node.cc +++ b/third_party/blink/renderer/platform/geometry/calculation_expression_node.cc
@@ -8,182 +8,280 @@ namespace blink { -// ------ CalculationExpressionLeafNode ------ +// ------ CalculationExpressionNumberNode ------ -float CalculationExpressionLeafNode::Evaluate(float max_value) const { +float CalculationExpressionNumberNode::Evaluate(float max_value) const { + return value_; +} + +bool CalculationExpressionNumberNode::operator==( + const CalculationExpressionNode& other) const { + if (!other.IsNumber()) + return false; + const auto& other_number = To<CalculationExpressionNumberNode>(other); + return value_ == other_number.Value(); +} + +scoped_refptr<const CalculationExpressionNode> +CalculationExpressionNumberNode::Zoom(double) const { + return base::MakeRefCounted<CalculationExpressionNumberNode>(value_); +} + +#if DCHECK_IS_ON() +CalculationExpressionNode::ResultType +CalculationExpressionNumberNode::ResolvedResultType() const { + return result_type_; +} +#endif + +// ------ CalculationExpressionPixelsAndPercentNode ------ + +float CalculationExpressionPixelsAndPercentNode::Evaluate( + float max_value) const { return value_.pixels + value_.percent / 100 * max_value; } -bool CalculationExpressionLeafNode::operator==( +bool CalculationExpressionPixelsAndPercentNode::operator==( const CalculationExpressionNode& other) const { - if (!other.IsLeaf()) + if (!other.IsPixelsAndPercent()) return false; - const auto& other_leaf = To<CalculationExpressionLeafNode>(other); - return value_.pixels == other_leaf.value_.pixels && - value_.percent == other_leaf.value_.percent; + const auto& other_pixels_and_percent = + To<CalculationExpressionPixelsAndPercentNode>(other); + return value_.pixels == other_pixels_and_percent.value_.pixels && + value_.percent == other_pixels_and_percent.value_.percent; } scoped_refptr<const CalculationExpressionNode> -CalculationExpressionLeafNode::Zoom(double factor) const { +CalculationExpressionPixelsAndPercentNode::Zoom(double factor) const { PixelsAndPercent result(value_.pixels * factor, value_.percent); - return base::MakeRefCounted<CalculationExpressionLeafNode>(result); + return base::MakeRefCounted<CalculationExpressionPixelsAndPercentNode>( + result); } -// ------ CalculationExpressionMultiplicationNode ------ +#if DCHECK_IS_ON() +CalculationExpressionNode::ResultType +CalculationExpressionPixelsAndPercentNode::ResolvedResultType() const { + return result_type_; +} +#endif + +// ------ CalculationExpressionOperatorNode ------ // static scoped_refptr<const CalculationExpressionNode> -CalculationExpressionMultiplicationNode::CreateSimplified( - scoped_refptr<const CalculationExpressionNode> node, - float factor) { - if (!node->IsLeaf()) { - return base::MakeRefCounted<CalculationExpressionMultiplicationNode>( - std::move(node), factor); +CalculationExpressionOperatorNode::CreateSimplified(Children&& children, + CalculationOperator op) { + switch (op) { + case CalculationOperator::kAdd: + case CalculationOperator::kSubtract: { + DCHECK_EQ(children.size(), 2u); + if (!children[0]->IsPixelsAndPercent() || + !children[1]->IsPixelsAndPercent()) { + return base::MakeRefCounted<CalculationExpressionOperatorNode>( + Children({std::move(children[0]), std::move(children[1])}), op); + } + const auto& left_pixels_and_percent = + To<CalculationExpressionPixelsAndPercentNode>(*children[0]); + const auto& right_pixels_and_percent = + To<CalculationExpressionPixelsAndPercentNode>(*children[1]); + PixelsAndPercent value = left_pixels_and_percent.GetPixelsAndPercent(); + if (op == CalculationOperator::kAdd) { + value.pixels += right_pixels_and_percent.Pixels(); + value.percent += right_pixels_and_percent.Percent(); + } else { + value.pixels -= right_pixels_and_percent.Pixels(); + value.percent -= right_pixels_and_percent.Percent(); + } + return base::MakeRefCounted<CalculationExpressionPixelsAndPercentNode>( + value); + } + case CalculationOperator::kMultiply: { + DCHECK_EQ(children.size(), 2u); + auto& maybe_pixels_and_percent_node = + children[0]->IsNumber() ? children[1] : children[0]; + if (!maybe_pixels_and_percent_node->IsPixelsAndPercent()) { + return base::MakeRefCounted<CalculationExpressionOperatorNode>( + Children({std::move(children[0]), std::move(children[1])}), op); + } + auto& number_node = children[0]->IsNumber() ? children[0] : children[1]; + const auto& number = To<CalculationExpressionNumberNode>(*number_node); + const auto& pixels_and_percent = + To<CalculationExpressionPixelsAndPercentNode>( + *maybe_pixels_and_percent_node); + PixelsAndPercent value(pixels_and_percent.Pixels() * number.Value(), + pixels_and_percent.Percent()); + return base::MakeRefCounted<CalculationExpressionPixelsAndPercentNode>( + value); + } + case CalculationOperator::kMin: + case CalculationOperator::kMax: { + DCHECK(children.size()); + float simplified_px; + bool can_simplify = true; + for (wtf_size_t i = 0; i < children.size(); ++i) { + const auto* pixels_and_percent = + DynamicTo<CalculationExpressionPixelsAndPercentNode>(*children[i]); + if (!pixels_and_percent || pixels_and_percent->Percent()) { + can_simplify = false; + break; + } + if (!i) { + simplified_px = pixels_and_percent->Pixels(); + } else { + if (op == CalculationOperator::kMin) { + simplified_px = + std::min(simplified_px, pixels_and_percent->Pixels()); + } else { + simplified_px = + std::max(simplified_px, pixels_and_percent->Pixels()); + } + } + } + if (can_simplify) { + return base::MakeRefCounted<CalculationExpressionPixelsAndPercentNode>( + PixelsAndPercent(simplified_px, 0)); + } + return base::MakeRefCounted<CalculationExpressionOperatorNode>( + std::move(children), op); + } + default: + NOTREACHED(); + return nullptr; } - const auto& leaf = To<CalculationExpressionLeafNode>(*node); - PixelsAndPercent value(leaf.Pixels() * factor, leaf.Percent() * factor); - return base::MakeRefCounted<CalculationExpressionLeafNode>(value); } -float CalculationExpressionMultiplicationNode::Evaluate(float max_value) const { - return child_->Evaluate(max_value) * factor_; -} - -bool CalculationExpressionMultiplicationNode::operator==( - const CalculationExpressionNode& other) const { - if (!other.IsMultiplication()) - return false; - const auto& other_multiply = - To<CalculationExpressionMultiplicationNode>(other); - return factor_ == other_multiply.factor_ && *child_ == *other_multiply.child_; -} - -scoped_refptr<const CalculationExpressionNode> -CalculationExpressionMultiplicationNode::Zoom(double factor) const { - return CreateSimplified(child_->Zoom(factor), factor_); -} - -// ------ CalculationExpressionAdditiveNode ------ - -// static -scoped_refptr<const CalculationExpressionNode> -CalculationExpressionAdditiveNode::CreateSimplified( - scoped_refptr<const CalculationExpressionNode> lhs, - scoped_refptr<const CalculationExpressionNode> rhs, - Type type) { - if (!lhs->IsLeaf() || !rhs->IsLeaf()) { - return base::MakeRefCounted<CalculationExpressionAdditiveNode>( - std::move(lhs), std::move(rhs), type); - } - const auto& left_leaf = To<CalculationExpressionLeafNode>(*lhs); - const auto& right_leaf = To<CalculationExpressionLeafNode>(*rhs); - PixelsAndPercent value = left_leaf.GetPixelsAndPercent(); - if (type == Type::kAdd) { - value.pixels += right_leaf.Pixels(); - value.percent += right_leaf.Percent(); - } else { - value.pixels -= right_leaf.Pixels(); - value.percent -= right_leaf.Percent(); - } - return base::MakeRefCounted<CalculationExpressionLeafNode>(value); -} - -float CalculationExpressionAdditiveNode::Evaluate(float max_value) const { - if (IsAdd()) - return lhs_->Evaluate(max_value) + rhs_->Evaluate(max_value); - if (IsSubtract()) - return lhs_->Evaluate(max_value) - rhs_->Evaluate(max_value); - NOTREACHED(); - return 0; -} - -bool CalculationExpressionAdditiveNode::operator==( - const CalculationExpressionNode& other) const { - if (!other.IsAdditive()) - return false; - const auto& other_add_subtract = To<CalculationExpressionAdditiveNode>(other); - // Do we need to consider add as commutative? - return type_ == other_add_subtract.type_ && - *lhs_ == *other_add_subtract.lhs_ && *rhs_ == *other_add_subtract.rhs_; -} - -scoped_refptr<const CalculationExpressionNode> -CalculationExpressionAdditiveNode::Zoom(double factor) const { - return CreateSimplified(lhs_->Zoom(factor), rhs_->Zoom(factor), type_); -} - -// ------ CalculationExpressionComparisonNode ------ - -// static -scoped_refptr<const CalculationExpressionNode> -CalculationExpressionComparisonNode::CreateSimplified( - Vector<scoped_refptr<const CalculationExpressionNode>>&& operands, - Type type) { - DCHECK(operands.size()); - float simplified_px; - bool can_simplify = true; - for (wtf_size_t i = 0; i < operands.size(); ++i) { - const auto* leaf = DynamicTo<CalculationExpressionLeafNode>(*operands[i]); - if (!leaf || leaf->Percent()) { - can_simplify = false; +float CalculationExpressionOperatorNode::Evaluate(float max_value) const { + switch (operator_) { + case CalculationOperator::kAdd: { + DCHECK_EQ(children_.size(), 2u); + float left = children_[0]->Evaluate(max_value); + float right = children_[1]->Evaluate(max_value); + return left + right; + } + case CalculationOperator::kSubtract: { + DCHECK_EQ(children_.size(), 2u); + float left = children_[0]->Evaluate(max_value); + float right = children_[1]->Evaluate(max_value); + return left - right; + } + case CalculationOperator::kMultiply: { + DCHECK_EQ(children_.size(), 2u); + float left = children_[0]->Evaluate(max_value); + float right = children_[1]->Evaluate(max_value); + return left * right; + } + case CalculationOperator::kMin: { + DCHECK(!children_.IsEmpty()); + float minimum = children_[0]->Evaluate(max_value); + for (auto& child : children_) + minimum = std::min(minimum, child->Evaluate(max_value)); + return minimum; + } + case CalculationOperator::kMax: { + DCHECK(!children_.IsEmpty()); + float maximum = children_[0]->Evaluate(max_value); + for (auto& child : children_) + maximum = std::max(maximum, child->Evaluate(max_value)); + return maximum; + } + default: break; - } - if (!i) { - simplified_px = leaf->Pixels(); - } else { - if (type == Type::kMin) - simplified_px = std::min(simplified_px, leaf->Pixels()); - else - simplified_px = std::max(simplified_px, leaf->Pixels()); - } + // TODO(crbug.com/1284199): Support other math functions. } - if (can_simplify) { - return base::MakeRefCounted<CalculationExpressionLeafNode>( - PixelsAndPercent(simplified_px, 0)); - } - return base::MakeRefCounted<CalculationExpressionComparisonNode>( - std::move(operands), type); + NOTREACHED(); + return std::numeric_limits<float>::quiet_NaN(); } -float CalculationExpressionComparisonNode::Evaluate(float max_value) const { - float result = operands_.front()->Evaluate(max_value); - if (IsMin()) { - for (wtf_size_t i = 1; i < operands_.size(); ++i) - result = std::min(result, operands_[i]->Evaluate(max_value)); - } else if (IsMax()) { - for (wtf_size_t i = 1; i < operands_.size(); ++i) - result = std::max(result, operands_[i]->Evaluate(max_value)); - } else { - NOTREACHED(); - } - return result; -} - -bool CalculationExpressionComparisonNode::operator==( +bool CalculationExpressionOperatorNode::operator==( const CalculationExpressionNode& other) const { - if (!other.IsComparison()) + if (!other.IsOperator()) return false; - const auto& other_comparison = To<CalculationExpressionComparisonNode>(other); - if (type_ != other_comparison.type_) - return false; - if (operands_.size() != other_comparison.operands_.size()) - return false; - // We may consider ignoring operand ordering to allow better memory - // optimization. The code complexity might not pay off, though. - for (wtf_size_t i = 0; i < operands_.size(); ++i) { - if (*operands_[i] != *other_comparison.operands_[i]) - return false; - } - return true; + const auto& other_operation = To<CalculationExpressionOperatorNode>(other); + return operator_ == other_operation.GetOperator() && + children_ == other_operation.GetChildren(); } scoped_refptr<const CalculationExpressionNode> -CalculationExpressionComparisonNode::Zoom(double factor) const { - Vector<scoped_refptr<const CalculationExpressionNode>> cloned_operands; - cloned_operands.ReserveCapacity(operands_.size()); - for (const auto& operand : operands_) - cloned_operands.push_back(operand->Zoom(factor)); - return CreateSimplified(std::move(cloned_operands), type_); +CalculationExpressionOperatorNode::Zoom(double factor) const { + switch (operator_) { + case CalculationOperator::kAdd: + case CalculationOperator::kSubtract: + DCHECK_EQ(children_.size(), 2u); + return CreateSimplified( + Children({children_[0]->Zoom(factor), children_[1]->Zoom(factor)}), + operator_); + case CalculationOperator::kMultiply: { + DCHECK_EQ(children_.size(), 2u); + auto& number = children_[0]->IsNumber() ? children_[0] : children_[1]; + auto& pixels_and_percent = + children_[0]->IsNumber() ? children_[1] : children_[0]; + return CreateSimplified( + Children({pixels_and_percent->Zoom(factor), number}), operator_); + } + case CalculationOperator::kMin: + case CalculationOperator::kMax: { + DCHECK(children_.size()); + Vector<scoped_refptr<const CalculationExpressionNode>> cloned_operands; + cloned_operands.ReserveCapacity(children_.size()); + for (const auto& child : children_) + cloned_operands.push_back(child->Zoom(factor)); + return CreateSimplified(std::move(cloned_operands), operator_); + } + default: + NOTREACHED(); + return nullptr; + } } +#if DCHECK_IS_ON() +CalculationExpressionNode::ResultType +CalculationExpressionOperatorNode::ResolvedResultType() const { + switch (operator_) { + case CalculationOperator::kAdd: + case CalculationOperator::kSubtract: { + DCHECK_EQ(children_.size(), 2u); + auto left_type = children_[0]->ResolvedResultType(); + auto right_type = children_[1]->ResolvedResultType(); + if (left_type == ResultType::kInvalid || + right_type == ResultType::kInvalid || left_type != right_type) + return ResultType::kInvalid; + + return left_type; + } + case CalculationOperator::kMultiply: { + DCHECK_EQ(children_.size(), 2u); + auto left_type = children_[0]->ResolvedResultType(); + auto right_type = children_[1]->ResolvedResultType(); + if (left_type == ResultType::kInvalid || + right_type == ResultType::kInvalid || + (left_type == ResultType::kPixelsAndPercent && + right_type == ResultType::kPixelsAndPercent)) + return ResultType::kInvalid; + + if ((left_type == ResultType::kPixelsAndPercent && + right_type == ResultType::kNumber) || + (left_type == ResultType::kNumber && + right_type == ResultType::kPixelsAndPercent)) + return ResultType::kPixelsAndPercent; + + return ResultType::kNumber; + } + case CalculationOperator::kMin: + case CalculationOperator::kMax: { + DCHECK(children_.size()); + auto first_child_type = children_.front()->ResolvedResultType(); + for (const auto& child : children_) { + if (first_child_type != child->ResolvedResultType()) + return ResultType::kInvalid; + } + + return first_child_type; + } + default: + NOTREACHED(); + return result_type_; + } +} +#endif + } // namespace blink
diff --git a/third_party/blink/renderer/platform/geometry/calculation_expression_node.h b/third_party/blink/renderer/platform/geometry/calculation_expression_node.h index 7123200..a772a21 100644 --- a/third_party/blink/renderer/platform/geometry/calculation_expression_node.h +++ b/third_party/blink/renderer/platform/geometry/calculation_expression_node.h
@@ -12,9 +12,18 @@ namespace blink { -// Represents an expression composed of |PixelsAndPercent| and multiple types of -// operators. To be consumed by |Length| values that involve non-trivial math -// functions like min() and max(). +enum class CalculationOperator { + kAdd, + kSubtract, + kMultiply, // Division is converted to multiplication and use this value too. + kMin, + kMax, + kInvalid +}; + +// Represents an expression composed of numbers, |PixelsAndPercent| and multiple +// types of operators. To be consumed by |Length| values that involve +// non-trivial math functions like min() and max(). class PLATFORM_EXPORT CalculationExpressionNode : public RefCounted<CalculationExpressionNode> { public: @@ -24,21 +33,68 @@ return !operator==(other); } - virtual bool IsLeaf() const { return false; } - virtual bool IsMultiplication() const { return false; } - virtual bool IsAdditive() const { return false; } - virtual bool IsComparison() const { return false; } + virtual bool IsNumber() const { return false; } + virtual bool IsPixelsAndPercent() const { return false; } + virtual bool IsOperator() const { return false; } virtual scoped_refptr<const CalculationExpressionNode> Zoom( double factor) const = 0; virtual ~CalculationExpressionNode() = default; + +#if DCHECK_IS_ON() + enum class ResultType { kInvalid, kNumber, kPixelsAndPercent }; + + virtual ResultType ResolvedResultType() const = 0; + + protected: + ResultType result_type_; +#endif }; -class PLATFORM_EXPORT CalculationExpressionLeafNode final +class PLATFORM_EXPORT CalculationExpressionNumberNode final : public CalculationExpressionNode { public: - CalculationExpressionLeafNode(PixelsAndPercent value) : value_(value) {} + CalculationExpressionNumberNode(float value) : value_(value) { +#if DCHECK_IS_ON() + result_type_ = ResultType::kNumber; +#endif + } + + float Value() const { return value_; } + + // Implement |CalculationExpressionNode|: + float Evaluate(float max_value) const final; + bool operator==(const CalculationExpressionNode& other) const final; + scoped_refptr<const CalculationExpressionNode> Zoom( + double factor) const final; + bool IsNumber() const final { return true; } + ~CalculationExpressionNumberNode() final = default; + +#if DCHECK_IS_ON() + ResultType ResolvedResultType() const final; +#endif + + private: + float value_; +}; + +template <> +struct DowncastTraits<CalculationExpressionNumberNode> { + static bool AllowFrom(const CalculationExpressionNode& node) { + return node.IsNumber(); + } +}; + +class PLATFORM_EXPORT CalculationExpressionPixelsAndPercentNode final + : public CalculationExpressionNode { + public: + CalculationExpressionPixelsAndPercentNode(PixelsAndPercent value) + : value_(value) { +#if DCHECK_IS_ON() + result_type_ = ResultType::kPixelsAndPercent; +#endif + } float Pixels() const { return value_.pixels; } float Percent() const { return value_.percent; } @@ -49,136 +105,65 @@ bool operator==(const CalculationExpressionNode& other) const final; scoped_refptr<const CalculationExpressionNode> Zoom( double factor) const final; - bool IsLeaf() const final { return true; } - ~CalculationExpressionLeafNode() final = default; + bool IsPixelsAndPercent() const final { return true; } + ~CalculationExpressionPixelsAndPercentNode() final = default; + +#if DCHECK_IS_ON() + ResultType ResolvedResultType() const final; +#endif private: PixelsAndPercent value_; }; template <> -struct DowncastTraits<CalculationExpressionLeafNode> { +struct DowncastTraits<CalculationExpressionPixelsAndPercentNode> { static bool AllowFrom(const CalculationExpressionNode& node) { - return node.IsLeaf(); + return node.IsPixelsAndPercent(); } }; -class PLATFORM_EXPORT CalculationExpressionMultiplicationNode final +class PLATFORM_EXPORT CalculationExpressionOperatorNode final : public CalculationExpressionNode { public: + using Children = Vector<scoped_refptr<const CalculationExpressionNode>>; + static scoped_refptr<const CalculationExpressionNode> CreateSimplified( - scoped_refptr<const CalculationExpressionNode> node, - float factor); + Children&& children, + CalculationOperator op); - CalculationExpressionMultiplicationNode( - scoped_refptr<const CalculationExpressionNode> node, - float factor) - : child_(std::move(node)), factor_(factor) {} + CalculationExpressionOperatorNode(Children&& children, CalculationOperator op) + : children_(std::move(children)), operator_(op) { +#if DCHECK_IS_ON() + result_type_ = ResolvedResultType(); + DCHECK_NE(result_type_, ResultType::kInvalid); +#endif + } - const CalculationExpressionNode& GetChild() const { return *child_; } - float GetFactor() const { return factor_; } + const Children& GetChildren() const { return children_; } + CalculationOperator GetOperator() const { return operator_; } // Implement |CalculationExpressionNode|: float Evaluate(float max_value) const final; bool operator==(const CalculationExpressionNode& other) const final; scoped_refptr<const CalculationExpressionNode> Zoom( double factor) const final; - bool IsMultiplication() const final { return true; } - ~CalculationExpressionMultiplicationNode() final = default; + bool IsOperator() const final { return true; } + ~CalculationExpressionOperatorNode() final = default; + +#if DCHECK_IS_ON() + ResultType ResolvedResultType() const final; +#endif private: - scoped_refptr<const CalculationExpressionNode> child_; - float factor_; + Children children_; + CalculationOperator operator_; }; template <> -struct DowncastTraits<CalculationExpressionMultiplicationNode> { +struct DowncastTraits<CalculationExpressionOperatorNode> { static bool AllowFrom(const CalculationExpressionNode& node) { - return node.IsMultiplication(); - } -}; - -class PLATFORM_EXPORT CalculationExpressionAdditiveNode final - : public CalculationExpressionNode { - public: - enum class Type { kAdd, kSubtract }; - - static scoped_refptr<const CalculationExpressionNode> CreateSimplified( - scoped_refptr<const CalculationExpressionNode> lhs, - scoped_refptr<const CalculationExpressionNode> rhs, - Type type); - - CalculationExpressionAdditiveNode( - scoped_refptr<const CalculationExpressionNode> lhs, - scoped_refptr<const CalculationExpressionNode> rhs, - Type type) - : lhs_(std::move(lhs)), rhs_(std::move(rhs)), type_(type) {} - - const CalculationExpressionNode& GetLeftSide() const { return *lhs_; } - const CalculationExpressionNode& GetRightSide() const { return *rhs_; } - bool IsAdd() const { return type_ == Type::kAdd; } - bool IsSubtract() const { return type_ == Type::kSubtract; } - - // Implement |CalculationExpressionNode|: - float Evaluate(float max_value) const final; - bool operator==(const CalculationExpressionNode& other) const final; - scoped_refptr<const CalculationExpressionNode> Zoom( - double factor) const final; - bool IsAdditive() const final { return true; } - ~CalculationExpressionAdditiveNode() final = default; - - private: - scoped_refptr<const CalculationExpressionNode> lhs_; - scoped_refptr<const CalculationExpressionNode> rhs_; - Type type_; -}; - -template <> -struct DowncastTraits<CalculationExpressionAdditiveNode> { - static bool AllowFrom(const CalculationExpressionNode& node) { - return node.IsAdditive(); - } -}; - -class PLATFORM_EXPORT CalculationExpressionComparisonNode final - : public CalculationExpressionNode { - public: - enum class Type { kMin, kMax }; - - static scoped_refptr<const CalculationExpressionNode> CreateSimplified( - Vector<scoped_refptr<const CalculationExpressionNode>>&& operands, - Type type); - - CalculationExpressionComparisonNode( - Vector<scoped_refptr<const CalculationExpressionNode>>&& operands, - Type type) - : operands_(std::move(operands)), type_(type) {} - - const Vector<scoped_refptr<const CalculationExpressionNode>>& GetOperands() - const { - return operands_; - } - - bool IsMin() const { return type_ == Type::kMin; } - bool IsMax() const { return type_ == Type::kMax; } - - // Implement |CalculationExpressionNode|: - float Evaluate(float max_value) const final; - bool operator==(const CalculationExpressionNode& other) const final; - scoped_refptr<const CalculationExpressionNode> Zoom( - double factor) const final; - bool IsComparison() const final { return true; } - ~CalculationExpressionComparisonNode() final = default; - - private: - Vector<scoped_refptr<const CalculationExpressionNode>> operands_; - Type type_; -}; - -template <> -struct DowncastTraits<CalculationExpressionComparisonNode> { - static bool AllowFrom(const CalculationExpressionNode& node) { - return node.IsComparison(); + return node.IsOperator(); } };
diff --git a/third_party/blink/renderer/platform/geometry/calculation_value.cc b/third_party/blink/renderer/platform/geometry/calculation_value.cc index 99243e54f..d2ef8080 100644 --- a/third_party/blink/renderer/platform/geometry/calculation_value.cc +++ b/third_party/blink/renderer/platform/geometry/calculation_value.cc
@@ -22,10 +22,10 @@ scoped_refptr<const CalculationValue> CalculationValue::CreateSimplified( scoped_refptr<const CalculationExpressionNode> expression, Length::ValueRange range) { - if (expression->IsLeaf()) { - return Create( - To<CalculationExpressionLeafNode>(*expression).GetPixelsAndPercent(), - range); + if (expression->IsPixelsAndPercent()) { + return Create(To<CalculationExpressionPixelsAndPercentNode>(*expression) + .GetPixelsAndPercent(), + range); } return base::AdoptRef(new CalculationValue(std::move(expression), range)); } @@ -62,7 +62,7 @@ CalculationValue::GetOrCreateExpression() const { if (IsExpression()) return data_.expression; - return base::MakeRefCounted<CalculationExpressionLeafNode>( + return base::MakeRefCounted<CalculationExpressionPixelsAndPercentNode>( GetPixelsAndPercent()); } @@ -80,14 +80,21 @@ return Create(PixelsAndPercent(pixels, percent), range); } - auto blended_from = CalculationExpressionMultiplicationNode::CreateSimplified( - from.GetOrCreateExpression(), 1.0 - progress); - auto blended_to = CalculationExpressionMultiplicationNode::CreateSimplified( - GetOrCreateExpression(), progress); - auto result_expression = CalculationExpressionAdditiveNode::CreateSimplified( - std::move(blended_from), std::move(blended_to), - CalculationExpressionAdditiveNode::Type::kAdd); - return CreateSimplified(std::move(result_expression), range); + auto blended_from = CalculationExpressionOperatorNode::CreateSimplified( + CalculationExpressionOperatorNode::Children( + {from.GetOrCreateExpression(), + base::MakeRefCounted<CalculationExpressionNumberNode>(1.0 - + progress)}), + CalculationOperator::kMultiply); + auto blended_to = CalculationExpressionOperatorNode::CreateSimplified( + CalculationExpressionOperatorNode::Children( + {GetOrCreateExpression(), + base::MakeRefCounted<CalculationExpressionNumberNode>(progress)}), + CalculationOperator::kMultiply); + auto result_expression = CalculationExpressionOperatorNode::CreateSimplified( + {std::move(blended_from), std::move(blended_to)}, + CalculationOperator::kAdd); + return CreateSimplified(result_expression, range); } scoped_refptr<const CalculationValue> @@ -96,11 +103,13 @@ PixelsAndPercent result(-Pixels(), 100 - Percent()); return Create(result, Length::ValueRange::kAll); } - auto hundred_percent = base::MakeRefCounted<CalculationExpressionLeafNode>( - PixelsAndPercent(0, 100)); - auto result_expression = CalculationExpressionAdditiveNode::CreateSimplified( - std::move(hundred_percent), GetOrCreateExpression(), - CalculationExpressionAdditiveNode::Type::kSubtract); + auto hundred_percent = + base::MakeRefCounted<CalculationExpressionPixelsAndPercentNode>( + PixelsAndPercent(0, 100)); + auto result_expression = CalculationExpressionOperatorNode::CreateSimplified( + CalculationExpressionOperatorNode::Children( + {std::move(hundred_percent), GetOrCreateExpression()}), + CalculationOperator::kSubtract); return CreateSimplified(std::move(result_expression), Length::ValueRange::kAll); }
diff --git a/third_party/blink/renderer/platform/geometry/length_test.cc b/third_party/blink/renderer/platform/geometry/length_test.cc index 0b855a1..3b6c14b 100644 --- a/third_party/blink/renderer/platform/geometry/length_test.cc +++ b/third_party/blink/renderer/platform/geometry/length_test.cc
@@ -14,6 +14,7 @@ const PixelsAndPercent ten_px(10, 0); const PixelsAndPercent twenty_px(20, 0); +const PixelsAndPercent thirty_px(30, 0); const PixelsAndPercent ten_percent(0, 10); const PixelsAndPercent twenty_percent(0, 20); @@ -23,41 +24,41 @@ public: using Pointer = scoped_refptr<const CalculationExpressionNode>; - Pointer Leaf(PixelsAndPercent value) { - return base::MakeRefCounted<CalculationExpressionLeafNode>(value); + Pointer PixelsAndPercent(PixelsAndPercent value) { + return base::MakeRefCounted<CalculationExpressionPixelsAndPercentNode>( + value); } Pointer Add(Pointer lhs, Pointer rhs) { - return base::MakeRefCounted<CalculationExpressionAdditiveNode>( - std::move(lhs), std::move(rhs), - CalculationExpressionAdditiveNode::Type::kAdd); + return base::MakeRefCounted<CalculationExpressionOperatorNode>( + CalculationExpressionOperatorNode::Children( + {std::move(lhs), std::move(rhs)}), + CalculationOperator::kAdd); } Pointer Subtract(Pointer lhs, Pointer rhs) { - return base::MakeRefCounted<CalculationExpressionAdditiveNode>( - std::move(lhs), std::move(rhs), - CalculationExpressionAdditiveNode::Type::kSubtract); + return base::MakeRefCounted<CalculationExpressionOperatorNode>( + CalculationExpressionOperatorNode::Children( + {std::move(lhs), std::move(rhs)}), + CalculationOperator::kSubtract); } Pointer Multiply(Pointer node, float factor) { - return base::MakeRefCounted<CalculationExpressionMultiplicationNode>( - std::move(node), factor); + return base::MakeRefCounted<CalculationExpressionOperatorNode>( + CalculationExpressionOperatorNode::Children( + {std::move(node), + base::MakeRefCounted<CalculationExpressionNumberNode>(factor)}), + CalculationOperator::kMultiply); } - Pointer Min(Pointer op1, Pointer op2) { - Vector<Pointer> operands; - operands.push_back(std::move(op1)); - operands.push_back(std::move(op2)); - return base::MakeRefCounted<CalculationExpressionComparisonNode>( - std::move(operands), CalculationExpressionComparisonNode::Type::kMin); + Pointer Min(Vector<Pointer>&& operands) { + return base::MakeRefCounted<CalculationExpressionOperatorNode>( + std::move(operands), CalculationOperator::kMin); } - Pointer Max(Pointer op1, Pointer op2) { - Vector<Pointer> operands; - operands.push_back(std::move(op1)); - operands.push_back(std::move(op2)); - return base::MakeRefCounted<CalculationExpressionComparisonNode>( - std::move(operands), CalculationExpressionComparisonNode::Type::kMax); + Pointer Max(Vector<Pointer>&& operands) { + return base::MakeRefCounted<CalculationExpressionOperatorNode>( + std::move(operands), CalculationOperator::kMax); } Length CreateLength(Pointer expression) { @@ -69,7 +70,8 @@ TEST_F(LengthTest, EvaluateSimpleComparison) { // min(10px, 20px) { - Length length = CreateLength(Min(Leaf(ten_px), Leaf(twenty_px))); + Length length = CreateLength( + Min({PixelsAndPercent(ten_px), PixelsAndPercent(twenty_px)})); EXPECT_EQ(10.0f, length.GetCalculationValue().Evaluate(-200)); EXPECT_EQ(10.0f, length.GetCalculationValue().Evaluate(-100)); EXPECT_EQ(10.0f, length.GetCalculationValue().Evaluate(0)); @@ -79,7 +81,8 @@ // min(10%, 20%) { - Length length = CreateLength(Min(Leaf(ten_percent), Leaf(twenty_percent))); + Length length = CreateLength( + Min({PixelsAndPercent(ten_percent), PixelsAndPercent(twenty_percent)})); EXPECT_EQ(-40.0f, length.GetCalculationValue().Evaluate(-200)); EXPECT_EQ(-20.0f, length.GetCalculationValue().Evaluate(-100)); EXPECT_EQ(0.0f, length.GetCalculationValue().Evaluate(0)); @@ -89,7 +92,8 @@ // min(10px, 10%) { - Length length = CreateLength(Min(Leaf(ten_px), Leaf(twenty_percent))); + Length length = CreateLength( + Min({PixelsAndPercent(ten_px), PixelsAndPercent(twenty_percent)})); EXPECT_EQ(-40.0f, length.GetCalculationValue().Evaluate(-200)); EXPECT_EQ(-20.0f, length.GetCalculationValue().Evaluate(-100)); EXPECT_EQ(0.0f, length.GetCalculationValue().Evaluate(0)); @@ -99,7 +103,8 @@ // max(10px, 20px) { - Length length = CreateLength(Max(Leaf(ten_px), Leaf(twenty_px))); + Length length = CreateLength( + Max({PixelsAndPercent(ten_px), PixelsAndPercent(twenty_px)})); EXPECT_EQ(20.0f, length.GetCalculationValue().Evaluate(-200)); EXPECT_EQ(20.0f, length.GetCalculationValue().Evaluate(-100)); EXPECT_EQ(20.0f, length.GetCalculationValue().Evaluate(0)); @@ -109,7 +114,8 @@ // max(10%, 20%) { - Length length = CreateLength(Max(Leaf(ten_percent), Leaf(twenty_percent))); + Length length = CreateLength( + Max({PixelsAndPercent(ten_percent), PixelsAndPercent(twenty_percent)})); EXPECT_EQ(-20.0f, length.GetCalculationValue().Evaluate(-200)); EXPECT_EQ(-10.0f, length.GetCalculationValue().Evaluate(-100)); EXPECT_EQ(0.0f, length.GetCalculationValue().Evaluate(0)); @@ -119,7 +125,8 @@ // max(10px, 10%) { - Length length = CreateLength(Max(Leaf(ten_px), Leaf(ten_percent))); + Length length = CreateLength( + Max({PixelsAndPercent(ten_px), PixelsAndPercent(ten_percent)})); EXPECT_EQ(10.0f, length.GetCalculationValue().Evaluate(-200)); EXPECT_EQ(10.0f, length.GetCalculationValue().Evaluate(-100)); EXPECT_EQ(10.0f, length.GetCalculationValue().Evaluate(0)); @@ -131,8 +138,9 @@ TEST_F(LengthTest, EvaluateNestedComparisons) { // max(10px, min(10%, 20px)) { - Length length = CreateLength( - Max(Leaf(ten_px), Min(Leaf(ten_percent), Leaf(twenty_px)))); + Length length = CreateLength(Max( + {PixelsAndPercent(ten_px), + Min({PixelsAndPercent(ten_percent), PixelsAndPercent(twenty_px)})})); EXPECT_EQ(10.0f, length.GetCalculationValue().Evaluate(50)); EXPECT_EQ(15.0f, length.GetCalculationValue().Evaluate(150)); EXPECT_EQ(20.0f, length.GetCalculationValue().Evaluate(250)); @@ -140,8 +148,9 @@ // max(10%, min(10px, 20%)) { - Length length = CreateLength( - Max(Leaf(ten_percent), Min(Leaf(ten_px), Leaf(twenty_percent)))); + Length length = CreateLength(Max( + {PixelsAndPercent(ten_percent), + Min({PixelsAndPercent(ten_px), PixelsAndPercent(twenty_percent)})})); EXPECT_EQ(5.0f, length.GetCalculationValue().Evaluate(25)); EXPECT_EQ(10.0f, length.GetCalculationValue().Evaluate(50)); EXPECT_EQ(10.0f, length.GetCalculationValue().Evaluate(75)); @@ -152,7 +161,8 @@ // min(max(10px, 10%), 20px) { Length length = CreateLength( - Min(Max(Leaf(ten_px), Leaf(ten_percent)), Leaf(twenty_px))); + Min({Max({PixelsAndPercent(ten_px), PixelsAndPercent(ten_percent)}), + PixelsAndPercent(twenty_px)})); EXPECT_EQ(10.0f, length.GetCalculationValue().Evaluate(50)); EXPECT_EQ(15.0f, length.GetCalculationValue().Evaluate(150)); EXPECT_EQ(20.0f, length.GetCalculationValue().Evaluate(250)); @@ -161,7 +171,8 @@ // min(max(10%, 10px), 20%) { Length length = CreateLength( - Min(Max(Leaf(ten_percent), Leaf(ten_px)), Leaf(twenty_percent))); + Min({Max({PixelsAndPercent(ten_percent), PixelsAndPercent(ten_px)}), + PixelsAndPercent(twenty_percent)})); EXPECT_EQ(5.0f, length.GetCalculationValue().Evaluate(25)); EXPECT_EQ(10.0f, length.GetCalculationValue().Evaluate(50)); EXPECT_EQ(10.0f, length.GetCalculationValue().Evaluate(75)); @@ -173,8 +184,9 @@ TEST_F(LengthTest, EvaluateAdditive) { // min(10%, 10px) + 10px { - Length length = - CreateLength(Add(Min(Leaf(ten_percent), Leaf(ten_px)), Leaf(ten_px))); + Length length = CreateLength( + Add(Min({PixelsAndPercent(ten_percent), PixelsAndPercent(ten_px)}), + PixelsAndPercent(ten_px))); EXPECT_EQ(15.0f, length.GetCalculationValue().Evaluate(50)); EXPECT_EQ(20.0f, length.GetCalculationValue().Evaluate(100)); EXPECT_EQ(20.0f, length.GetCalculationValue().Evaluate(150)); @@ -183,7 +195,8 @@ // min(10%, 10px) - 10px { Length length = CreateLength( - Subtract(Min(Leaf(ten_percent), Leaf(ten_px)), Leaf(ten_px))); + Subtract(Min({PixelsAndPercent(ten_percent), PixelsAndPercent(ten_px)}), + PixelsAndPercent(ten_px))); EXPECT_EQ(-5.0f, length.GetCalculationValue().Evaluate(50)); EXPECT_EQ(0.0f, length.GetCalculationValue().Evaluate(100)); EXPECT_EQ(0.0f, length.GetCalculationValue().Evaluate(150)); @@ -191,8 +204,9 @@ // 10px + max(10%, 10px) { - Length length = - CreateLength(Add(Leaf(ten_px), Max(Leaf(ten_percent), Leaf(ten_px)))); + Length length = CreateLength( + Add(PixelsAndPercent(ten_px), + Max({PixelsAndPercent(ten_percent), PixelsAndPercent(ten_px)}))); EXPECT_EQ(20.0f, length.GetCalculationValue().Evaluate(50)); EXPECT_EQ(20.0f, length.GetCalculationValue().Evaluate(100)); EXPECT_EQ(25.0f, length.GetCalculationValue().Evaluate(150)); @@ -200,8 +214,9 @@ // 10px - max(10%, 10px) { - Length length = CreateLength( - Subtract(Leaf(ten_px), Max(Leaf(ten_percent), Leaf(ten_px)))); + Length length = CreateLength(Subtract( + PixelsAndPercent(ten_px), + Max({PixelsAndPercent(ten_percent), PixelsAndPercent(ten_px)}))); EXPECT_EQ(0.0f, length.GetCalculationValue().Evaluate(50)); EXPECT_EQ(0.0f, length.GetCalculationValue().Evaluate(100)); EXPECT_EQ(-5.0f, length.GetCalculationValue().Evaluate(150)); @@ -211,8 +226,8 @@ TEST_F(LengthTest, EvaluateMultiplicative) { // min(10px, 10%) * 2 { - Length length = - CreateLength(Multiply(Min(Leaf(ten_px), Leaf(ten_percent)), 2)); + Length length = CreateLength(Multiply( + Min({PixelsAndPercent(ten_px), PixelsAndPercent(ten_percent)}), 2)); EXPECT_EQ(10.0f, length.GetCalculationValue().Evaluate(50)); EXPECT_EQ(20.0f, length.GetCalculationValue().Evaluate(100)); EXPECT_EQ(20.0f, length.GetCalculationValue().Evaluate(150)); @@ -220,8 +235,8 @@ // max(10px, 10%) * 0.5 { - Length length = - CreateLength(Multiply(Max(Leaf(ten_px), Leaf(ten_percent)), 0.5)); + Length length = CreateLength(Multiply( + Max({PixelsAndPercent(ten_px), PixelsAndPercent(ten_percent)}), 0.5)); EXPECT_EQ(5.0f, length.GetCalculationValue().Evaluate(50)); EXPECT_EQ(5.0f, length.GetCalculationValue().Evaluate(100)); EXPECT_EQ(10.0f, length.GetCalculationValue().Evaluate(200)); @@ -233,8 +248,10 @@ // To: max(20px, 10%) // Progress: 0.25 - Length from_length = CreateLength(Min(Leaf(ten_px), Leaf(twenty_percent))); - Length to_length = CreateLength(Max(Leaf(twenty_px), Leaf(ten_percent))); + Length from_length = CreateLength( + Min({PixelsAndPercent(ten_px), PixelsAndPercent(twenty_percent)})); + Length to_length = CreateLength( + Max({PixelsAndPercent(twenty_px), PixelsAndPercent(ten_percent)})); Length blended = to_length.Blend(from_length, 0.25, Length::ValueRange::kAll); EXPECT_EQ(8.75f, blended.GetCalculationValue().Evaluate(25)); @@ -248,7 +265,8 @@ // Original: min(10px, 10%) // Factor: 2.0 { - Length original = CreateLength(Min(Leaf(ten_px), Leaf(ten_percent))); + Length original = CreateLength( + Min({PixelsAndPercent(ten_px), PixelsAndPercent(ten_percent)})); Length zoomed = original.Zoom(2); EXPECT_EQ(10.0f, zoomed.GetCalculationValue().Evaluate(100)); EXPECT_EQ(20.0f, zoomed.GetCalculationValue().Evaluate(200)); @@ -258,7 +276,8 @@ // Original: max(10px, 10%) // Factor: 0.5 { - Length original = CreateLength(Max(Leaf(ten_px), Leaf(ten_percent))); + Length original = CreateLength( + Max({PixelsAndPercent(ten_px), PixelsAndPercent(ten_percent)})); Length zoomed = original.Zoom(0.5); EXPECT_EQ(5.0f, zoomed.GetCalculationValue().Evaluate(25)); EXPECT_EQ(5.0f, zoomed.GetCalculationValue().Evaluate(50)); @@ -269,7 +288,8 @@ TEST_F(LengthTest, SubtractExpressionFromOneHundredPercent) { // min(10px, 20%) { - Length original = CreateLength(Min(Leaf(ten_px), Leaf(twenty_percent))); + Length original = CreateLength( + Min({PixelsAndPercent(ten_px), PixelsAndPercent(twenty_percent)})); Length result = original.SubtractFromOneHundredPercent(); EXPECT_EQ(20.0f, result.GetCalculationValue().Evaluate(25)); EXPECT_EQ(40.0f, result.GetCalculationValue().Evaluate(50)); @@ -278,7 +298,8 @@ // max(20px, 10%) { - Length original = CreateLength(Max(Leaf(twenty_px), Leaf(ten_percent))); + Length original = CreateLength( + Max({PixelsAndPercent(twenty_px), PixelsAndPercent(ten_percent)})); Length result = original.SubtractFromOneHundredPercent(); EXPECT_EQ(80.0f, result.GetCalculationValue().Evaluate(100)); EXPECT_EQ(180.0f, result.GetCalculationValue().Evaluate(200)); @@ -286,4 +307,78 @@ } } +TEST_F(LengthTest, SimplifiedExpressionFromComparisonCreation) { + // min(10px, 20px, 30px) + { + Length original = + CreateLength(Min({PixelsAndPercent(ten_px), PixelsAndPercent(twenty_px), + PixelsAndPercent(thirty_px)})); + Length zoomed = original.Zoom(1); + // If it was not simplified, DCHECK fails in + // CalculationValue::GetPixelsAndPercent. + auto result = zoomed.GetCalculationValue().GetPixelsAndPercent(); + EXPECT_EQ(10.0f, result.pixels); + } + + // max(10px, 20px, 30px) + { + Length original = + CreateLength(Max({PixelsAndPercent(ten_px), PixelsAndPercent(twenty_px), + PixelsAndPercent(thirty_px)})); + Length zoomed = original.Zoom(1); + auto result = zoomed.GetCalculationValue().GetPixelsAndPercent(); + EXPECT_EQ(30.0f, result.pixels); + } +} + +TEST_F(LengthTest, ZoomToOperator) { + // Add 10px + 20px + { + Length original = CreateLength( + Add(PixelsAndPercent(ten_px), PixelsAndPercent(twenty_px))); + Length zoomed = original.Zoom(1); + // If it was not simplified, DCHECK fails in + // CalculationValue::GetPixelsAndPercent. + auto result = zoomed.GetCalculationValue().GetPixelsAndPercent(); + EXPECT_EQ(30.0f, result.pixels); + } + + // Subtract 20px - 10px + { + Length original = CreateLength( + Subtract(PixelsAndPercent(twenty_px), PixelsAndPercent(ten_px))); + Length zoomed = original.Zoom(1); + auto result = zoomed.GetCalculationValue().GetPixelsAndPercent(); + EXPECT_EQ(10.0f, result.pixels); + } + + // Multiply 30px by 3 + { + Length original = CreateLength(Multiply(PixelsAndPercent(thirty_px), 3)); + Length zoomed = original.Zoom(1); + auto result = zoomed.GetCalculationValue().GetPixelsAndPercent(); + EXPECT_EQ(90.0f, result.pixels); + } + + // min(10px, 20px, 30px) with zoom by 2 + { + Length original = + CreateLength(Min({PixelsAndPercent(ten_px), PixelsAndPercent(twenty_px), + PixelsAndPercent(thirty_px)})); + Length zoomed = original.Zoom(2); + auto result = zoomed.GetCalculationValue().GetPixelsAndPercent(); + EXPECT_EQ(20.0f, result.pixels); + } + + // max(10px, 20px, 30px) with zoom by 2 + { + Length original = + CreateLength(Max({PixelsAndPercent(ten_px), PixelsAndPercent(twenty_px), + PixelsAndPercent(thirty_px)})); + Length zoomed = original.Zoom(2); + auto result = zoomed.GetCalculationValue().GetPixelsAndPercent(); + EXPECT_EQ(60.0f, result.pixels); + } +} + } // namespace blink
diff --git a/third_party/blink/renderer/platform/heap/handle.h b/third_party/blink/renderer/platform/heap/handle.h index a66b689..2362f19 100644 --- a/third_party/blink/renderer/platform/heap/handle.h +++ b/third_party/blink/renderer/platform/heap/handle.h
@@ -35,6 +35,5 @@ // IWYU for users of platform/heap. #include "third_party/blink/renderer/platform/heap/garbage_collected.h" -#include "third_party/blink/renderer/platform/heap/member.h" #endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_HEAP_HANDLE_H_
diff --git a/third_party/blink/renderer/platform/peerconnection/rtc_video_decoder_adapter.cc b/third_party/blink/renderer/platform/peerconnection/rtc_video_decoder_adapter.cc index 0bc3ee2..8fcfe72 100644 --- a/third_party/blink/renderer/platform/peerconnection/rtc_video_decoder_adapter.cc +++ b/third_party/blink/renderer/platform/peerconnection/rtc_video_decoder_adapter.cc
@@ -542,9 +542,9 @@ const base::TimeDelta timestamp = frame->timestamp(); webrtc::VideoFrame rtc_frame = webrtc::VideoFrame::Builder() - .set_video_frame_buffer( + .set_video_frame_buffer(rtc::scoped_refptr<WebRtcVideoFrameAdapter>( new rtc::RefCountedObject<WebRtcVideoFrameAdapter>( - std::move(frame))) + std::move(frame)))) .set_timestamp_rtp(static_cast<uint32_t>(timestamp.InMicroseconds())) .set_timestamp_us(0) .set_rotation(webrtc::kVideoRotation_0)
diff --git a/third_party/blink/renderer/platform/peerconnection/rtc_video_decoder_factory.cc b/third_party/blink/renderer/platform/peerconnection/rtc_video_decoder_factory.cc index eda9ebc0..31545e2 100644 --- a/third_party/blink/renderer/platform/peerconnection/rtc_video_decoder_factory.cc +++ b/third_party/blink/renderer/platform/peerconnection/rtc_video_decoder_factory.cc
@@ -44,7 +44,7 @@ media::VideoCodecProfile profile; }; -constexpr std::array<CodecConfig, 8> kCodecConfigs = {{ +constexpr std::array<CodecConfig, 9> kCodecConfigs = {{ {media::VideoCodec::kVP8, media::VP8PROFILE_ANY}, {media::VideoCodec::kVP9, media::VP9PROFILE_PROFILE0}, {media::VideoCodec::kVP9, media::VP9PROFILE_PROFILE1}, @@ -52,6 +52,7 @@ {media::VideoCodec::kH264, media::H264PROFILE_BASELINE}, {media::VideoCodec::kH264, media::H264PROFILE_MAIN}, {media::VideoCodec::kH264, media::H264PROFILE_HIGH}, + {media::VideoCodec::kH264, media::H264PROFILE_HIGH444PREDICTIVEPROFILE}, {media::VideoCodec::kAV1, media::AV1PROFILE_PROFILE_MAIN}, }}; @@ -96,6 +97,9 @@ case media::H264PROFILE_HIGH: h264_profile = webrtc::H264Profile::kProfileHigh; break; + case media::H264PROFILE_HIGH444PREDICTIVEPROFILE: + h264_profile = webrtc::H264Profile::kProfilePredictiveHigh444; + break; default: // Unsupported H264 profile in WebRTC. return absl::nullopt;
diff --git a/third_party/blink/renderer/platform/peerconnection/rtc_video_decoder_stream_adapter.cc b/third_party/blink/renderer/platform/peerconnection/rtc_video_decoder_stream_adapter.cc index a32b693..578b1c6 100644 --- a/third_party/blink/renderer/platform/peerconnection/rtc_video_decoder_stream_adapter.cc +++ b/third_party/blink/renderer/platform/peerconnection/rtc_video_decoder_stream_adapter.cc
@@ -870,9 +870,9 @@ const base::TimeDelta timestamp = frame->timestamp(); webrtc::VideoFrame rtc_frame = webrtc::VideoFrame::Builder() - .set_video_frame_buffer( + .set_video_frame_buffer(rtc::scoped_refptr<webrtc::VideoFrameBuffer>( new rtc::RefCountedObject<WebRtcVideoFrameAdapter>( - std::move(frame))) + std::move(frame)))) .set_timestamp_rtp(static_cast<uint32_t>(timestamp.InMicroseconds())) .set_timestamp_us(0) .set_rotation(webrtc::kVideoRotation_0)
diff --git a/third_party/blink/renderer/platform/peerconnection/webrtc_audio_sink.cc b/third_party/blink/renderer/platform/peerconnection/webrtc_audio_sink.cc index 3ee5a45ab..a49a14d 100644 --- a/third_party/blink/renderer/platform/peerconnection/webrtc_audio_sink.cc +++ b/third_party/blink/renderer/platform/peerconnection/webrtc_audio_sink.cc
@@ -275,7 +275,8 @@ WebRtcAudioSink::Adapter::GetAudioProcessor() { DCHECK(!signaling_task_runner_ || signaling_task_runner_->RunsTasksInCurrentSequence()); - return audio_processor_.get(); + return rtc::scoped_refptr<webrtc::AudioProcessorInterface>( + audio_processor_.get()); } webrtc::AudioSourceInterface* WebRtcAudioSink::Adapter::GetSource() const {
diff --git a/third_party/blink/renderer/platform/webrtc/convert_to_webrtc_video_frame_buffer.cc b/third_party/blink/renderer/platform/webrtc/convert_to_webrtc_video_frame_buffer.cc index 22627234..0112b62 100644 --- a/third_party/blink/renderer/platform/webrtc/convert_to_webrtc_video_frame_buffer.cc +++ b/third_party/blink/renderer/platform/webrtc/convert_to_webrtc_video_frame_buffer.cc
@@ -173,14 +173,14 @@ scoped_refptr<media::VideoFrame> video_frame) { switch (video_frame->format()) { case media::PIXEL_FORMAT_I420: - return new rtc::RefCountedObject<I420FrameAdapter>( - std::move(video_frame)); + return rtc::scoped_refptr<webrtc::VideoFrameBuffer>( + new rtc::RefCountedObject<I420FrameAdapter>(std::move(video_frame))); case media::PIXEL_FORMAT_I420A: - return new rtc::RefCountedObject<I420AFrameAdapter>( - std::move(video_frame)); + return rtc::scoped_refptr<webrtc::VideoFrameBuffer>( + new rtc::RefCountedObject<I420AFrameAdapter>(std::move(video_frame))); case media::PIXEL_FORMAT_NV12: - return new rtc::RefCountedObject<NV12FrameAdapter>( - std::move(video_frame)); + return rtc::scoped_refptr<webrtc::VideoFrameBuffer>( + new rtc::RefCountedObject<NV12FrameAdapter>(std::move(video_frame))); default: NOTREACHED(); return nullptr;
diff --git a/third_party/blink/renderer/platform/webrtc/webrtc_video_frame_adapter.cc b/third_party/blink/renderer/platform/webrtc/webrtc_video_frame_adapter.cc index b019cb4a..5d8e46d 100644 --- a/third_party/blink/renderer/platform/webrtc/webrtc_video_frame_adapter.cc +++ b/third_party/blink/renderer/platform/webrtc/webrtc_video_frame_adapter.cc
@@ -407,9 +407,11 @@ int crop_height, int scaled_width, int scaled_height) { - return new rtc::RefCountedObject<ScaledBuffer>( - parent_, size_.CropAndScale(offset_x, offset_y, crop_width, crop_height, - scaled_width, scaled_height)); + return rtc::scoped_refptr<webrtc::VideoFrameBuffer>( + new rtc::RefCountedObject<ScaledBuffer>( + parent_, + size_.CropAndScale(offset_x, offset_y, crop_width, crop_height, + scaled_width, scaled_height))); } WebRtcVideoFrameAdapter::WebRtcVideoFrameAdapter( @@ -488,9 +490,11 @@ int crop_height, int scaled_width, int scaled_height) { - return new rtc::RefCountedObject<ScaledBuffer>( - this, full_size_.CropAndScale(offset_x, offset_y, crop_width, crop_height, - scaled_width, scaled_height)); + return rtc::scoped_refptr<webrtc::VideoFrameBuffer>( + new rtc::RefCountedObject<ScaledBuffer>( + this, + full_size_.CropAndScale(offset_x, offset_y, crop_width, crop_height, + scaled_width, scaled_height))); } rtc::scoped_refptr<webrtc::VideoFrameBuffer>
diff --git a/third_party/blink/web_tests/FlagExpectations/disable-layout-ng b/third_party/blink/web_tests/FlagExpectations/disable-layout-ng index feeecdd..d85c742 100644 --- a/third_party/blink/web_tests/FlagExpectations/disable-layout-ng +++ b/third_party/blink/web_tests/FlagExpectations/disable-layout-ng
@@ -111,6 +111,7 @@ crbug.com/829028 external/wpt/css/css-break/fieldset-005.html [ Failure ] crbug.com/829028 external/wpt/css/css-break/fieldset-006.html [ Failure ] crbug.com/829028 external/wpt/css/css-break/forced-break-at-fragmentainer-start-000.html [ Failure ] +crbug.com/829028 external/wpt/css/css-break/hit-test-transformed.html [ Failure ] crbug.com/829028 external/wpt/css/css-break/monolithic-with-overflow-lr.html [ Failure ] crbug.com/829028 external/wpt/css/css-break/monolithic-with-overflow-rl.html [ Failure ] crbug.com/829028 external/wpt/css/css-break/monolithic-with-overflow.html [ Failure ]
diff --git a/third_party/blink/web_tests/PRESUBMIT.py b/third_party/blink/web_tests/PRESUBMIT.py index 32d7b6e..f14e8c4 100644 --- a/third_party/blink/web_tests/PRESUBMIT.py +++ b/third_party/blink/web_tests/PRESUBMIT.py
@@ -235,7 +235,7 @@ if check_all: for f in input_api.change.AllFiles( os_path.join(input_api.PresubmitLocalPath(), "virtual")): - suite = f.split(os_path.sep)[0] + suite = f.split('/')[0] if not suite in known_virtual_suites: path = os_path.relpath( os_path.join(input_api.PresubmitLocalPath(), "virtual", f), @@ -247,7 +247,7 @@ for subdir in ["platform", "flag-specific"]: for f in input_api.change.AllFiles( os_path.join(input_api.PresubmitLocalPath(), subdir)): - path_components = f.split(os_path.sep) + path_components = f.split('/') if len(path_components) < 3 or path_components[1] != 'virtual': continue suite = path_components[2]
diff --git a/third_party/blink/web_tests/TestExpectations b/third_party/blink/web_tests/TestExpectations index 41827072..8e45faf 100644 --- a/third_party/blink/web_tests/TestExpectations +++ b/third_party/blink/web_tests/TestExpectations
@@ -194,15 +194,9 @@ # --- END CanvasFormattedText tests -# These tests were disabled to allow enabling WebAssembly Reference Types. -crbug.com/v8/7581 external/wpt/wasm/jsapi/global/type.tentative.any.html [ Failure Pass ] -crbug.com/v8/7581 external/wpt/wasm/jsapi/global/type.tentative.any.worker.html [ Failure Pass ] - # These tests block fixes done in V8. The tests run on the V8 bots as well. crbug.com/v8/12227 external/wpt/wasm/jsapi/exception/toString.tentative.any.html [ Failure Pass ] crbug.com/v8/12227 external/wpt/wasm/jsapi/exception/toString.tentative.any.worker.html [ Failure Pass ] -crbug.com/v8/12227 external/wpt/wasm/jsapi/table/type.tentative.any.html [ Failure Pass ] -crbug.com/v8/12227 external/wpt/wasm/jsapi/table/type.tentative.any.worker.html [ Failure Pass ] # Sheriff on 2020-09-03 crbug.com/1124352 media/picture-in-picture/clear-after-request.html [ Crash Pass ] @@ -4328,7 +4322,6 @@ crbug.com/614667 external/wpt/css/css-break/grid/grid-item-fragmentation-037.html [ Failure ] crbug.com/614667 external/wpt/css/css-break/grid/grid-item-fragmentation-038.html [ Failure ] crbug.com/614667 external/wpt/css/css-break/grid/grid-item-fragmentation-039.html [ Failure ] -crbug.com/1066629 external/wpt/css/css-break/hit-test-transformed.html [ Failure ] crbug.com/1058792 external/wpt/css/css-break/transform-007.html [ Failure ] crbug.com/1224888 external/wpt/css/css-break/transform-009.html [ Failure ] crbug.com/1156312 external/wpt/css/css-break/widows-orphans-017.html [ Failure ]
diff --git a/third_party/blink/web_tests/external/wpt/wasm/jsapi/global/type.tentative.any-expected.txt b/third_party/blink/web_tests/external/wpt/wasm/jsapi/global/type.tentative.any-expected.txt new file mode 100644 index 0000000..2aec539c --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/wasm/jsapi/global/type.tentative.any-expected.txt
@@ -0,0 +1,16 @@ +This is a testharness.js-based test. +FAIL i32, mutable myglobal.type is not a function +FAIL i32, immutable myglobal.type is not a function +FAIL i64, mutable myglobal.type is not a function +FAIL i64, immutable myglobal.type is not a function +FAIL f32, mutable myglobal.type is not a function +FAIL f32, immutable myglobal.type is not a function +FAIL f64, mutable myglobal.type is not a function +FAIL f64, immutable myglobal.type is not a function +FAIL externref, mutable myglobal.type is not a function +FAIL externref, immutable myglobal.type is not a function +FAIL anyfunc, mutable myglobal.type is not a function +FAIL anyfunc, immutable myglobal.type is not a function +FAIL key ordering myglobal.type is not a function +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/wasm/jsapi/global/type.tentative.any.worker-expected.txt b/third_party/blink/web_tests/external/wpt/wasm/jsapi/global/type.tentative.any.worker-expected.txt new file mode 100644 index 0000000..2aec539c --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/wasm/jsapi/global/type.tentative.any.worker-expected.txt
@@ -0,0 +1,16 @@ +This is a testharness.js-based test. +FAIL i32, mutable myglobal.type is not a function +FAIL i32, immutable myglobal.type is not a function +FAIL i64, mutable myglobal.type is not a function +FAIL i64, immutable myglobal.type is not a function +FAIL f32, mutable myglobal.type is not a function +FAIL f32, immutable myglobal.type is not a function +FAIL f64, mutable myglobal.type is not a function +FAIL f64, immutable myglobal.type is not a function +FAIL externref, mutable myglobal.type is not a function +FAIL externref, immutable myglobal.type is not a function +FAIL anyfunc, mutable myglobal.type is not a function +FAIL anyfunc, immutable myglobal.type is not a function +FAIL key ordering myglobal.type is not a function +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/wasm/jsapi/table/type.tentative.any-expected.txt b/third_party/blink/web_tests/external/wpt/wasm/jsapi/table/type.tentative.any-expected.txt new file mode 100644 index 0000000..f65819c --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/wasm/jsapi/table/type.tentative.any-expected.txt
@@ -0,0 +1,7 @@ +This is a testharness.js-based test. +FAIL Zero initial, no maximum WebAssembly.Table(): Property 'initial' is required +FAIL Non-zero initial, no maximum WebAssembly.Table(): Property 'initial' is required +FAIL Zero maximum WebAssembly.Table(): Property 'initial' is required +FAIL Non-zero maximum WebAssembly.Table(): Property 'initial' is required +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/wasm/jsapi/table/type.tentative.any.worker-expected.txt b/third_party/blink/web_tests/external/wpt/wasm/jsapi/table/type.tentative.any.worker-expected.txt new file mode 100644 index 0000000..f65819c --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/wasm/jsapi/table/type.tentative.any.worker-expected.txt
@@ -0,0 +1,7 @@ +This is a testharness.js-based test. +FAIL Zero initial, no maximum WebAssembly.Table(): Property 'initial' is required +FAIL Non-zero initial, no maximum WebAssembly.Table(): Property 'initial' is required +FAIL Zero maximum WebAssembly.Table(): Property 'initial' is required +FAIL Non-zero maximum WebAssembly.Table(): Property 'initial' is required +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/inspector-protocol/runtime/runtime-console-async-tagging-api-recurring-expected.txt b/third_party/blink/web_tests/inspector-protocol/runtime/runtime-console-async-tagging-api-recurring-expected.txt new file mode 100644 index 0000000..9972365 --- /dev/null +++ b/third_party/blink/web_tests/inspector-protocol/runtime/runtime-console-async-tagging-api-recurring-expected.txt
@@ -0,0 +1,3 @@ +Tests that async stack tagging API (recurring) works as expected. +Skipping: async stack tagging API not enabled. +
diff --git a/third_party/blink/web_tests/inspector-protocol/runtime/runtime-console-async-tagging-api-recurring.js b/third_party/blink/web_tests/inspector-protocol/runtime/runtime-console-async-tagging-api-recurring.js new file mode 100644 index 0000000..2c25580 --- /dev/null +++ b/third_party/blink/web_tests/inspector-protocol/runtime/runtime-console-async-tagging-api-recurring.js
@@ -0,0 +1,127 @@ +(async function(testRunner) { + var {session, dp} = await testRunner.startBlank( + 'Tests that async stack tagging API (recurring) works as expected.'); + + dp.Runtime.enable(); + dp.Debugger.setAsyncCallStackDepth({maxDepth: 32}); + + const response1 = await dp.Runtime.onceExecutionContextCreated(); + const pageContextId = response1.params.context.id; // main page + session.evaluate(` + window.frame = document.createElement('iframe'); + frame.src = '${testRunner.url('../resources/blank.html')}'; + document.body.appendChild(frame); + `); + const response2 = await dp.Runtime.onceExecutionContextCreated(); + const frameContextId = response2.params.context.id; // IFrame + + const apiEnabled = await dp.Runtime.evaluate( + {expression: `"scheduleAsyncTask" in console`, contextId: pageContextId}); + if (!apiEnabled.result.result.value) { + testRunner.log('Skipping: async stack tagging API not enabled.'); + testRunner.completeTest(); + return; + } + + const configs = [pageContextId, frameContextId]; + + dp.Runtime.onConsoleAPICalled((result) => testRunner.log(result)); + dp.Runtime.onExceptionThrown((result) => testRunner.log(result)); + + const code = ` + /* --- Runtime --- */ + + // Something akin to requestIdleCallback, but deterministic. + + const BUDGET = 2; + + function fakeRequestIdleCallback(cb) { + function makeDeadline() { + let ticks = BUDGET; + + return { + ticksRemaining() { + return ticks--; + }, + }; + } + + cb(makeDeadline()); + } + + /* --- Library --- */ + + function makeTask(id, name, jobs) { + return { + runNextJob() { + const f = jobs.shift(); + console.startAsyncTask(id); + f(); + console.finishAsyncTask(id); + + if (jobs.length) { + return false; + } + + console.cancelAsyncTask(id); + return true; + }, + }; + } + + function makeScheduler() { + const tasks = []; + + function workLoop(deadline) { + while (deadline.ticksRemaining() > 0 && tasks.length) { + const task = tasks[0]; + const finished = task.runNextJob(); + if (finished) { + tasks.shift(); + } + } + + if (tasks.length) { + fakeRequestIdleCallback(workLoop); + return; + } + + } + + return { + scheduleTask(name, jobs) { + const id = console.scheduleAsyncTask(name, true); + tasks.push(makeTask(id, name, jobs)); + }, + + scheduleWorkLoop() { + fakeRequestIdleCallback(workLoop); + }, + }; + } + + /* --- Userland --- */ + + function makeJob(i) { + return function someJob() { + console.trace(\`completeWork: job \${i}\`); + }; + } + + const scheduler = makeScheduler(); + + function businessLogic() { + scheduler.scheduleTask("fooTask", [makeJob(1), makeJob(2), makeJob(3)]); + scheduler.scheduleTask("barBask", [makeJob(4), makeJob(5)]); + } + + businessLogic(); + scheduler.scheduleWorkLoop(); + `; + + for (const contextId of configs) { + await dp.Runtime.evaluate({expression: code, contextId}); + } + + testRunner.completeTest(); +});
diff --git a/third_party/blink/web_tests/inspector-protocol/runtime/runtime-console-async-tagging-errors.js b/third_party/blink/web_tests/inspector-protocol/runtime/runtime-console-async-tagging-errors.js index 78bdb59..d27912b 100644 --- a/third_party/blink/web_tests/inspector-protocol/runtime/runtime-console-async-tagging-errors.js +++ b/third_party/blink/web_tests/inspector-protocol/runtime/runtime-console-async-tagging-errors.js
@@ -34,10 +34,17 @@ ` }; + const failsScheduleWithBadRecurringArg = { + name: 'Scheduling an async task with a bad recurring flag should fail', + code: ` + console.scheduleAsyncTask("foo", 42); + ` + }; + const failsScheduleWithTooManyArgs = { name: 'Scheduling an async task with too many arguments should fail', code: ` - console.scheduleAsyncTask("foo", 42); + console.scheduleAsyncTask("foo", false, 42); ` }; @@ -127,6 +134,7 @@ const checks = [ failsScheduleWithNotEnoughArgs, + failsScheduleWithBadRecurringArg, failsScheduleWithTooManyArgs, failsStartWithBadTaskId, failsStartWithWrongTaskId,
diff --git a/third_party/blink/web_tests/virtual/enable-experimental-async-stack-tagging-api/inspector-protocol/runtime/runtime-console-async-tagging-api-recurring-expected.txt b/third_party/blink/web_tests/virtual/enable-experimental-async-stack-tagging-api/inspector-protocol/runtime/runtime-console-async-tagging-api-recurring-expected.txt new file mode 100644 index 0000000..4cf0e360 --- /dev/null +++ b/third_party/blink/web_tests/virtual/enable-experimental-async-stack-tagging-api/inspector-protocol/runtime/runtime-console-async-tagging-api-recurring-expected.txt
@@ -0,0 +1,984 @@ +Tests that async stack tagging API (recurring) works as expected. +{ + method : Runtime.consoleAPICalled + params : { + args : [ + [0] : { + type : string + value : completeWork: job 1 + } + ] + executionContextId : <number> + stackTrace : { + callFrames : [ + [0] : { + columnNumber : 14 + functionName : someJob + lineNumber : 76 + scriptId : <string> + url : + } + [1] : { + columnNumber : 8 + functionName : runNextJob + lineNumber : 28 + scriptId : <string> + url : + } + [2] : { + columnNumber : 30 + functionName : workLoop + lineNumber : 47 + scriptId : <string> + url : + } + [3] : { + columnNumber : 4 + functionName : fakeRequestIdleCallback + lineNumber : 18 + scriptId : <string> + url : + } + [4] : { + columnNumber : 8 + functionName : scheduleWorkLoop + lineNumber : 67 + scriptId : <string> + url : + } + [5] : { + columnNumber : 12 + functionName : + lineNumber : 88 + scriptId : <string> + url : + } + ] + parent : { + callFrames : [ + [0] : { + columnNumber : 27 + functionName : scheduleTask + lineNumber : 62 + scriptId : <string> + url : + } + [1] : { + columnNumber : 14 + functionName : businessLogic + lineNumber : 83 + scriptId : <string> + url : + } + [2] : { + columnNumber : 2 + functionName : + lineNumber : 87 + scriptId : <string> + url : + } + ] + description : fooTask + } + } + timestamp : <number> + type : trace + } + sessionId : <string> +} +{ + method : Runtime.consoleAPICalled + params : { + args : [ + [0] : { + type : string + value : completeWork: job 2 + } + ] + executionContextId : <number> + stackTrace : { + callFrames : [ + [0] : { + columnNumber : 14 + functionName : someJob + lineNumber : 76 + scriptId : <string> + url : + } + [1] : { + columnNumber : 8 + functionName : runNextJob + lineNumber : 28 + scriptId : <string> + url : + } + [2] : { + columnNumber : 30 + functionName : workLoop + lineNumber : 47 + scriptId : <string> + url : + } + [3] : { + columnNumber : 4 + functionName : fakeRequestIdleCallback + lineNumber : 18 + scriptId : <string> + url : + } + [4] : { + columnNumber : 8 + functionName : scheduleWorkLoop + lineNumber : 67 + scriptId : <string> + url : + } + [5] : { + columnNumber : 12 + functionName : + lineNumber : 88 + scriptId : <string> + url : + } + ] + parent : { + callFrames : [ + [0] : { + columnNumber : 27 + functionName : scheduleTask + lineNumber : 62 + scriptId : <string> + url : + } + [1] : { + columnNumber : 14 + functionName : businessLogic + lineNumber : 83 + scriptId : <string> + url : + } + [2] : { + columnNumber : 2 + functionName : + lineNumber : 87 + scriptId : <string> + url : + } + ] + description : fooTask + } + } + timestamp : <number> + type : trace + } + sessionId : <string> +} +{ + method : Runtime.consoleAPICalled + params : { + args : [ + [0] : { + type : string + value : completeWork: job 3 + } + ] + executionContextId : <number> + stackTrace : { + callFrames : [ + [0] : { + columnNumber : 14 + functionName : someJob + lineNumber : 76 + scriptId : <string> + url : + } + [1] : { + columnNumber : 8 + functionName : runNextJob + lineNumber : 28 + scriptId : <string> + url : + } + [2] : { + columnNumber : 30 + functionName : workLoop + lineNumber : 47 + scriptId : <string> + url : + } + [3] : { + columnNumber : 4 + functionName : fakeRequestIdleCallback + lineNumber : 18 + scriptId : <string> + url : + } + [4] : { + columnNumber : 8 + functionName : workLoop + lineNumber : 54 + scriptId : <string> + url : + } + [5] : { + columnNumber : 4 + functionName : fakeRequestIdleCallback + lineNumber : 18 + scriptId : <string> + url : + } + [6] : { + columnNumber : 8 + functionName : scheduleWorkLoop + lineNumber : 67 + scriptId : <string> + url : + } + [7] : { + columnNumber : 12 + functionName : + lineNumber : 88 + scriptId : <string> + url : + } + ] + parent : { + callFrames : [ + [0] : { + columnNumber : 27 + functionName : scheduleTask + lineNumber : 62 + scriptId : <string> + url : + } + [1] : { + columnNumber : 14 + functionName : businessLogic + lineNumber : 83 + scriptId : <string> + url : + } + [2] : { + columnNumber : 2 + functionName : + lineNumber : 87 + scriptId : <string> + url : + } + ] + description : fooTask + } + } + timestamp : <number> + type : trace + } + sessionId : <string> +} +{ + method : Runtime.consoleAPICalled + params : { + args : [ + [0] : { + type : string + value : completeWork: job 4 + } + ] + executionContextId : <number> + stackTrace : { + callFrames : [ + [0] : { + columnNumber : 14 + functionName : someJob + lineNumber : 76 + scriptId : <string> + url : + } + [1] : { + columnNumber : 8 + functionName : runNextJob + lineNumber : 28 + scriptId : <string> + url : + } + [2] : { + columnNumber : 30 + functionName : workLoop + lineNumber : 47 + scriptId : <string> + url : + } + [3] : { + columnNumber : 4 + functionName : fakeRequestIdleCallback + lineNumber : 18 + scriptId : <string> + url : + } + [4] : { + columnNumber : 8 + functionName : workLoop + lineNumber : 54 + scriptId : <string> + url : + } + [5] : { + columnNumber : 4 + functionName : fakeRequestIdleCallback + lineNumber : 18 + scriptId : <string> + url : + } + [6] : { + columnNumber : 8 + functionName : scheduleWorkLoop + lineNumber : 67 + scriptId : <string> + url : + } + [7] : { + columnNumber : 12 + functionName : + lineNumber : 88 + scriptId : <string> + url : + } + ] + parent : { + callFrames : [ + [0] : { + columnNumber : 27 + functionName : scheduleTask + lineNumber : 62 + scriptId : <string> + url : + } + [1] : { + columnNumber : 14 + functionName : businessLogic + lineNumber : 84 + scriptId : <string> + url : + } + [2] : { + columnNumber : 2 + functionName : + lineNumber : 87 + scriptId : <string> + url : + } + ] + description : barBask + } + } + timestamp : <number> + type : trace + } + sessionId : <string> +} +{ + method : Runtime.consoleAPICalled + params : { + args : [ + [0] : { + type : string + value : completeWork: job 5 + } + ] + executionContextId : <number> + stackTrace : { + callFrames : [ + [0] : { + columnNumber : 14 + functionName : someJob + lineNumber : 76 + scriptId : <string> + url : + } + [1] : { + columnNumber : 8 + functionName : runNextJob + lineNumber : 28 + scriptId : <string> + url : + } + [2] : { + columnNumber : 30 + functionName : workLoop + lineNumber : 47 + scriptId : <string> + url : + } + [3] : { + columnNumber : 4 + functionName : fakeRequestIdleCallback + lineNumber : 18 + scriptId : <string> + url : + } + [4] : { + columnNumber : 8 + functionName : workLoop + lineNumber : 54 + scriptId : <string> + url : + } + [5] : { + columnNumber : 4 + functionName : fakeRequestIdleCallback + lineNumber : 18 + scriptId : <string> + url : + } + [6] : { + columnNumber : 8 + functionName : workLoop + lineNumber : 54 + scriptId : <string> + url : + } + [7] : { + columnNumber : 4 + functionName : fakeRequestIdleCallback + lineNumber : 18 + scriptId : <string> + url : + } + [8] : { + columnNumber : 8 + functionName : scheduleWorkLoop + lineNumber : 67 + scriptId : <string> + url : + } + [9] : { + columnNumber : 12 + functionName : + lineNumber : 88 + scriptId : <string> + url : + } + ] + parent : { + callFrames : [ + [0] : { + columnNumber : 27 + functionName : scheduleTask + lineNumber : 62 + scriptId : <string> + url : + } + [1] : { + columnNumber : 14 + functionName : businessLogic + lineNumber : 84 + scriptId : <string> + url : + } + [2] : { + columnNumber : 2 + functionName : + lineNumber : 87 + scriptId : <string> + url : + } + ] + description : barBask + } + } + timestamp : <number> + type : trace + } + sessionId : <string> +} +{ + method : Runtime.consoleAPICalled + params : { + args : [ + [0] : { + type : string + value : completeWork: job 1 + } + ] + executionContextId : <number> + stackTrace : { + callFrames : [ + [0] : { + columnNumber : 14 + functionName : someJob + lineNumber : 76 + scriptId : <string> + url : + } + [1] : { + columnNumber : 8 + functionName : runNextJob + lineNumber : 28 + scriptId : <string> + url : + } + [2] : { + columnNumber : 30 + functionName : workLoop + lineNumber : 47 + scriptId : <string> + url : + } + [3] : { + columnNumber : 4 + functionName : fakeRequestIdleCallback + lineNumber : 18 + scriptId : <string> + url : + } + [4] : { + columnNumber : 8 + functionName : scheduleWorkLoop + lineNumber : 67 + scriptId : <string> + url : + } + [5] : { + columnNumber : 12 + functionName : + lineNumber : 88 + scriptId : <string> + url : + } + ] + parent : { + callFrames : [ + [0] : { + columnNumber : 27 + functionName : scheduleTask + lineNumber : 62 + scriptId : <string> + url : + } + [1] : { + columnNumber : 14 + functionName : businessLogic + lineNumber : 83 + scriptId : <string> + url : + } + [2] : { + columnNumber : 2 + functionName : + lineNumber : 87 + scriptId : <string> + url : + } + ] + description : fooTask + } + } + timestamp : <number> + type : trace + } + sessionId : <string> +} +{ + method : Runtime.consoleAPICalled + params : { + args : [ + [0] : { + type : string + value : completeWork: job 2 + } + ] + executionContextId : <number> + stackTrace : { + callFrames : [ + [0] : { + columnNumber : 14 + functionName : someJob + lineNumber : 76 + scriptId : <string> + url : + } + [1] : { + columnNumber : 8 + functionName : runNextJob + lineNumber : 28 + scriptId : <string> + url : + } + [2] : { + columnNumber : 30 + functionName : workLoop + lineNumber : 47 + scriptId : <string> + url : + } + [3] : { + columnNumber : 4 + functionName : fakeRequestIdleCallback + lineNumber : 18 + scriptId : <string> + url : + } + [4] : { + columnNumber : 8 + functionName : scheduleWorkLoop + lineNumber : 67 + scriptId : <string> + url : + } + [5] : { + columnNumber : 12 + functionName : + lineNumber : 88 + scriptId : <string> + url : + } + ] + parent : { + callFrames : [ + [0] : { + columnNumber : 27 + functionName : scheduleTask + lineNumber : 62 + scriptId : <string> + url : + } + [1] : { + columnNumber : 14 + functionName : businessLogic + lineNumber : 83 + scriptId : <string> + url : + } + [2] : { + columnNumber : 2 + functionName : + lineNumber : 87 + scriptId : <string> + url : + } + ] + description : fooTask + } + } + timestamp : <number> + type : trace + } + sessionId : <string> +} +{ + method : Runtime.consoleAPICalled + params : { + args : [ + [0] : { + type : string + value : completeWork: job 3 + } + ] + executionContextId : <number> + stackTrace : { + callFrames : [ + [0] : { + columnNumber : 14 + functionName : someJob + lineNumber : 76 + scriptId : <string> + url : + } + [1] : { + columnNumber : 8 + functionName : runNextJob + lineNumber : 28 + scriptId : <string> + url : + } + [2] : { + columnNumber : 30 + functionName : workLoop + lineNumber : 47 + scriptId : <string> + url : + } + [3] : { + columnNumber : 4 + functionName : fakeRequestIdleCallback + lineNumber : 18 + scriptId : <string> + url : + } + [4] : { + columnNumber : 8 + functionName : workLoop + lineNumber : 54 + scriptId : <string> + url : + } + [5] : { + columnNumber : 4 + functionName : fakeRequestIdleCallback + lineNumber : 18 + scriptId : <string> + url : + } + [6] : { + columnNumber : 8 + functionName : scheduleWorkLoop + lineNumber : 67 + scriptId : <string> + url : + } + [7] : { + columnNumber : 12 + functionName : + lineNumber : 88 + scriptId : <string> + url : + } + ] + parent : { + callFrames : [ + [0] : { + columnNumber : 27 + functionName : scheduleTask + lineNumber : 62 + scriptId : <string> + url : + } + [1] : { + columnNumber : 14 + functionName : businessLogic + lineNumber : 83 + scriptId : <string> + url : + } + [2] : { + columnNumber : 2 + functionName : + lineNumber : 87 + scriptId : <string> + url : + } + ] + description : fooTask + } + } + timestamp : <number> + type : trace + } + sessionId : <string> +} +{ + method : Runtime.consoleAPICalled + params : { + args : [ + [0] : { + type : string + value : completeWork: job 4 + } + ] + executionContextId : <number> + stackTrace : { + callFrames : [ + [0] : { + columnNumber : 14 + functionName : someJob + lineNumber : 76 + scriptId : <string> + url : + } + [1] : { + columnNumber : 8 + functionName : runNextJob + lineNumber : 28 + scriptId : <string> + url : + } + [2] : { + columnNumber : 30 + functionName : workLoop + lineNumber : 47 + scriptId : <string> + url : + } + [3] : { + columnNumber : 4 + functionName : fakeRequestIdleCallback + lineNumber : 18 + scriptId : <string> + url : + } + [4] : { + columnNumber : 8 + functionName : workLoop + lineNumber : 54 + scriptId : <string> + url : + } + [5] : { + columnNumber : 4 + functionName : fakeRequestIdleCallback + lineNumber : 18 + scriptId : <string> + url : + } + [6] : { + columnNumber : 8 + functionName : scheduleWorkLoop + lineNumber : 67 + scriptId : <string> + url : + } + [7] : { + columnNumber : 12 + functionName : + lineNumber : 88 + scriptId : <string> + url : + } + ] + parent : { + callFrames : [ + [0] : { + columnNumber : 27 + functionName : scheduleTask + lineNumber : 62 + scriptId : <string> + url : + } + [1] : { + columnNumber : 14 + functionName : businessLogic + lineNumber : 84 + scriptId : <string> + url : + } + [2] : { + columnNumber : 2 + functionName : + lineNumber : 87 + scriptId : <string> + url : + } + ] + description : barBask + } + } + timestamp : <number> + type : trace + } + sessionId : <string> +} +{ + method : Runtime.consoleAPICalled + params : { + args : [ + [0] : { + type : string + value : completeWork: job 5 + } + ] + executionContextId : <number> + stackTrace : { + callFrames : [ + [0] : { + columnNumber : 14 + functionName : someJob + lineNumber : 76 + scriptId : <string> + url : + } + [1] : { + columnNumber : 8 + functionName : runNextJob + lineNumber : 28 + scriptId : <string> + url : + } + [2] : { + columnNumber : 30 + functionName : workLoop + lineNumber : 47 + scriptId : <string> + url : + } + [3] : { + columnNumber : 4 + functionName : fakeRequestIdleCallback + lineNumber : 18 + scriptId : <string> + url : + } + [4] : { + columnNumber : 8 + functionName : workLoop + lineNumber : 54 + scriptId : <string> + url : + } + [5] : { + columnNumber : 4 + functionName : fakeRequestIdleCallback + lineNumber : 18 + scriptId : <string> + url : + } + [6] : { + columnNumber : 8 + functionName : workLoop + lineNumber : 54 + scriptId : <string> + url : + } + [7] : { + columnNumber : 4 + functionName : fakeRequestIdleCallback + lineNumber : 18 + scriptId : <string> + url : + } + [8] : { + columnNumber : 8 + functionName : scheduleWorkLoop + lineNumber : 67 + scriptId : <string> + url : + } + [9] : { + columnNumber : 12 + functionName : + lineNumber : 88 + scriptId : <string> + url : + } + ] + parent : { + callFrames : [ + [0] : { + columnNumber : 27 + functionName : scheduleTask + lineNumber : 62 + scriptId : <string> + url : + } + [1] : { + columnNumber : 14 + functionName : businessLogic + lineNumber : 84 + scriptId : <string> + url : + } + [2] : { + columnNumber : 2 + functionName : + lineNumber : 87 + scriptId : <string> + url : + } + ] + description : barBask + } + } + timestamp : <number> + type : trace + } + sessionId : <string> +} +
diff --git a/third_party/blink/web_tests/virtual/enable-experimental-async-stack-tagging-api/inspector-protocol/runtime/runtime-console-async-tagging-errors-expected.txt b/third_party/blink/web_tests/virtual/enable-experimental-async-stack-tagging-api/inspector-protocol/runtime/runtime-console-async-tagging-errors-expected.txt index 5cad7fba..4fcf16a 100644 --- a/third_party/blink/web_tests/virtual/enable-experimental-async-stack-tagging-api/inspector-protocol/runtime/runtime-console-async-tagging-errors-expected.txt +++ b/third_party/blink/web_tests/virtual/enable-experimental-async-stack-tagging-api/inspector-protocol/runtime/runtime-console-async-tagging-errors-expected.txt
@@ -26,6 +26,33 @@ } sessionId : <string> } +Scheduling an async task with a bad recurring flag should fail +{ + method : Runtime.consoleAPICalled + params : { + args : [ + [0] : { + type : string + value : Unexpected arguments + } + ] + executionContextId : <number> + stackTrace : { + callFrames : [ + [0] : { + columnNumber : 27 + functionName : + lineNumber : 2 + scriptId : <string> + url : + } + ] + } + timestamp : <number> + type : log + } + sessionId : <string> +} Scheduling an async task with too many arguments should fail { method : Runtime.consoleAPICalled @@ -458,6 +485,33 @@ } sessionId : <string> } +Scheduling an async task with a bad recurring flag should fail +{ + method : Runtime.consoleAPICalled + params : { + args : [ + [0] : { + type : string + value : Unexpected arguments + } + ] + executionContextId : <number> + stackTrace : { + callFrames : [ + [0] : { + columnNumber : 27 + functionName : + lineNumber : 2 + scriptId : <string> + url : + } + ] + } + timestamp : <number> + type : log + } + sessionId : <string> +} Scheduling an async task with too many arguments should fail { method : Runtime.consoleAPICalled
diff --git a/tools/json_schema_compiler/util.cc b/tools/json_schema_compiler/util.cc index 393c5e45..613eced 100644 --- a/tools/json_schema_compiler/util.cc +++ b/tools/json_schema_compiler/util.cc
@@ -116,25 +116,6 @@ return true; } -bool PopulateItem(const base::Value& from, - std::unique_ptr<base::DictionaryValue>* out) { - const base::DictionaryValue* dict = nullptr; - if (!from.GetAsDictionary(&dict)) - return false; - *out = dict->CreateDeepCopy(); - return true; -} - -bool PopulateItem(const base::Value& from, - std::unique_ptr<base::DictionaryValue>* out, - std::u16string* error) { - const base::DictionaryValue* dict = nullptr; - if (!from.GetAsDictionary(&dict)) - return ReportError(from, base::Value::Type::DICTIONARY, error); - *out = dict->CreateDeepCopy(); - return true; -} - void AddItemToList(const int from, base::ListValue* out) { out->Append(from); } @@ -160,10 +141,5 @@ out->Append(from->Clone()); } -void AddItemToList(const std::unique_ptr<base::DictionaryValue>& from, - base::ListValue* out) { - out->Append(from->CreateDeepCopy()); -} - } // namespace util } // namespace json_schema_compiler
diff --git a/tools/mb/mb_config.pyl b/tools/mb/mb_config.pyl index 19598b4..24f95f5 100644 --- a/tools/mb/mb_config.pyl +++ b/tools/mb/mb_config.pyl
@@ -38,6 +38,7 @@ 'android-arm32-pgo': 'official_goma_android_arm32_pgo', 'android-arm64-pgo': 'official_goma_android_arm64_pgo', 'linux-pgo': 'official_goma_linux_pgo', + 'mac-arm-pgo': 'official_goma_mac_arm_pgo', 'mac-pgo': 'official_goma_mac_pgo', 'win32-pgo': 'official_goma_x86_pgo', 'win64-pgo': 'official_goma_x64_pgo', @@ -920,6 +921,7 @@ 'android-arm32-pgo': 'official_goma_android_arm32_pgo', 'android-arm64-pgo': 'official_goma_android_arm64_pgo', 'linux-pgo': 'official_goma_linux_pgo', + 'mac-arm-pgo': 'official_goma_mac_arm_pgo', 'mac-pgo': 'official_goma_mac_pgo', 'win32-pgo': 'official_goma_x86_pgo', 'win64-pgo': 'official_goma_x64_pgo', @@ -2727,6 +2729,10 @@ 'official', 'goma', 'no_keystone_registration_framework', 'no_widevine_cdm_host_verification', 'full_symbols', 'arm64', 'pgo_phase_0', 'use_py3_for_perf' ], + 'official_goma_mac_arm_pgo': [ + 'official', 'goma', 'no_keystone_registration_framework', 'no_widevine_cdm_host_verification', 'arm64', 'disable_widevine_signing', 'static', 'no_symbols', 'pgo_phase_1' + ], + 'official_goma_mac_pgo': [ 'official', 'goma', 'no_keystone_registration_framework', 'no_widevine_cdm_host_verification', 'disable_widevine_signing', 'static', 'no_symbols', 'pgo_phase_1' ],
diff --git a/tools/mb/mb_config_expectations/chrome.pgo.json b/tools/mb/mb_config_expectations/chrome.pgo.json index fd49a37..80ae786 100644 --- a/tools/mb/mb_config_expectations/chrome.pgo.json +++ b/tools/mb/mb_config_expectations/chrome.pgo.json
@@ -40,6 +40,21 @@ "use_goma": true } }, + "mac-arm-pgo": { + "gn_args": { + "chrome_pgo_phase": 1, + "enable_keystone_registration_framework": false, + "enable_widevine_cdm_host_verification": false, + "ignore_missing_widevine_signing_cert": true, + "is_chrome_branded": true, + "is_component_build": false, + "is_official_build": true, + "strip_absolute_paths_from_debug_symbols": true, + "symbol_level": 0, + "target_cpu": "arm64", + "use_goma": true + } + }, "mac-pgo": { "gn_args": { "chrome_pgo_phase": 1,
diff --git a/tools/mb/mb_config_expectations/tryserver.chrome.pgo.json b/tools/mb/mb_config_expectations/tryserver.chrome.pgo.json index fd49a37..80ae786 100644 --- a/tools/mb/mb_config_expectations/tryserver.chrome.pgo.json +++ b/tools/mb/mb_config_expectations/tryserver.chrome.pgo.json
@@ -40,6 +40,21 @@ "use_goma": true } }, + "mac-arm-pgo": { + "gn_args": { + "chrome_pgo_phase": 1, + "enable_keystone_registration_framework": false, + "enable_widevine_cdm_host_verification": false, + "ignore_missing_widevine_signing_cert": true, + "is_chrome_branded": true, + "is_component_build": false, + "is_official_build": true, + "strip_absolute_paths_from_debug_symbols": true, + "symbol_level": 0, + "target_cpu": "arm64", + "use_goma": true + } + }, "mac-pgo": { "gn_args": { "chrome_pgo_phase": 1,
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index 35f0e50e..4357c5c 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -11738,6 +11738,15 @@ <int value="7" label="Failed to open low latency stream"/> </enum> +<enum name="CartDiscountConsentStatus"> + <summary>ChromeCart discount consent status.</summary> + <int value="0" label="Accepted"/> + <int value="1" label="Declined"/> + <int value="2" label="Ignored"/> + <int value="3" label="No show"/> + <int value="4" label="Never shown"/> +</enum> + <enum name="CartDiscountDataType"> <summary>Discount related data associated with the cart module.</summary> <int value="0" label="cart_discount_info"/> @@ -36774,6 +36783,7 @@ <int value="4109" label="WebAppManifestHandleLinks"/> <int value="4110" label="HTMLParamElementURLParameterInUsePdf"/> <int value="4111" label="HTMLParamElementURLParameterInUseNonPdf"/> + <int value="4112" label="WebTransportServerCertificateHashes"/> </enum> <enum name="FeaturePolicyAllowlistType"> @@ -53090,6 +53100,7 @@ <int value="-415186532" label="AndroidSiteSettingsUIRefresh:enabled"/> <int value="-414900505" label="ScrollCapture:enabled"/> <int value="-413562235" label="MessagesForAndroidUpdatePassword:disabled"/> + <int value="-413273557" label="EcheSWAInBackground:disabled"/> <int value="-412736561" label="EnableZeroStateMixedTypesRanker:enabled"/> <int value="-412645531" label="AutofillTokenPrefixMatching:enabled"/> <int value="-410852857" label="ImprovedA2HS:disabled"/> @@ -55915,6 +55926,7 @@ <int value="1670161209" label="ClickToOpenPDFPlaceholder:enabled"/> <int value="1670799163" label="ChromeHomeShowGoogleGWhenUrlCleared:enabled"/> <int value="1671021713" label="AutofillImportDynamicForms:disabled"/> + <int value="1671384669" label="EcheSWAInBackground:enabled"/> <int value="1671985641" label="WebViewVulkan:enabled"/> <int value="1673185316" label="EarlyCodeCache:enabled"/> <int value="1673427566" label="ChromeHomeExpandButton:disabled"/>
diff --git a/tools/metrics/histograms/metadata/content/histograms.xml b/tools/metrics/histograms/metadata/content/histograms.xml index 4ae4e15b..f029ce2 100644 --- a/tools/metrics/histograms/metadata/content/histograms.xml +++ b/tools/metrics/histograms/metadata/content/histograms.xml
@@ -22,6 +22,20 @@ <histograms> +<variants name="FeedNetworkRequestType"> + <variant name=".FeedQuery" summary="FeedQuery"/> + <variant name=".FollowWebFeed" summary="FollowWebFeed"/> + <variant name=".ListFollowedWebFeeds" summary="ListFollowedWebFeeds"/> + <variant name=".ListRecommendedWebFeeds" summary="ListRecommendedWebFeeds"/> + <variant name=".NextPage" summary="NextPage"/> + <variant name=".QueryBackgroundFeed" summary="QueryBackgroundFeed"/> + <variant name=".QueryInteractiveFeed" summary="QueryInteractiveFeed"/> + <variant name=".QueryNextPage" summary="QueryNextPage"/> + <variant name=".UnfollowWebFeed" summary="UnfollowWebFeed"/> + <variant name=".UploadActions" summary="UploadActions"/> + <variant name=".WebFeedListContents" summary="WebFeedListContents"/> +</variants> + <histogram name="ContentCapture.CaptureContentDelayTime" units="ms" expires_after="2022-12-01"> <owner>michaelbai@chromium.org</owner> @@ -640,43 +654,51 @@ </summary> </histogram> -<histogram name="ContentSuggestions.Feed.Network.CompressedResponseSizeKB" +<histogram name="ContentSuggestions.Feed.LoadTime" units="ms" + expires_after="M89"> + <obsolete> + Removed along with FeedV1 in M89 + </obsolete> + <owner>carlosk@chromium.org</owner> + <owner>harringtond@chromium.org</owner> + <owner>feed@chromium.org</owner> + <summary> + The time it takes for the Feed to load entries from the storage. + </summary> +</histogram> + +<histogram + name="ContentSuggestions.Feed.Network.CompressedResponseSizeKB{NetworkRequestType}" units="KB" expires_after="2022-07-03"> <owner>carlosk@chromium.org</owner> <owner>harringtond@chromium.org</owner> <owner>feed@chromium.org</owner> <summary> - Android: The wire size (potentially compressed) of a Feed network response - received by the Feed's networking host. Recorded when a successful response - is received. + Android: The wire size (potentially compressed) of a {NetworkRequestType} + network response received by the Feed's networking host. Recorded when a + successful response is received. </summary> + <token key="NetworkRequestType" variants="FeedNetworkRequestType"> + <variant name="" summary="Feed"/> + </token> </histogram> -<histogram name="ContentSuggestions.Feed.Network.Duration" units="ms" - expires_after="2022-07-11"> - <owner>carlosk@chromium.org</owner> - <owner>harringtond@chromium.org</owner> - <owner>feed@chromium.org</owner> - <summary> - The duration of a network request made by the Feed component. Recorded when - each network request is completed. This includes the time it takes to get an - auth token for signed in users. - </summary> -</histogram> - -<histogram name="ContentSuggestions.Feed.Network.Duration.{NetworkEvent}" - units="ms" expires_after="2022-03-01"> +<histogram name="ContentSuggestions.Feed.Network.Duration{NetworkEvent}" + units="ms" expires_after="2022-07-03"> <owner>sczs@chromium.org</owner> <owner>harringtond@chromium.org</owner> <owner>feed@chromium.org</owner> <summary>The amount of time a {NetworkEvent} network event took.</summary> - <token key="NetworkEvent"> - <variant name="ActionUploadFailure"/> - <variant name="ActionUploadSuccess"/> - <variant name="ArticlesFetchFailure"/> - <variant name="ArticlesFetchSuccess"/> - <variant name="MoreArticlesFetchFailure"/> - <variant name="MoreArticlesFetchSuccess"/> + <token key="NetworkEvent" variants="FeedNetworkRequestType"> + <variant name="" summary="Feed component"/> + <variant name=".ActionUploadFailure" summary="ActionUploadFailure"/> + <variant name=".ActionUploadSuccess" summary="ActionUploadSuccess"/> + <variant name=".ArticlesFetchFailure" summary="ArticlesFetchFailure"/> + <variant name=".ArticlesFetchSuccess" summary="ArticlesFetchSuccess"/> + <variant name=".MoreArticlesFetchFailure" + summary="MoreArticlesFetchFailure"/> + <variant name=".MoreArticlesFetchSuccess" + summary="MoreArticlesFetchSuccess"/> </token> </histogram> @@ -714,7 +736,7 @@ </summary> </histogram> -<histogram name="ContentSuggestions.Feed.Network.ResponseStatus" +<histogram name="ContentSuggestions.Feed.Network.ResponseStatus{Type}" enum="CombinedHttpResponseAndNetErrorCode" expires_after="2022-07-03"> <owner>carlosk@chromium.org</owner> <owner>harringtond@chromium.org</owner> @@ -722,6 +744,20 @@ <summary> The HTTP response status for a network request made by the Feed component. </summary> + <token key="Type" variants="FeedNetworkRequestType"/> +</histogram> + +<histogram name="ContentSuggestions.Feed.Network.TokenDuration" units="ms" + expires_after="M89"> + <obsolete> + Removed along with FeedV1 in M89 + </obsolete> + <owner>carlosk@chromium.org</owner> + <owner>harringtond@chromium.org</owner> + <owner>feed@chromium.org</owner> + <summary> + The amount of time it takes to get an access token for signed in users. + </summary> </histogram> <histogram name="ContentSuggestions.Feed.Network.TokenFetchStatus"
diff --git a/tools/metrics/histograms/metadata/histogram_suffixes_list.xml b/tools/metrics/histograms/metadata/histogram_suffixes_list.xml index 84f5a46..f6a8318 100644 --- a/tools/metrics/histograms/metadata/histogram_suffixes_list.xml +++ b/tools/metrics/histograms/metadata/histogram_suffixes_list.xml
@@ -4939,30 +4939,6 @@ <affected-histogram name="ContentSuggestions.Feed.LoadStepLatency"/> </histogram_suffixes> -<histogram_suffixes name="FeedNetworkRequestType" separator="."> - <suffix name="FeedQuery" label="Requests to fetch new feed content"/> - <suffix name="FollowWebFeed" label="Requests to follow a web feed"/> - <suffix name="ListFollowedWebFeeds" - label="Requests to list followed web feeds"/> - <suffix name="ListRecommendedWebFeeds" - label="Requests to list recommended web feeds"/> - <suffix name="NextPage" label="Requests to fetch the next page of the feed"/> - <suffix name="QueryBackgroundFeed" - label="Background requests to DiscoFeed to fetch new feed content"/> - <suffix name="QueryInteractiveFeed" - label="Requests to DiscoFeed to fetch new feed content"/> - <suffix name="QueryNextPage" - label="Requests to DiscoFeed to fetch the next page of content"/> - <suffix name="UnfollowWebFeed" label="Requests to unfollow a web feed"/> - <suffix name="UploadActions" label="Requests to upload user action data"/> - <suffix name="WebFeedListContents" - label="Request to fetch the contents of the web feed"/> - <affected-histogram - name="ContentSuggestions.Feed.Network.CompressedResponseSizeKB"/> - <affected-histogram name="ContentSuggestions.Feed.Network.Duration"/> - <affected-histogram name="ContentSuggestions.Feed.Network.ResponseStatus"/> -</histogram_suffixes> - <histogram_suffixes name="FeedOrHostOlder" separator="."> <suffix name="FeedIsOlder" label=""/> <suffix name="HostIsOlder" label=""/>
diff --git a/tools/metrics/histograms/metadata/new_tab_page/histograms.xml b/tools/metrics/histograms/metadata/new_tab_page/histograms.xml index e9f100f..06b5a84 100644 --- a/tools/metrics/histograms/metadata/new_tab_page/histograms.xml +++ b/tools/metrics/histograms/metadata/new_tab_page/histograms.xml
@@ -171,6 +171,25 @@ </summary> </histogram> +<histogram name="NewTabPage.Carts.DiscountConsentStatusAtLoad" + enum="CartDiscountConsentStatus" expires_after="2022-06-19"> + <owner>yuezhanggg@chromium.org</owner> + <owner>wychen@chromium.org</owner> + <owner>chrome-shopping@google.com</owner> + <summary> + Logged when the cart module is created and if there is at least one + abandoned cart. "Accept" and "Decline" to record + interaction result for users who have acted on the consent; + "IGNORED" for users who have seen the consent before but never + acted on it, and the consent is showing now; "No show" for users + who have seen the consent before but never acted on it, and the consent is + not showing now; "Never shown" for users who have never seen the + consent. Only logged on the 1P NTP. Note that even if the user has Google as + their default search engine, Incognito and Guest mode NTPs are not + considered 1P and don't log this histogram. + </summary> +</histogram> + <histogram name="NewTabPage.Carts.DiscountCountAtLoad" units="count" expires_after="2022-06-19"> <owner>meiliang@chromium.org</owner>
diff --git a/tools/perf/core/perfetto_binary_roller/binary_deps.json b/tools/perf/core/perfetto_binary_roller/binary_deps.json index 0434ee6..1f72f6d4 100644 --- a/tools/perf/core/perfetto_binary_roller/binary_deps.json +++ b/tools/perf/core/perfetto_binary_roller/binary_deps.json
@@ -5,24 +5,24 @@ "remote_path": "perfetto_binaries/trace_processor_shell/linux_arm64/49b4b5dcbc312d8d2c3751cf29238b8efeb4e494/trace_processor_shell" }, "win": { - "hash": "fac45c375ca5740c962699bf1badc5ef6ef9d1a6", - "remote_path": "perfetto_binaries/trace_processor_shell/win/eaf3141878e1188b63767f2e81a932a9fea6bec7/trace_processor_shell.exe" + "hash": "d6cb1144b9294741e65294ca97dba70916de332c", + "remote_path": "perfetto_binaries/trace_processor_shell/win/5a202e1c1c7fb14817bb4df498d5f0ea71915653/trace_processor_shell.exe" }, "linux_arm": { "hash": "58893933be305d3bfe0a72ebebcacde2ac3ca893", "remote_path": "perfetto_binaries/trace_processor_shell/linux_arm/49b4b5dcbc312d8d2c3751cf29238b8efeb4e494/trace_processor_shell" }, "mac": { - "hash": "b260bbb0f435d260abb220022d6573caad908616", - "remote_path": "perfetto_binaries/trace_processor_shell/mac/eaf3141878e1188b63767f2e81a932a9fea6bec7/trace_processor_shell" + "hash": "27f08c64c371ac3295e79f133c7ccb246efa163d", + "remote_path": "perfetto_binaries/trace_processor_shell/mac/5a202e1c1c7fb14817bb4df498d5f0ea71915653/trace_processor_shell" }, "mac_arm64": { "hash": "c0397e87456ad6c6a7aa0133e5b81c97adbab4ab", "remote_path": "perfetto_binaries/trace_processor_shell/mac_arm64/cefb3e0ec3a0580c996f801e854fe02963c03d5c/trace_processor_shell" }, "linux": { - "hash": "5e8d99ad4425aed5bcd5a79eefbe7470fced823b", - "remote_path": "perfetto_binaries/trace_processor_shell/linux/56f2ccce0511ebd51e2f7d2fa659719a712a6044/trace_processor_shell" + "hash": "9ae761116a94bc1979e1940862dd29fdc32d3a82", + "remote_path": "perfetto_binaries/trace_processor_shell/linux/5a202e1c1c7fb14817bb4df498d5f0ea71915653/trace_processor_shell" } }, "power_profile.sql": {
diff --git a/ui/events/ozone/evdev/BUILD.gn b/ui/events/ozone/evdev/BUILD.gn index 454e4f6e..8e6a5774 100644 --- a/ui/events/ozone/evdev/BUILD.gn +++ b/ui/events/ozone/evdev/BUILD.gn
@@ -159,6 +159,8 @@ "libgestures_glue/gesture_property_provider.h", "libgestures_glue/gesture_timer_provider.cc", "libgestures_glue/gesture_timer_provider.h", + "libgestures_glue/haptic_touchpad_handler.cc", + "libgestures_glue/haptic_touchpad_handler.h", ] deps += [ "//ui/ozone/public/mojom:gesture_properties_service" ] @@ -233,6 +235,9 @@ "gamepad_event_converter_evdev_unittest.cc", "input_controller_evdev_unittest.cc", "input_injector_evdev_unittest.cc", + "libgestures_glue/haptic_touchpad_handler.cc", + "libgestures_glue/haptic_touchpad_handler.h", + "libgestures_glue/haptic_touchpad_handler_unittest.cc", "microphone_mute_switch_event_converter_evdev_unittest.cc", "stylus_button_event_converter_evdev_unittest.cc", "tablet_event_converter_evdev_unittest.cc",
diff --git a/ui/events/ozone/evdev/event_device_info.cc b/ui/events/ozone/evdev/event_device_info.cc index febf0194..c2ff953 100644 --- a/ui/events/ozone/evdev/event_device_info.cc +++ b/ui/events/ozone/evdev/event_device_info.cc
@@ -21,6 +21,10 @@ #define EVIOCGMTSLOTS(len) _IOC(_IOC_READ, 'E', 0x0a, len) #endif +#ifndef INPUT_PROP_HAPTICPAD +#define INPUT_PROP_HAPTICPAD 0x07 +#endif + namespace ui { namespace { @@ -627,6 +631,10 @@ return HasAbsXY() && HasPointer() && !HasStylus(); } +bool EventDeviceInfo::HasHapticTouchpad() const { + return HasTouchpad() && HasProp(INPUT_PROP_HAPTICPAD); +} + bool EventDeviceInfo::HasTablet() const { return HasAbsXY() && HasPointer() && HasStylus(); }
diff --git a/ui/events/ozone/evdev/event_device_info.h b/ui/events/ozone/evdev/event_device_info.h index d0a0049..88cc90d 100644 --- a/ui/events/ozone/evdev/event_device_info.h +++ b/ui/events/ozone/evdev/event_device_info.h
@@ -149,6 +149,9 @@ // Determine whether there's a touchpad on this device. bool HasTouchpad() const; + // Determine whether there's a haptic touchpad on this device. + bool HasHapticTouchpad() const; + // Determine whether there's a tablet on this device. bool HasTablet() const;
diff --git a/ui/events/ozone/evdev/event_device_info_unittest.cc b/ui/events/ozone/evdev/event_device_info_unittest.cc index 5ade2bb..41b2e7a 100644 --- a/ui/events/ozone/evdev/event_device_info_unittest.cc +++ b/ui/events/ozone/evdev/event_device_info_unittest.cc
@@ -22,6 +22,7 @@ EXPECT_FALSE(devinfo.HasMouse()); EXPECT_FALSE(devinfo.HasPointingStick()); EXPECT_FALSE(devinfo.HasTouchpad()); + EXPECT_FALSE(devinfo.HasHapticTouchpad()); EXPECT_FALSE(devinfo.HasTouchscreen()); EXPECT_FALSE(devinfo.HasTablet()); EXPECT_TRUE(devinfo.HasGamepad()); @@ -40,6 +41,7 @@ EXPECT_FALSE(devinfo.HasMouse()); EXPECT_FALSE(devinfo.HasPointingStick()); EXPECT_FALSE(devinfo.HasTouchpad()); + EXPECT_FALSE(devinfo.HasHapticTouchpad()); EXPECT_FALSE(devinfo.HasTouchscreen()); EXPECT_FALSE(devinfo.HasTablet()); EXPECT_FALSE(devinfo.HasGamepad()); @@ -56,6 +58,7 @@ EXPECT_FALSE(devinfo.HasMouse()); EXPECT_FALSE(devinfo.HasPointingStick()); EXPECT_FALSE(devinfo.HasTouchpad()); + EXPECT_FALSE(devinfo.HasHapticTouchpad()); EXPECT_FALSE(devinfo.HasTouchscreen()); EXPECT_FALSE(devinfo.HasTablet()); EXPECT_FALSE(devinfo.HasGamepad()); @@ -72,6 +75,7 @@ EXPECT_FALSE(devinfo.HasMouse()); EXPECT_FALSE(devinfo.HasPointingStick()); EXPECT_FALSE(devinfo.HasTouchpad()); + EXPECT_FALSE(devinfo.HasHapticTouchpad()); EXPECT_TRUE(devinfo.HasTouchscreen()); EXPECT_FALSE(devinfo.HasTablet()); EXPECT_FALSE(devinfo.HasGamepad()); @@ -90,6 +94,26 @@ EXPECT_FALSE(devinfo.HasMouse()); EXPECT_FALSE(devinfo.HasPointingStick()); EXPECT_TRUE(devinfo.HasTouchpad()); + EXPECT_FALSE(devinfo.HasHapticTouchpad()); + EXPECT_FALSE(devinfo.HasTouchscreen()); + EXPECT_FALSE(devinfo.HasTablet()); + EXPECT_FALSE(devinfo.HasGamepad()); + EXPECT_FALSE(devinfo.IsStylusButtonDevice()); + EXPECT_FALSE(devinfo.HasStylusSwitch()); + EXPECT_FALSE(devinfo.HasNumberpad()); + + EXPECT_EQ(ui::InputDeviceType::INPUT_DEVICE_INTERNAL, devinfo.device_type()); +} + +TEST(EventDeviceInfoTest, HapticCrosTouchpad) { + EventDeviceInfo devinfo; + EXPECT_TRUE(CapabilitiesToDeviceInfo(kRedrixTouchpad, &devinfo)); + + EXPECT_FALSE(devinfo.HasKeyboard()); + EXPECT_FALSE(devinfo.HasMouse()); + EXPECT_FALSE(devinfo.HasPointingStick()); + EXPECT_TRUE(devinfo.HasTouchpad()); + EXPECT_TRUE(devinfo.HasHapticTouchpad()); EXPECT_FALSE(devinfo.HasTouchscreen()); EXPECT_FALSE(devinfo.HasTablet()); EXPECT_FALSE(devinfo.HasGamepad()); @@ -108,6 +132,7 @@ EXPECT_FALSE(devinfo.HasMouse()); EXPECT_TRUE(devinfo.HasPointingStick()); EXPECT_FALSE(devinfo.HasTouchpad()); + EXPECT_FALSE(devinfo.HasHapticTouchpad()); EXPECT_FALSE(devinfo.HasTouchscreen()); EXPECT_FALSE(devinfo.HasTablet()); EXPECT_FALSE(devinfo.HasGamepad()); @@ -124,6 +149,7 @@ EXPECT_FALSE(devinfo.HasMouse()); EXPECT_FALSE(devinfo.HasPointingStick()); EXPECT_FALSE(devinfo.HasTouchpad()); + EXPECT_FALSE(devinfo.HasHapticTouchpad()); EXPECT_FALSE(devinfo.HasTouchscreen()); EXPECT_FALSE(devinfo.HasTablet()); EXPECT_FALSE(devinfo.HasGamepad()); @@ -142,6 +168,7 @@ EXPECT_FALSE(devinfo.HasMouse()); EXPECT_FALSE(devinfo.HasPointingStick()); EXPECT_FALSE(devinfo.HasTouchpad()); + EXPECT_FALSE(devinfo.HasHapticTouchpad()); EXPECT_FALSE(devinfo.HasTouchscreen()); EXPECT_FALSE(devinfo.HasTablet()); EXPECT_FALSE(devinfo.HasGamepad()); @@ -160,6 +187,7 @@ EXPECT_TRUE(devinfo.HasMouse()); EXPECT_FALSE(devinfo.HasPointingStick()); EXPECT_FALSE(devinfo.HasTouchpad()); + EXPECT_FALSE(devinfo.HasHapticTouchpad()); EXPECT_FALSE(devinfo.HasTouchscreen()); EXPECT_FALSE(devinfo.HasTablet()); EXPECT_FALSE(devinfo.HasGamepad()); @@ -175,6 +203,7 @@ EXPECT_FALSE(devinfo.HasMouse()); EXPECT_FALSE(devinfo.HasPointingStick()); EXPECT_FALSE(devinfo.HasTouchpad()); + EXPECT_FALSE(devinfo.HasHapticTouchpad()); EXPECT_TRUE(devinfo.HasTouchscreen()); EXPECT_FALSE(devinfo.HasTablet()); EXPECT_FALSE(devinfo.HasGamepad()); @@ -192,6 +221,7 @@ EXPECT_FALSE(devinfo.HasMouse()); EXPECT_FALSE(devinfo.HasPointingStick()); EXPECT_FALSE(devinfo.HasTouchpad()); + EXPECT_FALSE(devinfo.HasHapticTouchpad()); EXPECT_FALSE(devinfo.HasTouchscreen()); EXPECT_TRUE(devinfo.HasTablet()); EXPECT_FALSE(devinfo.HasGamepad()); @@ -209,6 +239,7 @@ EXPECT_FALSE(devinfo.HasMouse()); EXPECT_FALSE(devinfo.HasPointingStick()); EXPECT_TRUE(devinfo.HasTouchpad()); + EXPECT_FALSE(devinfo.HasHapticTouchpad()); EXPECT_FALSE(devinfo.HasTouchscreen()); EXPECT_FALSE(devinfo.HasTablet()); EXPECT_FALSE(devinfo.HasGamepad()); @@ -225,6 +256,7 @@ EXPECT_TRUE(devinfo.HasMouse()); EXPECT_FALSE(devinfo.HasPointingStick()); EXPECT_FALSE(devinfo.HasTouchpad()); + EXPECT_FALSE(devinfo.HasHapticTouchpad()); EXPECT_FALSE(devinfo.HasTouchscreen()); EXPECT_FALSE(devinfo.HasTablet()); EXPECT_FALSE(devinfo.HasGamepad()); @@ -241,6 +273,7 @@ EXPECT_FALSE(devinfo.HasMouse()); EXPECT_FALSE(devinfo.HasPointingStick()); EXPECT_FALSE(devinfo.HasTouchpad()); + EXPECT_FALSE(devinfo.HasHapticTouchpad()); EXPECT_TRUE(devinfo.HasTouchscreen()); EXPECT_FALSE(devinfo.HasTablet()); EXPECT_FALSE(devinfo.HasGamepad()); @@ -258,6 +291,7 @@ EXPECT_FALSE(devinfo.HasMouse()); EXPECT_FALSE(devinfo.HasPointingStick()); EXPECT_FALSE(devinfo.HasTouchpad()); + EXPECT_FALSE(devinfo.HasHapticTouchpad()); EXPECT_TRUE(devinfo.HasTouchscreen()); EXPECT_FALSE(devinfo.HasTablet()); EXPECT_FALSE(devinfo.HasGamepad()); @@ -275,6 +309,7 @@ EXPECT_FALSE(devinfo.HasMouse()); EXPECT_FALSE(devinfo.HasPointingStick()); EXPECT_FALSE(devinfo.HasTouchpad()); + EXPECT_FALSE(devinfo.HasHapticTouchpad()); EXPECT_FALSE(devinfo.HasTouchscreen()); EXPECT_FALSE(devinfo.HasTablet()); EXPECT_FALSE(devinfo.HasGamepad()); @@ -293,6 +328,7 @@ EXPECT_FALSE(devinfo.HasMouse()); EXPECT_FALSE(devinfo.HasPointingStick()); EXPECT_TRUE(devinfo.HasTouchpad()); + EXPECT_FALSE(devinfo.HasHapticTouchpad()); EXPECT_FALSE(devinfo.HasTouchscreen()); EXPECT_FALSE(devinfo.HasTablet()); EXPECT_FALSE(devinfo.HasGamepad()); @@ -311,6 +347,7 @@ EXPECT_FALSE(devinfo.HasMouse()); EXPECT_FALSE(devinfo.HasPointingStick()); EXPECT_FALSE(devinfo.HasTouchpad()); + EXPECT_FALSE(devinfo.HasHapticTouchpad()); EXPECT_FALSE(devinfo.HasTouchscreen()); EXPECT_FALSE(devinfo.HasTablet()); EXPECT_FALSE(devinfo.HasGamepad()); @@ -329,6 +366,7 @@ EXPECT_FALSE(devinfo.HasMouse()); EXPECT_FALSE(devinfo.HasPointingStick()); EXPECT_FALSE(devinfo.HasTouchpad()); + EXPECT_FALSE(devinfo.HasHapticTouchpad()); EXPECT_TRUE(devinfo.HasTouchscreen()); EXPECT_FALSE(devinfo.HasTablet()); EXPECT_FALSE(devinfo.HasGamepad()); @@ -354,6 +392,7 @@ EXPECT_FALSE(devinfo.HasMouse()); EXPECT_FALSE(devinfo.HasPointingStick()); EXPECT_FALSE(devinfo.HasTouchpad()); + EXPECT_FALSE(devinfo.HasHapticTouchpad()); EXPECT_FALSE(devinfo.HasTouchscreen()); EXPECT_FALSE(devinfo.HasTablet()); EXPECT_TRUE(devinfo.HasGamepad()); @@ -372,6 +411,7 @@ EXPECT_FALSE(devinfo.HasMouse()); EXPECT_FALSE(devinfo.HasPointingStick()); EXPECT_FALSE(devinfo.HasTouchpad()); + EXPECT_FALSE(devinfo.HasHapticTouchpad()); EXPECT_FALSE(devinfo.HasTouchscreen()); EXPECT_FALSE(devinfo.HasTablet()); EXPECT_FALSE(devinfo.HasGamepad()); @@ -390,6 +430,7 @@ EXPECT_FALSE(devinfo.HasMouse()); EXPECT_FALSE(devinfo.HasPointingStick()); EXPECT_FALSE(devinfo.HasTouchpad()); + EXPECT_FALSE(devinfo.HasHapticTouchpad()); EXPECT_FALSE(devinfo.HasTouchscreen()); EXPECT_FALSE(devinfo.HasTablet()); EXPECT_FALSE(devinfo.HasGamepad()); @@ -408,6 +449,7 @@ EXPECT_FALSE(devinfo.HasMouse()); EXPECT_FALSE(devinfo.HasPointingStick()); EXPECT_FALSE(devinfo.HasTouchpad()); + EXPECT_FALSE(devinfo.HasHapticTouchpad()); EXPECT_FALSE(devinfo.HasTouchscreen()); EXPECT_FALSE(devinfo.HasTablet()); EXPECT_FALSE(devinfo.HasGamepad()); @@ -426,6 +468,7 @@ EXPECT_FALSE(devinfo.HasMouse()); EXPECT_FALSE(devinfo.HasPointingStick()); EXPECT_TRUE(devinfo.HasTouchpad()); + EXPECT_FALSE(devinfo.HasHapticTouchpad()); EXPECT_FALSE(devinfo.HasTouchscreen()); EXPECT_FALSE(devinfo.HasTablet()); EXPECT_FALSE(devinfo.HasGamepad()); @@ -445,6 +488,7 @@ EXPECT_FALSE(devinfo.HasMouse()); EXPECT_FALSE(devinfo.HasPointingStick()); EXPECT_TRUE(devinfo.HasTouchpad()); + EXPECT_FALSE(devinfo.HasHapticTouchpad()); EXPECT_FALSE(devinfo.HasTouchscreen()); EXPECT_FALSE(devinfo.HasTablet()); EXPECT_FALSE(devinfo.HasGamepad());
diff --git a/ui/events/ozone/evdev/event_device_test_util.cc b/ui/events/ozone/evdev/event_device_test_util.cc index e117bf0c..bac784b8 100644 --- a/ui/events/ozone/evdev/event_device_test_util.cc +++ b/ui/events/ozone/evdev/event_device_test_util.cc
@@ -1398,6 +1398,46 @@ /* kbd_top_row_layout */ "", }; +// Captured from Redrix. Haptic touchpad. +const DeviceAbsoluteAxis kRedrixTouchpadAxes[] = { + {ABS_X, {0, 0, 3630, 0, 0, 32}}, + {ABS_Y, {0, 0, 2346, 0, 0, 31}}, + {ABS_PRESSURE, {0, 0, 4095, 0, 0, 4}}, + {ABS_MISC, {0, 1, 15, 0, 0, 0}}, + {ABS_MT_SLOT, {0, 0, 4, 0, 0, 0}}, + {ABS_MT_TOUCH_MAJOR, {0, 0, 4095, 0, 0, 0}}, + {ABS_MT_TOUCH_MINOR, {0, 0, 4095, 0, 0, 0}}, + {ABS_MT_ORIENTATION, {0, 0, 1, 0, 0, 0}}, + {ABS_MT_POSITION_X, {0, 0, 3630, 0, 0, 32}}, + {ABS_MT_POSITION_Y, {0, 0, 2346, 0, 0, 31}}, + {ABS_MT_TOOL_TYPE, {0, 0, 2, 0, 0, 0}}, + {ABS_MT_TRACKING_ID, {0, 0, 65535, 0, 0, 0}}, + {ABS_MT_PRESSURE, {0, 0, 4095, 0, 0, 4}}, +}; +const DeviceCapabilities kRedrixTouchpad = { + /* path */ + "/sys/devices/pci0000:00/0000:00:19.1/i2c_designware.5/i2c-18/" + "i2c-ELAN2703:00/0018:04F3:323B.0001/input/input7/event6", + /* name */ "ELAN2703:00 04F3:323B Touchpad", + /* phys */ "i2c-ELAN2703:00", + /* uniq */ "", + /* bustype */ "0018", + /* vendor */ "04f3", + /* product */ "323b", + /* version */ "0100", + /* prop */ "85", + /* ev */ "20001b", + /* key */ "e520 10000 0 0 0 0", + /* rel */ "0", + /* abs */ "6f3810001000003", + /* msc */ "20", + /* sw */ "0", + /* led */ "0", + /* ff */ "8000 0", + kRedrixTouchpadAxes, + base::size(kRedrixTouchpadAxes), +}; + // NB: Please use the capture_device_capabilities.py script to add more // test data here. This will help ensure the data matches what the kernel // reports for a real device and is entered correctly.
diff --git a/ui/events/ozone/evdev/event_device_test_util.h b/ui/events/ozone/evdev/event_device_test_util.h index aa0a255..05cd4104 100644 --- a/ui/events/ozone/evdev/event_device_test_util.h +++ b/ui/events/ozone/evdev/event_device_test_util.h
@@ -77,6 +77,7 @@ extern const DeviceCapabilities kLinkTouchscreen; extern const DeviceCapabilities kLinkWithToolTypeTouchscreen; extern const DeviceCapabilities kLinkTouchpad; +extern const DeviceCapabilities kRedrixTouchpad; extern const DeviceCapabilities kMorphiusPointingStick; extern const DeviceCapabilities kHpUsbKeyboard; extern const DeviceCapabilities kHpUsbKeyboard_Extra;
diff --git a/ui/events/ozone/evdev/input_device_factory_evdev.cc b/ui/events/ozone/evdev/input_device_factory_evdev.cc index db5f1d37c..cfdd898 100644 --- a/ui/events/ozone/evdev/input_device_factory_evdev.cc +++ b/ui/events/ozone/evdev/input_device_factory_evdev.cc
@@ -356,6 +356,9 @@ void InputDeviceFactoryEvdev::ApplyInputDeviceSettings() { TRACE_EVENT0("evdev", "ApplyInputDeviceSettings"); + SetIntPropertyForOneType( + DT_TOUCHPAD, "Haptic Button Sensitivity", + input_device_settings_.touchpad_haptic_click_sensitivity); SetIntPropertyForOneType(DT_TOUCHPAD, "Pointer Sensitivity", input_device_settings_.touchpad_sensitivity); SetIntPropertyForOneType(DT_TOUCHPAD, "Scroll Sensitivity",
diff --git a/ui/events/ozone/evdev/libgestures_glue/event_reader_libevdev_cros.cc b/ui/events/ozone/evdev/libgestures_glue/event_reader_libevdev_cros.cc index 748c914..e14201d9 100644 --- a/ui/events/ozone/evdev/libgestures_glue/event_reader_libevdev_cros.cc +++ b/ui/events/ozone/evdev/libgestures_glue/event_reader_libevdev_cros.cc
@@ -48,6 +48,7 @@ has_touchpad_(devinfo.HasTouchpad()), has_stylus_switch_(devinfo.HasSwEvent(SW_PEN_INSERTED)), has_caps_lock_led_(devinfo.HasLedEvent(LED_CAPSL)), + touch_count_(0), delegate_(std::move(delegate)) { // This class assumes it does not deal with internal keyboards. CHECK(!has_keyboard_ || type() != INPUT_DEVICE_INTERNAL); @@ -65,7 +66,13 @@ Event_Open(&evdev_); + haptic_touchpad_handler_ = HapticTouchpadHandler::Create(fd_, devinfo); delegate_->OnLibEvdevCrosOpen(&evdev_, &evstate_); + if (haptic_touchpad_handler_) { + delegate_->SetupHapticButtonGeneration( + base::BindRepeating(&HapticTouchpadHandler::OnGestureClick, + base::Unretained(haptic_touchpad_handler_.get()))); + } } EventReaderLibevdevCros::~EventReaderLibevdevCros() { @@ -105,6 +112,39 @@ return has_touchpad_; } +bool EventReaderLibevdevCros::HasHapticTouchpad() const { + return haptic_touchpad_handler_ != nullptr; +} + +bool EventReaderLibevdevCros::CanHandleHapticFeedback() { + return haptic_touchpad_handler_ && haptic_feedback_enabled_ && + touch_count_ > 0; +} + +void EventReaderLibevdevCros::PlayHapticTouchpadEffect( + HapticTouchpadEffect effect, + HapticTouchpadEffectStrength strength) { + if (CanHandleHapticFeedback()) + haptic_touchpad_handler_->PlayEffect(effect, strength); +} + +void EventReaderLibevdevCros::SetHapticTouchpadEffectForNextButtonRelease( + HapticTouchpadEffect effect, + HapticTouchpadEffectStrength strength) { + if (CanHandleHapticFeedback()) + haptic_touchpad_handler_->SetEffectForNextButtonRelease(effect, strength); +} + +void EventReaderLibevdevCros::ApplyDeviceSettings( + const InputDeviceSettingsEvdev& settings) { + if (haptic_touchpad_handler_) { + haptic_touchpad_handler_->SetClickStrength( + static_cast<HapticTouchpadEffectStrength>( + settings.touchpad_haptic_click_sensitivity)); + } + haptic_feedback_enabled_ = settings.touchpad_haptic_feedback_enabled; +} + bool EventReaderLibevdevCros::HasCapsLockLed() const { return has_caps_lock_led_; } @@ -125,6 +165,7 @@ if (!reader->IsEnabled()) return; + reader->touch_count_ = Event_Get_Touch_Count(&reader->evdev_); reader->delegate_->OnLibEvdevCrosEvent(&reader->evdev_, evstate, *tv); }
diff --git a/ui/events/ozone/evdev/libgestures_glue/event_reader_libevdev_cros.h b/ui/events/ozone/evdev/libgestures_glue/event_reader_libevdev_cros.h index 101b316..3657d5cc 100644 --- a/ui/events/ozone/evdev/libgestures_glue/event_reader_libevdev_cros.h +++ b/ui/events/ozone/evdev/libgestures_glue/event_reader_libevdev_cros.h
@@ -9,10 +9,13 @@ #include <memory> +#include "base/callback.h" #include "base/files/file_path.h" #include "base/files/scoped_file.h" #include "ui/events/ozone/evdev/event_converter_evdev.h" #include "ui/events/ozone/evdev/event_device_info.h" +#include "ui/events/ozone/evdev/input_device_settings_evdev.h" +#include "ui/events/ozone/evdev/libgestures_glue/haptic_touchpad_handler.h" namespace ui { @@ -39,6 +42,13 @@ // Notifier for stop. This is called with the final event state. virtual void OnLibEvdevCrosStopped(Evdev* evdev, EventStateRec* state) = 0; + + // For haptic touchpads. Start using gesture library to determine when + // physical clicks occur, based on force thresholds. + // The passed callback function should be called whenever the gesture + // library determines that a physical click has occurred. + virtual void SetupHapticButtonGeneration( + const base::RepeatingCallback<void(bool)>& callback) = 0; }; EventReaderLibevdevCros(base::ScopedFD fd, @@ -58,9 +68,16 @@ bool HasMouse() const override; bool HasPointingStick() const override; bool HasTouchpad() const override; + bool HasHapticTouchpad() const override; bool HasCapsLockLed() const override; bool HasStylusSwitch() const override; void OnDisabled() override; + void PlayHapticTouchpadEffect(HapticTouchpadEffect effect, + HapticTouchpadEffectStrength strength) override; + void SetHapticTouchpadEffectForNextButtonRelease( + HapticTouchpadEffect effect, + HapticTouchpadEffectStrength strength) override; + void ApplyDeviceSettings(const InputDeviceSettingsEvdev& settings) override; private: static void OnSynReport(void* data, @@ -68,6 +85,10 @@ struct timeval* tv); static void OnLogMessage(void*, int level, const char*, ...); + // Returns true if this is a haptic touchpad, UI haptics are enabled, and it + // is actively being touched. + bool CanHandleHapticFeedback(); + // Input modalities for this device. bool has_keyboard_; bool has_mouse_; @@ -87,8 +108,17 @@ // Path to input device. base::FilePath path_; + // For touchpads, number of fingers present. + int touch_count_; + + // Is UI haptic feedback enabled? + bool haptic_feedback_enabled_; + // Delegate for event processing. std::unique_ptr<Delegate> delegate_; + + // Haptic effect handling for touchpads + std::unique_ptr<HapticTouchpadHandler> haptic_touchpad_handler_; }; } // namespace ui
diff --git a/ui/events/ozone/evdev/libgestures_glue/gesture_interpreter_libevdev_cros.cc b/ui/events/ozone/evdev/libgestures_glue/gesture_interpreter_libevdev_cros.cc index 3bc71b51..a87af19 100644 --- a/ui/events/ozone/evdev/libgestures_glue/gesture_interpreter_libevdev_cros.cc +++ b/ui/events/ozone/evdev/libgestures_glue/gesture_interpreter_libevdev_cros.cc
@@ -29,6 +29,10 @@ #define REL_WHEEL_HI_RES 0x0b #endif +#ifndef INPUT_PROP_HAPTICPAD +#define INPUT_PROP_HAPTICPAD 0x07 +#endif + namespace ui { namespace { @@ -72,6 +76,8 @@ hwprops.support_semi_mt = Event_Get_Semi_MT(evdev); /* buttonpad means a physical button under the touch surface */ hwprops.is_button_pad = Event_Get_Button_Pad(evdev); + hwprops.is_haptic_pad = + EvdevBitIsSet(evdev->info.prop_bitmask, INPUT_PROP_HAPTICPAD); hwprops.has_wheel = EvdevBitIsSet(evdev->info.rel_bitmask, REL_WHEEL) || EvdevBitIsSet(evdev->info.rel_bitmask, REL_HWHEEL); hwprops.wheel_is_hi_res = @@ -243,6 +249,15 @@ ReleaseMouseButtons(timestamp); } +void GestureInterpreterLibevdevCros::SetupHapticButtonGeneration( + const base::RepeatingCallback<void(bool)>& callback) { + click_callback_ = callback; + + GesturesProp* property = + property_provider_->GetProperty(id_, "Enable Haptic Button Generation"); + property->SetBoolValue(std::vector<bool>(1, true)); +} + void GestureInterpreterLibevdevCros::OnGestureReady(const Gesture* gesture) { switch (gesture->type) { case kGestureTypeMove: @@ -359,6 +374,10 @@ if (!cursor_) return; // No cursor! + if (!buttons->is_tap && click_callback_) { + click_callback_.Run(buttons->down); + } + DispatchChangedMouseButtons(buttons->down, true, gesture->end_time); DispatchChangedMouseButtons(buttons->up, false, gesture->end_time); }
diff --git a/ui/events/ozone/evdev/libgestures_glue/gesture_interpreter_libevdev_cros.h b/ui/events/ozone/evdev/libgestures_glue/gesture_interpreter_libevdev_cros.h index c2a89c7f..67f3f3f 100644 --- a/ui/events/ozone/evdev/libgestures_glue/gesture_interpreter_libevdev_cros.h +++ b/ui/events/ozone/evdev/libgestures_glue/gesture_interpreter_libevdev_cros.h
@@ -59,6 +59,8 @@ EventStateRec* evstate, const timeval& time) override; void OnLibEvdevCrosStopped(Evdev* evdev, EventStateRec* state) override; + void SetupHapticButtonGeneration( + const base::RepeatingCallback<void(bool)>& callback) override; // Handler for gesture events generated from libgestures. void OnGestureReady(const Gesture* gesture); @@ -133,6 +135,9 @@ // The number of pixels to count as one "tick" on a multitouch mouse. static const int kMultitouchMousePixelsPerTick = 50; + + // Callback for physical button clicks. + base::RepeatingCallback<void(bool)> click_callback_; }; } // namespace ui
diff --git a/ui/events/ozone/evdev/libgestures_glue/haptic_touchpad_handler.cc b/ui/events/ozone/evdev/libgestures_glue/haptic_touchpad_handler.cc new file mode 100644 index 0000000..25bcc4c1 --- /dev/null +++ b/ui/events/ozone/evdev/libgestures_glue/haptic_touchpad_handler.cc
@@ -0,0 +1,263 @@ +// 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 "ui/events/ozone/evdev/libgestures_glue/haptic_touchpad_handler.h" + +#include <linux/input.h> +#include <sys/ioctl.h> +#include <unistd.h> + +#include "base/logging.h" +#include "base/posix/eintr_wrapper.h" +#include "ui/events/ozone/evdev/input_device_settings_evdev.h" + +namespace ui { + +namespace { +constexpr int kInvalidEffectId = -1; +#if defined(EVIOCFFTAKECONTROL) +constexpr int kReleaseEffectId = 0; +constexpr int kPressEffectId = 1; + +constexpr uint16_t kGoogleVendorId = 0x18d1; +constexpr uint8_t kHIDWaveformUsagePage = 0x01; +#endif // defined(EVIOCFFTAKECONTROL) + +constexpr struct { + HapticTouchpadEffect effect; + uint16_t usage; + struct { + HapticTouchpadEffectStrength strength; + uint16_t percent; + } strength_to_percent[3]; +} kEffectToHIDUsage[] = { + {HapticTouchpadEffect::kSnap, + 0x2003, + {{HapticTouchpadEffectStrength::kLow, 20}, + {HapticTouchpadEffectStrength::kMedium, 50}, + {HapticTouchpadEffectStrength::kHigh, 80}}}, + {HapticTouchpadEffect::kSnapReverse, + 0x2004, + {{HapticTouchpadEffectStrength::kLow, 20}, + {HapticTouchpadEffectStrength::kMedium, 50}, + {HapticTouchpadEffectStrength::kHigh, 80}}}, + {HapticTouchpadEffect::kKnock, + 0x2005, + {{HapticTouchpadEffectStrength::kLow, 20}, + {HapticTouchpadEffectStrength::kMedium, 50}, + {HapticTouchpadEffectStrength::kHigh, 80}}}, + {HapticTouchpadEffect::kTick, + 0x2006, + {{HapticTouchpadEffectStrength::kLow, 20}, + {HapticTouchpadEffectStrength::kMedium, 50}, + {HapticTouchpadEffectStrength::kHigh, 70}}}, + {HapticTouchpadEffect::kToggleOn, + 0x2007, + {{HapticTouchpadEffectStrength::kLow, 15}, + {HapticTouchpadEffectStrength::kMedium, 30}, + {HapticTouchpadEffectStrength::kHigh, 50}}}, + {HapticTouchpadEffect::kToggleOff, + 0x2008, + {{HapticTouchpadEffectStrength::kLow, 20}, + {HapticTouchpadEffectStrength::kMedium, 50}, + {HapticTouchpadEffectStrength::kHigh, 80}}}, + {HapticTouchpadEffect::kPress, + 0x1006, + {{HapticTouchpadEffectStrength::kLow, 75}, + {HapticTouchpadEffectStrength::kMedium, 90}, + {HapticTouchpadEffectStrength::kHigh, 90}}}, + {HapticTouchpadEffect::kRelease, + 0x1007, + {{HapticTouchpadEffectStrength::kLow, 55}, + {HapticTouchpadEffectStrength::kMedium, 65}, + {HapticTouchpadEffectStrength::kHigh, 65}}}, + {HapticTouchpadEffect::kDeepPress, + 0x2001, + {{HapticTouchpadEffectStrength::kLow, 35}, + {HapticTouchpadEffectStrength::kMedium, 60}, + {HapticTouchpadEffectStrength::kHigh, 80}}}, + {HapticTouchpadEffect::kDeepRelease, + 0x2002, + {{HapticTouchpadEffectStrength::kLow, 20}, + {HapticTouchpadEffectStrength::kMedium, 40}, + {HapticTouchpadEffectStrength::kHigh, 70}}}, +}; + +} // namespace + +// static +std::unique_ptr<HapticTouchpadHandler> HapticTouchpadHandler::Create( + int fd, + const EventDeviceInfo& devinfo) { + if (!devinfo.HasHapticTouchpad()) + return nullptr; + auto handler = std::make_unique<HapticTouchpadHandler>(fd); + handler->Initialize(); + if (!handler->IsValid()) { + return nullptr; + } + return handler; +} + +HapticTouchpadHandler::HapticTouchpadHandler(int fd) + : fd_(fd), + next_click_release_effect_(HapticTouchpadEffect::kRelease), + click_strength_(HapticTouchpadEffectStrength::kMedium), + button_pressed_(false) {} + +void HapticTouchpadHandler::Initialize() { + haptics_enabled_ = SetupFf(); + if (!haptics_enabled_) { + ReleaseControlOfClickEffects(); + DestroyAllFfEffects(); + } +} + +HapticTouchpadHandler::~HapticTouchpadHandler() = default; + +bool HapticTouchpadHandler::IsValid() { + return haptics_enabled_; +} + +void HapticTouchpadHandler::SetEffectForNextButtonRelease( + HapticTouchpadEffect effect, + HapticTouchpadEffectStrength strength) { + if (!button_pressed_) + return; + next_click_release_effect_ = effect; + next_click_release_strength_ = strength; +} + +void HapticTouchpadHandler::SetClickStrength( + HapticTouchpadEffectStrength strength) { + click_strength_ = strength; +} + +void HapticTouchpadHandler::OnGestureClick(bool press) { + button_pressed_ = press; + if (press) { + PlayEffect(HapticTouchpadEffect::kPress, click_strength_); + } else { + HapticTouchpadEffectStrength strength; + if (next_click_release_effect_ == HapticTouchpadEffect::kRelease) { + strength = click_strength_; + } else { + strength = next_click_release_strength_; + } + PlayEffect(next_click_release_effect_, strength); + next_click_release_effect_ = HapticTouchpadEffect::kRelease; + } +} + +void HapticTouchpadHandler::PlayEffect(HapticTouchpadEffect effect, + HapticTouchpadEffectStrength strength) { + PlayFfEffect(ff_effect_id_[effect][strength]); +} + +bool HapticTouchpadHandler::SetupFf() { + if (!TakeControlOfClickEffects()) + return false; + + for (const auto& effect_data : kEffectToHIDUsage) { + for (const auto& strength_pair : effect_data.strength_to_percent) { + int effect_id = UploadFfEffect(effect_data.usage, strength_pair.percent); + if (effect_id == kInvalidEffectId) + return false; + ff_effect_id_[effect_data.effect][strength_pair.strength] = effect_id; + } + } + + return true; +} + +void HapticTouchpadHandler::DestroyAllFfEffects() { + for (const auto& effect_data : kEffectToHIDUsage) { + for (const auto& strength_pair : effect_data.strength_to_percent) { + int effect_id = ff_effect_id_[effect_data.effect][strength_pair.strength]; + DestroyFfEffect(effect_id); + } + } +} + +void HapticTouchpadHandler::DestroyFfEffect(int effect_id) { + if (effect_id == kInvalidEffectId) + return; + + if (HANDLE_EINTR(ioctl(fd_, EVIOCRMFF, effect_id)) < 0) { + PLOG(ERROR) << "Error destroying force feedback effect."; + } +} + +void HapticTouchpadHandler::PlayFfEffect(int effect_id) { + struct input_event event; + memset(&event, 0, sizeof(event)); + event.type = EV_FF; + event.code = effect_id; + event.value = 1; + + ssize_t nbytes = + HANDLE_EINTR(write(fd_, static_cast<const void*>(&event), sizeof(event))); + if (nbytes != sizeof(event)) { + PLOG(ERROR) << "Error playing the force feedback effect."; + } +} + +#if defined(EVIOCFFTAKECONTROL) + +int HapticTouchpadHandler::UploadFfEffect(uint16_t hid_usage, + uint8_t intensity) { + struct ff_effect effect; + memset(&effect, 0, sizeof(effect)); + + effect.id = kInvalidEffectId; + effect.type = FF_HID; + effect.u.hid.hid_usage = hid_usage; + effect.u.hid.vendor_id = kGoogleVendorId; + effect.u.hid.vendor_waveform_page = kHIDWaveformUsagePage; + effect.u.hid.intensity = intensity; + if (HANDLE_EINTR(ioctl(fd_, EVIOCSFF, &effect)) < 0) { + PLOG(ERROR) << "Error uploading force feedback effect."; + return kInvalidEffectId; + } + + return effect.id; +} + +bool HapticTouchpadHandler::TakeControlOfClickEffects() { + if (HANDLE_EINTR(ioctl(fd_, EVIOCFFTAKECONTROL, kPressEffectId)) < 0) { + PLOG(ERROR) << "Error taking control of force feedback press effect."; + return false; + } + if (HANDLE_EINTR(ioctl(fd_, EVIOCFFTAKECONTROL, kReleaseEffectId)) < 0) { + PLOG(ERROR) << "Error taking control of force feedback release effect."; + return false; + } + return true; +} + +void HapticTouchpadHandler::ReleaseControlOfClickEffects() { + if (HANDLE_EINTR(ioctl(fd_, EVIOCFFRELEASECONTROL, kPressEffectId)) < 0) { + PLOG(ERROR) << "Error releasing control of force feedback press effect."; + } + if (HANDLE_EINTR(ioctl(fd_, EVIOCFFRELEASECONTROL, kReleaseEffectId)) < 0) { + PLOG(ERROR) << "Error releasing control of force feedback release effect."; + } +} + +#else // defined(EVIOCFFTAKECONTROL) + +int HapticTouchpadHandler::UploadFfEffect(uint16_t hid_usage, + uint8_t intensity) { + return kInvalidEffectId; +} + +bool HapticTouchpadHandler::TakeControlOfClickEffects() { + return false; +} + +void HapticTouchpadHandler::ReleaseControlOfClickEffects() {} + +#endif // defined(EVIOCFFTAKECONTROL) + +} // namespace ui
diff --git a/ui/events/ozone/evdev/libgestures_glue/haptic_touchpad_handler.h b/ui/events/ozone/evdev/libgestures_glue/haptic_touchpad_handler.h new file mode 100644 index 0000000..9528096 --- /dev/null +++ b/ui/events/ozone/evdev/libgestures_glue/haptic_touchpad_handler.h
@@ -0,0 +1,124 @@ +// 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 UI_EVENTS_OZONE_EVDEV_LIBGESTURES_GLUE_HAPTIC_TOUCHPAD_HANDLER_H_ +#define UI_EVENTS_OZONE_EVDEV_LIBGESTURES_GLUE_HAPTIC_TOUCHPAD_HANDLER_H_ + +#include <map> +#include <memory> + +#include "ui/events/devices/haptic_touchpad_effects.h" +#include "ui/events/ozone/evdev/event_device_info.h" + +namespace ui { + +// Handles communication with haptic touchpads via the evdev force feedback +// interface. +// +// Checks that the device is capable of performing all of the required haptic +// effects, then takes control over haptic effects from the kernel. +// +// Performs haptic effects requested by the UI, and also provides a callback to +// perform the appropriate haptic effects when the gesture library determines +// that a physical button click (press or release) has occurred. +class HapticTouchpadHandler { + public: + explicit HapticTouchpadHandler(int fd); + HapticTouchpadHandler(const HapticTouchpadHandler&) = delete; + HapticTouchpadHandler& operator=(const HapticTouchpadHandler&) = delete; + + virtual ~HapticTouchpadHandler(); + + // Will return a nullptr if the device does not support all the required + // haptic features. + static std::unique_ptr<HapticTouchpadHandler> Create( + int fd, + const EventDeviceInfo& devinfo); + + virtual void Initialize(); + + // Was haptics setup successful? + bool IsValid(); + + // Set the effect to use on the next button release. Will only have an effect + // if the button is currently pressed. + void SetEffectForNextButtonRelease(HapticTouchpadEffect effect_type, + HapticTouchpadEffectStrength strength); + + // Set the strength to use for clicks. + void SetClickStrength(HapticTouchpadEffectStrength strength); + + // Handler for physical clicks as determined by libgestures. + void OnGestureClick(bool press); + + // Play the given effect at the given strength. + void PlayEffect(HapticTouchpadEffect effect, + HapticTouchpadEffectStrength strength); + + private: + // Set up the force feedback interface by taking control of click haptics and + // uploading required effects. Returns true if successful. + bool SetupFf(); + + // Destroy all force feedback effects that have been uploaded to the kernel. + void DestroyAllFfEffects(); + + // Destroy the force feedback effect with the given effect ID. + virtual void DestroyFfEffect(int effect_id); + + // Play the force feedback effect with the given effect ID + virtual void PlayFfEffect(int effect_id); + + // The next three methods (UploadFfEffect, TakeControlOfClickEffects, and + // ReleaseControlOfClickEffects) depend on new changes to the linux userspace + // API. Therefore, if the new ioctl EVIOCFFTAKECONTROL is not defined, their + // definition is simplified. When a HapticTouchpadHandler is initialized + // without the required linux userspace API, haptics setup will fail and the + // device will act as a normal non-haptic touchpad, with click haptics handled + // by the touchpad controller. + + // Upload an effect to the touchpad with the given HID waveform usage and + // intensity percentage. Returns the newly assigned effect ID if successful, + // or -1 if unsuccessful. + virtual int UploadFfEffect(uint16_t hid_usage, uint8_t intensity); + + // Take control of click effects from the kernel. After we take control, the + // kernel will no longer perform haptics to emulate button clicks, but it will + // continue to send button change events. Return true if successful. + virtual bool TakeControlOfClickEffects(); + + // Release control of click effects back to the kernel. + void ReleaseControlOfClickEffects(); + + // File descriptor for device. + const int fd_; + + // Which effect and strength the touchpad should play next time the physical + // button is released. If next_click_release_effect_ is set to kRelease, use + // click_strength_ instead of next_click_release_strength_. + HapticTouchpadEffect next_click_release_effect_; + HapticTouchpadEffectStrength next_click_release_strength_; + + // What strength should be used for physical button press and release haptics. + HapticTouchpadEffectStrength click_strength_; + + // Tells which force feedback effect ID is associated with each + // effect-strength pair. + std::map<HapticTouchpadEffect, std::map<HapticTouchpadEffectStrength, int>> + ff_effect_id_; + + // Is the physical button currently pressed, as determined by the gesture + // library? + bool button_pressed_; + + // Are non-autonomous haptics enabled at all? This will be false if the + // touchpad doesn't support all the required effects. In that case, the + // touchpad acts like a normal touchpad: UI feedback is disabled and click + // sensitivity cannot be customized. + bool haptics_enabled_; +}; + +} // namespace ui + +#endif // UI_EVENTS_OZONE_EVDEV_LIBGESTURES_GLUE_HAPTIC_TOUCHPAD_HANDLER_H_
diff --git a/ui/events/ozone/evdev/libgestures_glue/haptic_touchpad_handler_unittest.cc b/ui/events/ozone/evdev/libgestures_glue/haptic_touchpad_handler_unittest.cc new file mode 100644 index 0000000..62f3fe3 --- /dev/null +++ b/ui/events/ozone/evdev/libgestures_glue/haptic_touchpad_handler_unittest.cc
@@ -0,0 +1,150 @@ +// 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 "ui/events/ozone/evdev/libgestures_glue/haptic_touchpad_handler.h" + +#include "testing/gtest/include/gtest/gtest.h" +#include "ui/events/ozone/evdev/event_device_test_util.h" + +namespace ui { + +class TestHapticTouchpadHandler : public HapticTouchpadHandler { + public: + explicit TestHapticTouchpadHandler(int fd) : HapticTouchpadHandler(fd) {} + + ~TestHapticTouchpadHandler() override = default; + + void PlayFfEffect(int effect_id) override { + played_effect_ids_.push_back(effect_id); + } + + int UploadFfEffect(uint16_t hid_usage, uint8_t intensity) override { + return ++num_effects_uploaded_; + } + + bool TakeControlOfClickEffects() override { return true; } + + void DestroyFfEffect(int effect_id) override {} + + int num_effects_uploaded_ = 0; + std::vector<int> played_effect_ids_; +}; + +class HapticTouchpadHandlerTest : public testing::Test { + public: + HapticTouchpadHandlerTest() = default; + + HapticTouchpadHandlerTest(const HapticTouchpadHandlerTest&) = delete; + HapticTouchpadHandlerTest& operator=(const HapticTouchpadHandlerTest&) = + delete; + + std::unique_ptr<ui::TestHapticTouchpadHandler> CreateHandler( + const ui::DeviceCapabilities& caps) { + ui::EventDeviceInfo devinfo; + CapabilitiesToDeviceInfo(caps, &devinfo); + return std::make_unique<TestHapticTouchpadHandler>(1234); + } +}; + +TEST_F(HapticTouchpadHandlerTest, BasicUiEffects) { + std::unique_ptr<ui::TestHapticTouchpadHandler> handler = + CreateHandler(kRedrixTouchpad); + handler->Initialize(); + + EXPECT_TRUE(handler->IsValid()); + + // Three effects requested from the UI. The first and last are the same, so + // should use the same effect ID. + handler->PlayEffect(HapticTouchpadEffect::kSnap, + HapticTouchpadEffectStrength::kLow); + handler->PlayEffect(HapticTouchpadEffect::kSnap, + HapticTouchpadEffectStrength::kMedium); + handler->PlayEffect(HapticTouchpadEffect::kSnap, + HapticTouchpadEffectStrength::kLow); + + EXPECT_EQ(3UL, handler->played_effect_ids_.size()); + EXPECT_EQ(handler->played_effect_ids_[0], handler->played_effect_ids_[2]); + EXPECT_NE(handler->played_effect_ids_[0], handler->played_effect_ids_[1]); +} + +TEST_F(HapticTouchpadHandlerTest, BasicButtonClickEffects) { + std::unique_ptr<ui::TestHapticTouchpadHandler> handler = + CreateHandler(kRedrixTouchpad); + handler->Initialize(); + + // Two full button clicks. The press effects should be the same as each other, + // but different from the release effects. + handler->OnGestureClick(true); + handler->OnGestureClick(false); + handler->OnGestureClick(true); + handler->OnGestureClick(false); + + EXPECT_EQ(4UL, handler->played_effect_ids_.size()); + EXPECT_EQ(handler->played_effect_ids_[0], handler->played_effect_ids_[2]); + EXPECT_EQ(handler->played_effect_ids_[1], handler->played_effect_ids_[3]); + EXPECT_NE(handler->played_effect_ids_[0], handler->played_effect_ids_[1]); +} + +TEST_F(HapticTouchpadHandlerTest, SetReleaseEffectWhenButtonNotPressed) { + std::unique_ptr<ui::TestHapticTouchpadHandler> handler = + CreateHandler(kRedrixTouchpad); + handler->Initialize(); + + // Set the effect for next button release when the button is _not_ currently + // pressed: No effect, use the default release effect. + handler->OnGestureClick(true); + handler->OnGestureClick(false); + handler->SetEffectForNextButtonRelease(HapticTouchpadEffect::kKnock, + HapticTouchpadEffectStrength::kHigh); + handler->OnGestureClick(true); + handler->OnGestureClick(false); + + EXPECT_EQ(4UL, handler->played_effect_ids_.size()); + EXPECT_EQ(handler->played_effect_ids_[1], handler->played_effect_ids_[3]); +} + +TEST_F(HapticTouchpadHandlerTest, SetReleaseEffectWhenButtonIsPressed) { + std::unique_ptr<ui::TestHapticTouchpadHandler> handler = + CreateHandler(kRedrixTouchpad); + handler->Initialize(); + + // Set the effect for next button release when the button is currently + // pressed: Use new release effect once, then revert to default. + handler->OnGestureClick(true); + handler->OnGestureClick(false); + handler->OnGestureClick(true); + handler->SetEffectForNextButtonRelease(HapticTouchpadEffect::kKnock, + HapticTouchpadEffectStrength::kHigh); + handler->OnGestureClick(false); + handler->OnGestureClick(true); + handler->OnGestureClick(false); + + EXPECT_EQ(6UL, handler->played_effect_ids_.size()); + EXPECT_NE(handler->played_effect_ids_[1], handler->played_effect_ids_[3]); + EXPECT_EQ(handler->played_effect_ids_[1], handler->played_effect_ids_[5]); +} + +TEST_F(HapticTouchpadHandlerTest, SetStrengthForClickEffects) { + std::unique_ptr<ui::TestHapticTouchpadHandler> handler = + CreateHandler(kRedrixTouchpad); + handler->Initialize(); + + // Set the strength for click effects. The effect ID should change for press + // and release. + handler->OnGestureClick(true); + handler->OnGestureClick(false); + handler->SetClickStrength(HapticTouchpadEffectStrength::kHigh); + handler->OnGestureClick(true); + handler->OnGestureClick(false); + handler->OnGestureClick(true); + handler->OnGestureClick(false); + + EXPECT_EQ(6UL, handler->played_effect_ids_.size()); + EXPECT_NE(handler->played_effect_ids_[0], handler->played_effect_ids_[2]); + EXPECT_NE(handler->played_effect_ids_[1], handler->played_effect_ids_[3]); + EXPECT_EQ(handler->played_effect_ids_[2], handler->played_effect_ids_[4]); + EXPECT_EQ(handler->played_effect_ids_[3], handler->played_effect_ids_[5]); +} + +} // namespace ui
diff --git a/ui/webui/resources/cr_components/app_management/BUILD.gn b/ui/webui/resources/cr_components/app_management/BUILD.gn index d66d1e5..c30e643 100644 --- a/ui/webui/resources/cr_components/app_management/BUILD.gn +++ b/ui/webui/resources/cr_components/app_management/BUILD.gn
@@ -19,6 +19,7 @@ "shared_style.ts", "shared_vars.ts", "toggle_row.ts", + "uninstall_button.ts", ] non_web_component_files = [
diff --git a/ui/webui/resources/cr_components/app_management/shared_vars.html b/ui/webui/resources/cr_components/app_management/shared_vars.html index d1825cf..e6d17350 100644 --- a/ui/webui/resources/cr_components/app_management/shared_vars.html +++ b/ui/webui/resources/cr_components/app_management/shared_vars.html
@@ -20,6 +20,7 @@ --help-icon-padding: 6px; --info-text-row-height: 48px; --help-icon-size: 20px; + --app-management-controlled-by-spacing: var(--cr-controlled-by-spacing); } </style> </custom-style>
diff --git a/ui/webui/resources/cr_components/app_management/shared_vars.ts b/ui/webui/resources/cr_components/app_management/shared_vars.ts index e49b1a9..d2a1a49 100644 --- a/ui/webui/resources/cr_components/app_management/shared_vars.ts +++ b/ui/webui/resources/cr_components/app_management/shared_vars.ts
@@ -8,4 +8,4 @@ const $_documentContainer = document.createElement('template'); $_documentContainer.innerHTML = `{__html_template__}`; -document.head.appendChild($_documentContainer.content); \ No newline at end of file +document.head.appendChild($_documentContainer.content);
diff --git a/ui/webui/resources/cr_components/app_management/toggle_row.html b/ui/webui/resources/cr_components/app_management/toggle_row.html index a0e88cf9..8bf549d8 100644 --- a/ui/webui/resources/cr_components/app_management/toggle_row.html +++ b/ui/webui/resources/cr_components/app_management/toggle_row.html
@@ -11,7 +11,7 @@ } #policyIndicator { - padding-inline-end: var(--settings-controlled-by-spacing); + padding-inline-end: var(--app-management-controlled-by-spacing); } </style>
diff --git a/ui/webui/resources/cr_components/app_management/uninstall_button.html b/ui/webui/resources/cr_components/app_management/uninstall_button.html new file mode 100644 index 0000000..07eff61b --- /dev/null +++ b/ui/webui/resources/cr_components/app_management/uninstall_button.html
@@ -0,0 +1,26 @@ +<style include="app-management-shared-css"> + :host { + align-items: center; + display: flex; + flex-direction: row; + } + + #policyIndicator { + padding-inline-end: var(--app-management-controlled-by-spacing); + } +</style> +<template is="dom-if" if="[[showPolicyIndicator_(app)]]"> + <cr-tooltip-icon + id="policyIndicator" + icon-class="cr20:domain" + tooltip-text="[[policyLabel]]" + icon-aria-label="[[policyLabel]]" + tooltip-position="bottom"> + </cr-tooltip-icon> +</template> +<template is="dom-if" if="[[showUninstallButton_(app)]]"> + <cr-button id="uninstallButton" on-click="onClick_" + disabled$="[[getDisableState_(app)]]"> + [[uninstallLabel]] + </cr-button> +</template>
diff --git a/ui/webui/resources/cr_components/app_management/uninstall_button.ts b/ui/webui/resources/cr_components/app_management/uninstall_button.ts new file mode 100644 index 0000000..e03a986 --- /dev/null +++ b/ui/webui/resources/cr_components/app_management/uninstall_button.ts
@@ -0,0 +1,90 @@ +// Copyright 2019 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 './shared_style.js'; +import '//resources/cr_elements/cr_button/cr_button.m.js'; +import '//resources/cr_elements/policy/cr_tooltip_icon.m.js'; + +import {assertNotReached} from '//resources/js/assert.m.js'; +import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; + +import {App} from './app_management.mojom-webui.js'; +import {BrowserProxy} from './browser_proxy.js'; +import {AppManagementUserAction, InstallReason} from './constants.js'; +import {recordAppManagementUserAction} from './util.js'; + +export class AppManamentUninstallButtonElement extends PolymerElement { + static get is() { + return 'app-management-uninstall-button'; + } + + static get template() { + return html`{__html_template__}`; + } + + static get properties() { + return { + app: Object, + uninstallLabel: String, + policyLabel: String, + }; + } + + app: App; + uninstallLabel: string; + policyLabel: string; + + /** + * Returns true if the button should be disabled due to app install type. + */ + getDisableState_(app: App): boolean { + if (!app) { + return true; + } + + switch (app.installReason) { + case InstallReason.kSystem: + case InstallReason.kPolicy: + return true; + case InstallReason.kOem: + case InstallReason.kDefault: + case InstallReason.kSync: + case InstallReason.kUser: + case InstallReason.kUnknown: + return false; + default: + assertNotReached(); + return false; + } + } + + /** + * Returns true if the app was installed by a policy. + */ + private showPolicyIndicator_(app: App): boolean { + if (!app) { + return false; + } + return app.installReason === InstallReason.kPolicy; + } + + /** + * Returns true if the uninstall button should be shown. + */ + private showUninstallButton_(app: App): boolean { + if (!app) { + return false; + } + return app.installReason !== InstallReason.kSystem; + } + + private onClick_() { + BrowserProxy.getInstance().handler.uninstall(this.app.id); + recordAppManagementUserAction( + this.app.type, AppManagementUserAction.UninstallDialogLaunched); + } +} + +customElements.define( + AppManamentUninstallButtonElement.is, AppManamentUninstallButtonElement);