diff --git a/DEPS b/DEPS index 76526eb..bac4680 100644 --- a/DEPS +++ b/DEPS
@@ -310,23 +310,23 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling Skia # and whatever else without interference from each other. - 'skia_revision': '4e51918bba1fe22900ab054934c7fe22ed648cda', + 'skia_revision': 'de61ea34de5d530f38e0f34b1460617b20e6aa04', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling V8 # and whatever else without interference from each other. - 'v8_revision': '600fab3b6cffe654175bb0ec9ab8c75fa7778c9d', + 'v8_revision': '49282d1f592cb736c7162f4287b909f7cc2b1ccc', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling ANGLE # and whatever else without interference from each other. - 'angle_revision': 'd78f7d20627effb75a5e1f10608b77502e70beef', + 'angle_revision': '76a3f05092077c71267cf72071556b363217f3f7', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling SwiftShader # and whatever else without interference from each other. - 'swiftshader_revision': '495c41ce34af6b97096f8873fbfc22a38c00d715', + 'swiftshader_revision': 'bd8f8a8fc544ec74858ebe4dc0f38c7e3442fc4c', # 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': 'd9ccef4697904e362c83c6263cecaf1f1a5ae43b', + 'pdfium_revision': '2ed2550ad7464e645ec44fcd556f0616b1d9707e', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling BoringSSL # and whatever else without interference from each other. @@ -389,7 +389,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': '822c80abac6ccbb3a30e1a6c3b97aaa1be2e64e3', + 'devtools_frontend_revision': '399ac4e06a4c4321b0034ec4de959c8a089e4b80', # 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. @@ -425,7 +425,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': '9087a5c28dfdb8f86f588fd6b0aeaa1fd11355a4', + 'dawn_revision': '1a27c55aa520497270371c99fa45c173226b580e', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. @@ -807,7 +807,7 @@ Var('chromium_git') + '/external/github.com/toji/webvr.info.git' + '@' + 'c58ae99b9ff9e2aa4c524633519570bf33536248', 'src/docs/website': { - 'url': Var('chromium_git') + '/website.git' + '@' + '89cfcc7f0ae00163a3a935e420cb7146c0764a35', + 'url': Var('chromium_git') + '/website.git' + '@' + '4b7c5e1cc2b74de503ace0529c32eab23f145e80', }, 'src/ios/third_party/earl_grey2/src': { @@ -986,7 +986,7 @@ 'packages': [ { 'package': 'chromium/third_party/androidx', - 'version': '57GvG50OUQda15ok8arvlweTpZAfD2QHyBuSpD1-LY0C', + 'version': 'b_Q5YZffVu01kaZODWwf-JnDH9QK1dox5RHMfSJ8LDQC', }, ], 'condition': 'checkout_android', @@ -1235,7 +1235,7 @@ Var('chromium_git') + '/devtools/devtools-frontend' + '@' + Var('devtools_frontend_revision'), 'src/third_party/devtools-frontend-internal': { - 'url': 'https://chrome-internal.googlesource.com/devtools/devtools-internal.git' + '@' + 'a8a47f90d9997abf4736c0528001f84cd2f6e158', + 'url': 'https://chrome-internal.googlesource.com/devtools/devtools-internal.git' + '@' + 'fccdaad38dad9c1c62b4bef078db0789964da35c', 'condition': 'checkout_src_internal', }, @@ -1623,7 +1623,7 @@ }, 'src/third_party/perfetto': - Var('android_git') + '/platform/external/perfetto.git' + '@' + 'b2829a1f2f115581d5ab091770e7c1878c243b82', + Var('android_git') + '/platform/external/perfetto.git' + '@' + '768b3f226580167fd3ca2d07774033648ebacd2e', 'src/third_party/perl': { 'url': Var('chromium_git') + '/chromium/deps/perl.git' + '@' + '6f3e5028eb65d0b4c5fdd792106ac4c84eee1eb3', @@ -1805,10 +1805,10 @@ Var('chromium_git') + '/external/khronosgroup/webgl.git' + '@' + 'd1b65aa5a88f6efd900604dfcda840154e9f16e2', 'src/third_party/webgpu-cts/src': - Var('chromium_git') + '/external/github.com/gpuweb/cts.git' + '@' + '09db8676589efc7003d5a2f219b3de8e7f85a652', + Var('chromium_git') + '/external/github.com/gpuweb/cts.git' + '@' + '2a4dfd9f513e52866dcd726fb929bd66678a43d4', 'src/third_party/webrtc': - Var('webrtc_git') + '/src.git' + '@' + 'f68a06c34b79c01137d4f1178627e6af853bbd5f', + Var('webrtc_git') + '/src.git' + '@' + '29a0e2716c8cc964c6bf3540a74b6afdaba97178', 'src/third_party/libgifcodec': Var('skia_git') + '/libgifcodec' + '@'+ Var('libgifcodec_revision'), @@ -1881,7 +1881,7 @@ Var('chromium_git') + '/v8/v8.git' + '@' + Var('v8_revision'), 'src-internal': { - 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@0d0825928fc9025796f965aeb87efffa23c02b9a', + 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@07ea10bb8048c968a31c53ba5005ec90716a2718', 'condition': 'checkout_src_internal', },
diff --git a/WATCHLISTS b/WATCHLISTS index a81b3a9..e6a2d8c6 100644 --- a/WATCHLISTS +++ b/WATCHLISTS
@@ -1657,9 +1657,6 @@ 'prefetch_proxy': { 'filepath': 'chrome/browser/preloading/prefetch/prefetch_proxy', }, - 'prepopulated_engines': { - 'filepath': 'components/search_engines/prepopulated_engines.json', - }, 'prerender': { 'filepath': 'chrome/browser/chrome_content_browser_client_binder_policies' \ '|chrome/browser/preloading/prerender/' \ @@ -2844,7 +2841,6 @@ 'precache': ['wifiprefetch-reviews@google.com'], 'prefetch_proxy': ['marcinjb+p4watch@google.com', 'spelchat+chromereviews@google.com'], - 'prepopulated_engines': ['vasilii+watch@chromium.org'], 'prerender': ['gavinp+prer@chromium.org', 'prerendering-reviews@chromium.org', 'tburkard+watch@chromium.org'],
diff --git a/ash/BUILD.gn b/ash/BUILD.gn index a5d4912..b0b0950 100644 --- a/ash/BUILD.gn +++ b/ash/BUILD.gn
@@ -374,6 +374,13 @@ "controls/rounded_scroll_bar.h", "controls/scroll_view_gradient_helper.cc", "controls/scroll_view_gradient_helper.h", + "curtain/security_curtain_controller.h", + "curtain/security_curtain_controller_impl.cc", + "curtain/security_curtain_controller_impl.h", + "curtain/security_curtain_widget_controller.cc", + "curtain/security_curtain_widget_controller.h", + "curtain/session.cc", + "curtain/session.h", "dbus/ash_dbus_services.cc", "dbus/ash_dbus_services.h", "dbus/display_service_provider.cc", @@ -2637,6 +2644,7 @@ "controls/contextual_tooltip_unittest.cc", "controls/rounded_scroll_bar_unittest.cc", "controls/scroll_view_gradient_helper_unittest.cc", + "curtain/security_curtain_controller_impl_unittest.cc", "dbus/gesture_properties_service_provider_unittest.cc", "dbus/url_handler_service_provider_unittest.cc", "detachable_base/detachable_base_handler_unittest.cc",
diff --git a/ash/ash_strings.grd b/ash/ash_strings.grd index a0fabd2..3cd7dd1a 100644 --- a/ash/ash_strings.grd +++ b/ash/ash_strings.grd
@@ -1333,7 +1333,7 @@ Open Files </message> <message name="IDS_ASH_HOLDING_SPACE_SUGGESTIONS_TITLE" desc="Title of the suggestions area in the holding space bubble."> - Suggested for you + Suggested files </message> <message name="IDS_ASH_HOLDING_SPACE_DOWNLOADS_TITLE" desc="Title of the downloads area in the holding space bubble."> Downloads @@ -3954,6 +3954,17 @@ App settings </message> + <!-- Strings for camera privacy hub switch notification --> + <message name="IDS_PRIVACY_HUB_CAMERA_OFF_NOTIFICATION_TITLE" desc="Title for a notification shown to the users when an app tries to use the camera while the camera is disabled."> + Camera access is off on this device + </message> + <message name="IDS_PRIVACY_HUB_CAMERA_OFF_NOTIFICATION_MESSAGE" desc="Message for a notification shown to the users when an app tries to use the camera while the camera is off."> + Turn on camera access to allow apps and webpages with the camera permission to use the camera(s) connected to this device. + </message> + <message name="IDS_PRIVACY_HUB_CAMERA_OFF_NOTIFICATION_ACTION_BUTTON" desc="Label for an action button in a notification shown to the users when an app tries to use the camera while the camera is off. The button, when tapped enables the camera."> + Turn on camera access. + </message> + <!-- Strings for microphone mute switch notification --> <message name="IDS_MICROPHONE_MUTED_NOTIFICATION_TITLE" desc="Title for a notification shown to the users when an app tries to use the microphone while the microphone is muted.i Similar to IDS_MICROPHONE_MUTED_NOTIFICATION_TITLE_WITH_APP_NAME, except this message contains a generic app name string. Used when the name of the app that's using the microphone cannot be determined."> An app wants to use the microphone
diff --git a/ash/ash_strings_grd/IDS_ASH_HOLDING_SPACE_SUGGESTIONS_TITLE.png.sha1 b/ash/ash_strings_grd/IDS_ASH_HOLDING_SPACE_SUGGESTIONS_TITLE.png.sha1 index d95cf8b..b975c8f 100644 --- a/ash/ash_strings_grd/IDS_ASH_HOLDING_SPACE_SUGGESTIONS_TITLE.png.sha1 +++ b/ash/ash_strings_grd/IDS_ASH_HOLDING_SPACE_SUGGESTIONS_TITLE.png.sha1
@@ -1 +1 @@ -6e878e019465ccb1a3a7a908c7c6a8020f8289ec \ No newline at end of file +20afbc8b7286d78b362f08e364d456df5732c5f7 \ No newline at end of file
diff --git a/ash/ash_strings_grd/IDS_PRIVACY_HUB_CAMERA_OFF_NOTIFICATION_ACTION_BUTTON.png.sha1 b/ash/ash_strings_grd/IDS_PRIVACY_HUB_CAMERA_OFF_NOTIFICATION_ACTION_BUTTON.png.sha1 new file mode 100644 index 0000000..a28a3d8e --- /dev/null +++ b/ash/ash_strings_grd/IDS_PRIVACY_HUB_CAMERA_OFF_NOTIFICATION_ACTION_BUTTON.png.sha1
@@ -0,0 +1 @@ +fec376b7f80d5acb18aa84cedc2165e2cdf3afe3 \ No newline at end of file
diff --git a/ash/ash_strings_grd/IDS_PRIVACY_HUB_CAMERA_OFF_NOTIFICATION_MEASSAGE.png.sha1 b/ash/ash_strings_grd/IDS_PRIVACY_HUB_CAMERA_OFF_NOTIFICATION_MEASSAGE.png.sha1 new file mode 100644 index 0000000..a28a3d8e --- /dev/null +++ b/ash/ash_strings_grd/IDS_PRIVACY_HUB_CAMERA_OFF_NOTIFICATION_MEASSAGE.png.sha1
@@ -0,0 +1 @@ +fec376b7f80d5acb18aa84cedc2165e2cdf3afe3 \ No newline at end of file
diff --git a/ash/ash_strings_grd/IDS_PRIVACY_HUB_CAMERA_OFF_NOTIFICATION_MESSAGE.png.sha1 b/ash/ash_strings_grd/IDS_PRIVACY_HUB_CAMERA_OFF_NOTIFICATION_MESSAGE.png.sha1 new file mode 100644 index 0000000..a28a3d8e --- /dev/null +++ b/ash/ash_strings_grd/IDS_PRIVACY_HUB_CAMERA_OFF_NOTIFICATION_MESSAGE.png.sha1
@@ -0,0 +1 @@ +fec376b7f80d5acb18aa84cedc2165e2cdf3afe3 \ No newline at end of file
diff --git a/ash/ash_strings_grd/IDS_PRIVACY_HUB_CAMERA_OFF_NOTIFICATION_TITLE.png.sha1 b/ash/ash_strings_grd/IDS_PRIVACY_HUB_CAMERA_OFF_NOTIFICATION_TITLE.png.sha1 new file mode 100644 index 0000000..a28a3d8e --- /dev/null +++ b/ash/ash_strings_grd/IDS_PRIVACY_HUB_CAMERA_OFF_NOTIFICATION_TITLE.png.sha1
@@ -0,0 +1 @@ +fec376b7f80d5acb18aa84cedc2165e2cdf3afe3 \ No newline at end of file
diff --git a/ash/components/arc/arc_features.cc b/ash/components/arc/arc_features.cc index 24d9b54..d35755e 100644 --- a/ash/components/arc/arc_features.cc +++ b/ash/components/arc/arc_features.cc
@@ -112,7 +112,7 @@ // for a currently-active ARCVM game. BASE_FEATURE(kGameModeFeature, "ArcGameModeFeature", - base::FEATURE_DISABLED_BY_DEFAULT); + base::FEATURE_ENABLED_BY_DEFAULT); // Controls whether the guest zram is enabled. This is only for ARCVM. BASE_FEATURE(kGuestZram, "ArcGuestZram", base::FEATURE_DISABLED_BY_DEFAULT);
diff --git a/ash/constants/notifier_catalogs.h b/ash/constants/notifier_catalogs.h index 6e742fa..cd6e676 100644 --- a/ash/constants/notifier_catalogs.h +++ b/ash/constants/notifier_catalogs.h
@@ -166,7 +166,8 @@ kArcLowDiskSpacePreStop = 151, kArcLowDiskSpacePostStop = 152, kMultiCapture = 153, - kMaxValue = kMultiCapture + kPrivacyHubCamera = 154, + kMaxValue = kPrivacyHubCamera }; // A living catalog that registers system nudges.
diff --git a/ash/curtain/OWNERS b/ash/curtain/OWNERS new file mode 100644 index 0000000..fd8ff62 --- /dev/null +++ b/ash/curtain/OWNERS
@@ -0,0 +1,2 @@ +jeroendh@chromium.org +bfranz@chromium.org
diff --git a/ash/curtain/security_curtain_controller.h b/ash/curtain/security_curtain_controller.h new file mode 100644 index 0000000..89506f84 --- /dev/null +++ b/ash/curtain/security_curtain_controller.h
@@ -0,0 +1,33 @@ +// Copyright 2022 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef ASH_CURTAIN_SECURITY_CURTAIN_CONTROLLER_H_ +#define ASH_CURTAIN_SECURITY_CURTAIN_CONTROLLER_H_ + +namespace ash::curtain { + +// Controller for enabling/disabling the security curtain. +// The security curtain is an overlay that is displayed over all monitors, +// effectively making it impossible for the local user and/or a passerby to see +// what's happening on the ChromeOS device. +// This can for example be used during a Remote Desktop session where the remote +// user wants to ensure their privacy. +class SecurityCurtainController { + public: + virtual ~SecurityCurtainController() = default; + + // Enable the security curtain. This will show a curtain overlay over all + // displays and block all local user input. + virtual void Enable() = 0; + + // Disable the security curtain. + virtual void Disable() = 0; + + // Returns if the security curtain is currently enabled or not. + virtual bool IsEnabled() const = 0; +}; + +} // namespace ash::curtain + +#endif // ASH_CURTAIN_SECURITY_CURTAIN_CONTROLLER_H_
diff --git a/ash/curtain/security_curtain_controller_impl.cc b/ash/curtain/security_curtain_controller_impl.cc new file mode 100644 index 0000000..b6f7264c --- /dev/null +++ b/ash/curtain/security_curtain_controller_impl.cc
@@ -0,0 +1,30 @@ +// Copyright 2022 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ash/curtain/security_curtain_controller_impl.h" + +#include "ash/curtain/session.h" +#include "ash/shell.h" + +namespace ash::curtain { + +SecurityCurtainControllerImpl::SecurityCurtainControllerImpl(ash::Shell* shell) + : shell_(*shell) {} + +SecurityCurtainControllerImpl::~SecurityCurtainControllerImpl() = default; + +void SecurityCurtainControllerImpl::Enable() { + DCHECK_EQ(session_, nullptr); + session_ = std::make_unique<Session>(&shell_); +} + +void SecurityCurtainControllerImpl::Disable() { + session_ = nullptr; +} + +bool SecurityCurtainControllerImpl::IsEnabled() const { + return session_ != nullptr; +} + +} // namespace ash::curtain
diff --git a/ash/curtain/security_curtain_controller_impl.h b/ash/curtain/security_curtain_controller_impl.h new file mode 100644 index 0000000..2192925e --- /dev/null +++ b/ash/curtain/security_curtain_controller_impl.h
@@ -0,0 +1,45 @@ +// Copyright 2022 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef ASH_CURTAIN_SECURITY_CURTAIN_CONTROLLER_IMPL_H_ +#define ASH_CURTAIN_SECURITY_CURTAIN_CONTROLLER_IMPL_H_ + +#include "ash/curtain/security_curtain_controller.h" + +#include <memory> + +#include "ash/ash_export.h" +#include "ash/curtain/session.h" +#include "base/memory/raw_ref.h" + +namespace ash { +class Shell; +} // namespace ash + +namespace ash::curtain { + +class ASH_EXPORT SecurityCurtainControllerImpl + : public SecurityCurtainController { + public: + explicit SecurityCurtainControllerImpl(ash::Shell* shell); + SecurityCurtainControllerImpl(const SecurityCurtainControllerImpl&) = delete; + SecurityCurtainControllerImpl& operator=( + const SecurityCurtainControllerImpl&) = delete; + ~SecurityCurtainControllerImpl() override; + + // SecurityCurtainController implementation: + void Enable() override; + void Disable() override; + bool IsEnabled() const override; + + private: + // Only present while the security curtain is enabled. + std::unique_ptr<Session> session_; + + raw_ref<Shell> shell_; +}; + +} // namespace ash::curtain + +#endif // ASH_CURTAIN_SECURITY_CURTAIN_CONTROLLER_IMPL_H_
diff --git a/ash/curtain/security_curtain_controller_impl_unittest.cc b/ash/curtain/security_curtain_controller_impl_unittest.cc new file mode 100644 index 0000000..7003d2d6 --- /dev/null +++ b/ash/curtain/security_curtain_controller_impl_unittest.cc
@@ -0,0 +1,332 @@ +// Copyright 2022 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ash/curtain/security_curtain_controller_impl.h" + +#include "ash/curtain/security_curtain_widget_controller.h" +#include "ash/public/cpp/shell_window_ids.h" +#include "ash/root_window_controller.h" +#include "ash/shell.h" +#include "ash/test/ash_test_base.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "ui/display/manager/display_manager.h" +#include "ui/views/widget/widget.h" + +namespace aura { +// This improves the error output for our tests that compare OcclusionState. +std::ostream& operator<<(std::ostream& os, Window::OcclusionState state) { + os << Window::OcclusionStateToString(state); + return os; +} +} // namespace aura + +namespace ash::curtain { +namespace { + +using ::testing::Eq; +using ::testing::Ne; + +using DisplayId = uint64_t; + +// Simple event handler that can track mouse presses. +class TestEventHandler : public ui::EventHandler { + public: + TestEventHandler() = default; + ~TestEventHandler() override = default; + + // ui::EventHandler: + void OnMouseEvent(ui::MouseEvent* event) override { + if (event->type() != ui::ET_MOUSE_PRESSED) + return; + + has_seen_mouse_press_ = true; + event->SetHandled(); + event->StopPropagation(); + } + bool HasSeenMousePress() { return has_seen_mouse_press_; } + + private: + bool has_seen_mouse_press_ = false; +}; + +class SecurityCurtainControllerImplTest : public AshTestBase { + public: + SecurityCurtainControllerImplTest() = default; + SecurityCurtainControllerImplTest(const SecurityCurtainControllerImplTest&) = + delete; + SecurityCurtainControllerImplTest& operator=( + const SecurityCurtainControllerImplTest&) = delete; + ~SecurityCurtainControllerImplTest() override = default; + + void SetUp() override { + AshTestBase::SetUp(); + security_curtain_controller_.emplace(ash::Shell::Get()); + } + + void TearDown() override { + // SecurityCurtainController cannot outlive Ash::Shell(); + security_curtain_controller_.reset(); + AshTestBase::TearDown(); + } + + SecurityCurtainController& security_curtain_controller() { + return security_curtain_controller_.value(); + } + + bool IsCurtainShownOnDisplay(const display::Display& display) { + return IsCurtainShownOnDisplay(display.id()); + } + + bool IsCurtainShownOnDisplay(DisplayId display_id) { + auto* root_window_controller = + Shell::GetRootWindowControllerWithDisplayId(display_id); + if (!root_window_controller) { + return false; + } + + const auto* controller = + root_window_controller->security_curtain_widget_controller(); + + return controller != nullptr; + } + + views::Widget& GetCurtainForDisplay(const display::Display& display) { + auto* controller = Shell::GetRootWindowControllerWithDisplayId(display.id()) + ->security_curtain_widget_controller(); + EXPECT_THAT(controller, testing::NotNull()) + << "Missing curtain widget for display " << display.ToString(); + + return controller->GetWidget(); + } + + display::Displays GetDisplays() { + return display_manager()->active_display_list(); + } + + display::Display GetFirstDisplay() { + DCHECK(!GetDisplays().empty()); + return GetDisplays().front(); + } + + display::Display CreateSingleDisplay() { + UpdateDisplay("1111x111"); + return GetFirstDisplay(); + } + void CreateMultipleDisplays() { UpdateDisplay("1111x111,2222x222,3333x333"); } + + void ResizeDisplay(const display::Display& display, + gfx::Size new_resolution) { + // display::DisplayManagerTestApi offers a `SetDisplayResolution()` method, + // but that does not seem to work (it does not relay the new resolution to + // root window associated with the display). + // So instead of using that method, we simply call `UpdateDisplay`. + CHECK_EQ(GetDisplays().size(), 1u) + << "This method only support single display setups!"; + + UpdateDisplay(new_resolution.ToString()); + + // Sanity check to ensure UpdateDisplay() didn't remote the existing display + CHECK_EQ(GetFirstDisplay().id(), display.id()); + } + + DisplayId RemoveAllButFirstDisplay() { + CHECK_GT(GetDisplays().size(), 1u) + << "This method only works in multi display setups!"; + + // UpdateDisplay() will reuse the existing display ids, so by calling it + // with only a single display, all but the first display will be deleted. + DisplayId last_display_id = GetDisplays().back().id(); + UpdateDisplay("1111x111"); + + CHECK(!display_manager()->IsActiveDisplayId(last_display_id)); + return last_display_id; + } + + void SimulateMouseClickOn(const aura::Window& window) { + auto* event_generator = GetEventGenerator(); + event_generator->MoveMouseTo(window.GetBoundsInScreen().CenterPoint()); + event_generator->ClickLeftButton(); + } + + private: + absl::optional<SecurityCurtainControllerImpl> security_curtain_controller_; +}; + +TEST_F(SecurityCurtainControllerImplTest, + ShouldNotBeEnabledBeforeEnableIsCalled) { + EXPECT_THAT(security_curtain_controller().IsEnabled(), Eq(false)); +} + +TEST_F(SecurityCurtainControllerImplTest, + NoCurtainsShouldBeCreatedBeforeEnableIsCalled) { + CreateMultipleDisplays(); + + for (auto display : GetDisplays()) { + EXPECT_THAT(IsCurtainShownOnDisplay(display), Eq(false)) + << "Curtain should not be shown on display " << display.ToString(); + } +} + +TEST_F(SecurityCurtainControllerImplTest, ShouldBeEnabledWhenCallingEnable) { + security_curtain_controller().Enable(); + + EXPECT_THAT(security_curtain_controller().IsEnabled(), Eq(true)); +} + +TEST_F(SecurityCurtainControllerImplTest, + ShouldNotBeEnabledWhenCallingDisable) { + security_curtain_controller().Enable(); + security_curtain_controller().Disable(); + + EXPECT_THAT(security_curtain_controller().IsEnabled(), Eq(false)); +} + +TEST_F(SecurityCurtainControllerImplTest, + CurtainsShouldBeCreatedWhenCallingEnable) { + CreateMultipleDisplays(); + + security_curtain_controller().Enable(); + + for (auto display : GetDisplays()) { + EXPECT_THAT(IsCurtainShownOnDisplay(display), Eq(true)) + << "Curtain should be shown on display " << display.ToString(); + } +} + +TEST_F(SecurityCurtainControllerImplTest, + CurtainsShouldBeDestroyedWhenCallingDisable) { + CreateMultipleDisplays(); + + security_curtain_controller().Enable(); + security_curtain_controller().Disable(); + + for (auto display : GetDisplays()) { + EXPECT_THAT(IsCurtainShownOnDisplay(display), Eq(false)) + << "Curtain should no longer be shown on display " + << display.ToString(); + } +} + +TEST_F(SecurityCurtainControllerImplTest, CurtainsShouldCoverTheEntireDisplay) { + CreateMultipleDisplays(); + security_curtain_controller().Enable(); + + for (auto display : GetDisplays()) { + const views::Widget& curtain = GetCurtainForDisplay(display); + EXPECT_THAT(curtain.IsVisible(), Eq(true)); + EXPECT_THAT(curtain.GetWindowBoundsInScreen(), Eq(display.bounds())); + } +} + +TEST_F(SecurityCurtainControllerImplTest, + CurtainShouldKeepCoveringTheEntireDisplayAfterResizing) { + display::Display display = CreateSingleDisplay(); + + security_curtain_controller().Enable(); + + const views::Widget& curtain = GetCurtainForDisplay(display); + + for (gfx::Size new_resolution : + {gfx::Size(1000, 500), gfx::Size(2000, 1000)}) { + ResizeDisplay(display, new_resolution); + EXPECT_THAT(curtain.GetWindowBoundsInScreen().size(), Eq(new_resolution)); + } +} + +TEST_F(SecurityCurtainControllerImplTest, + UncurtainedContainerShouldKeepCoveringTheEntireDisplayAfterResizing) { + // This test ensures the uncurtained container also has the correct size. + // That's very important for Chrome Remote Desktop as it streams this + // container, and if it has the wrong size the stream will fail. + display::Display display = CreateSingleDisplay(); + + security_curtain_controller().Enable(); + + const aura::Window* curtained_off_container = Shell::GetContainer( + Shell::GetRootWindowForDisplayId(GetFirstDisplay().id()), + kShellWindowId_ScreenAnimationContainer); + + EXPECT_THAT(curtained_off_container->bounds().size(), + Eq(display.bounds().size())); + + for (gfx::Size new_resolution : + {gfx::Size(1000, 500), gfx::Size(2000, 1000)}) { + ResizeDisplay(display, new_resolution); + EXPECT_THAT(curtained_off_container->bounds().size(), Eq(new_resolution)); + } +} + +TEST_F(SecurityCurtainControllerImplTest, CurtainShouldNotConsumeMouseEvents) { + security_curtain_controller().Enable(); + + auto other_window = CreateTestWindow(gfx::Rect(100, 100)); + TestEventHandler other_window_event_handler; + other_window->SetTargetHandler(&other_window_event_handler); + + SimulateMouseClickOn(*other_window); + + EXPECT_THAT(other_window_event_handler.HasSeenMousePress(), Eq(true)); +} + +TEST_F(SecurityCurtainControllerImplTest, CurtainShouldNotOccludeOtherWindows) { + auto other_window = CreateTestWindow(gfx::Rect(100, 100)); + other_window->TrackOcclusionState(); + ASSERT_THAT(other_window->GetOcclusionState(), + Eq(aura::Window::OcclusionState::VISIBLE)); + + security_curtain_controller().Enable(); + + EXPECT_THAT(other_window->GetOcclusionState(), + Ne(aura::Window::OcclusionState::OCCLUDED)); +} + +TEST_F(SecurityCurtainControllerImplTest, CurtainShouldNotStealFocus) { + auto other_window = CreateTestWindow(gfx::Rect(100, 100)); + other_window->Focus(); + ASSERT_THAT(other_window->HasFocus(), Eq(true)); + + security_curtain_controller().Enable(); + + EXPECT_THAT(other_window->HasFocus(), Eq(true)); +} + +TEST_F(SecurityCurtainControllerImplTest, ShouldAddCurtainToNewDisplays) { + CreateSingleDisplay(); + + security_curtain_controller().Enable(); + + CreateMultipleDisplays(); + for (auto display : GetDisplays()) { + EXPECT_THAT(IsCurtainShownOnDisplay(display), Eq(true)) + << "Curtain should be shown on display " << display.ToString(); + } +} + +TEST_F(SecurityCurtainControllerImplTest, + ShouldRemoveCurtainFromRemovedDisplays) { + CreateMultipleDisplays(); + + security_curtain_controller().Enable(); + DisplayId removed_display_id = RemoveAllButFirstDisplay(); + + EXPECT_THAT(IsCurtainShownOnDisplay(removed_display_id), Eq(false)); +} + +TEST_F(SecurityCurtainControllerImplTest, + ShouldNotAddCurtainToNewDisplaysAfterCallingDisable) { + CreateSingleDisplay(); + + security_curtain_controller().Enable(); + security_curtain_controller().Disable(); + + CreateMultipleDisplays(); + for (auto display : GetDisplays()) { + EXPECT_THAT(IsCurtainShownOnDisplay(display), Eq(false)) + << "No curtain should be shown on display " << display.ToString(); + } +} + +} // namespace +} // namespace ash::curtain
diff --git a/ash/curtain/security_curtain_widget_controller.cc b/ash/curtain/security_curtain_widget_controller.cc new file mode 100644 index 0000000..e8582a4 --- /dev/null +++ b/ash/curtain/security_curtain_widget_controller.cc
@@ -0,0 +1,164 @@ +// Copyright 2022 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ash/curtain/security_curtain_widget_controller.h" + +#include "base/scoped_observation.h" +#include "third_party/skia/include/core/SkColor.h" +#include "ui/aura/window_observer.h" +#include "ui/compositor/layer.h" +#include "ui/compositor/layer_type.h" +#include "ui/views/background.h" +#include "ui/views/layout/fill_layout.h" +#include "ui/views/widget/widget.h" +#include "ui/views/widget/widget_delegate.h" + +namespace ash::curtain { + +namespace { + +std::vector<std::unique_ptr<ui::Layer>> InitWidgetLayers( + ui::Layer& root_layer) { + // In rare cases the compositor might fail to allocate the textures. + // To prevent the widget from being transparent in this case, we add a + // solid color layer. + auto solid_color_layer = std::make_unique<ui::Layer>(ui::LAYER_SOLID_COLOR); + solid_color_layer->SetColor(SK_ColorLTGRAY); + root_layer.Add(solid_color_layer.get()); + + auto textured_layer = std::make_unique<ui::Layer>(ui::LAYER_TEXTURED); + root_layer.Add(textured_layer.get()); + root_layer.StackAtTop(textured_layer.get()); + + std::vector<std::unique_ptr<ui::Layer>> layers; + layers.push_back(std::move(solid_color_layer)); + layers.push_back(std::move(textured_layer)); + return layers; +} + +views::Widget::InitParams GetWidgetInitParams(aura::Window* parent) { + views::Widget::InitParams result; + result.type = views::Widget::InitParams::TYPE_WINDOW_FRAMELESS; + result.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; + result.name = "CurtainOverlayWidget"; + result.opacity = views::Widget::InitParams::WindowOpacity::kOpaque; + result.parent = parent; + // The curtain screen should not consume any events, but instead the windows + // below should continue to receive all mouse/keyboard/... events. + result.accept_events = false; + // No need to set `show_state` as the window bounds are managed by the parent. + return result; +} + +std::unique_ptr<views::View> CreateContentsView() { + // Use a simple solid colored curtain for now. + // TODO(b/243626980): Update once UX has decided on the content of the + // curtain screen. + auto result = std::make_unique<views::View>(); + result->SetLayoutManager(std::make_unique<views::FillLayout>()); + result->SetBackground(views::CreateSolidBackground(SK_ColorYELLOW)); + return result; +} + +std::unique_ptr<views::Widget> CreateWidget(aura::Window* parent) { + auto widget = std::make_unique<views::Widget>(); + widget->Init(GetWidgetInitParams(parent)); + widget->SetVisibilityAnimationTransition(views::Widget::ANIMATE_NONE); + widget->SetContentsView(CreateContentsView()); + return widget; +} + +} // namespace + +//////////////////////////////////////////////////////////////////////////////// +// WidgetMaximizer +//////////////////////////////////////////////////////////////////////////////// + +// Helper class that ensures the curtain widget is always maximized, +// even when the display is resized. +class SecurityCurtainWidgetController::WidgetMaximizer + : public aura::WindowObserver { + public: + explicit WidgetMaximizer(views::Widget* widget) : widget_(*widget) { + // Observe resizes + root_window_observation_.Observe(&root_window()); + + // Set initial layer dimensions + OnRootWindowResized(); + } + WidgetMaximizer(const WidgetMaximizer&) = delete; + WidgetMaximizer& operator=(const WidgetMaximizer&) = delete; + ~WidgetMaximizer() override = default; + + private: + // aura::WindowObserver implementation: + void OnWindowBoundsChanged(aura::Window* root, + const gfx::Rect& old_bounds, + const gfx::Rect& new_bounds, + ui::PropertyChangeReason reason) override { + OnRootWindowResized(); + } + + void OnRootWindowResized() { + gfx::Rect new_bounds(root_window().layer()->bounds().size()); + widget_->SetBounds(new_bounds); + } + + aura::Window& root_window() { + auto* result = widget_->GetNativeWindow()->GetRootWindow(); + DCHECK(result); + return *result; + } + + // We should track when the root window is resized to ensure our widget + // remains full screen. + base::ScopedObservation<aura::Window, aura::WindowObserver> + root_window_observation_{this}; + + raw_ref<views::Widget> widget_; +}; + +//////////////////////////////////////////////////////////////////////////////// +// SecurityCurtainWidgetController +//////////////////////////////////////////////////////////////////////////////// + +SecurityCurtainWidgetController::SecurityCurtainWidgetController( + SecurityCurtainWidgetController&&) = default; +SecurityCurtainWidgetController& SecurityCurtainWidgetController::operator=( + SecurityCurtainWidgetController&&) = default; +SecurityCurtainWidgetController::~SecurityCurtainWidgetController() = default; + +SecurityCurtainWidgetController::SecurityCurtainWidgetController( + std::unique_ptr<views::Widget> widget, + Layers layers) + : widget_layers_(std::move(layers)), + widget_(std::move(widget)), + occlusion_tracker_exclude_( + std::make_unique<aura::WindowOcclusionTracker::ScopedExclude>( + widget_->GetNativeView())), + widget_maximizer_(std::make_unique<WidgetMaximizer>(widget_.get())) { + DCHECK(widget_); + widget_->Show(); +} + +// static +SecurityCurtainWidgetController +SecurityCurtainWidgetController::CreateForRootWindow( + aura::Window* root_window) { + auto widget = CreateWidget(root_window); + auto layers = InitWidgetLayers(*widget->GetLayer()); + return SecurityCurtainWidgetController(std::move(widget), std::move(layers)); +} + +const views::Widget& SecurityCurtainWidgetController::GetWidget() const { + DCHECK(widget_); + return *widget_; +} + +views::Widget& SecurityCurtainWidgetController::GetWidget() { + DCHECK(widget_); + return *widget_; +} + +} // namespace ash::curtain
diff --git a/ash/curtain/security_curtain_widget_controller.h b/ash/curtain/security_curtain_widget_controller.h new file mode 100644 index 0000000..305f18e4 --- /dev/null +++ b/ash/curtain/security_curtain_widget_controller.h
@@ -0,0 +1,65 @@ +// Copyright 2022 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef ASH_CURTAIN_SECURITY_CURTAIN_WIDGET_CONTROLLER_H_ +#define ASH_CURTAIN_SECURITY_CURTAIN_WIDGET_CONTROLLER_H_ + +#include <cstdint> +#include <memory> + +#include "ash/ash_export.h" +#include "ui/aura/window_occlusion_tracker.h" + +namespace aura { +class Window; +} // namespace aura + +namespace views { +class Widget; +} // namespace views + +namespace ui { +class Layer; +} // namespace ui + +namespace ash::curtain { + +// Displays a curtain widget over a single display, which will cover all other +// content, preventing local users and passerby's from observing the display. +// Owns the widget. +class ASH_EXPORT SecurityCurtainWidgetController { + public: + SecurityCurtainWidgetController(SecurityCurtainWidgetController&&); + SecurityCurtainWidgetController& operator=(SecurityCurtainWidgetController&&); + ~SecurityCurtainWidgetController(); + + // Creates a new curtain overlay. + static SecurityCurtainWidgetController CreateForRootWindow( + aura::Window* curtain_container); + + const views::Widget& GetWidget() const; + views::Widget& GetWidget(); + + private: + class WidgetMaximizer; + + using Layers = std::vector<std::unique_ptr<ui::Layer>>; + SecurityCurtainWidgetController(std::unique_ptr<views::Widget> widget, + Layers layers); + + Layers widget_layers_; + std::unique_ptr<views::Widget> widget_; + // The curtain widget should not occlude any other windows, otherwise they + // might not be rendered (which will be a problem when streaming the + // uncurtained desktop for example through Chrome Remote Desktop). + std::unique_ptr<aura::WindowOcclusionTracker::ScopedExclude> + occlusion_tracker_exclude_; + + // Ensures the widget is always maximized, even when the display is resized. + std::unique_ptr<WidgetMaximizer> widget_maximizer_; +}; + +} // namespace ash::curtain + +#endif // ASH_CURTAIN_SECURITY_CURTAIN_WIDGET_CONTROLLER_H_
diff --git a/ash/curtain/session.cc b/ash/curtain/session.cc new file mode 100644 index 0000000..4b056af --- /dev/null +++ b/ash/curtain/session.cc
@@ -0,0 +1,102 @@ +// Copyright 2022 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ash/curtain/session.h" + +#include "ash/curtain/security_curtain_widget_controller.h" +#include "ash/root_window_controller.h" +#include "ash/shell.h" +#include "ash/shell_observer.h" +#include "base/logging.h" +#include "base/scoped_observation.h" + +namespace ash::curtain { + +//////////////////////////////////////////////////////////////////////////////// +// RootWindowsObserver +//////////////////////////////////////////////////////////////////////////////// + +class Session::RootWindowsObserver : public ShellObserver { + public: + RootWindowsObserver(Session* parent, Shell* shell); + RootWindowsObserver(const RootWindowsObserver&) = delete; + RootWindowsObserver& operator=(const RootWindowsObserver&) = delete; + ~RootWindowsObserver() override; + + std::vector<display::Display> GetActiveDisplays(Shell& shell) const; + + private: + // ShellObserver implementation: + void OnRootWindowAdded(aura::Window* root_window) override; + + raw_ptr<Session> parent_; + + base::ScopedObservation<Shell, + ShellObserver, + &Shell::AddShellObserver, + &Shell::RemoveShellObserver> + shell_observation_{this}; +}; + +Session::RootWindowsObserver::RootWindowsObserver(Session* parent, Shell* shell) + : parent_(parent) { + shell_observation_.Observe(shell); +} + +Session::RootWindowsObserver::~RootWindowsObserver() = default; + +void Session::RootWindowsObserver::OnRootWindowAdded( + aura::Window* new_root_window) { + parent_->CurtainOffRootWindow(new_root_window); +} + +//////////////////////////////////////////////////////////////////////////////// +// Session +//////////////////////////////////////////////////////////////////////////////// + +Session::Session(Shell* shell) + : shell_(*shell), + root_windows_observer_( + std::make_unique<RootWindowsObserver>(this, shell)) { + CurtainOffAllRootWindows(); +} + +Session::~Session() { + RemoveCurtainOfAllRootWindows(); +} + +void Session::CurtainOffAllRootWindows() { + for (auto* root_window : shell_->GetAllRootWindows()) { + CurtainOffRootWindow(root_window); + } +} + +void Session::CurtainOffRootWindow(aura::Window* root_window) { + DCHECK(root_window->IsRootWindow()); + VLOG(1) << "Adding security curtain over root window " << root_window; + + auto* controller = RootWindowController::ForWindow(root_window); + DCHECK(controller); + + controller->SetSecurityCurtainWidgetController( + std::make_unique<SecurityCurtainWidgetController>( + SecurityCurtainWidgetController::CreateForRootWindow(root_window))); +} + +void Session::RemoveCurtainOfAllRootWindows() { + for (auto* root_window : shell_->GetAllRootWindows()) { + RemoveCurtainOfRootWindow(root_window); + } +} + +void Session::RemoveCurtainOfRootWindow(const aura::Window* root_window) { + VLOG(1) << "Removing security curtain from root window " << root_window; + + auto* controller = RootWindowController::ForWindow(root_window); + DCHECK(controller); + + controller->ClearSecurityCurtainWidgetController(); +} + +} // namespace ash::curtain
diff --git a/ash/curtain/session.h b/ash/curtain/session.h new file mode 100644 index 0000000..025baa2 --- /dev/null +++ b/ash/curtain/session.h
@@ -0,0 +1,50 @@ +// Copyright 2022 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef ASH_CURTAIN_SESSION_H_ +#define ASH_CURTAIN_SESSION_H_ + +#include <memory> + +#include "base/memory/raw_ref.h" + +namespace ash { +class Shell; +} // namespace ash + +namespace aura { +class Window; +} // namespace aura + +namespace ash::curtain { + +// Helper class, created when the security curtain is enabled and destroyed +// when the curtain is disabled. +// +// Will observe root window changes (adding/removing), and update the security +// curtain overlay accordingly to ensure all displays are constantly fully +// curtained off. +class Session { + public: + explicit Session(Shell* shell); + Session(const Session&) = delete; + Session& operator=(const Session&) = delete; + ~Session(); + + private: + void CurtainOffAllRootWindows(); + void CurtainOffRootWindow(aura::Window* root_window); + void RemoveCurtainOfAllRootWindows(); + void RemoveCurtainOfRootWindow(const aura::Window* root_window); + + // Helper class observing all root windows being added/removed. + class RootWindowsObserver; + + raw_ref<Shell> shell_; + std::unique_ptr<RootWindowsObserver> root_windows_observer_; +}; + +} // namespace ash::curtain + +#endif // ASH_CURTAIN_SESSION_H_
diff --git a/ash/public/cpp/holding_space/holding_space_item.cc b/ash/public/cpp/holding_space/holding_space_item.cc index b7a58408..3f46b7d 100644 --- a/ash/public/cpp/holding_space/holding_space_item.cc +++ b/ash/public/cpp/holding_space/holding_space_item.cc
@@ -159,7 +159,7 @@ const absl::optional<int> version = dict.FindIntPath(kVersionPath); DCHECK(version.has_value() && version.value() == kVersion); - const Type type = static_cast<Type>(dict.FindIntPath(kTypePath).value()); + const Type type = DeserializeType(dict); const base::FilePath file_path = DeserializeFilePath(dict); // NOTE: `std::make_unique` does not work with private constructors. @@ -198,6 +198,17 @@ return file_path.value(); } +// static +// NOTE: This method must remain in sync with `Serialize()`. If multiple +// serialization versions are supported, care must be taken to handle each. +HoldingSpaceItem::Type HoldingSpaceItem::DeserializeType( + const base::DictionaryValue& dict) { + const absl::optional<int> version = dict.FindIntPath(kVersionPath); + DCHECK(version.has_value() && version.value() == kVersion); + + return static_cast<Type>(dict.FindIntPath(kTypePath).value()); +} + // NOTE: This method must remain in sync with `Deserialize()`. The // return value will be written to preferences so this implementation must // maintain backwards compatibility so long as `kVersion` remains unchanged.
diff --git a/ash/public/cpp/holding_space/holding_space_item.h b/ash/public/cpp/holding_space/holding_space_item.h index 1b64c4c..fe42b02c 100644 --- a/ash/public/cpp/holding_space/holding_space_item.h +++ b/ash/public/cpp/holding_space/holding_space_item.h
@@ -136,6 +136,9 @@ // Deserializes `file_path_` from a serialized `HoldingSpaceItem`. static base::FilePath DeserializeFilePath(const base::DictionaryValue& dict); + // Deserializes `type_` from a serialized `HoldingSpaceItem`. + static Type DeserializeType(const base::DictionaryValue& dict); + // Serializes from `HoldingSpaceItem` to `base::DictionaryValue`. base::DictionaryValue Serialize() const;
diff --git a/ash/root_window_controller.cc b/ash/root_window_controller.cc index 1bc1006..466ed41 100644 --- a/ash/root_window_controller.cc +++ b/ash/root_window_controller.cc
@@ -18,6 +18,7 @@ #include "ash/constants/ash_constants.h" #include "ash/constants/ash_features.h" #include "ash/constants/ash_switches.h" +#include "ash/curtain/security_curtain_widget_controller.h" #include "ash/focus_cycler.h" #include "ash/host/ash_window_tree_host.h" #include "ash/keyboard/arc/arc_virtual_keyboard_container_layout_manager.h" @@ -908,6 +909,21 @@ return GetAccessibilityPanelLayoutManager(); } +void RootWindowController::SetSecurityCurtainWidgetController( + std::unique_ptr<curtain::SecurityCurtainWidgetController> controller) { + DCHECK(!security_curtain_widget_controller_); + security_curtain_widget_controller_ = std::move(controller); +} + +void RootWindowController::ClearSecurityCurtainWidgetController() { + security_curtain_widget_controller_ = nullptr; +} + +curtain::SecurityCurtainWidgetController* +RootWindowController::security_curtain_widget_controller() { + return security_curtain_widget_controller_.get(); +} + //////////////////////////////////////////////////////////////////////////////// // RootWindowController, private:
diff --git a/ash/root_window_controller.h b/ash/root_window_controller.h index 445887ef..6ed0e29 100644 --- a/ash/root_window_controller.h +++ b/ash/root_window_controller.h
@@ -28,7 +28,7 @@ namespace ui { class WindowTreeHost; class SimpleMenuModel; -} +} // namespace ui namespace views { class MenuRunner; @@ -60,6 +60,10 @@ class WallpaperWidgetController; class WorkAreaInsets; +namespace curtain { +class SecurityCurtainWidgetController; +} + // This class maintains the per root window state for ash. This class // owns the root window and other dependent objects that should be // deleted upon the deletion of the root window. This object is @@ -242,6 +246,12 @@ // Returns accessibility panel layout manager for this root window. AccessibilityPanelLayoutManager* GetAccessibilityPanelLayoutManagerForTest(); + void SetSecurityCurtainWidgetController( + std::unique_ptr<curtain::SecurityCurtainWidgetController> controller); + void ClearSecurityCurtainWidgetController(); + curtain::SecurityCurtainWidgetController* + security_curtain_widget_controller(); + private: FRIEND_TEST_ALL_PREFIXES(RootWindowControllerTest, ContextMenuDisappearsInTabletMode); @@ -318,6 +328,9 @@ std::unique_ptr<views::Widget> ambient_widget_; + std::unique_ptr<curtain::SecurityCurtainWidgetController> + security_curtain_widget_controller_; + std::unique_ptr<AshColorProviderSource> color_provider_source_; // Whether child windows have been closed during shutdown. Exists to avoid
diff --git a/ash/rotator/screen_rotation_animator.cc b/ash/rotator/screen_rotation_animator.cc index a3d730e3..88deed5 100644 --- a/ash/rotator/screen_rotation_animator.cc +++ b/ash/rotator/screen_rotation_animator.cc
@@ -102,10 +102,13 @@ return (Is180DegreeFlip(initial_rotation, new_rotation) ? 180 : 90); } -void AddLayerAtTopOfWindowLayers(aura::Window* root_window, ui::Layer* layer) { +void AddLayerAboveWindowLayer(aura::Window* root_window, + ui::Layer* container_layer, + ui::Layer* layer) { // Add the cloned/copied layer tree into the root, so it will be rendered. + DCHECK_EQ(container_layer->parent(), root_window->layer()); root_window->layer()->Add(layer); - root_window->layer()->StackAtTop(layer); + root_window->layer()->StackAbove(layer, container_layer); } void AddLayerBelowWindowLayer(aura::Window* root_window, @@ -306,7 +309,9 @@ } old_layer_tree_owner_ = CopyLayerTree(std::move(result)); - AddLayerAtTopOfWindowLayers(root_window_, old_layer_tree_owner_->root()); + AddLayerAboveWindowLayer(root_window_, + GetScreenRotationContainer(root_window_)->layer(), + old_layer_tree_owner_->root()); // TODO(oshima): We need a better way to control animation and other // activities during system wide animation. @@ -357,7 +362,9 @@ void ScreenRotationAnimator::CreateOldLayerTreeForSlowAnimation() { old_layer_tree_owner_ = ::wm::RecreateLayers(root_window_); - AddLayerAtTopOfWindowLayers(root_window_, old_layer_tree_owner_->root()); + AddLayerAboveWindowLayer(root_window_, + GetScreenRotationContainer(root_window_)->layer(), + old_layer_tree_owner_->root()); } std::unique_ptr<ui::LayerTreeOwner> ScreenRotationAnimator::CopyLayerTree(
diff --git a/ash/shell.cc b/ash/shell.cc index 9cefe57..ee6c2831 100644 --- a/ash/shell.cc +++ b/ash/shell.cc
@@ -37,6 +37,7 @@ #include "ash/constants/ash_features.h" #include "ash/constants/ash_switches.h" #include "ash/controls/contextual_tooltip.h" +#include "ash/curtain/security_curtain_controller_impl.h" #include "ash/dbus/ash_dbus_services.h" #include "ash/detachable_base/detachable_base_handler.h" #include "ash/detachable_base/detachable_base_notification_controller.h" @@ -1346,6 +1347,9 @@ color_enhancement_controller_ = std::make_unique<ColorEnhancementController>(); + security_curtain_controller_ = + std::make_unique<curtain::SecurityCurtainControllerImpl>(this); + docked_magnifier_controller_ = std::make_unique<DockedMagnifierController>(); video_detector_ = std::make_unique<VideoDetector>();
diff --git a/ash/shell.h b/ash/shell.h index e6bab81..9f87040 100644 --- a/ash/shell.h +++ b/ash/shell.h
@@ -236,6 +236,10 @@ class Mediator; } // namespace quick_pair +namespace curtain { +class SecurityCurtainController; +} // namespace curtain + // Shell is a singleton object that presents the Shell API and implements the // RootWindow's delegate interface. // @@ -390,6 +394,9 @@ return cros_display_config_.get(); } ::wm::CursorManager* cursor_manager() { return cursor_manager_.get(); } + curtain::SecurityCurtainController& security_curtain_controller() { + return *security_curtain_controller_; + } DarkLightModeControllerImpl* dark_light_mode_controller() { return dark_light_mode_controller_.get(); } @@ -812,6 +819,8 @@ std::unique_ptr<BrightnessControlDelegate> brightness_control_delegate_; std::unique_ptr<CalendarController> calendar_controller_; std::unique_ptr<CrosDisplayConfig> cros_display_config_; + std::unique_ptr<curtain::SecurityCurtainController> + security_curtain_controller_; std::unique_ptr<DarkLightModeControllerImpl> dark_light_mode_controller_; std::unique_ptr<DesksController> desks_controller_; std::unique_ptr<DesksTemplatesDelegate> desks_templates_delegate_;
diff --git a/ash/system/privacy_hub/camera_privacy_switch_controller.cc b/ash/system/privacy_hub/camera_privacy_switch_controller.cc index ba8632e6..90a0789 100644 --- a/ash/system/privacy_hub/camera_privacy_switch_controller.cc +++ b/ash/system/privacy_hub/camera_privacy_switch_controller.cc
@@ -7,17 +7,27 @@ #include <utility> #include "ash/constants/ash_pref_names.h" +#include "ash/public/cpp/notification_utils.h" #include "ash/public/cpp/session/session_observer.h" #include "ash/session/session_controller_impl.h" #include "ash/shell.h" +#include "ash/strings/grit/ash_strings.h" #include "ash/system/privacy_hub/privacy_hub_controller.h" #include "base/bind.h" #include "base/check.h" #include "components/prefs/pref_service.h" +#include "components/vector_icons/vector_icons.h" #include "media/capture/video/chromeos/camera_hal_dispatcher_impl.h" +#include "ui/base/l10n/l10n_util.h" +#include "ui/message_center/message_center.h" namespace ash { +// The ID for a notification shown when the user tries to use a camera while the +// camera is disabled in Privacy Hub. +constexpr char kPrivacyHubCameraOffNotificationId[] = + "ash.media.privacy_hub.activity_with_disabled_camera"; + namespace { // Wraps and adapts the VCD API. @@ -115,4 +125,46 @@ return camera_privacy_switch_state_; } +void CameraPrivacySwitchController::ShowNotification( + const std::u16string& app_name) { + message_center::RichNotificationData notification_data; + notification_data.pinned = true; + notification_data.buttons.emplace_back(l10n_util::GetStringUTF16( + IDS_PRIVACY_HUB_CAMERA_OFF_NOTIFICATION_ACTION_BUTTON)); + + scoped_refptr<message_center::NotificationDelegate> delegate = + base::MakeRefCounted<message_center::HandleNotificationClickDelegate>( + base::BindRepeating([](absl::optional<int> button_index) { + if (button_index) { + PrefService* const pref_service = + Shell::Get()->session_controller()->GetActivePrefService(); + if (pref_service) { + pref_service->SetBoolean(prefs::kUserCameraAllowed, true); + } + } else { + // Click on the notification body is no-op. + } + })); + + message_center::MessageCenter::Get()->RemoveNotification( + kPrivacyHubCameraOffNotificationId, /*by_user=*/false); + message_center::MessageCenter::Get()->AddNotification( + ash::CreateSystemNotification( + message_center::NOTIFICATION_TYPE_SIMPLE, + kPrivacyHubCameraOffNotificationId, + l10n_util::GetStringUTF16( + IDS_PRIVACY_HUB_CAMERA_OFF_NOTIFICATION_TITLE), + l10n_util::GetStringUTF16( + IDS_PRIVACY_HUB_CAMERA_OFF_NOTIFICATION_MESSAGE), + /*display_source=*/std::u16string(), + /*origin_url=*/GURL(), + message_center::NotifierId( + message_center::NotifierType::SYSTEM_COMPONENT, + kPrivacyHubCameraOffNotificationId, + ash::NotificationCatalogName::kPrivacyHubCamera), + notification_data, std::move(delegate), + vector_icons::kVideocamOffIcon, + message_center::SystemNotificationWarningLevel::NORMAL)); +} + } // namespace ash
diff --git a/ash/system/privacy_hub/camera_privacy_switch_controller.h b/ash/system/privacy_hub/camera_privacy_switch_controller.h index 0ac414e..ad072d65 100644 --- a/ash/system/privacy_hub/camera_privacy_switch_controller.h +++ b/ash/system/privacy_hub/camera_privacy_switch_controller.h
@@ -57,10 +57,13 @@ // Returns the last observed HW switch state for the camera. cros::mojom::CameraPrivacySwitchState HWSwitchState() const; - // Sets Privacy switch API for testing + // Sets Privacy switch API for testing. void SetCameraPrivacySwitchAPIForTest( std::unique_ptr<CameraPrivacySwitchAPI> switch_api); + // Displays the camera off notification. + void ShowNotification(const std::u16string& app_name); + private: // Retrieves the current value of the user pref. CameraSWPrivacySwitchSetting GetUserSwitchPreference();
diff --git a/ash/webui/common/resources/network_health/network_health_summary.js b/ash/webui/common/resources/network_health/network_health_summary.js index 1053bad6..73cf9233 100644 --- a/ash/webui/common/resources/network_health/network_health_summary.js +++ b/ash/webui/common/resources/network_health/network_health_summary.js
@@ -3,16 +3,15 @@ // found in the LICENSE file. import 'chrome://resources/cr_elements/cr_shared_style.css.js'; -import '../network/network_shared_css.js'; +import 'chrome://resources/cr_components/chromeos/network/network_shared_css.js'; import {Polymer} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js'; +import {OncMojo} from 'chrome://resources/cr_components/chromeos/network/onc_mojo.js'; import {I18nBehavior} from 'chrome://resources/cr_elements/i18n_behavior.js'; import {assertNotReached} from 'chrome://resources/js/assert.m.js'; import {NetworkType, PortalState} from 'chrome://resources/mojo/chromeos/services/network_config/public/mojom/network_types.mojom-webui.js'; import {Network, NetworkHealthService, NetworkHealthServiceRemote, NetworkHealthState, NetworkState, UInt32Value} from 'chrome://resources/mojo/chromeos/services/network_health/public/mojom/network_health.mojom-webui.js'; -import {OncMojo} from '../network/onc_mojo.js'; - import {getTemplate} from './network_health_summary.html.js'; const TechnologyIcons = {
diff --git a/base/BUILD.gn b/base/BUILD.gn index c6196e9..71c2d615 100644 --- a/base/BUILD.gn +++ b/base/BUILD.gn
@@ -548,6 +548,10 @@ "pending_task.h", "pickle.cc", "pickle.h", + "power_monitor/battery_level_provider.cc", + "power_monitor/battery_level_provider.h", + "power_monitor/battery_state_sampler.cc", + "power_monitor/battery_state_sampler.h", "power_monitor/moving_average.cc", "power_monitor/moving_average.h", "power_monitor/power_monitor.cc", @@ -1078,11 +1082,7 @@ "message_loop/message_pump_win.cc", "message_loop/message_pump_win.h", "native_library_win.cc", - "power_monitor/battery_level_provider.cc", - "power_monitor/battery_level_provider.h", "power_monitor/battery_level_provider_win.cc", - "power_monitor/battery_state_sampler.cc", - "power_monitor/battery_state_sampler.h", "power_monitor/power_monitor_device_source_win.cc", "power_monitor/speed_limit_observer_win.cc", "power_monitor/speed_limit_observer_win.h", @@ -1308,11 +1308,7 @@ "message_loop/message_pump_mac.h", "message_loop/message_pump_mac.mm", "native_library_mac.mm", - "power_monitor/battery_level_provider.cc", - "power_monitor/battery_level_provider.h", "power_monitor/battery_level_provider_mac.mm", - "power_monitor/battery_state_sampler.cc", - "power_monitor/battery_state_sampler.h", "power_monitor/battery_state_sampler_mac.cc", "power_monitor/iopm_power_source_sampling_event_source.cc", "power_monitor/iopm_power_source_sampling_event_source.h", @@ -3241,6 +3237,8 @@ "parameter_pack_unittest.cc", "path_service_unittest.cc", "pickle_unittest.cc", + "power_monitor/battery_level_provider_unittest.cc", + "power_monitor/battery_state_sampler_unittest.cc", "power_monitor/moving_average_unittest.cc", "power_monitor/power_monitor_device_source_unittest.cc", "power_monitor/power_monitor_unittest.cc", @@ -3507,8 +3505,6 @@ sources += [ "debug/gdi_debug_util_win_unittest.cc", "file_version_info_win_unittest.cc", - "power_monitor/battery_level_provider_unittest.cc", - "power_monitor/battery_state_sampler_unittest.cc", "process/launch_unittest_win.cc", "test/fake_iasync_operation_win_unittest.cc", "test/test_file_util_win_unittest.cc", @@ -3597,8 +3593,6 @@ "mac/scoped_objc_class_swizzler_unittest.mm", "mac/scoped_sending_event_unittest.mm", "message_loop/message_pump_mac_unittest.mm", - "power_monitor/battery_level_provider_unittest.cc", - "power_monitor/battery_state_sampler_unittest.cc", "power_monitor/thermal_state_observer_mac_unittest.mm", "process/memory_unittest_mac.h", "process/memory_unittest_mac.mm",
diff --git a/base/allocator/partition_alloc_support_unittest.cc b/base/allocator/partition_alloc_support_unittest.cc index 971b97bf..7844e249 100644 --- a/base/allocator/partition_alloc_support_unittest.cc +++ b/base/allocator/partition_alloc_support_unittest.cc
@@ -13,6 +13,7 @@ #include "base/allocator/partition_allocator/dangling_raw_ptr_checks.h" #include "base/allocator/partition_allocator/partition_alloc_config.h" #include "base/feature_list.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" @@ -224,16 +225,16 @@ HasSubstr("The dangling raw_ptr was released at:"))); } +// DCHECK message are stripped in official build. It causes death tests with +// matchers to fail. +#if !defined(OFFICIAL_BUILD) || !defined(NDEBUG) TEST(PartitionAllocDanglingPtrChecks, DoubleDetection) { ScopedInstallDanglingRawPtrChecks scoped_install_dangling_checks; partition_alloc::GetDanglingRawPtrDetectedFn()(42); -#if DCHECK_IS_ON() - EXPECT_DEATH(partition_alloc::GetDanglingRawPtrDetectedFn()(42), - AllOf(HasSubstr("Check failed: !entry || entry->id != id"))); -#else - partition_alloc::GetDanglingRawPtrDetectedFn()(42); -#endif + EXPECT_DCHECK_DEATH_WITH(partition_alloc::GetDanglingRawPtrDetectedFn()(42), + "Check failed: !entry \\|\\| entry->id != id"); } +#endif // !defined(OFFICIAL_BUILD) || !defined(NDEBUG) #endif
diff --git a/base/allocator/partition_allocator/BUILD.gn b/base/allocator/partition_allocator/BUILD.gn index 4a759b7..ccd05977 100644 --- a/base/allocator/partition_allocator/BUILD.gn +++ b/base/allocator/partition_allocator/BUILD.gn
@@ -115,6 +115,7 @@ "partition_alloc_base/scoped_clear_last_error.h", "partition_alloc_base/strings/stringprintf.cc", "partition_alloc_base/strings/stringprintf.h", + "partition_alloc_base/system/sys_info.h", "partition_alloc_base/thread_annotations.h", "partition_alloc_base/threading/platform_thread.cc", "partition_alloc_base/threading/platform_thread.h", @@ -258,11 +259,23 @@ sources += [ "partition_alloc_base/mac/foundation_util.h", "partition_alloc_base/mac/foundation_util.mm", - "partition_alloc_base/mac/mac_util.h", - "partition_alloc_base/mac/mac_util.mm", "partition_alloc_base/mac/scoped_cftyperef.h", "partition_alloc_base/mac/scoped_typeref.h", ] + if (is_ios) { + sources += [ + "partition_alloc_base/ios/ios_util.h", + "partition_alloc_base/ios/ios_util.mm", + "partition_alloc_base/system/sys_info_ios.mm", + ] + } + if (is_mac) { + sources += [ + "partition_alloc_base/mac/mac_util.h", + "partition_alloc_base/mac/mac_util.mm", + "partition_alloc_base/system/sys_info_mac.mm", + ] + } } if (build_with_chromium) { if (current_cpu == "x64") { @@ -318,8 +331,11 @@ frameworks += [ "Security.framework" ] } - if (is_component_build && is_apple) { - frameworks += [ "CoreFoundation.framework" ] + if (is_apple) { + frameworks += [ + "CoreFoundation.framework", + "Foundation.framework", + ] } configs += [ "//build/config/compiler:wexit_time_destructors" ]
diff --git a/base/allocator/partition_allocator/page_allocator_internals_posix.h b/base/allocator/partition_allocator/page_allocator_internals_posix.h index 38c916f..940e3bf 100644 --- a/base/allocator/partition_allocator/page_allocator_internals_posix.h +++ b/base/allocator/partition_allocator/page_allocator_internals_posix.h
@@ -21,7 +21,13 @@ #if BUILDFLAG(IS_APPLE) #include "base/allocator/partition_allocator/partition_alloc_base/mac/foundation_util.h" +#if BUILDFLAG(IS_IOS) +#include "base/allocator/partition_allocator/partition_alloc_base/ios/ios_util.h" +#elif BUILDFLAG(IS_MAC) #include "base/allocator/partition_allocator/partition_alloc_base/mac/mac_util.h" +#else +#error "Unknown platform" +#endif #include "base/allocator/partition_allocator/partition_alloc_base/mac/scoped_cftyperef.h" #include <Availability.h>
diff --git a/base/allocator/partition_allocator/partition_address_space.h b/base/allocator/partition_allocator/partition_address_space.h index 9b4dacc..65bb1a5 100644 --- a/base/allocator/partition_allocator/partition_address_space.h +++ b/base/allocator/partition_allocator/partition_address_space.h
@@ -165,8 +165,9 @@ } else if (pool == kBRPPoolHandle) { return brp_pool_shadow_offset_; } else { - // Shadow is not created for ConfigurablePool, so this part should be - // unreachable. + // TODO(crbug.com/1362969): Add shadow for configurable pool as well. + // Shadow is not created for ConfigurablePool for now, so this part should + // be unreachable. PA_NOTREACHED(); return 0; } @@ -331,6 +332,12 @@ return PartitionAddressSpace::OffsetInBRPPool(address); } +#if defined(PA_ENABLE_SHADOW_METADATA) +PA_ALWAYS_INLINE std::ptrdiff_t ShadowPoolOffset(pool_handle pool) { + return PartitionAddressSpace::ShadowPoolOffset(pool); +} +#endif + } // namespace internal // Returns false for nullptr.
diff --git a/base/allocator/partition_allocator/partition_alloc_base/ios/ios_util.h b/base/allocator/partition_allocator/partition_alloc_base/ios/ios_util.h new file mode 100644 index 0000000..d855866 --- /dev/null +++ b/base/allocator/partition_allocator/partition_alloc_base/ios/ios_util.h
@@ -0,0 +1,36 @@ +// Copyright 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef BASE_ALLOCATOR_PARTITION_ALLOCATOR_PARTITION_ALLOC_BASE_IOS_IOS_UTIL_H_ +#define BASE_ALLOCATOR_PARTITION_ALLOCATOR_PARTITION_ALLOC_BASE_IOS_IOS_UTIL_H_ + +#include <stdint.h> + +#include "base/allocator/partition_allocator/partition_alloc_base/component_export.h" + +namespace partition_alloc::internal::base::ios { + +// Returns whether the operating system is iOS 12 or later. +// TODO(crbug.com/1129482): Remove once minimum supported version is at least 12 +PA_COMPONENT_EXPORT(PARTITION_ALLOC) bool IsRunningOnIOS12OrLater(); + +// Returns whether the operating system is iOS 13 or later. +// TODO(crbug.com/1129483): Remove once minimum supported version is at least 13 +PA_COMPONENT_EXPORT(PARTITION_ALLOC) bool IsRunningOnIOS13OrLater(); + +// Returns whether the operating system is iOS 14 or later. +// TODO(crbug.com/1129484): Remove once minimum supported version is at least 14 +PA_COMPONENT_EXPORT(PARTITION_ALLOC) bool IsRunningOnIOS14OrLater(); + +// Returns whether the operating system is iOS 15 or later. +// TODO(crbug.com/1227419): Remove once minimum supported version is at least 15 +PA_COMPONENT_EXPORT(PARTITION_ALLOC) bool IsRunningOnIOS15OrLater(); + +// Returns whether the operating system is at the given version or later. +PA_COMPONENT_EXPORT(PARTITION_ALLOC) +bool IsRunningOnOrLater(int32_t major, int32_t minor, int32_t bug_fix); + +} // namespace partition_alloc::internal::base::ios + +#endif // BASE_ALLOCATOR_PARTITION_ALLOCATOR_PARTITION_ALLOC_BASE_IOS_IOS_UTIL_H_
diff --git a/base/allocator/partition_allocator/partition_alloc_base/ios/ios_util.mm b/base/allocator/partition_allocator/partition_alloc_base/ios/ios_util.mm new file mode 100644 index 0000000..d5d607dd --- /dev/null +++ b/base/allocator/partition_allocator/partition_alloc_base/ios/ios_util.mm
@@ -0,0 +1,57 @@ +// Copyright 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "base/allocator/partition_allocator/partition_alloc_base/ios/ios_util.h" + +#include <array> + +#include "base/allocator/partition_allocator/partition_alloc_base/system/sys_info.h" + +namespace partition_alloc::internal::base::ios { + +bool IsRunningOnIOS12OrLater() { + static const bool is_running_on_or_later = IsRunningOnOrLater(12, 0, 0); + return is_running_on_or_later; +} + +bool IsRunningOnIOS13OrLater() { + static const bool is_running_on_or_later = IsRunningOnOrLater(13, 0, 0); + return is_running_on_or_later; +} + +bool IsRunningOnIOS14OrLater() { + static const bool is_running_on_or_later = IsRunningOnOrLater(14, 0, 0); + return is_running_on_or_later; +} + +bool IsRunningOnIOS15OrLater() { + static const bool is_running_on_or_later = IsRunningOnOrLater(15, 0, 0); + return is_running_on_or_later; +} + +bool IsRunningOnOrLater(int32_t major, int32_t minor, int32_t bug_fix) { + static const class OSVersion { + public: + OSVersion() { + SysInfo::OperatingSystemVersionNumbers( + ¤t_version_[0], ¤t_version_[1], ¤t_version_[2]); + } + + bool IsRunningOnOrLater(int32_t version[3]) const { + for (size_t i = 0; i < std::size(current_version_); ++i) { + if (current_version_[i] != version[i]) + return current_version_[i] > version[i]; + } + return true; + } + + private: + int32_t current_version_[3]; + } kOSVersion; + + int32_t version[3] = {major, minor, bug_fix}; + return kOSVersion.IsRunningOnOrLater(version); +} + +} // namespace partition_alloc::internal::base::ios
diff --git a/base/allocator/partition_allocator/partition_alloc_base/logging.cc b/base/allocator/partition_allocator/partition_alloc_base/logging.cc index c5d4f565..464a352 100644 --- a/base/allocator/partition_allocator/partition_alloc_base/logging.cc +++ b/base/allocator/partition_allocator/partition_alloc_base/logging.cc
@@ -67,12 +67,13 @@ // A log message handler that gets notified of every log message we process. LogMessageHandlerFunction g_log_message_handler = nullptr; -void WriteToFd(int fd, const char* data, size_t length) { +#if !BUILDFLAG(IS_WIN) +void WriteToStderr(const char* data, size_t length) { size_t bytes_written = 0; int rv; while (bytes_written < length) { rv = PA_HANDLE_EINTR( - write(fd, data + bytes_written, length - bytes_written)); + write(STDERR_FILENO, data + bytes_written, length - bytes_written)); if (rv < 0) { // Give up, nothing we can do now. break; @@ -80,6 +81,22 @@ bytes_written += rv; } } +#else // !BUILDFLAG(IS_WIN) +void WriteToStderr(const char* data, size_t length) { + HANDLE handle = ::GetStdHandle(STD_ERROR_HANDLE); + const char* ptr = data; + const char* ptr_end = data + length; + while (ptr < ptr_end) { + DWORD bytes_written = 0; + if (!::WriteFile(handle, ptr, ptr_end - ptr, &bytes_written, nullptr) || + bytes_written == 0) { + // Give up, nothing we can do now. + break; + } + ptr += bytes_written; + } +} +#endif // !BUILDFLAG(IS_WIN) } // namespace @@ -245,18 +262,15 @@ void RawLog(int level, const char* message) { if (level >= g_min_log_level && message) { +#if !BUILDFLAG(IS_WIN) const size_t message_len = strlen(message); - WriteToFd(STDERR_FILENO, message, message_len); +#else // !BUILDFLAG(IS_WIN) + const size_t message_len = ::lstrlenA(message); +#endif // !BUILDFLAG(IS_WIN) + WriteToStderr(message, message_len); if (message_len > 0 && message[message_len - 1] != '\n') { - int rv; - do { - rv = PA_HANDLE_EINTR(write(STDERR_FILENO, "\n", 1)); - if (rv < 0) { - // Give up, nothing we can do now. - break; - } - } while (rv != 1); + WriteToStderr("\n", 1); } }
diff --git a/base/allocator/partition_allocator/partition_alloc_base/mac/mac_util.h b/base/allocator/partition_allocator/partition_alloc_base/mac/mac_util.h index 97728e1dd..b9279f45 100644 --- a/base/allocator/partition_allocator/partition_alloc_base/mac/mac_util.h +++ b/base/allocator/partition_allocator/partition_alloc_base/mac/mac_util.h
@@ -7,9 +7,8 @@ #include <AvailabilityMacros.h> #import <CoreGraphics/CoreGraphics.h> -#include <stdint.h> -#include <string> +#include "base/allocator/partition_allocator/partition_alloc_base/component_export.h" namespace partition_alloc::internal::base::mac { @@ -19,7 +18,7 @@ // integer value. For example, for macOS Sierra this returns 1012, and for macOS // Big Sur it returns 1100. Note that the accuracy returned by this function is // as granular as the major version number of Darwin. -int MacOSVersion(); +PA_COMPONENT_EXPORT(PARTITION_ALLOC) int MacOSVersion(); } // namespace internal @@ -96,6 +95,12 @@ PA_DEFINE_IS_OS_FUNCS(12, PA_IGNORE_DEPLOYMENT_TARGET) #endif +#ifdef MAC_OS_VERSION_13_0 +PA_DEFINE_IS_OS_FUNCS(13, PA_TEST_DEPLOYMENT_TARGET) +#else +PA_DEFINE_IS_OS_FUNCS(13, PA_IGNORE_DEPLOYMENT_TARGET) +#endif + #undef PA_DEFINE_OLD_IS_OS_FUNCS_CR_MIN_REQUIRED #undef PA_DEFINE_OLD_IS_OS_FUNCS #undef PA_DEFINE_IS_OS_FUNCS_CR_MIN_REQUIRED @@ -104,6 +109,13 @@ #undef PA_TEST_DEPLOYMENT_TARGET #undef PA_IGNORE_DEPLOYMENT_TARGET +// This should be infrequently used. It only makes sense to use this to avoid +// codepaths that are very likely to break on future (unreleased, untested, +// unborn) OS releases, or to log when the OS is newer than any known version. +inline bool IsOSLaterThan13_DontCallThis() { + return !IsAtMostOS13(); +} + } // namespace partition_alloc::internal::base::mac #endif // BASE_ALLOCATOR_PARTITION_ALLOCATOR_PARTITION_ALLOC_BASE_MAC_MAC_UTIL_H_
diff --git a/base/allocator/partition_allocator/partition_alloc_base/system/sys_info.h b/base/allocator/partition_allocator/partition_alloc_base/system/sys_info.h new file mode 100644 index 0000000..d7d2437 --- /dev/null +++ b/base/allocator/partition_allocator/partition_alloc_base/system/sys_info.h
@@ -0,0 +1,29 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef BASE_ALLOCATOR_PARTITION_ALLOCATOR_PARTITION_ALLOC_BASE_SYSTEM_SYS_INFO_H_ +#define BASE_ALLOCATOR_PARTITION_ALLOCATOR_PARTITION_ALLOC_BASE_SYSTEM_SYS_INFO_H_ + +#include <cstdint> + +#include "base/allocator/partition_allocator/partition_alloc_base/component_export.h" + +namespace partition_alloc::internal::base { + +class PA_COMPONENT_EXPORT(PARTITION_ALLOC) SysInfo { + public: + // Retrieves detailed numeric values for the OS version. + // DON'T USE THIS ON THE MAC OR WINDOWS to determine the current OS release + // for OS version-specific feature checks and workarounds. If you must use + // an OS version check instead of a feature check, use the base::mac::IsOS* + // family from base/mac/mac_util.h, or base::win::GetVersion from + // base/win/windows_version.h. + static void OperatingSystemVersionNumbers(int32_t* major_version, + int32_t* minor_version, + int32_t* bugfix_version); +}; + +} // namespace partition_alloc::internal::base + +#endif // BASE_ALLOCATOR_PARTITION_ALLOCATOR_PARTITION_ALLOC_BASE_SYSTEM_SYS_INFO_H_
diff --git a/base/allocator/partition_allocator/partition_alloc_base/system/sys_info_ios.mm b/base/allocator/partition_allocator/partition_alloc_base/system/sys_info_ios.mm new file mode 100644 index 0000000..e6b7ce8 --- /dev/null +++ b/base/allocator/partition_allocator/partition_alloc_base/system/sys_info_ios.mm
@@ -0,0 +1,24 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "base/allocator/partition_allocator/partition_alloc_base/system/sys_info.h" + +#import <Foundation/Foundation.h> + +#include "base/allocator/partition_allocator/partition_alloc_base/numerics/safe_conversions.h" + +namespace partition_alloc::internal::base { + +// static +void SysInfo::OperatingSystemVersionNumbers(int32_t* major_version, + int32_t* minor_version, + int32_t* bugfix_version) { + NSOperatingSystemVersion version = + [[NSProcessInfo processInfo] operatingSystemVersion]; + *major_version = saturated_cast<int32_t>(version.majorVersion); + *minor_version = saturated_cast<int32_t>(version.minorVersion); + *bugfix_version = saturated_cast<int32_t>(version.patchVersion); +} + +} // namespace partition_alloc::internal::base
diff --git a/base/allocator/partition_allocator/partition_alloc_base/system/sys_info_mac.mm b/base/allocator/partition_allocator/partition_alloc_base/system/sys_info_mac.mm new file mode 100644 index 0000000..100a67e --- /dev/null +++ b/base/allocator/partition_allocator/partition_alloc_base/system/sys_info_mac.mm
@@ -0,0 +1,24 @@ +// 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. + +#include "base/allocator/partition_allocator/partition_alloc_base/system/sys_info.h" + +#import <Foundation/Foundation.h> + +#include "base/allocator/partition_allocator/partition_alloc_base/numerics/safe_conversions.h" + +namespace partition_alloc::internal::base { + +// static +void SysInfo::OperatingSystemVersionNumbers(int32_t* major_version, + int32_t* minor_version, + int32_t* bugfix_version) { + NSOperatingSystemVersion version = + [[NSProcessInfo processInfo] operatingSystemVersion]; + *major_version = saturated_cast<int32_t>(version.majorVersion); + *minor_version = saturated_cast<int32_t>(version.minorVersion); + *bugfix_version = saturated_cast<int32_t>(version.patchVersion); +} + +} // namespace partition_alloc::internal::base
diff --git a/base/allocator/partition_allocator/partition_alloc_unittest.cc b/base/allocator/partition_allocator/partition_alloc_unittest.cc index 27b744c..986cf44 100644 --- a/base/allocator/partition_allocator/partition_alloc_unittest.cc +++ b/base/allocator/partition_allocator/partition_alloc_unittest.cc
@@ -4092,6 +4092,9 @@ } #if defined(PA_HAS_DEATH_TESTS) +// DCHECK message are stripped in official build. It causes death tests with +// matchers to fail. +#if !defined(OFFICIAL_BUILD) || !defined(NDEBUG) // Acquire() once, Release() twice => CRASH TEST_P(PartitionAllocDeathTest, ReleaseUnderflowRawPtr) { @@ -4115,6 +4118,7 @@ allocator.root()->Free(ptr); } +#endif //! defined(OFFICIAL_BUILD) || !defined(NDEBUG) #endif // defined(PA_HAS_DEATH_TESTS) #endif // BUILDFLAG(ENABLE_DANGLING_RAW_PTR_CHECKS) @@ -4318,14 +4322,13 @@ } #if defined(PA_HAS_DEATH_TESTS) +// DCHECK message are stripped in official build. It causes death tests with +// matchers to fail. #if !defined(OFFICIAL_BUILD) || !defined(NDEBUG) TEST_P(PartitionAllocDeathTest, CheckTriggered) { - using ::testing::ContainsRegex; -#if BUILDFLAG(PA_DCHECK_IS_ON) - EXPECT_DEATH(PA_CHECK(5 == 7), ContainsRegex("Check failed.*5 == 7")); -#endif - EXPECT_DEATH(PA_CHECK(5 == 7), ContainsRegex("Check failed.*5 == 7")); + EXPECT_DCHECK_DEATH_WITH(PA_CHECK(5 == 7), "Check failed.*5 == 7"); + EXPECT_DEATH(PA_CHECK(5 == 7), "Check failed.*5 == 7"); } #endif // !defined(OFFICIAL_BUILD) && !defined(NDEBUG)
diff --git a/base/allocator/partition_allocator/partition_bucket.cc b/base/allocator/partition_allocator/partition_bucket.cc index 0b06869b..5917d75 100644 --- a/base/allocator/partition_allocator/partition_bucket.cc +++ b/base/allocator/partition_allocator/partition_bucket.cc
@@ -45,6 +45,17 @@ namespace { +#if defined(PA_ENABLE_SHADOW_METADATA) +PA_ALWAYS_INLINE uintptr_t ShadowMetadataStart(uintptr_t super_page, + pool_handle pool) { + uintptr_t shadow_metadata_start = + super_page + SystemPageSize() + ShadowPoolOffset(pool); + PA_DCHECK(!PartitionAddressSpace::IsInRegularPool(shadow_metadata_start)); + PA_DCHECK(!PartitionAddressSpace::IsInBRPPool(shadow_metadata_start)); + return shadow_metadata_start; +} +#endif + template <bool thread_safe> [[noreturn]] PA_NOINLINE void PartitionOutOfMemoryMappingFailure( PartitionRoot<thread_safe>* root, @@ -294,21 +305,39 @@ { ScopedSyscallTimer timer{root}; - RecommitSystemPages( - reservation_start + SystemPageSize(), -#if BUILDFLAG(PUT_REF_COUNT_IN_PREVIOUS_SLOT) - // If PUT_REF_COUNT_IN_PREVIOUS_SLOT is on, and if the BRP pool is - // used, allocate 2 SystemPages, one for SuperPage metadata and the - // other for RefCount "bitmap" (only one of its elements will be - // used). - (pool == GetBRPPool()) ? SystemPageSize() * 2 : SystemPageSize(), + RecommitSystemPages(reservation_start + SystemPageSize(), + SystemPageSize(), +#if defined(PA_ENABLE_SHADOW_METADATA) + PageAccessibilityConfiguration::kRead, #else - SystemPageSize(), + PageAccessibilityConfiguration::kReadWrite, #endif - PageAccessibilityConfiguration::kReadWrite, - PageAccessibilityDisposition::kRequireUpdate); + PageAccessibilityDisposition::kRequireUpdate); } +#if BUILDFLAG(PUT_REF_COUNT_IN_PREVIOUS_SLOT) + // If PUT_REF_COUNT_IN_PREVIOUS_SLOT is on, and if the BRP pool is + // used, allocate a SystemPage for RefCount "bitmap" (only one of its + // elements will be used). + if (pool == GetBRPPool()) { + ScopedSyscallTimer timer{root}; + RecommitSystemPages(reservation_start + SystemPageSize() * 2, + SystemPageSize(), + PageAccessibilityConfiguration::kReadWrite, + PageAccessibilityDisposition::kRequireUpdate); + } +#endif + +#if defined(PA_ENABLE_SHADOW_METADATA) + { + ScopedSyscallTimer timer{root}; + RecommitSystemPages(ShadowMetadataStart(reservation_start, pool), + SystemPageSize(), + PageAccessibilityConfiguration::kReadWrite, + PageAccessibilityDisposition::kRequireUpdate); + } +#endif + // No need to hold root->lock_. Now that memory is reserved, no other // overlapping region can be allocated (because of how GigaCage works), // so no other thread can update the same offset table entries at the @@ -774,20 +803,35 @@ // also a tiny amount of extent metadata. { ScopedSyscallTimer timer{root}; - RecommitSystemPages(super_page + SystemPageSize(), -#if BUILDFLAG(PUT_REF_COUNT_IN_PREVIOUS_SLOT) - // If PUT_REF_COUNT_IN_PREVIOUS_SLOT is on, and if the - // BRP pool is used, allocate 2 SystemPages, one for - // SuperPage metadata and the other for RefCount bitmap. - (root->ChoosePool() == GetBRPPool()) - ? SystemPageSize() * 2 - : SystemPageSize(), + RecommitSystemPages(super_page + SystemPageSize(), SystemPageSize(), +#if defined(PA_ENABLE_SHADOW_METADATA) + PageAccessibilityConfiguration::kRead, #else - SystemPageSize(), + PageAccessibilityConfiguration::kReadWrite, #endif + PageAccessibilityDisposition::kRequireUpdate); + } + +#if BUILDFLAG(PUT_REF_COUNT_IN_PREVIOUS_SLOT) + // If PUT_REF_COUNT_IN_PREVIOUS_SLOT is on, and if the BRP pool is + // used, allocate a SystemPage for RefCount bitmap. + if (root->ChoosePool() == GetBRPPool()) { + ScopedSyscallTimer timer{root}; + RecommitSystemPages(super_page + SystemPageSize() * 2, SystemPageSize(), PageAccessibilityConfiguration::kReadWrite, PageAccessibilityDisposition::kRequireUpdate); } +#endif + +#if defined(PA_ENABLE_SHADOW_METADATA) + { + ScopedSyscallTimer timer{root}; + RecommitSystemPages(ShadowMetadataStart(super_page, root->ChoosePool()), + SystemPageSize(), + PageAccessibilityConfiguration::kReadWrite, + PageAccessibilityDisposition::kRequireUpdate); + } +#endif // If we were after a specific address, but didn't get it, assume that // the system chose a lousy address. Here most OS'es have a default
diff --git a/base/allocator/partition_allocator/partition_root.cc b/base/allocator/partition_allocator/partition_root.cc index 87cf94f..ab9fbf1 100644 --- a/base/allocator/partition_allocator/partition_root.cc +++ b/base/allocator/partition_allocator/partition_root.cc
@@ -768,7 +768,8 @@ PartitionOptions::BackupRefPtrZapping::kEnabled; PA_CHECK(!flags.brp_zapping_enabled_ || flags.brp_enabled_); #if defined(PA_ENABLE_MAC11_MALLOC_SIZE_HACK) && BUILDFLAG(IS_APPLE) - flags.mac11_malloc_size_hack_enabled_ = internal::base::mac::IsOS11(); + flags.mac11_malloc_size_hack_enabled_ = + flags.brp_enabled_ && internal::base::mac::IsOS11(); #endif // defined(PA_ENABLE_MAC11_MALLOC_SIZE_HACK) && BUILDFLAG(IS_APPLE) #else // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) PA_CHECK(opts.backup_ref_ptr == PartitionOptions::BackupRefPtr::kDisabled);
diff --git a/base/allocator/partition_allocator/shim/DEPS b/base/allocator/partition_allocator/shim/DEPS index ad1a1b37..142f45b 100644 --- a/base/allocator/partition_allocator/shim/DEPS +++ b/base/allocator/partition_allocator/shim/DEPS
@@ -10,13 +10,12 @@ "+base/allocator/buildflags.h", "+base/allocator/early_zone_registration_mac.h", "+base/allocator/partition_alloc_features.h", + "+base/allocator/partition_allocator/partition_alloc_base", "+base/base_export.h", "+base/bind.h", "+base/compiler_specific.h", "+base/feature_list.h", - "+base/ios/ios_util.h", "+base/logging.h", - "+base/mac/mac_util.h", "+base/mac/mach_logging.h", "+base/memory/nonscannable_memory.h", "+base/memory/page_size.h", @@ -35,7 +34,6 @@ specific_include_rules = { "allocator_shim_unittest\.cc$": [ - "+base/mac/mac_util.h", "+base/synchronization/waitable_event.h", "+base/threading/thread_local.h", ],
diff --git a/base/allocator/partition_allocator/shim/allocator_interception_mac.mm b/base/allocator/partition_allocator/shim/allocator_interception_mac.mm index 26320c93..0350821 100644 --- a/base/allocator/partition_allocator/shim/allocator_interception_mac.mm +++ b/base/allocator/partition_allocator/shim/allocator_interception_mac.mm
@@ -39,9 +39,9 @@ #include "third_party/apple_apsl/CFBase.h" #if BUILDFLAG(IS_IOS) -#include "base/ios/ios_util.h" +#include "base/allocator/partition_allocator/partition_alloc_base/ios/ios_util.h" #else -#include "base/mac/mac_util.h" +#include "base/allocator/partition_allocator/partition_alloc_base/mac/mac_util.h" #endif namespace allocator_shim { @@ -236,9 +236,9 @@ bool CanGetContextForCFAllocator() { #if BUILDFLAG(IS_IOS) - return !base::ios::IsRunningOnOrLater(17, 0, 0); + return !partition_alloc::internal::base::ios::IsRunningOnOrLater(17, 0, 0); #else - return !base::mac::IsOSLaterThan13_DontCallThis(); + return !partition_alloc::internal::base::mac::IsOSLaterThan13_DontCallThis(); #endif }
diff --git a/base/allocator/partition_allocator/shim/allocator_shim_unittest.cc b/base/allocator/partition_allocator/shim/allocator_shim_unittest.cc index 384f445..6caf9d6 100644 --- a/base/allocator/partition_allocator/shim/allocator_shim_unittest.cc +++ b/base/allocator/partition_allocator/shim/allocator_shim_unittest.cc
@@ -30,7 +30,6 @@ #elif BUILDFLAG(IS_APPLE) #include <malloc/malloc.h> #include "base/allocator/partition_allocator/shim/allocator_interception_mac.h" -#include "base/mac/mac_util.h" #include "third_party/apple_apsl/malloc.h" #else #include <malloc.h>
diff --git a/base/power_monitor/battery_level_provider.cc b/base/power_monitor/battery_level_provider.cc index d9bb46d..3e6c633 100644 --- a/base/power_monitor/battery_level_provider.cc +++ b/base/power_monitor/battery_level_provider.cc
@@ -4,10 +4,17 @@ #include "base/power_monitor/battery_level_provider.h" +#include "base/power_monitor/power_monitor_buildflags.h" #include "base/ranges/algorithm.h" namespace base { +#if !BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) +std::unique_ptr<BatteryLevelProvider> BatteryLevelProvider::Create() { + return nullptr; +} +#endif + BatteryLevelProvider::BatteryState BatteryLevelProvider::MakeBatteryState( const std::vector<BatteryDetails>& battery_details) { BatteryState state;
diff --git a/base/power_monitor/battery_level_provider.h b/base/power_monitor/battery_level_provider.h index dfd5e11d..b22cd4b8 100644 --- a/base/power_monitor/battery_level_provider.h +++ b/base/power_monitor/battery_level_provider.h
@@ -10,16 +10,10 @@ #include <vector> #include "base/callback.h" -#include "base/power_monitor/power_monitor_buildflags.h" #include "base/time/time.h" #include "build/build_config.h" #include "third_party/abseil-cpp/absl/types/optional.h" -#if !BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) -#error battery_level_provider.h can only be included on platforms with a \ - working implementation. -#endif - namespace base { // BatteryLevelProvider provides an interface for querying battery state.
diff --git a/base/power_monitor/battery_state_sampler.cc b/base/power_monitor/battery_state_sampler.cc index f18c683..7765b05 100644 --- a/base/power_monitor/battery_state_sampler.cc +++ b/base/power_monitor/battery_state_sampler.cc
@@ -4,6 +4,8 @@ #include "base/power_monitor/battery_state_sampler.h" +#include "base/power_monitor/power_monitor_buildflags.h" + #if !BUILDFLAG(IS_MAC) #include "base/power_monitor/timer_sampling_event_source.h" #endif @@ -46,7 +48,11 @@ // static BatteryStateSampler* BatteryStateSampler::Get() { + // On a platform with a BatteryLevelProvider implementation, the global + // instance must be created before accessing it. +#if BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) DCHECK(g_battery_state_sampler); +#endif return g_battery_state_sampler; }
diff --git a/base/power_monitor/battery_state_sampler.h b/base/power_monitor/battery_state_sampler.h index dec19ee5..2ea542d 100644 --- a/base/power_monitor/battery_state_sampler.h +++ b/base/power_monitor/battery_state_sampler.h
@@ -42,7 +42,8 @@ BatteryLevelProvider::Create()); ~BatteryStateSampler(); - // Returns the unique instance. + // Returns the unique instance, or nullptr on platforms without a + // `BatteryLevelProvider` implementation. static BatteryStateSampler* Get(); // Adds/removes an observer. `OnBatteryStateSampled` will be immediately
diff --git a/base/power_monitor/battery_state_sampler_unittest.cc b/base/power_monitor/battery_state_sampler_unittest.cc index deb3964..93b7e5e 100644 --- a/base/power_monitor/battery_state_sampler_unittest.cc +++ b/base/power_monitor/battery_state_sampler_unittest.cc
@@ -7,6 +7,7 @@ #include <queue> #include <utility> +#include "base/power_monitor/power_monitor_buildflags.h" #include "base/power_monitor/sampling_event_source.h" #include "base/run_loop.h" #include "base/test/bind.h" @@ -139,8 +140,15 @@ } TEST(BatteryStateSamplerTest, GlobalInstance) { - // Can't get an non-existent sampler. +#if BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) + // Get() DCHECKs on platforms with a battery level provider if it's called + // without being initialized EXPECT_DCHECK_DEATH(BatteryStateSampler::Get()); +#else + // Get() returns null if the sampler doesn't exist on platforms without a + // battery level provider. + EXPECT_FALSE(BatteryStateSampler::Get()); +#endif auto battery_level_provider = std::make_unique<TestBatteryLevelProvider>(); battery_level_provider->PushBatteryState(kTestBatteryState1); @@ -163,7 +171,11 @@ battery_state_sampler.reset(); // The sampler no longer exists. +#if BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) EXPECT_DCHECK_DEATH(BatteryStateSampler::Get()); +#else + EXPECT_FALSE(BatteryStateSampler::Get()); +#endif } TEST(BatteryStateSamplerTest, InitialSample) {
diff --git a/build/config/compiler/BUILD.gn b/build/config/compiler/BUILD.gn index 9e78337b3..c52a714 100644 --- a/build/config/compiler/BUILD.gn +++ b/build/config/compiler/BUILD.gn
@@ -1179,6 +1179,15 @@ ldflags += [ "--target=riscv64-linux-gnu" ] } cflags += [ "-mabi=lp64d" ] + } else if (current_cpu == "loong64") { + if (is_clang) { + cflags += [ "--target=loongarch64-linux-gnu" ] + ldflags += [ "--target=loongarch64-linux-gnu" ] + } + cflags += [ + "-mabi=lp64d", + "-mcmodel=medium", + ] } else if (current_cpu == "s390x") { cflags += [ "-m64" ] ldflags += [ "-m64" ] @@ -1632,7 +1641,7 @@ if (!is_debug && !using_sanitizer && current_cpu != "s390x" && current_cpu != "s390" && current_cpu != "ppc64" && current_cpu != "mips" && current_cpu != "mips64" && - current_cpu != "riscv64") { + current_cpu != "riscv64" && current_cpu != "loong64") { # Non-chromium code is not guaranteed to compile cleanly with # _FORTIFY_SOURCE. Also, fortified build may fail when optimizations are # disabled, so only do that for Release build. @@ -2398,10 +2407,11 @@ } configs = [] + # Compress debug on 32-bit ARM to stay under 4GB for ChromeOS # https://b/243982712. if (symbol_level == 2 && is_chromeos_device && !use_debug_fission && - !is_nacl && current_cpu == "arm") { + !is_nacl && current_cpu == "arm") { configs += [ "//build/config:compress_debug_sections" ] }
diff --git a/build/fuchsia/cipd/BUILD.gn b/build/fuchsia/cipd/BUILD.gn index fa9bb70..5c0ebce 100644 --- a/build/fuchsia/cipd/BUILD.gn +++ b/build/fuchsia/cipd/BUILD.gn
@@ -280,7 +280,6 @@ deps = [ "//base:base_unittests_pkg", - "//fuchsia_web/runners:cast_runner_integration_tests_cfv1_pkg", "//fuchsia_web/runners:cast_runner_integration_tests_pkg", "//fuchsia_web/runners:web_runner_integration_tests_pkg", "//fuchsia_web/webengine:web_engine_integration_tests_cfv1_pkg", @@ -306,7 +305,6 @@ "${root_gen_dir}/third_party/blink/common/blink_common_unittests/blink_common_unittests.far", ] cfv1_far_sources = [ - "${root_gen_dir}/fuchsia_web/runners/cast_runner_integration_tests_cfv1/cast_runner_integration_tests_cfv1.far", "${root_gen_dir}/fuchsia_web/runners/web_runner_integration_tests/web_runner_integration_tests.far", "${root_gen_dir}/fuchsia_web/webengine/web_engine_integration_tests_cfv1/web_engine_integration_tests_cfv1.far", ] @@ -333,7 +331,6 @@ { manifest_path = "${target_gen_dir}/cast_runner_tests_manifest.json" far_sources = [ "${root_gen_dir}/fuchsia_web/runners/cast_runner_integration_tests/cast_runner_integration_tests.far" ] - cfv1_far_sources = [ "${root_gen_dir}/fuchsia_web/runners/cast_runner_integration_tests_cfv1/cast_runner_integration_tests_cfv1.far" ] }, ] }
diff --git a/build/toolchain/linux/BUILD.gn b/build/toolchain/linux/BUILD.gn index b9308ccf..f559f52 100644 --- a/build/toolchain/linux/BUILD.gn +++ b/build/toolchain/linux/BUILD.gn
@@ -416,7 +416,7 @@ } gcc_toolchain("loong64") { - toolprefix = "loongarch64-linux-gnu" + toolprefix = "loongarch64-unknown-linux-gnu" cc = "${toolprefix}-gcc" cxx = "${toolprefix}-g++"
diff --git a/chrome/VERSION b/chrome/VERSION index a995c86d..ad7ca98 100644 --- a/chrome/VERSION +++ b/chrome/VERSION
@@ -1,4 +1,4 @@ MAJOR=108 MINOR=0 -BUILD=5315 +BUILD=5316 PATCH=0
diff --git a/chrome/android/features/keyboard_accessory/javatests/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/PasswordAccessoryIntegrationTest.java b/chrome/android/features/keyboard_accessory/javatests/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/PasswordAccessoryIntegrationTest.java index 05dd639..eee7195e 100644 --- a/chrome/android/features/keyboard_accessory/javatests/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/PasswordAccessoryIntegrationTest.java +++ b/chrome/android/features/keyboard_accessory/javatests/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/PasswordAccessoryIntegrationTest.java
@@ -30,10 +30,10 @@ import org.junit.Test; import org.junit.runner.RunWith; +import org.chromium.base.test.util.Batch; import org.chromium.base.test.util.CommandLineFlags; import org.chromium.base.test.util.CriteriaHelper; import org.chromium.base.test.util.DisableIf; -import org.chromium.base.test.util.DisabledTest; import org.chromium.chrome.browser.flags.ChromeFeatureList; import org.chromium.chrome.browser.flags.ChromeSwitches; import org.chromium.chrome.browser.keyboard_accessory.ManualFillingTestHelper; @@ -49,6 +49,7 @@ * Integration tests for password accessory views. */ @RunWith(ChromeJUnit4ClassRunner.class) +@Batch(Batch.PER_CLASS) @CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE}) public class PasswordAccessoryIntegrationTest { @Rule @@ -95,9 +96,13 @@ @Test @SmallTest - @DisabledTest(message = "crbug/1365613") - public void testPasswordSheetDisplaysOptions() throws TimeoutException { + @EnableFeatures({ChromeFeatureList.RECOVER_FROM_NEVER_SAVE_ANDROID, + ChromeFeatureList.AUTOFILL_KEYBOARD_ACCESSORY}) + public void + testPasswordSheetDisplaysOptions() throws TimeoutException { mHelper.loadTestPage(false); + // Marking the origin as denylisted shows only a very minimal accessory. + mHelper.cacheCredentials(new String[0], new String[0], true); // Focus the field to bring up the accessory. mHelper.focusPasswordField(); @@ -133,8 +138,10 @@ @Test @SmallTest - @DisabledTest(message = "crbug/1365613") - public void testDisplaysEmptyStateMessageWithoutSavedPasswords() throws TimeoutException { + @EnableFeatures({ChromeFeatureList.RECOVER_FROM_NEVER_SAVE_ANDROID, + ChromeFeatureList.AUTOFILL_KEYBOARD_ACCESSORY}) + public void + testDisplaysEmptyStateMessageWithoutSavedPasswords() throws TimeoutException { mHelper.loadTestPage(false); // Mark the origin as denylisted to have a reason to show the accessory in the first place. mHelper.cacheCredentials(new String[0], new String[0], true);
diff --git a/chrome/android/features/start_surface/java/src/org/chromium/chrome/features/start_surface/StartSurfaceConfiguration.java b/chrome/android/features/start_surface/java/src/org/chromium/chrome/features/start_surface/StartSurfaceConfiguration.java index 38dae77f..3e63871 100644 --- a/chrome/android/features/start_surface/java/src/org/chromium/chrome/features/start_surface/StartSurfaceConfiguration.java +++ b/chrome/android/features/start_surface/java/src/org/chromium/chrome/features/start_surface/StartSurfaceConfiguration.java
@@ -59,12 +59,6 @@ new BooleanCachedFieldTrialParameter( ChromeFeatureList.START_SURFACE_ANDROID, SUPPORT_ACCESSIBILITY_PARAM, true); - private static final String CHECK_SYNC_BEFORE_SHOW_START_AT_STARTUP_PARAM = - "check_sync_before_show_start_at_startup"; - public static final BooleanCachedFieldTrialParameter CHECK_SYNC_BEFORE_SHOW_START_AT_STARTUP = - new BooleanCachedFieldTrialParameter(ChromeFeatureList.START_SURFACE_ANDROID, - CHECK_SYNC_BEFORE_SHOW_START_AT_STARTUP_PARAM, false); - private static final String BEHAVIOURAL_TARGETING_PARAM = "behavioural_targeting"; public static final StringCachedFieldTrialParameter BEHAVIOURAL_TARGETING = new StringCachedFieldTrialParameter(
diff --git a/chrome/android/features/start_surface/java/src/org/chromium/chrome/features/start_surface/StartSurfaceCoordinator.java b/chrome/android/features/start_surface/java/src/org/chromium/chrome/features/start_surface/StartSurfaceCoordinator.java index b680255..e9ab84ca 100644 --- a/chrome/android/features/start_surface/java/src/org/chromium/chrome/features/start_surface/StartSurfaceCoordinator.java +++ b/chrome/android/features/start_surface/java/src/org/chromium/chrome/features/start_surface/StartSurfaceCoordinator.java
@@ -577,9 +577,6 @@ mFeedPlaceholderCoordinator.onOverviewShownAtLaunch(activityCreationTimeMs); } } - if (StartSurfaceConfiguration.CHECK_SYNC_BEFORE_SHOW_START_AT_STARTUP.getValue()) { - ReturnToChromeUtil.cachePrimaryAccountSyncStatus(); - } if (ReturnToChromeUtil.isStartSurfaceEnabled(mActivity)) { Log.i(TAG, "Recorded %s = %b", START_SHOWN_AT_STARTUP_UMA, isOverviewShownOnStartup); RecordHistogram.recordBooleanHistogram(
diff --git a/chrome/android/features/start_surface/junit/src/org/chromium/chrome/features/start_surface/StartSurfaceCoordinatorUnitTest.java b/chrome/android/features/start_surface/junit/src/org/chromium/chrome/features/start_surface/StartSurfaceCoordinatorUnitTest.java index 91775ab..7e58ef45 100644 --- a/chrome/android/features/start_surface/junit/src/org/chromium/chrome/features/start_surface/StartSurfaceCoordinatorUnitTest.java +++ b/chrome/android/features/start_surface/junit/src/org/chromium/chrome/features/start_surface/StartSurfaceCoordinatorUnitTest.java
@@ -4,10 +4,6 @@ package org.chromium.chrome.features.start_surface; -import static org.mockito.Mockito.when; - -import android.app.Activity; -import android.content.Intent; import android.view.View; import androidx.test.filters.MediumTest; @@ -18,7 +14,6 @@ import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.robolectric.annotation.Config; @@ -26,11 +21,9 @@ import org.chromium.base.metrics.RecordHistogram; import org.chromium.base.metrics.UmaRecorderHolder; import org.chromium.base.test.BaseRobolectricTestRunner; -import org.chromium.chrome.browser.ChromeInactivityTracker; import org.chromium.chrome.browser.flags.ChromeFeatureList; import org.chromium.chrome.browser.preferences.ChromePreferenceKeys; import org.chromium.chrome.browser.preferences.SharedPreferencesManager; -import org.chromium.chrome.browser.tabmodel.TabModelSelector; import org.chromium.chrome.browser.tasks.ReturnToChromeUtil; import org.chromium.chrome.test.util.browser.Features; import org.chromium.chrome.test.util.browser.Features.EnableFeatures; @@ -47,8 +40,6 @@ @Rule public StartSurfaceCoordinatorUnitTestRule mTestRule = new StartSurfaceCoordinatorUnitTestRule(); - @Mock - ChromeInactivityTracker mChromeInactivityTracker; StartSurfaceCoordinator mCoordinator; @@ -283,36 +274,6 @@ } @Test - @Features.EnableFeatures( - {ChromeFeatureList.START_SURFACE_ANDROID, ChromeFeatureList.TAB_SWITCHER_ON_RETURN}) - // clang-format off - public void testShowStartWithSyncCheck() { - // clang-format on - TabModelSelector mTabModelSelector = mTestRule.getTabModelSelector(); - Activity mActivity = mTestRule.getActivity(); - - StartSurfaceConfiguration.CHECK_SYNC_BEFORE_SHOW_START_AT_STARTUP.setForTesting(true); - ReturnToChromeUtil.TAB_SWITCHER_ON_RETURN_MS.setForTesting(0); - when(mTabModelSelector.isTabStateInitialized()).thenReturn(true); - when(mTabModelSelector.getTotalTabCount()).thenReturn(1); - - mActivity.getIntent().setAction(Intent.ACTION_MAIN); - mActivity.getIntent().addCategory(Intent.CATEGORY_LAUNCHER); - when(mChromeInactivityTracker.getLastBackgroundedTimeMs()).thenReturn(10L); - - Assert.assertFalse(ReturnToChromeUtil.isPrimaryAccountSync()); - Assert.assertFalse( - ReturnToChromeUtil.shouldShowOverviewPageOnStart(mActivity, mActivity.getIntent(), - mTabModelSelector, mChromeInactivityTracker, false /* isTablet */)); - ReturnToChromeUtil.setSyncForTesting(true); - Assert.assertTrue(ReturnToChromeUtil.isPrimaryAccountSync()); - Assert.assertTrue( - ReturnToChromeUtil.shouldShowOverviewPageOnStart(mActivity, mActivity.getIntent(), - mTabModelSelector, mChromeInactivityTracker, false /* isTablet */)); - - ReturnToChromeUtil.setSyncForTesting(false); - } - @Test @MediumTest @EnableFeatures({ChromeFeatureList.FEED_INTERACTIVE_REFRESH}) public void testFeedSwipeLayoutVisibility() {
diff --git a/chrome/android/features/start_surface/junit/src/org/chromium/chrome/features/start_surface/StartSurfaceCoordinatorUnitTestRule.java b/chrome/android/features/start_surface/junit/src/org/chromium/chrome/features/start_surface/StartSurfaceCoordinatorUnitTestRule.java index 016041fa..c99e4914 100644 --- a/chrome/android/features/start_surface/junit/src/org/chromium/chrome/features/start_surface/StartSurfaceCoordinatorUnitTestRule.java +++ b/chrome/android/features/start_surface/junit/src/org/chromium/chrome/features/start_surface/StartSurfaceCoordinatorUnitTestRule.java
@@ -170,14 +170,6 @@ return mCoordinator; } - public TabModelSelector getTabModelSelector() { - return mTabModelSelector; - } - - public Activity getActivity() { - return mActivity; - } - private void initJniMocks() { Profile profile = Mockito.mock(Profile.class); PrefService prefService = Mockito.mock(PrefService.class);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/app/feed/feedmanagement/FeedManagementActivity.java b/chrome/android/java/src/org/chromium/chrome/browser/app/feed/feedmanagement/FeedManagementActivity.java index 75abe71..5dc4146 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/app/feed/feedmanagement/FeedManagementActivity.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/app/feed/feedmanagement/FeedManagementActivity.java
@@ -7,6 +7,9 @@ import android.content.Context; import android.content.Intent; import android.os.Bundle; +import android.view.MenuItem; + +import androidx.appcompat.widget.Toolbar; import org.chromium.base.Log; import org.chromium.chrome.browser.SnackbarActivity; @@ -39,6 +42,22 @@ FeedManagementCoordinator coordinator = new FeedManagementCoordinator(this, this, this, streamKind); setContentView(coordinator.getView()); + + // Set up the toolbar and back button. + Toolbar toolbar = (Toolbar) findViewById(org.chromium.chrome.browser.feed.R.id.action_bar); + setSupportActionBar(toolbar); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case android.R.id.home: + finish(); + return true; + default: + return super.onOptionsItemSelected(item); + } } // FollowManagementLauncher method.
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/app/feed/followmanagement/FollowManagementActivity.java b/chrome/android/java/src/org/chromium/chrome/browser/app/feed/followmanagement/FollowManagementActivity.java index 79758c0..f3ea30bc 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/app/feed/followmanagement/FollowManagementActivity.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/app/feed/followmanagement/FollowManagementActivity.java
@@ -5,6 +5,9 @@ package org.chromium.chrome.browser.app.feed.followmanagement; import android.os.Bundle; +import android.view.MenuItem; + +import androidx.appcompat.widget.Toolbar; import org.chromium.base.Log; import org.chromium.chrome.browser.SnackbarActivity; @@ -23,5 +26,21 @@ FollowManagementCoordinator coordinator = new FollowManagementCoordinator(this); setContentView(coordinator.getView()); + + // Set up the toolbar and back button. + Toolbar toolbar = (Toolbar) findViewById(org.chromium.chrome.browser.feed.R.id.action_bar); + setSupportActionBar(toolbar); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case android.R.id.home: + finish(); + return true; + default: + return super.onOptionsItemSelected(item); + } } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/app/flags/ChromeCachedFlags.java b/chrome/android/java/src/org/chromium/chrome/browser/app/flags/ChromeCachedFlags.java index ab4bf89..cf0cf6bf 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/app/flags/ChromeCachedFlags.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/app/flags/ChromeCachedFlags.java
@@ -157,7 +157,6 @@ add(CustomTabIntentDataProvider.THIRD_PARTIES_DEFAULT_POLICY); add(CustomTabIntentDataProvider.DENYLIST_ENTRIES); add(CustomTabIntentDataProvider.ALLOWLIST_ENTRIES); - add(StartSurfaceConfiguration.CHECK_SYNC_BEFORE_SHOW_START_AT_STARTUP); add(StartSurfaceConfiguration.HIDE_START_WHEN_LAST_VISITED_TAB_IS_SRP); add(StartSurfaceConfiguration.IS_DOODLE_SUPPORTED); add(StartSurfaceConfiguration.NUM_DAYS_KEEP_SHOW_START_AT_STARTUP);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tasks/ReturnToChromeUtil.java b/chrome/android/java/src/org/chromium/chrome/browser/tasks/ReturnToChromeUtil.java index e9964b9..dc64a5a 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tasks/ReturnToChromeUtil.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/tasks/ReturnToChromeUtil.java
@@ -40,7 +40,6 @@ import org.chromium.chrome.browser.preferences.SharedPreferencesManager; import org.chromium.chrome.browser.profiles.Profile; import org.chromium.chrome.browser.segmentation_platform.SegmentationPlatformServiceFactory; -import org.chromium.chrome.browser.signin.services.IdentityServicesProvider; import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.tab.TabLaunchType; import org.chromium.chrome.browser.tabmodel.TabModelSelector; @@ -54,7 +53,6 @@ import org.chromium.components.segmentation_platform.SegmentSelectionResult; import org.chromium.components.segmentation_platform.SegmentationPlatformService; import org.chromium.components.segmentation_platform.proto.SegmentationProto.SegmentId; -import org.chromium.components.signin.identitymanager.ConsentLevel; import org.chromium.components.user_prefs.UserPrefs; import org.chromium.content_public.browser.LoadUrlParams; import org.chromium.content_public.common.ResourceRequestBody; @@ -498,15 +496,9 @@ // If the overview page won't be shown on startup, stops here. if (!tabSwitcherOnReturn) return false; - if (isStartSurfaceEnabled) { - if (StartSurfaceConfiguration.CHECK_SYNC_BEFORE_SHOW_START_AT_STARTUP.getValue()) { - // We only check the sync status when flag CHECK_SYNC_BEFORE_SHOW_START_AT_STARTUP - // and the Start surface are both enabled. - return ReturnToChromeUtil.isPrimaryAccountSync(); - } else if (!TextUtils.isEmpty( - StartSurfaceConfiguration.BEHAVIOURAL_TARGETING.getValue())) { - return ReturnToChromeUtil.userBehaviourSupported(); - } + if (isStartSurfaceEnabled + && !TextUtils.isEmpty(StartSurfaceConfiguration.BEHAVIOURAL_TARGETING.getValue())) { + return ReturnToChromeUtil.userBehaviourSupported(); } // If Start surface is disable and should show the Grid tab switcher at startup, or flag @@ -516,28 +508,6 @@ } /** - * Returns whether user has a primary account with syncing on. - */ - @VisibleForTesting - public static boolean isPrimaryAccountSync() { - return SharedPreferencesManager.getInstance().readBoolean( - ChromePreferenceKeys.PRIMARY_ACCOUNT_SYNC, false); - } - - /** - * Caches the status of whether the primary account is synced. - */ - public static void cachePrimaryAccountSyncStatus() { - boolean isPrimaryAccountSync = - IdentityServicesProvider.get() - .getSigninManager(Profile.getLastUsedRegularProfile()) - .getIdentityManager() - .hasPrimaryAccount(ConsentLevel.SYNC); - SharedPreferencesManager.getInstance().writeBoolean( - ChromePreferenceKeys.PRIMARY_ACCOUNT_SYNC, isPrimaryAccountSync); - } - - /** * @param currentTab The current {@link Tab}. * @return Whether the Tab is launched with launchType TabLaunchType.FROM_START_SURFACE or it * has "OpenedFromStart" property. @@ -955,12 +925,6 @@ return getBehaviourType(key); } - @VisibleForTesting - public static void setSyncForTesting(boolean isSyncing) { - SharedPreferencesManager manager = SharedPreferencesManager.getInstance(); - manager.writeBoolean(ChromePreferenceKeys.PRIMARY_ACCOUNT_SYNC, isSyncing); - } - /** * Records a user action that Start surface is showing due to tapping the back button. * @param from: Where the back navigation is initiated, either "FromTab" or "FromTabSwitcher".
diff --git a/chrome/app/generated_resources.grd b/chrome/app/generated_resources.grd index 2b49ff3aa..b0f1a75 100644 --- a/chrome/app/generated_resources.grd +++ b/chrome/app/generated_resources.grd
@@ -9421,6 +9421,11 @@ Partitioned </message> + <!-- Page specific site data dialog (redesign of Collected cookies window) --> + <message name="IDS_PAGE_SPECIFIC_SITE_DATA_DIALOG_EMPTY_STATE_LABEL" desc="The text used to explain to users that there are no cookies set and that this is the place where they will be shown. The label is shown in the `Cookies and site data` dialog."> + If a site uses cookies, it will appear here + </message> + <!-- Accessiblility strings for Infobars in Views --> <if expr="toolkit_views"> <message name="IDS_ACCNAME_INFOBAR_CONTAINER" desc="The accessible name for the infobar container.">
diff --git a/chrome/app/generated_resources_grd/IDS_PAGE_SPECIFIC_SITE_DATA_DIALOG_EMPTY_STATE_LABEL.png.sha1 b/chrome/app/generated_resources_grd/IDS_PAGE_SPECIFIC_SITE_DATA_DIALOG_EMPTY_STATE_LABEL.png.sha1 new file mode 100644 index 0000000..3ca5b02 --- /dev/null +++ b/chrome/app/generated_resources_grd/IDS_PAGE_SPECIFIC_SITE_DATA_DIALOG_EMPTY_STATE_LABEL.png.sha1
@@ -0,0 +1 @@ +e936553ba96b2ac24dde2596e7965af8dd7dbe1f \ No newline at end of file
diff --git a/chrome/browser/BUILD.gn b/chrome/browser/BUILD.gn index 25ee2c09..65ffa8ed 100644 --- a/chrome/browser/BUILD.gn +++ b/chrome/browser/BUILD.gn
@@ -987,6 +987,8 @@ "page_info/about_this_site_service_factory.h", "page_info/chrome_about_this_site_service_client.cc", "page_info/chrome_about_this_site_service_client.h", + "page_info/page_info_features.cc", + "page_info/page_info_features.h", "page_load_metrics/observers/core/amp_page_load_metrics_observer.cc", "page_load_metrics/observers/core/amp_page_load_metrics_observer.h", "page_load_metrics/observers/core/ukm_page_load_metrics_observer.cc",
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index f4e0fc051..efe1c852 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -45,6 +45,7 @@ #include "chrome/browser/net/stub_resolver_config_reader.h" #include "chrome/browser/net/system_network_context_manager.h" #include "chrome/browser/notifications/scheduler/public/features.h" +#include "chrome/browser/page_info/page_info_features.h" #include "chrome/browser/permissions/notifications_permission_revocation_config.h" #include "chrome/browser/permissions/quiet_notification_permission_ui_config.h" #include "chrome/browser/predictors/loading_predictor_config.h" @@ -7464,11 +7465,13 @@ FEATURE_VALUE_TYPE( page_info::kPageInfoAboutThisSiteDescriptionPlaceholder)}, +#if !BUILDFLAG(IS_ANDROID) {"page-info-about-this-page-persistent-side-panel-entry", flag_descriptions::kPageInfoboutThisPagePersistentEntryName, flag_descriptions::kPageInfoboutThisPagePersistentEntryDescription, kOsDesktop, FEATURE_VALUE_TYPE(page_info::kAboutThisSitePersistentSidePanelEntry)}, +#endif #if BUILDFLAG(IS_CHROMEOS_ASH) {kClipboardHistoryReorderInternalName, @@ -9205,9 +9208,17 @@ #endif // BUILDFLAG(IS_ANDROID) #if !BUILDFLAG(IS_ANDROID) - {"safety-check-permissions", flag_descriptions::kSafetyCheckPermissionsName, - flag_descriptions::kSafetyCheckPermissionsDescription, kOsDesktop, - FEATURE_VALUE_TYPE(features::kSafetyCheckPermissions)}, + {"safety-check-notification-permissions", + flag_descriptions::kSafetyCheckNotificationPermissionsName, + flag_descriptions::kSafetyCheckNotificationPermissionsDescription, + kOsDesktop, + FEATURE_VALUE_TYPE(features::kSafetyCheckNotificationPermissions)}, + + {"safety-check-unused-site-permissions", + flag_descriptions::kSafetyCheckUnusedSitePermissionsName, + flag_descriptions::kSafetyCheckUnusedSitePermissionsDescription, + kOsDesktop, + FEATURE_VALUE_TYPE(features::kSafetyCheckUnusedSitePermissions)}, #endif // !BUILDFLAG(IS_ANDROID) #if BUILDFLAG(IS_ANDROID)
diff --git a/chrome/browser/ash/arc/input_overlay/arc_input_overlay_manager.cc b/chrome/browser/ash/arc/input_overlay/arc_input_overlay_manager.cc index d6256f2..c6d4630 100644 --- a/chrome/browser/ash/arc/input_overlay/arc_input_overlay_manager.cc +++ b/chrome/browser/ash/arc/input_overlay/arc_input_overlay_manager.cc
@@ -112,46 +112,53 @@ void ArcInputOverlayManager::ReadData(const std::string& package_name, aura::Window* top_level_window) { + auto touch_injector = std::make_unique<input_overlay::TouchInjector>( + top_level_window, + base::BindRepeating(&ArcInputOverlayManager::OnSaveProtoFile, + weak_ptr_factory_.GetWeakPtr())); + loading_data_windows_.insert(top_level_window); + task_runner_->PostTaskAndReplyWithResult( FROM_HERE, base::BindOnce(&ArcInputOverlayManager::ReadDefaultData, Unretained(this), - package_name, top_level_window), + package_name, std::move(touch_injector)), base::BindOnce(&ArcInputOverlayManager::ReadCustomizedData, Unretained(this), package_name)); } -input_overlay::TouchInjector* ArcInputOverlayManager::ReadDefaultData( +std::unique_ptr<input_overlay::TouchInjector> +ArcInputOverlayManager::ReadDefaultData( const std::string& package_name, - aura::Window* top_level_window) { + std::unique_ptr<input_overlay::TouchInjector> touch_injector) { + DCHECK(touch_injector); + auto resource_id = GetInputOverlayResourceId(package_name); - if (!resource_id) + if (!resource_id) { + ResetForPendingTouchInjector(std::move(touch_injector)); return nullptr; + } auto json_file = ui::ResourceBundle::GetSharedInstance().GetRawDataResource( resource_id.value()); if (json_file.empty()) { LOG(WARNING) << "No content for: " << package_name; + ResetForPendingTouchInjector(std::move(touch_injector)); return nullptr; } auto result = base::JSONReader::ReadAndReturnValueWithError(json_file); DCHECK(result.has_value()) << "Could not load input overlay data file: " << result.error().message; - if (!result.has_value()) + if (!result.has_value()) { + ResetForPendingTouchInjector(std::move(touch_injector)); return nullptr; + } - auto injector = std::make_unique<input_overlay::TouchInjector>( - top_level_window, - base::BindRepeating(&ArcInputOverlayManager::OnSaveProtoFile, - weak_ptr_factory_.GetWeakPtr())); - injector->ParseActions(*result); - auto res = input_overlay_enabled_windows_.emplace(top_level_window, - std::move(injector)); - DCHECK(res.second); - return res.first->second.get(); + touch_injector->ParseActions(*result); + return touch_injector; } void ArcInputOverlayManager::ReadCustomizedData( const std::string& package_name, - input_overlay::TouchInjector* touch_injector) { + std::unique_ptr<input_overlay::TouchInjector> touch_injector) { if (!touch_injector) return; @@ -160,7 +167,7 @@ base::BindOnce(&ArcInputOverlayManager::GetProto, Unretained(this), package_name), base::BindOnce(&ArcInputOverlayManager::OnProtoDataAvailable, - Unretained(this), touch_injector)); + Unretained(this), std::move(touch_injector))); } std::unique_ptr<input_overlay::AppDataProto> ArcInputOverlayManager::GetProto( @@ -171,16 +178,29 @@ } void ArcInputOverlayManager::OnProtoDataAvailable( - input_overlay::TouchInjector* touch_injector, + std::unique_ptr<input_overlay::TouchInjector> touch_injector, std::unique_ptr<input_overlay::AppDataProto> proto) { + DCHECK(touch_injector); + if (proto) { touch_injector->OnProtoDataAvailable(*proto); } else { touch_injector->NotifyFirstTimeLaunch(); } - touch_injector->set_data_reading_finished(true); + auto* window = touch_injector->window(); + DCHECK(window); + // Check if |window| is destroyed or destroying when calling this function. + if (!loading_data_windows_.contains(window) || window->is_destroying()) { + ResetForPendingTouchInjector(std::move(touch_injector)); + return; + } + touch_injector->RecordMenuStateOnLaunch(); + // Now we can safely add <*window, touch_injector> in + // |input_overlay_enabled_windows_|. + input_overlay_enabled_windows_.emplace(window, std::move(touch_injector)); + loading_data_windows_.erase(window); RegisterFocusedWindow(); } @@ -236,12 +256,6 @@ auto it = input_overlay_enabled_windows_.find(window); if (it == input_overlay_enabled_windows_.end()) return; - DCHECK(!registered_top_level_window_); - // Don't register window if the data reading is not finished. It still will be - // registered after data reading finished by |RegisterFocusedWindow|. - if (!it->second->data_reading_finished()) - return; - it->second->RegisterEventRewriter(); registered_top_level_window_ = window; AddObserverToInputMethod(); @@ -330,6 +344,7 @@ window_observations_.RemoveObservation(window); UnRegisterWindow(window); input_overlay_enabled_windows_.erase(window); + loading_data_windows_.erase(window); } void ArcInputOverlayManager::OnWindowAddedToRootWindow(aura::Window* window) { @@ -428,4 +443,10 @@ it->second->UpdateForDisplayMetricsChanged(); } +void ArcInputOverlayManager::ResetForPendingTouchInjector( + std::unique_ptr<input_overlay::TouchInjector> touch_injector) { + loading_data_windows_.erase(touch_injector->window()); + touch_injector.reset(); +} + } // namespace arc
diff --git a/chrome/browser/ash/arc/input_overlay/arc_input_overlay_manager.h b/chrome/browser/ash/arc/input_overlay/arc_input_overlay_manager.h index 3986286..9a95f875 100644 --- a/chrome/browser/ash/arc/input_overlay/arc_input_overlay_manager.h +++ b/chrome/browser/ash/arc/input_overlay/arc_input_overlay_manager.h
@@ -96,6 +96,11 @@ window_observations_{this}; base::flat_map<aura::Window*, std::unique_ptr<input_overlay::TouchInjector>> input_overlay_enabled_windows_; + // To avoid UAF issue reported in crbug.com/1363030. Save the windows which + // prepare or start loading the GIO default key mapping data. Once window is + // destroying or the GIO data reading is finished, window is removed from this + // set. + base::flat_set<aura::Window*> loading_data_windows_; bool is_text_input_active_ = false; raw_ptr<ui::InputMethod> input_method_ = nullptr; std::unique_ptr<InputMethodObserver> input_method_observer_; @@ -112,18 +117,21 @@ void ReadData(const std::string& package_name, aura::Window* top_level_window); // Read default data. - input_overlay::TouchInjector* ReadDefaultData(const std::string& package_name, - aura::Window* top_level_window); + std::unique_ptr<input_overlay::TouchInjector> ReadDefaultData( + const std::string& package_name, + std::unique_ptr<input_overlay::TouchInjector> touch_injector); // Read customized data. Customized data will overrides the default data if // there is any. - void ReadCustomizedData(const std::string& package_name, - input_overlay::TouchInjector* touch_injector); + void ReadCustomizedData( + const std::string& package_name, + std::unique_ptr<input_overlay::TouchInjector> touch_injector); // Get the Proto object from customized data. std::unique_ptr<input_overlay::AppDataProto> GetProto( const std::string& package_name); // Apply the customized proto data. - void OnProtoDataAvailable(input_overlay::TouchInjector* touch_injector, - std::unique_ptr<input_overlay::AppDataProto> proto); + void OnProtoDataAvailable( + std::unique_ptr<input_overlay::TouchInjector> touch_injector, + std::unique_ptr<input_overlay::AppDataProto> proto); // Callback function triggered by Save button. void OnSaveProtoFile(std::unique_ptr<input_overlay::AppDataProto> proto, const std::string& package_name); @@ -140,6 +148,10 @@ void AddDisplayOverlayController( input_overlay::TouchInjector* touch_injector); void RemoveDisplayOverlayController(); + // Reset for removing pending |touch_injector| because of no GIO data or + // window destroying. + void ResetForPendingTouchInjector( + std::unique_ptr<input_overlay::TouchInjector> touch_injector); base::WeakPtrFactory<ArcInputOverlayManager> weak_ptr_factory_{this}; };
diff --git a/chrome/browser/ash/arc/input_overlay/arc_input_overlay_manager_unittest.cc b/chrome/browser/ash/arc/input_overlay/arc_input_overlay_manager_unittest.cc index 51d3c8d..05b9f52b 100644 --- a/chrome/browser/ash/arc/input_overlay/arc_input_overlay_manager_unittest.cc +++ b/chrome/browser/ash/arc/input_overlay/arc_input_overlay_manager_unittest.cc
@@ -129,6 +129,22 @@ EXPECT_FALSE(IsInputOverlayEnabled(arc_window_no_data->GetWindow())); } +TEST_F(ArcInputOverlayManagerTest, TestWindowDestroyNoWait) { + // This test is to check UAF issue reported in crbug.com/1363030. + auto arc_window = std::make_unique<input_overlay::test::ArcTestWindow>( + exo_test_helper(), ash::Shell::GetPrimaryRootWindow(), + kEnabledPackageName); + const auto* arc_window_ptr = arc_window->GetWindow(); + + // Destroy window before finishing I/O reading. The window can't be destroyed + // during ReadDefaultData(), but it can be destroyed before + // ReadCustomizedData() and TouchInjector.RecordMenuStateOnLaunch() would + // catch it. + arc_window.reset(); + task_environment()->FastForwardBy(kIORead); + EXPECT_FALSE(IsInputOverlayEnabled(arc_window_ptr)); +} + TEST_F(ArcInputOverlayManagerTest, TestInputMethodObsever) { ASSERT_FALSE(GetInputMethod()); ASSERT_FALSE(IsTextInputActive());
diff --git a/chrome/browser/ash/arc/input_overlay/display_overlay_controller_unittest.cc b/chrome/browser/ash/arc/input_overlay/display_overlay_controller_unittest.cc index 2426751..47fdbca 100644 --- a/chrome/browser/ash/arc/input_overlay/display_overlay_controller_unittest.cc +++ b/chrome/browser/ash/arc/input_overlay/display_overlay_controller_unittest.cc
@@ -28,14 +28,14 @@ } protected: - std::unique_ptr<input_overlay::test::ArcTestWindow> arc_test_window_; + std::unique_ptr<test::ArcTestWindow> arc_test_window_; std::unique_ptr<DisplayOverlayController> controller_; std::unique_ptr<TouchInjector> injector_; private: void SetUp() override { exo::test::ExoTestBase::SetUp(); - arc_test_window_ = std::make_unique<input_overlay::test::ArcTestWindow>( + arc_test_window_ = std::make_unique<test::ArcTestWindow>( exo_test_helper(), ash::Shell::GetPrimaryRootWindow(), "org.chromium.arc.testapp.inputoverlay"); injector_ = std::make_unique<TouchInjector>(
diff --git a/chrome/browser/ash/arc/input_overlay/touch_injector.h b/chrome/browser/ash/arc/input_overlay/touch_injector.h index 613f6a5..7b2e7d37 100644 --- a/chrome/browser/ash/arc/input_overlay/touch_injector.h +++ b/chrome/browser/ash/arc/input_overlay/touch_injector.h
@@ -76,11 +76,6 @@ bool show_nudge() const { return show_nudge_; } void set_show_nudge(bool show_nudge) { show_nudge_ = show_nudge; } - bool data_reading_finished() const { return data_reading_finished_; } - void set_data_reading_finished(bool finished) { - data_reading_finished_ = finished; - } - void set_display_mode(DisplayMode mode) { display_mode_ = mode; } void set_display_overlay_controller(DisplayOverlayController* controller) { display_overlay_controller_ = controller; @@ -260,8 +255,6 @@ // Check whether to show the nudge view. We only show the nudge view for the // first time launch and before it is dismissed. bool show_nudge_ = false; - // Data reading is finished after launching if the value is true. - bool data_reading_finished_ = false; // Key is the original touch id. Value is a struct containing required info // for this touch event.
diff --git a/chrome/browser/ash/arc/input_overlay/touch_injector_unittest.cc b/chrome/browser/ash/arc/input_overlay/touch_injector_unittest.cc index 53b5442..9cd42b5 100644 --- a/chrome/browser/ash/arc/input_overlay/touch_injector_unittest.cc +++ b/chrome/browser/ash/arc/input_overlay/touch_injector_unittest.cc
@@ -248,7 +248,7 @@ aura::Window* root_window() { return GetContext(); } - input_overlay::test::EventCapturer event_capturer_; + test::EventCapturer event_capturer_; std::unique_ptr<ui::test::EventGenerator> event_generator_; std::unique_ptr<views::Widget> widget_; @@ -586,7 +586,7 @@ event_generator_->PressKey(ui::VKEY_A, ui::EF_NONE, 1 /* keyboard id */); EXPECT_TRUE(*(action->touch_id()) == 0); EXPECT_TRUE(event_capturer_.key_events().empty()); - task_environment()->FastForwardBy(input_overlay::kSendTouchMoveDelay); + task_environment()->FastForwardBy(kSendTouchMoveDelay); EXPECT_TRUE((int)event_capturer_.touch_events().size() == 2); // Generate touch down event. event = event_capturer_.touch_events()[0].get(); @@ -617,8 +617,7 @@ EXPECT_TRUE(hover_binding->mouse_types().contains(ui::ET_MOUSE_EXITED)); EXPECT_EQ(0, hover_binding->mouse_flags()); - auto* right_action = - static_cast<input_overlay::ActionMove*>(injector_->actions()[1].get()); + auto* right_action = static_cast<ActionMove*>(injector_->actions()[1].get()); auto* right_binding = right_action->current_input(); EXPECT_EQ(right_binding->mouse_action(), MouseAction::SECONDARY_DRAG_MOVE); EXPECT_TRUE(right_binding->mouse_types().contains(ui::ET_MOUSE_PRESSED));
diff --git a/chrome/browser/ash/attestation/enrollment_certificate_uploader_impl.cc b/chrome/browser/ash/attestation/enrollment_certificate_uploader_impl.cc index 4971563f..f49cf1d4 100644 --- a/chrome/browser/ash/attestation/enrollment_certificate_uploader_impl.cc +++ b/chrome/browser/ash/attestation/enrollment_certificate_uploader_impl.cc
@@ -103,7 +103,7 @@ PROFILE_ENTERPRISE_ENROLLMENT_CERTIFICATE, EmptyAccountId(), // Not used. std::string(), // Not used. - force_new_key, ::attestation::KEY_TYPE_RSA, + force_new_key, ::attestation::KEY_TYPE_ECC, std::string(), // Leave key name empty to generate a default name. base::BindOnce( [](const base::RepeatingCallback<void(const std::string&)> on_success,
diff --git a/chrome/browser/ash/hats/hats_config.cc b/chrome/browser/ash/hats/hats_config.cc index d184c05..7e2d854 100644 --- a/chrome/browser/ash/hats/hats_config.cc +++ b/chrome/browser/ash/hats/hats_config.cc
@@ -177,4 +177,14 @@ prefs::kHatsPhotosExperienceCycleEndTs, // hatsCycleEndTimestampPrefName }; +// General Camera Survey -- shown after camera is closed after being open for +// at least 3 minutes by using any app (e.g. Chrome or Android app). +const HatsConfig kHatsGeneralCameraSurvey = { + ::features::kHappinessTrackingGeneralCamera, // feature + "Browser.ChromeOS.HatsSatisfaction.GeneralCamera", // histogram_name + base::Days(90), // new_device_threshold + prefs::kHatsGeneralCameraIsSelected, // is_selected_pref_name + prefs::kHatsGeneralCameraSurveyCycleEndTs, // cycle_end_timestamp_pref_name +}; + } // namespace ash
diff --git a/chrome/browser/ash/hats/hats_config.h b/chrome/browser/ash/hats/hats_config.h index 1ace434..e01d4e5f 100644 --- a/chrome/browser/ash/hats/hats_config.h +++ b/chrome/browser/ash/hats/hats_config.h
@@ -56,6 +56,7 @@ extern const HatsConfig kHatsMediaAppPdfSurvey; extern const HatsConfig kHatsCameraAppSurvey; extern const HatsConfig kHatsPhotosExperienceSurvey; +extern const HatsConfig kHatsGeneralCameraSurvey; } // namespace ash
diff --git a/chrome/browser/ash/policy/enrollment/enrollment_handler.cc b/chrome/browser/ash/policy/enrollment/enrollment_handler.cc index 1d5db06..cf58ced6 100644 --- a/chrome/browser/ash/policy/enrollment/enrollment_handler.cc +++ b/chrome/browser/ash/policy/enrollment/enrollment_handler.cc
@@ -520,7 +520,7 @@ attestation_flow_->GetCertificate( ash::attestation::PROFILE_ENTERPRISE_ENROLLMENT_CERTIFICATE, EmptyAccountId(), /*request_origin=*/std::string(), force_new_key, - ::attestation::KEY_TYPE_RSA, /*=key_name=*/std::string(), + ::attestation::KEY_TYPE_ECC, /*=key_name=*/std::string(), std::move(callback)); }
diff --git a/chrome/browser/ash/preferences.cc b/chrome/browser/ash/preferences.cc index 34253d8..79c5139 100644 --- a/chrome/browser/ash/preferences.cc +++ b/chrome/browser/ash/preferences.cc
@@ -447,6 +447,10 @@ registry->RegisterBooleanPref(::prefs::kHatsCameraAppDeviceIsSelected, false); + registry->RegisterInt64Pref(::prefs::kHatsGeneralCameraSurveyCycleEndTs, 0); + + registry->RegisterBooleanPref(::prefs::kHatsGeneralCameraIsSelected, false); + // Personalization HaTS survey prefs for avatar, screensaver, and wallpaper // features. registry->RegisterInt64Pref(
diff --git a/chrome/browser/ash/telemetry_extension/diagnostics_service_ash.cc b/chrome/browser/ash/telemetry_extension/diagnostics_service_ash.cc index 692df7c..92c298d 100644 --- a/chrome/browser/ash/telemetry_extension/diagnostics_service_ash.cc +++ b/chrome/browser/ash/telemetry_extension/diagnostics_service_ash.cc
@@ -311,4 +311,28 @@ std::move(callback))); } +void DiagnosticsServiceAsh::RunDnsResolutionRoutine( + RunDnsResolutionRoutineCallback callback) { + GetService()->RunDnsResolutionRoutine(base::BindOnce( + [](crosapi::mojom::DiagnosticsService::RunDnsResolutionRoutineCallback + callback, + cros_healthd::mojom::RunRoutineResponsePtr ptr) { + std::move(callback).Run( + converters::ConvertDiagnosticsPtr(std::move(ptr))); + }, + std::move(callback))); +} + +void DiagnosticsServiceAsh::RunSignalStrengthRoutine( + RunSignalStrengthRoutineCallback callback) { + GetService()->RunSignalStrengthRoutine(base::BindOnce( + [](crosapi::mojom::DiagnosticsService::RunSignalStrengthRoutineCallback + callback, + cros_healthd::mojom::RunRoutineResponsePtr ptr) { + std::move(callback).Run( + converters::ConvertDiagnosticsPtr(std::move(ptr))); + }, + std::move(callback))); +} + } // namespace ash
diff --git a/chrome/browser/ash/telemetry_extension/diagnostics_service_ash.h b/chrome/browser/ash/telemetry_extension/diagnostics_service_ash.h index 58947d8..dcfe95af 100644 --- a/chrome/browser/ash/telemetry_extension/diagnostics_service_ash.h +++ b/chrome/browser/ash/telemetry_extension/diagnostics_service_ash.h
@@ -95,6 +95,10 @@ void RunMemoryRoutine(RunMemoryRoutineCallback callback) override; void RunLanConnectivityRoutine( RunLanConnectivityRoutineCallback callback) override; + void RunDnsResolutionRoutine( + RunDnsResolutionRoutineCallback callback) override; + void RunSignalStrengthRoutine( + RunSignalStrengthRoutineCallback callback) override; // Pointer to real implementation. mojo::Remote<cros_healthd::mojom::CrosHealthdDiagnosticsService> service_;
diff --git a/chrome/browser/ash/telemetry_extension/diagnostics_service_converters.cc b/chrome/browser/ash/telemetry_extension/diagnostics_service_converters.cc index 7e3720de..cb805a021 100644 --- a/chrome/browser/ash/telemetry_extension/diagnostics_service_converters.cc +++ b/chrome/browser/ash/telemetry_extension/diagnostics_service_converters.cc
@@ -101,6 +101,10 @@ return crosapi::mojom::DiagnosticsRoutineEnum::kMemory; case cros_healthd::mojom::DiagnosticRoutineEnum::kLanConnectivity: return crosapi::mojom::DiagnosticsRoutineEnum::kLanConnectivity; + case cros_healthd::mojom::DiagnosticRoutineEnum::kDnsResolution: + return crosapi::mojom::DiagnosticsRoutineEnum::kDnsResolution; + case cros_healthd::mojom::DiagnosticRoutineEnum::kSignalStrength: + return crosapi::mojom::DiagnosticsRoutineEnum::kSignalStrength; default: return absl::nullopt; }
diff --git a/chrome/browser/chromeos/extensions/telemetry/api/base_telemetry_extension_api_guard_function_browsertest.cc b/chrome/browser/chromeos/extensions/telemetry/api/base_telemetry_extension_api_guard_function_browsertest.cc index eab7033..cca2213 100644 --- a/chrome/browser/chromeos/extensions/telemetry/api/base_telemetry_extension_api_guard_function_browsertest.cc +++ b/chrome/browser/chromeos/extensions/telemetry/api/base_telemetry_extension_api_guard_function_browsertest.cc
@@ -262,6 +262,15 @@ ); chrome.test.succeed(); }, + async function runDnsResolutionRoutine() { + await chrome.test.assertPromiseRejects( + chrome.os.diagnostics.runDnsResolutionRoutine(), + 'Error: Unauthorized access to ' + + 'chrome.os.diagnostics.runDnsResolutionRoutine. ' + + '%s' + ); + chrome.test.succeed(); + }, async function runLanConnectivityRoutine() { await chrome.test.assertPromiseRejects( chrome.os.diagnostics.runLanConnectivityRoutine(), @@ -293,6 +302,15 @@ ); chrome.test.succeed(); }, + async function runSignalStrengthRoutine() { + await chrome.test.assertPromiseRejects( + chrome.os.diagnostics.runSignalStrengthRoutine(), + 'Error: Unauthorized access to ' + + 'chrome.os.diagnostics.runSignalStrengthRoutine. ' + + '%s' + ); + chrome.test.succeed(); + }, async function runSmartctlCheckRoutine() { await chrome.test.assertPromiseRejects( chrome.os.diagnostics.runSmartctlCheckRoutine(),
diff --git a/chrome/browser/chromeos/extensions/telemetry/api/diagnostics_api.cc b/chrome/browser/chromeos/extensions/telemetry/api/diagnostics_api.cc index 53ce05a..acf68d0 100644 --- a/chrome/browser/chromeos/extensions/telemetry/api/diagnostics_api.cc +++ b/chrome/browser/chromeos/extensions/telemetry/api/diagnostics_api.cc
@@ -373,6 +373,20 @@ std::move(cb)); } +// OsDiagnosticsRunDnsResolutionRoutineFunction -------------------------------- + +OsDiagnosticsRunDnsResolutionRoutineFunction:: + OsDiagnosticsRunDnsResolutionRoutineFunction() = default; +OsDiagnosticsRunDnsResolutionRoutineFunction:: + ~OsDiagnosticsRunDnsResolutionRoutineFunction() = default; + +void OsDiagnosticsRunDnsResolutionRoutineFunction::RunIfAllowed() { + auto cb = + base::BindOnce(&DiagnosticsApiRunRoutineFunctionBase::OnResult, this); + + GetRemoteService()->RunDnsResolutionRoutine(std::move(cb)); +} + // OsDiagnosticsRunLanConnectivityRoutineFunction ------------------------------ OsDiagnosticsRunLanConnectivityRoutineFunction:: @@ -424,6 +438,20 @@ params->request.wear_level_threshold, std::move(cb)); } +// OsDiagnosticsRunSignalStrengthRoutineFunction ------------------------------- + +OsDiagnosticsRunSignalStrengthRoutineFunction:: + OsDiagnosticsRunSignalStrengthRoutineFunction() = default; +OsDiagnosticsRunSignalStrengthRoutineFunction:: + ~OsDiagnosticsRunSignalStrengthRoutineFunction() = default; + +void OsDiagnosticsRunSignalStrengthRoutineFunction::RunIfAllowed() { + auto cb = + base::BindOnce(&DiagnosticsApiRunRoutineFunctionBase::OnResult, this); + + GetRemoteService()->RunSignalStrengthRoutine(std::move(cb)); +} + // OsDiagnosticsRunSmartctlCheckRoutineFunction -------------------------------- OsDiagnosticsRunSmartctlCheckRoutineFunction::
diff --git a/chrome/browser/chromeos/extensions/telemetry/api/diagnostics_api.h b/chrome/browser/chromeos/extensions/telemetry/api/diagnostics_api.h index 399e2d79..0e45a5d 100644 --- a/chrome/browser/chromeos/extensions/telemetry/api/diagnostics_api.h +++ b/chrome/browser/chromeos/extensions/telemetry/api/diagnostics_api.h
@@ -289,6 +289,25 @@ void RunIfAllowed() override; }; +class OsDiagnosticsRunDnsResolutionRoutineFunction + : public DiagnosticsApiRunRoutineFunctionBase { + public: + DECLARE_EXTENSION_FUNCTION("os.diagnostics.runDnsResolutionRoutine", + OS_DIAGNOSTICS_RUNDNSRESOLUTIONROUTINE) + + OsDiagnosticsRunDnsResolutionRoutineFunction(); + OsDiagnosticsRunDnsResolutionRoutineFunction( + const OsDiagnosticsRunDnsResolutionRoutineFunction&) = delete; + OsDiagnosticsRunDnsResolutionRoutineFunction& operator=( + const OsDiagnosticsRunDnsResolutionRoutineFunction&) = delete; + + private: + ~OsDiagnosticsRunDnsResolutionRoutineFunction() override; + + // BaseTelemetryExtensionApiGuardFunction: + void RunIfAllowed() override; +}; + class OsDiagnosticsRunLanConnectivityRoutineFunction : public DiagnosticsApiRunRoutineFunctionBase { public: @@ -346,6 +365,25 @@ void RunIfAllowed() override; }; +class OsDiagnosticsRunSignalStrengthRoutineFunction + : public DiagnosticsApiRunRoutineFunctionBase { + public: + DECLARE_EXTENSION_FUNCTION("os.diagnostics.runSignalStrengthRoutine", + OS_DIAGNOSTICS_RUNSIGNALSTRENGTHROUTINE) + + OsDiagnosticsRunSignalStrengthRoutineFunction(); + OsDiagnosticsRunSignalStrengthRoutineFunction( + const OsDiagnosticsRunSignalStrengthRoutineFunction&) = delete; + OsDiagnosticsRunSignalStrengthRoutineFunction& operator=( + const OsDiagnosticsRunSignalStrengthRoutineFunction&) = delete; + + private: + ~OsDiagnosticsRunSignalStrengthRoutineFunction() override; + + // BaseTelemetryExtensionApiGuardFunction: + void RunIfAllowed() override; +}; + class OsDiagnosticsRunSmartctlCheckRoutineFunction : public DiagnosticsApiRunRoutineFunctionBase { public:
diff --git a/chrome/browser/chromeos/extensions/telemetry/api/diagnostics_api_browsertest.cc b/chrome/browser/chromeos/extensions/telemetry/api/diagnostics_api_browsertest.cc index 7a3d1c02..cecc267 100644 --- a/chrome/browser/chromeos/extensions/telemetry/api/diagnostics_api_browsertest.cc +++ b/chrome/browser/chromeos/extensions/telemetry/api/diagnostics_api_browsertest.cc
@@ -10,6 +10,7 @@ #include "build/chromeos_buildflags.h" #include "chrome/browser/chromeos/extensions/telemetry/api/base_telemetry_extension_browser_test.h" #include "chrome/browser/chromeos/extensions/telemetry/api/fake_diagnostics_service.h" +#include "chromeos/crosapi/mojom/diagnostics_service.mojom.h" #include "content/public/test/browser_test.h" #include "testing/gtest/include/gtest/gtest.h" @@ -19,7 +20,6 @@ #endif // BUILDFLAG(IS_CHROMEOS_ASH) #if BUILDFLAG(IS_CHROMEOS_LACROS) -#include "chromeos/crosapi/mojom/diagnostics_service.mojom.h" #include "chromeos/lacros/lacros_service.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #endif // BUILDFLAG(IS_CHROMEOS_LACROS) @@ -232,6 +232,14 @@ ); chrome.test.succeed(); }, + async function runDnsResolutionRoutine() { + await chrome.test.assertPromiseRejects( + chrome.os.diagnostics.runDnsResolutionRoutine(), + 'Error: API chrome.os.diagnostics.runDnsResolutionRoutine ' + + 'failed. Not supported by ash browser' + ); + chrome.test.succeed(); + }, async function runLanConnectivityRoutine() { await chrome.test.assertPromiseRejects( chrome.os.diagnostics.runLanConnectivityRoutine(), @@ -260,6 +268,14 @@ ); chrome.test.succeed(); }, + async function runSignalStrengthRoutine() { + await chrome.test.assertPromiseRejects( + chrome.os.diagnostics.runSignalStrengthRoutine(), + 'Error: API chrome.os.diagnostics.runSignalStrengthRoutine ' + + 'failed. Not supported by ash browser' + ); + chrome.test.succeed(); + }, async function runSmartctlCheckRoutine() { await chrome.test.assertPromiseRejects( chrome.os.diagnostics.runSmartctlCheckRoutine(), @@ -316,9 +332,11 @@ crosapi::mojom::DiagnosticsRoutineEnum::kPrimeSearch, crosapi::mojom::DiagnosticsRoutineEnum::kCpuStress, crosapi::mojom::DiagnosticsRoutineEnum::kDiskRead, + crosapi::mojom::DiagnosticsRoutineEnum::kDnsResolution, crosapi::mojom::DiagnosticsRoutineEnum::kLanConnectivity, crosapi::mojom::DiagnosticsRoutineEnum::kMemory, crosapi::mojom::DiagnosticsRoutineEnum::kNvmeWearLevel, + crosapi::mojom::DiagnosticsRoutineEnum::kSignalStrength, crosapi::mojom::DiagnosticsRoutineEnum::kSmartctlCheck, }); @@ -343,9 +361,11 @@ "cpu_prime_search", "cpu_stress", "disk_read", + "dns_resolution", "lan_connectivity", "memory", "nvme_wear_level", + "signal_strength", "smartctl_check" ] }, response); @@ -990,6 +1010,46 @@ } IN_PROC_BROWSER_TEST_F(TelemetryExtensionDiagnosticsApiBrowserTest, + RunDnsResolutionRoutineSuccess) { +#if BUILDFLAG(IS_CHROMEOS_LACROS) + // If Diagnostics interface is not available on this version of ash-chrome, + // this test suite will no-op. + if (!IsServiceAvailable()) { + return; + } +#endif // BUILDFLAG(IS_CHROMEOS_LACROS) + + // Configure FakeDiagnosticsService. + { + auto expected_response = + crosapi::mojom::DiagnosticsRunRoutineResponse::New(); + expected_response->id = 0; + expected_response->status = + crosapi::mojom::DiagnosticsRoutineStatusEnum::kReady; + + // Set the return value for a call to RunDiskReadRoutine. + auto fake_service_impl = std::make_unique<FakeDiagnosticsService>(); + fake_service_impl->SetRunRoutineResponse(std::move(expected_response)); + + fake_service_impl->SetExpectedLastCalledRoutine( + crosapi::mojom::DiagnosticsRoutineEnum::kDnsResolution); + + SetServiceForTesting(std::move(fake_service_impl)); + } + + CreateExtensionAndRunServiceWorker(R"( + chrome.test.runTests([ + async function runDnsResolutionRoutine() { + const response = + await chrome.os.diagnostics.runDnsResolutionRoutine(); + chrome.test.assertEq({id: 0, status: "ready"}, response); + chrome.test.succeed(); + } + ]); + )"); +} + +IN_PROC_BROWSER_TEST_F(TelemetryExtensionDiagnosticsApiBrowserTest, RunLanConnectivityRoutineSuccess) { #if BUILDFLAG(IS_CHROMEOS_LACROS) // If Diagnostics interface is not available on this version of ash-chrome, @@ -1122,6 +1182,47 @@ } IN_PROC_BROWSER_TEST_F(TelemetryExtensionDiagnosticsApiBrowserTest, + RunSignalStrengthRoutineSuccess) { +#if BUILDFLAG(IS_CHROMEOS_LACROS) + // If Diagnostics interface is not available on this version of ash-chrome, + // this test suite will no-op. + if (!IsServiceAvailable()) { + return; + } +#endif // BUILDFLAG(IS_CHROMEOS_LACROS) + + // Configure FakeDiagnosticsService. + { + auto expected_response = + crosapi::mojom::DiagnosticsRunRoutineResponse::New(); + expected_response->id = 0; + expected_response->status = + crosapi::mojom::DiagnosticsRoutineStatusEnum::kReady; + + // Set the return value for a call to RunSmartctlCheckRoutine. + auto fake_service_impl = std::make_unique<FakeDiagnosticsService>(); + fake_service_impl->SetRunRoutineResponse(std::move(expected_response)); + + // Set the expected called routine. + fake_service_impl->SetExpectedLastCalledRoutine( + crosapi::mojom::DiagnosticsRoutineEnum::kSignalStrength); + + SetServiceForTesting(std::move(fake_service_impl)); + } + + CreateExtensionAndRunServiceWorker(R"( + chrome.test.runTests([ + async function runSignalStrengthRoutine() { + const response = + await chrome.os.diagnostics.runSignalStrengthRoutine(); + chrome.test.assertEq({id: 0, status: "ready"}, response); + chrome.test.succeed(); + } + ]); + )"); +} + +IN_PROC_BROWSER_TEST_F(TelemetryExtensionDiagnosticsApiBrowserTest, RunSmartctlCheckRoutineSuccess) { #if BUILDFLAG(IS_CHROMEOS_LACROS) // If Diagnostics interface is not available on this version of ash-chrome,
diff --git a/chrome/browser/chromeos/extensions/telemetry/api/diagnostics_api_converters.cc b/chrome/browser/chromeos/extensions/telemetry/api/diagnostics_api_converters.cc index 3226199..9ee07c5 100644 --- a/chrome/browser/chromeos/extensions/telemetry/api/diagnostics_api_converters.cc +++ b/chrome/browser/chromeos/extensions/telemetry/api/diagnostics_api_converters.cc
@@ -66,6 +66,9 @@ case MojoRoutineType::kDiskRead: *out = RoutineType::ROUTINE_TYPE_DISK_READ; return true; + case MojoRoutineType::kDnsResolution: + *out = RoutineType::ROUTINE_TYPE_DNS_RESOLUTION; + return true; case MojoRoutineType::kLanConnectivity: *out = RoutineType::ROUTINE_TYPE_LAN_CONNECTIVITY; return true; @@ -75,6 +78,9 @@ case MojoRoutineType::kNvmeWearLevel: *out = RoutineType::ROUTINE_TYPE_NVME_WEAR_LEVEL; return true; + case MojoRoutineType::kSignalStrength: + *out = RoutineType::ROUTINE_TYPE_SIGNAL_STRENGTH; + return true; case MojoRoutineType::kSmartctlCheck: *out = RoutineType::ROUTINE_TYPE_SMARTCTL_CHECK; return true;
diff --git a/chrome/browser/chromeos/extensions/telemetry/api/diagnostics_api_converters_unittest.cc b/chrome/browser/chromeos/extensions/telemetry/api/diagnostics_api_converters_unittest.cc index d196518..6ca403f5 100644 --- a/chrome/browser/chromeos/extensions/telemetry/api/diagnostics_api_converters_unittest.cc +++ b/chrome/browser/chromeos/extensions/telemetry/api/diagnostics_api_converters_unittest.cc
@@ -90,6 +90,11 @@ EXPECT_EQ(out, RoutineType::ROUTINE_TYPE_DISK_READ); } { + RoutineType out = RoutineType::ROUTINE_TYPE_NONE; + EXPECT_TRUE(ConvertMojoRoutine(MojoRoutineType::kDnsResolution, &out)); + EXPECT_EQ(out, RoutineType::ROUTINE_TYPE_DNS_RESOLUTION); + } + { RoutineType out; EXPECT_TRUE(ConvertMojoRoutine(MojoRoutineType::kMemory, &out)); EXPECT_EQ(out, RoutineType::ROUTINE_TYPE_MEMORY); @@ -101,6 +106,11 @@ } { RoutineType out = RoutineType::ROUTINE_TYPE_NONE; + EXPECT_TRUE(ConvertMojoRoutine(MojoRoutineType::kSignalStrength, &out)); + EXPECT_EQ(out, RoutineType::ROUTINE_TYPE_SIGNAL_STRENGTH); + } + { + RoutineType out = RoutineType::ROUTINE_TYPE_NONE; EXPECT_TRUE(ConvertMojoRoutine(MojoRoutineType::kSmartctlCheck, &out)); EXPECT_EQ(out, RoutineType::ROUTINE_TYPE_SMARTCTL_CHECK); }
diff --git a/chrome/browser/chromeos/extensions/telemetry/api/fake_diagnostics_service.cc b/chrome/browser/chromeos/extensions/telemetry/api/fake_diagnostics_service.cc index 16f0095d..85f4b42e 100644 --- a/chrome/browser/chromeos/extensions/telemetry/api/fake_diagnostics_service.cc +++ b/chrome/browser/chromeos/extensions/telemetry/api/fake_diagnostics_service.cc
@@ -12,6 +12,7 @@ #include "base/location.h" #include "base/threading/sequenced_task_runner_handle.h" #include "base/values.h" +#include "chromeos/crosapi/mojom/diagnostics_service.mojom-shared.h" #include "chromeos/crosapi/mojom/diagnostics_service.mojom.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "testing/gtest/include/gtest/gtest.h" @@ -266,6 +267,26 @@ base::BindOnce(std::move(callback), run_routine_response_->Clone())); } +void FakeDiagnosticsService::RunDnsResolutionRoutine( + RunDnsResolutionRoutineCallback callback) { + actual_passed_parameters_.clear(); + actual_called_routine_ = + crosapi::mojom::DiagnosticsRoutineEnum::kDnsResolution; + base::SequencedTaskRunnerHandle::Get()->PostTask( + FROM_HERE, + base::BindOnce(std::move(callback), run_routine_response_->Clone())); +} + +void FakeDiagnosticsService::RunSignalStrengthRoutine( + RunSignalStrengthRoutineCallback callback) { + actual_passed_parameters_.clear(); + actual_called_routine_ = + crosapi::mojom::DiagnosticsRoutineEnum::kSignalStrength; + base::SequencedTaskRunnerHandle::Get()->PostTask( + FROM_HERE, + base::BindOnce(std::move(callback), run_routine_response_->Clone())); +} + void FakeDiagnosticsService::SetRunRoutineResponse( crosapi::mojom::DiagnosticsRunRoutineResponsePtr response) { run_routine_response_ = std::move(response);
diff --git a/chrome/browser/chromeos/extensions/telemetry/api/fake_diagnostics_service.h b/chrome/browser/chromeos/extensions/telemetry/api/fake_diagnostics_service.h index 87edc01..092814c6 100644 --- a/chrome/browser/chromeos/extensions/telemetry/api/fake_diagnostics_service.h +++ b/chrome/browser/chromeos/extensions/telemetry/api/fake_diagnostics_service.h
@@ -73,6 +73,10 @@ void RunMemoryRoutine(RunMemoryRoutineCallback callback) override; void RunLanConnectivityRoutine( RunLanConnectivityRoutineCallback callback) override; + void RunDnsResolutionRoutine( + RunDnsResolutionRoutineCallback callback) override; + void RunSignalStrengthRoutine( + RunSignalStrengthRoutineCallback callback) override; // Sets the return value for |Run*Routine|. void SetRunRoutineResponse(
diff --git a/chrome/browser/download/internal/android/java/src/org/chromium/chrome/browser/download/DownloadMessageUiControllerImpl.java b/chrome/browser/download/internal/android/java/src/org/chromium/chrome/browser/download/DownloadMessageUiControllerImpl.java index 0ddef067..6b30884c1 100644 --- a/chrome/browser/download/internal/android/java/src/org/chromium/chrome/browser/download/DownloadMessageUiControllerImpl.java +++ b/chrome/browser/download/internal/android/java/src/org/chromium/chrome/browser/download/DownloadMessageUiControllerImpl.java
@@ -412,9 +412,13 @@ */ @Override public boolean isDownloadInterstitialItem(GURL originalUrl, String guid) { - if (mDownloadInterstitialSources.contains(originalUrl)) { + if (mDownloadInterstitialSources != null + && mDownloadInterstitialSources.contains(originalUrl)) { return true; } + if (mInterstitialItems == null) { + return false; + } for (ContentId id : mInterstitialItems) { if (id.id.equals(guid)) { mInterstitialItems.remove(id);
diff --git a/chrome/browser/feed/android/BUILD.gn b/chrome/browser/feed/android/BUILD.gn index 0e96b84..60d17919 100644 --- a/chrome/browser/feed/android/BUILD.gn +++ b/chrome/browser/feed/android/BUILD.gn
@@ -174,7 +174,6 @@ "java/res/drawable-v24/header_title_tab_selected_background.xml", "java/res/drawable-xhdpi/follow_accelerator_shadow.9.png", "java/res/drawable-xxhdpi/follow_accelerator_shadow.9.png", - "java/res/drawable/back_arrow.xml", "java/res/drawable/back_to_top_arrow.xml", "java/res/drawable/crow_icon.xml", "java/res/drawable/header_title_section_tab_background.xml",
diff --git a/chrome/browser/feed/android/java/res/drawable/back_arrow.xml b/chrome/browser/feed/android/java/res/drawable/back_arrow.xml deleted file mode 100644 index 4609c08..0000000 --- a/chrome/browser/feed/android/java/res/drawable/back_arrow.xml +++ /dev/null
@@ -1,18 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -Copyright 2022 The Chromium Authors -Use of this source code is governed by a BSD-style license that can be -found in the LICENSE file. ---> - -<vector xmlns:android="http://schemas.android.com/apk/res/android" - android:width="24dp" - android:height="24dp" - android:viewportWidth="24" - android:viewportHeight="24" - android:autoMirrored="true"> - <path - android:pathData="M20,11H7.83l5.59,-5.59L12,4l-8,8 8,8 1.41,-1.41L7.83,13H20v-2z" - android:fillColor="@color/baseline_neutral_700" - android:fillType="nonZero"/> -</vector>
diff --git a/chrome/browser/feed/android/java/src/org/chromium/chrome/browser/feed/feedmanagement/FeedManagementCoordinator.java b/chrome/browser/feed/android/java/src/org/chromium/chrome/browser/feed/feedmanagement/FeedManagementCoordinator.java index 3fcf399..85e1428 100644 --- a/chrome/browser/feed/android/java/src/org/chromium/chrome/browser/feed/feedmanagement/FeedManagementCoordinator.java +++ b/chrome/browser/feed/android/java/src/org/chromium/chrome/browser/feed/feedmanagement/FeedManagementCoordinator.java
@@ -10,7 +10,6 @@ import android.widget.ListView; import androidx.appcompat.app.AppCompatActivity; -import androidx.appcompat.widget.Toolbar; import org.chromium.chrome.browser.feed.R; import org.chromium.chrome.browser.feed.StreamKind; @@ -45,11 +44,6 @@ ListView listView = (ListView) mView.findViewById(R.id.feed_management_menu); listView.setAdapter(adapter); - // Set up the toolbar and back button. - Toolbar toolbar = (Toolbar) mView.findViewById(R.id.action_bar); - toolbar.setNavigationIcon(R.drawable.back_arrow); - toolbar.setNavigationOnClickListener(this::handleBackArrowClick); - mMediator = new FeedManagementMediator(mActivity, listItems, followManagementLauncher, autoplayManagementLauncher, feedType); } @@ -57,9 +51,4 @@ public View getView() { return mView; } - - private void handleBackArrowClick(View view) { - // Navigate back. - mActivity.finish(); - } }
diff --git a/chrome/browser/feed/android/java/src/org/chromium/chrome/browser/feed/feedmanagement/FeedManagementCoordinatorTest.java b/chrome/browser/feed/android/java/src/org/chromium/chrome/browser/feed/feedmanagement/FeedManagementCoordinatorTest.java index efbc21e..dfca2ac 100644 --- a/chrome/browser/feed/android/java/src/org/chromium/chrome/browser/feed/feedmanagement/FeedManagementCoordinatorTest.java +++ b/chrome/browser/feed/android/java/src/org/chromium/chrome/browser/feed/feedmanagement/FeedManagementCoordinatorTest.java
@@ -7,10 +7,6 @@ import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.verify; -import android.view.View; -import android.view.ViewGroup; - -import androidx.appcompat.widget.AppCompatImageButton; import androidx.test.ext.junit.rules.ActivityScenarioRule; import org.junit.Before; @@ -25,7 +21,6 @@ import org.chromium.chrome.browser.feed.FeedServiceBridge; import org.chromium.chrome.browser.feed.FeedServiceBridgeJni; import org.chromium.chrome.browser.feed.StreamKind; -import org.chromium.chrome.browser.feed.test.R; import org.chromium.ui.base.TestActivity; /** @@ -62,24 +57,4 @@ public void testConstruction() { assertTrue(true); } - - @Test - public void testBackArrow() { - View outerView = mFeedManagementCoordinator.getView(); - // Send a click to the back arrow. - // Note that finding the back arrow view is ugly because it doesn't - // have an ID. - boolean clicked = false; - ViewGroup actionBar = outerView.findViewById(R.id.action_bar); - for (int i = 0; i < actionBar.getChildCount(); i++) { - try { - AppCompatImageButton button = (AppCompatImageButton) actionBar.getChildAt(i); - button.performClick(); - clicked = true; - } catch (ClassCastException e) { - } - } - - assertTrue(clicked); - } }
diff --git a/chrome/browser/feed/android/java/src/org/chromium/chrome/browser/feed/followmanagement/FollowManagementCoordinator.java b/chrome/browser/feed/android/java/src/org/chromium/chrome/browser/feed/followmanagement/FollowManagementCoordinator.java index c35b371..9f6a0faa 100644 --- a/chrome/browser/feed/android/java/src/org/chromium/chrome/browser/feed/followmanagement/FollowManagementCoordinator.java +++ b/chrome/browser/feed/android/java/src/org/chromium/chrome/browser/feed/followmanagement/FollowManagementCoordinator.java
@@ -10,7 +10,6 @@ import android.widget.LinearLayout; import androidx.appcompat.app.AppCompatActivity; -import androidx.appcompat.widget.Toolbar; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; @@ -55,11 +54,6 @@ recyclerView.setLayoutManager(manager); recyclerView.setAdapter(adapter); - // Set up the toolbar and back button. - Toolbar toolbar = mView.findViewById(R.id.action_bar); - toolbar.setNavigationIcon(R.drawable.back_arrow); - toolbar.setNavigationOnClickListener(this::handleBackArrowClick); - mMediator = new FollowManagementMediator( activity, listItems, new MediatorObserver(), WebFeedFaviconFetcher.createDefault()); } @@ -68,11 +62,6 @@ return mView; } - private void handleBackArrowClick(View view) { - // Navigate back. - mActivity.finish(); - } - private class MediatorObserver implements FollowManagementMediator.Observer { @Override public void networkConnectionError() {
diff --git a/chrome/browser/feed/android/java/src/org/chromium/chrome/browser/feed/followmanagement/FollowManagementCoordinatorTest.java b/chrome/browser/feed/android/java/src/org/chromium/chrome/browser/feed/followmanagement/FollowManagementCoordinatorTest.java index b75fdd9..286f5a43 100644 --- a/chrome/browser/feed/android/java/src/org/chromium/chrome/browser/feed/followmanagement/FollowManagementCoordinatorTest.java +++ b/chrome/browser/feed/android/java/src/org/chromium/chrome/browser/feed/followmanagement/FollowManagementCoordinatorTest.java
@@ -8,10 +8,6 @@ import static org.mockito.ArgumentMatchers.notNull; import static org.mockito.Mockito.verify; -import android.view.View; -import android.view.ViewGroup; - -import androidx.appcompat.widget.AppCompatImageButton; import androidx.test.ext.junit.rules.ActivityScenarioRule; import org.junit.After; @@ -24,7 +20,6 @@ import org.chromium.base.test.BaseRobolectricTestRunner; import org.chromium.base.test.util.JniMocker; -import org.chromium.chrome.browser.feed.test.R; import org.chromium.chrome.browser.feed.webfeed.WebFeedBridge; import org.chromium.chrome.browser.feed.webfeed.WebFeedBridgeJni; import org.chromium.chrome.browser.profiles.Profile; @@ -80,24 +75,4 @@ public void testConstruction() { assertTrue(true); } - - @Test - public void testBackArrow() { - View outerView = mFollowManagementCoordinator.getView(); - // Send a click to the back arrow. - // Note that finding the back arrow view is ugly because it doesn't - // have an ID. - boolean clicked = false; - ViewGroup actionBar = (ViewGroup) outerView.findViewById(R.id.action_bar); - for (int i = 0; i < actionBar.getChildCount(); i++) { - try { - AppCompatImageButton button = (AppCompatImageButton) actionBar.getChildAt(i); - button.performClick(); - clicked = true; - } catch (ClassCastException e) { - } - } - - assertTrue(clicked); - } }
diff --git a/chrome/browser/flag-metadata.json b/chrome/browser/flag-metadata.json index 23fc51f..f8e1a8c 100644 --- a/chrome/browser/flag-metadata.json +++ b/chrome/browser/flag-metadata.json
@@ -5799,9 +5799,14 @@ "expiry_milestone": 115 }, { - "name": "safety-check-permissions", + "name": "safety-check-notification-permissions", "owners": ["sideyilmaz"], - "expiry_milestone": 111 + "expiry_milestone": 115 + }, + { + "name": "safety-check-unused-site-permissions", + "owners": ["sideyilmaz"], + "expiry_milestone": 115 }, { "name": "sameparty-cookies-considered-first-party",
diff --git a/chrome/browser/flag_descriptions.cc b/chrome/browser/flag_descriptions.cc index fc0ab9d..7d72c82 100644 --- a/chrome/browser/flag_descriptions.cc +++ b/chrome/browser/flag_descriptions.cc
@@ -2509,10 +2509,17 @@ "Enables independent agent cluster scheduling, via the " "AgentSchedulingGroup infrastructure."; -const char kSafetyCheckPermissionsName[] = "Permission Modules on Safety Check"; -const char kSafetyCheckPermissionsDescription[] = - "When enabled, adds permission modules to Safety Check on desktop. " - "The modules will be shown depending on the browser state."; +const char kSafetyCheckNotificationPermissionsName[] = + "Permission Module for notifications in Safety Check"; +const char kSafetyCheckNotificationPermissionsDescription[] = + "When enabled, adds the notification permission module to Safety Check on " + "desktop. The module will be shown depending on the browser state."; + +const char kSafetyCheckUnusedSitePermissionsName[] = + "Permission Module for unused sites in Safety Check"; +const char kSafetyCheckUnusedSitePermissionsDescription[] = + "When enabled, adds the unused sites permission module to Safety Check on " + "desktop. The module will be shown depending on the browser state."; const char kSamePartyCookiesConsideredFirstPartyName[] = "Consider SameParty cookies to be first-party.";
diff --git a/chrome/browser/flag_descriptions.h b/chrome/browser/flag_descriptions.h index 892c9c6..8a28644 100644 --- a/chrome/browser/flag_descriptions.h +++ b/chrome/browser/flag_descriptions.h
@@ -1403,8 +1403,11 @@ extern const char kMBIModeName[]; extern const char kMBIModeDescription[]; -extern const char kSafetyCheckPermissionsName[]; -extern const char kSafetyCheckPermissionsDescription[]; +extern const char kSafetyCheckNotificationPermissionsName[]; +extern const char kSafetyCheckNotificationPermissionsDescription[]; + +extern const char kSafetyCheckUnusedSitePermissionsName[]; +extern const char kSafetyCheckUnusedSitePermissionsDescription[]; extern const char kSamePartyCookiesConsideredFirstPartyName[]; extern const char kSamePartyCookiesConsideredFirstPartyDescription[];
diff --git a/chrome/browser/metrics/power/power_metrics.cc b/chrome/browser/metrics/power/power_metrics.cc index e4e873d..a1724aa 100644 --- a/chrome/browser/metrics/power/power_metrics.cc +++ b/chrome/browser/metrics/power/power_metrics.cc
@@ -16,12 +16,10 @@ namespace { -#if BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) constexpr const char* kBatteryDischargeRateHistogramName = "Power.BatteryDischargeRate2"; constexpr const char* kBatteryDischargeModeHistogramName = "Power.BatteryDischargeMode2"; -#endif // BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) #if BUILDFLAG(IS_MAC) // Reports `proportion` of a time used to a histogram in permyriad (1/100 %). @@ -63,7 +61,6 @@ } } -#if BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) BatteryDischarge GetBatteryDischargeDuringInterval( const absl::optional<base::BatteryLevelProvider::BatteryState>& previous_battery_state, @@ -153,7 +150,6 @@ } } } -#endif // BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) #if BUILDFLAG(IS_MAC) void ReportShortIntervalHistograms(
diff --git a/chrome/browser/metrics/power/power_metrics.h b/chrome/browser/metrics/power/power_metrics.h index d0bbaac..033d370 100644 --- a/chrome/browser/metrics/power/power_metrics.h +++ b/chrome/browser/metrics/power/power_metrics.h
@@ -7,7 +7,7 @@ #include <vector> -#include "base/power_monitor/power_monitor_buildflags.h" +#include "base/power_monitor/battery_level_provider.h" #include "base/time/time.h" #include "build/build_config.h" #include "chrome/browser/metrics/power/process_monitor.h" @@ -18,10 +18,6 @@ #include "components/power_metrics/resource_coalition_mac.h" #endif -#if BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) -#include "base/power_monitor/battery_level_provider.h" -#endif - // Report aggregated process metrics to histograms with |suffixes|. void ReportAggregatedProcessMetricsHistograms( const ProcessMonitor::Metrics& aggregated_process_metrics, @@ -50,7 +46,6 @@ absl::optional<int64_t> rate; }; -#if BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) // Computes and returns the battery discharge mode and rate during the interval. // If the discharge rate isn't valid, the returned rate is nullopt and the // reason is indicated per BatteryDischargeMode. @@ -65,7 +60,6 @@ void ReportBatteryHistograms(base::TimeDelta interval_duration, BatteryDischarge battery_discharge, const std::vector<const char*>& suffixes); -#endif // BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) #if BUILDFLAG(IS_MAC) void ReportShortIntervalHistograms(
diff --git a/chrome/browser/metrics/power/power_metrics_reporter.cc b/chrome/browser/metrics/power/power_metrics_reporter.cc index a238aa9..9ecab446 100644 --- a/chrome/browser/metrics/power/power_metrics_reporter.cc +++ b/chrome/browser/metrics/power/power_metrics_reporter.cc
@@ -29,7 +29,6 @@ namespace { -#if BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) constexpr const char* kBatterySamplingDelayHistogramName = "Power.BatterySamplingDelay"; @@ -38,7 +37,6 @@ base::TimeDelta tolerance) { return (value - expected).magnitude() < tolerance; } -#endif // Calculates the UKM bucket |value| falls in and returns it. This uses an // exponential bucketing approach with an exponent base of 1.3, resulting in @@ -86,11 +84,8 @@ PowerMetricsReporter::PowerMetricsReporter( ProcessMonitor* process_monitor, UsageScenarioDataStore* short_usage_scenario_data_store, - UsageScenarioDataStore* long_usage_scenario_data_store -#if BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) - , + UsageScenarioDataStore* long_usage_scenario_data_store, std::unique_ptr<base::BatteryLevelProvider> battery_level_provider -#endif // BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) #if BUILDFLAG(IS_MAC) , std::unique_ptr<CoalitionResourceUsageProvider> @@ -99,11 +94,8 @@ ) : process_monitor_(process_monitor), short_usage_scenario_data_store_(short_usage_scenario_data_store), - long_usage_scenario_data_store_(long_usage_scenario_data_store) -#if BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) - , + long_usage_scenario_data_store_(long_usage_scenario_data_store), battery_level_provider_(std::move(battery_level_provider)) -#endif // BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) #if BUILDFLAG(IS_MAC) , coalition_resource_usage_provider_( @@ -124,12 +116,15 @@ interval_begin_ = base::TimeTicks::Now(); -#if BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) - // Unretained() is safe here because |this| outlive |battery_level_provider_|. - battery_level_provider_->GetBatteryState( - base::BindOnce(&PowerMetricsReporter::OnFirstBatteryStateSampled, - base::Unretained(this))); -#endif + // `battery_level_provider_` may be null on platforms that do not have an + // implementation. + if (battery_level_provider_) { + // Unretained() is safe here because |this| outlive + // |battery_level_provider_|. + battery_level_provider_->GetBatteryState( + base::BindOnce(&PowerMetricsReporter::OnFirstBatteryStateSampled, + base::Unretained(this))); + } #if BUILDFLAG(IS_MAC) iopm_power_source_sampling_event_source_.Start( @@ -150,14 +145,13 @@ return GetBucketForSample(value); } -#if BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) void PowerMetricsReporter::OnFirstBatteryStateSampled( const absl::optional<base::BatteryLevelProvider::BatteryState>& battery_state) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + DCHECK(battery_level_provider_); battery_state_ = battery_state; } -#endif // BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) void PowerMetricsReporter::StartNextLongInterval() { #if BUILDFLAG(IS_MAC) @@ -214,19 +208,21 @@ // Finally, retrieve the battery state before reporting the metrics. On // platform without a BatteryLevelProvider implementation, skip straight to // reporting the metrics. -#if BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) - // Note: The use of `Unretained()` is safe here because |this| outlives - // |battery_level_provider_|. - battery_level_provider_->GetBatteryState(base::BindOnce( - &PowerMetricsReporter::OnBatteryAndAggregatedProcessMetricsSampled, - base::Unretained(this), metrics, interval_duration, - /*battery_sample_begin_time=*/now)); -#else - ReportMetrics(interval_duration, metrics); -#endif + if (battery_level_provider_) { + // Note: The use of `Unretained()` is safe here because |this| outlives + // |battery_level_provider_|. + battery_level_provider_->GetBatteryState(base::BindOnce( + &PowerMetricsReporter::OnBatteryAndAggregatedProcessMetricsSampled, + base::Unretained(this), metrics, interval_duration, + /*battery_sample_begin_time=*/now)); + } else { + // Get usage scenario data. + auto long_interval_data = + long_usage_scenario_data_store_->ResetIntervalData(); + ReportMetrics(long_interval_data, interval_duration, metrics); + } } -#if BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) void PowerMetricsReporter::OnBatteryAndAggregatedProcessMetricsSampled( const ProcessMonitor::Metrics& aggregated_process_metrics, base::TimeDelta interval_duration, @@ -234,6 +230,7 @@ const absl::optional<base::BatteryLevelProvider::BatteryState>& new_battery_state) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + DCHECK(battery_level_provider_); // Report time it took to sample the battery state. base::UmaHistogramMicrosecondsTimes( @@ -264,23 +261,19 @@ } #endif - ReportMetrics(interval_duration, aggregated_process_metrics, - battery_discharge); -} -#endif // BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) - -void PowerMetricsReporter::ReportMetrics( - base::TimeDelta interval_duration, - const ProcessMonitor::Metrics& aggregated_process_metrics -#if BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) - , - BatteryDischarge battery_discharge -#endif -) { // Get usage scenario data. auto long_interval_data = long_usage_scenario_data_store_->ResetIntervalData(); + ReportMetrics(long_interval_data, interval_duration, + aggregated_process_metrics); + ReportBatterySpecificMetrics(long_interval_data, interval_duration, + aggregated_process_metrics, battery_discharge); +} +void PowerMetricsReporter::ReportMetrics( + const UsageScenarioDataStore::IntervalData& long_interval_data, + base::TimeDelta interval_duration, + const ProcessMonitor::Metrics& aggregated_process_metrics) { // Get scenario data. const auto long_interval_scenario_params = GetLongIntervalScenario(long_interval_data); @@ -295,26 +288,6 @@ base::UmaHistogramEnumeration("PerformanceMonitor.UsageScenario.LongInterval", long_interval_scenario_params.scenario); -#if BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) - // Report UKMs. - ReportUKMs(long_interval_data, aggregated_process_metrics, interval_duration, - battery_discharge); - - // Ratio by which the time elapsed can deviate from - // |kLongPowerMetricsIntervalDuration| without invalidating this sample. - // TODO(pmonette): Change to DCHECK after ensuring this never triggers. - CHECK_GE(interval_duration, kLongPowerMetricsIntervalDuration); - constexpr double kTolerableTimeElapsedRatio = 0.10; - if (battery_discharge.mode == BatteryDischargeMode::kDischarging && - !IsWithinTolerance( - interval_duration, kLongPowerMetricsIntervalDuration, - kLongPowerMetricsIntervalDuration * kTolerableTimeElapsedRatio)) { - battery_discharge.mode = BatteryDischargeMode::kInvalidInterval; - } - ReportBatteryHistograms(interval_duration, battery_discharge, - long_interval_suffixes); -#endif // BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) - #if BUILDFLAG(IS_MAC) // Sample coalition resource usage rate. absl::optional<power_metrics::CoalitionResourceUsageRate> @@ -352,8 +325,35 @@ StartNextLongInterval(); } -#if BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) -void PowerMetricsReporter::ReportUKMs( +void PowerMetricsReporter::ReportBatterySpecificMetrics( + const UsageScenarioDataStore::IntervalData& long_interval_data, + base::TimeDelta interval_duration, + const ProcessMonitor::Metrics& aggregated_process_metrics, + BatteryDischarge battery_discharge) { + DCHECK(battery_level_provider_); + + // Report UKMs. + ReportBatteryUKMs(long_interval_data, aggregated_process_metrics, + interval_duration, battery_discharge); + + // Ratio by which the time elapsed can deviate from + // |kLongPowerMetricsIntervalDuration| without invalidating this sample. + // TODO(pmonette): Change to DCHECK after ensuring this never triggers. + CHECK_GE(interval_duration, kLongPowerMetricsIntervalDuration); + constexpr double kTolerableTimeElapsedRatio = 0.10; + if (battery_discharge.mode == BatteryDischargeMode::kDischarging && + !IsWithinTolerance( + interval_duration, kLongPowerMetricsIntervalDuration, + kLongPowerMetricsIntervalDuration * kTolerableTimeElapsedRatio)) { + battery_discharge.mode = BatteryDischargeMode::kInvalidInterval; + } + + ReportBatteryHistograms( + interval_duration, battery_discharge, + {"", GetLongIntervalScenario(long_interval_data).histogram_suffix}); +} + +void PowerMetricsReporter::ReportBatteryUKMs( const UsageScenarioDataStore::IntervalData& interval_data, const ProcessMonitor::Metrics& metrics, base::TimeDelta interval_duration, @@ -425,7 +425,6 @@ builder.Record(ukm_recorder); } -#endif // BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) #if BUILDFLAG(IS_MAC) void PowerMetricsReporter::MaybeEmitHighCPUTraceEvent(
diff --git a/chrome/browser/metrics/power/power_metrics_reporter.h b/chrome/browser/metrics/power/power_metrics_reporter.h index e7e5e88..77c0813 100644 --- a/chrome/browser/metrics/power/power_metrics_reporter.h +++ b/chrome/browser/metrics/power/power_metrics_reporter.h
@@ -8,7 +8,7 @@ #include <memory> #include <utility> -#include "base/power_monitor/power_monitor_buildflags.h" +#include "base/power_monitor/battery_level_provider.h" #include "base/time/time.h" #include "base/timer/timer.h" #include "build/build_config.h" @@ -24,10 +24,6 @@ #include "chrome/browser/metrics/power/coalition_resource_usage_provider_mac.h" #endif // BUILDFLAG(IS_MAC) -#if BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) -#include "base/power_monitor/battery_level_provider.h" -#endif - // Reports metrics related to power (battery discharge, cpu time, etc.). // // Metrics are reported for 2 minutes intervals, with suffixes describing what @@ -59,12 +55,9 @@ explicit PowerMetricsReporter( ProcessMonitor* process_monitor, UsageScenarioDataStore* short_usage_scenario_data_store = nullptr, - UsageScenarioDataStore* long_usage_scenario_data_store = nullptr -#if BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) - , + UsageScenarioDataStore* long_usage_scenario_data_store = nullptr, std::unique_ptr<base::BatteryLevelProvider> battery_level_provider = base::BatteryLevelProvider::Create() -#endif // BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) #if BUILDFLAG(IS_MAC) , std::unique_ptr<CoalitionResourceUsageProvider> @@ -76,22 +69,18 @@ PowerMetricsReporter& operator=(const PowerMetricsReporter& rhs) = delete; ~PowerMetricsReporter() override; -#if BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) absl::optional<base::BatteryLevelProvider::BatteryState>& battery_state_for_testing() { return battery_state_; } -#endif // BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) static int64_t GetBucketForSampleForTesting(base::TimeDelta value); private: -#if BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) // Called when the initial battery state is obtained. void OnFirstBatteryStateSampled( const absl::optional<base::BatteryLevelProvider::BatteryState>& battery_state); -#endif // BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) // Starts the timer for the long interval. On Mac, this will fire for the // beginning of the short interval instead, which upon completion will mark @@ -114,32 +103,33 @@ void OnAggregatedMetricsSampled( const ProcessMonitor::Metrics& aggregated_process_metrics) override; -#if BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) void OnBatteryAndAggregatedProcessMetricsSampled( const ProcessMonitor::Metrics& aggregated_process_metrics, base::TimeDelta interval_duration, base::TimeTicks battery_sample_begin_time, const absl::optional<base::BatteryLevelProvider::BatteryState>& new_battery_state); -#endif // BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) // Called when the long interval (and the short one on Mac) ends. - void ReportMetrics(base::TimeDelta interval_duration, - const ProcessMonitor::Metrics& aggregated_process_metrics -#if BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) - , - BatteryDischarge battery_discharge -#endif - ); + void ReportMetrics( + const UsageScenarioDataStore::IntervalData& long_interval_data, + base::TimeDelta interval_duration, + const ProcessMonitor::Metrics& aggregated_process_metrics); -#if BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) + // Called after `ReportMetrics` on platforms where a `BatteryLevelProvider` is + // available to record metrics specific to the battery state. + void ReportBatterySpecificMetrics( + const UsageScenarioDataStore::IntervalData& long_interval_data, + base::TimeDelta interval_duration, + const ProcessMonitor::Metrics& aggregated_process_metrics, + BatteryDischarge battery_discharge); + // Report the UKMs for the past interval. - static void ReportUKMs( + static void ReportBatteryUKMs( const UsageScenarioDataStore::IntervalData& interval_data, const ProcessMonitor::Metrics& aggregated_process_metrics, base::TimeDelta interval_duration, BatteryDischarge battery_discharge); -#endif // BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) #if BUILDFLAG(IS_MAC) // Emit trace event when CPU usage is high for 10 secondes or more. @@ -160,11 +150,8 @@ std::unique_ptr<UsageScenarioTracker> long_usage_scenario_tracker_; raw_ptr<UsageScenarioDataStore> long_usage_scenario_data_store_; -#if BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) std::unique_ptr<base::BatteryLevelProvider> battery_level_provider_; - absl::optional<base::BatteryLevelProvider::BatteryState> battery_state_; -#endif // BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) base::TimeTicks interval_begin_;
diff --git a/chrome/browser/metrics/power/power_metrics_reporter_unittest.cc b/chrome/browser/metrics/power/power_metrics_reporter_unittest.cc index 5c804ca..5b008f9 100644 --- a/chrome/browser/metrics/power/power_metrics_reporter_unittest.cc +++ b/chrome/browser/metrics/power/power_metrics_reporter_unittest.cc
@@ -29,7 +29,6 @@ namespace { -#if BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) constexpr const char* kBatteryDischargeRateHistogramName = "Power.BatteryDischargeRate2"; constexpr const char* kBatteryDischargeModeHistogramName = @@ -48,7 +47,6 @@ .charge_unit = base::BatteryLevelProvider::BatteryLevelUnit::kMAh, .capture_time = base::TimeTicks::Now()}; } -#endif // BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) ProcessMonitor::Metrics GetFakeProcessMetrics() { ProcessMonitor::Metrics metrics; @@ -83,7 +81,6 @@ using UkmEntry = ukm::builders::PowerUsageScenariosIntervalData; -#if BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) class FakeBatteryLevelProvider : public base::BatteryLevelProvider { public: explicit FakeBatteryLevelProvider( @@ -104,7 +101,6 @@ raw_ptr<std::queue<absl::optional<base::BatteryLevelProvider::BatteryState>>> battery_states_; }; -#endif // BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) class TestProcessMonitor : public ProcessMonitor { public: @@ -162,23 +158,18 @@ // This doesn't use the typical {class being tested}Test name pattern because // there's already a PowerMetricsReporterTest class in the chromeos namespace // and this conflicts with it. -class PowerMetricsReporterUnitTest : public testing::Test { +class PowerMetricsReporterUnitTestBase : public testing::Test { public: - PowerMetricsReporterUnitTest() = default; - PowerMetricsReporterUnitTest(const PowerMetricsReporterUnitTest& rhs) = - delete; - PowerMetricsReporterUnitTest& operator=( - const PowerMetricsReporterUnitTest& rhs) = delete; - ~PowerMetricsReporterUnitTest() override = default; + PowerMetricsReporterUnitTestBase() = default; + PowerMetricsReporterUnitTestBase( + const PowerMetricsReporterUnitTestBase& rhs) = delete; + PowerMetricsReporterUnitTestBase& operator=( + const PowerMetricsReporterUnitTestBase& rhs) = delete; + ~PowerMetricsReporterUnitTestBase() override = default; void SetUp() override { -#if BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) - // Start with a half-full battery - battery_states_.push(MakeBatteryDischarginState(50)); - auto battery_provider = - std::make_unique<FakeBatteryLevelProvider>(&battery_states_); + auto battery_provider = CreateBatteryLevelProvider(); battery_provider_ = battery_provider.get(); -#endif // BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) #if BUILDFLAG(IS_MAC) auto coalition_resource_usage_provider = @@ -191,24 +182,22 @@ #endif // BUILDFLAG(IS_MAC) power_metrics_reporter_ = std::make_unique<PowerMetricsReporter>( - &process_monitor_, &short_data_store_, &long_data_store_ -#if BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) - , + &process_monitor_, &short_data_store_, &long_data_store_, std::move(battery_provider) -#endif // BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) #if BUILDFLAG(IS_MAC) , std::move(coalition_resource_usage_provider) #endif // BUILDFLAG(IS_MAC) ); -#if BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) // Ensure the first battery state is sampled. task_environment_.RunUntilIdle(); -#endif // BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) } protected: + virtual std::unique_ptr<base::BatteryLevelProvider> + CreateBatteryLevelProvider() = 0; + content::BrowserTaskEnvironment task_environment_{ base::test::TaskEnvironment::TimeSource::MOCK_TIME}; TestProcessMonitor process_monitor_; @@ -217,13 +206,9 @@ base::HistogramTester histogram_tester_; -#if BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) ukm::TestAutoSetUkmRecorder test_ukm_recorder_; - std::queue<absl::optional<base::BatteryLevelProvider::BatteryState>> - battery_states_; raw_ptr<base::BatteryLevelProvider> battery_provider_; -#endif // BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) #if BUILDFLAG(IS_MAC) raw_ptr<TestCoalitionResourceUsageProvider> @@ -233,13 +218,62 @@ std::unique_ptr<PowerMetricsReporter> power_metrics_reporter_; }; +class PowerMetricsReporterUnitTest : public PowerMetricsReporterUnitTestBase { + public: + ~PowerMetricsReporterUnitTest() override = default; + + std::unique_ptr<base::BatteryLevelProvider> CreateBatteryLevelProvider() + override { + // Start with a half-full battery + battery_states_.push(MakeBatteryDischarginState(50)); + auto battery_provider = + std::make_unique<FakeBatteryLevelProvider>(&battery_states_); + return std::move(battery_provider); + } + + protected: + std::queue<absl::optional<base::BatteryLevelProvider::BatteryState>> + battery_states_; +}; + +class PowerMetricsReporterWithoutBatteryLevelProviderUnitTest + : public PowerMetricsReporterUnitTestBase { + public: + ~PowerMetricsReporterWithoutBatteryLevelProviderUnitTest() override = default; + + std::unique_ptr<base::BatteryLevelProvider> CreateBatteryLevelProvider() + override { + return nullptr; + } +}; + } // namespace +TEST_F(PowerMetricsReporterWithoutBatteryLevelProviderUnitTest, + CPUTimeRecorded) { + process_monitor_.SetMetricsToReturn(GetFakeProcessMetrics()); + + UsageScenarioDataStore::IntervalData interval_data; + interval_data.max_tab_count = 1; + interval_data.max_visible_window_count = 1; + interval_data.time_capturing_video = base::Seconds(1); + long_data_store_.SetIntervalDataToReturn(interval_data); + + task_environment_.FastForwardBy(kLongPowerMetricsIntervalDuration); + +// Windows ARM64 does not support Constant Rate TSC so +// PerformanceMonitor.AverageCPU6.Total is not recorded there. +#if !BUILDFLAG(IS_WIN) || !defined(ARCH_CPU_ARM64) + const char* kScenarioSuffix = ".VideoCapture"; + const std::vector<const char*> suffixes({"", kScenarioSuffix}); + ExpectHistogramSamples(&histogram_tester_, suffixes, + {{"PerformanceMonitor.AverageCPU6.Total", 500}}); +#endif +} + TEST_F(PowerMetricsReporterUnitTest, LongIntervalHistograms) { process_monitor_.SetMetricsToReturn(GetFakeProcessMetrics()); -#if BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) battery_states_.push(MakeBatteryDischarginState(30)); -#endif UsageScenarioDataStore::IntervalData interval_data; interval_data.max_tab_count = 1; @@ -293,7 +327,6 @@ } #endif -#if BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) TEST_F(PowerMetricsReporterUnitTest, BatteryDischargeCaptureIsTooLate) { ProcessMonitor::Metrics aggregated_process_metrics = {}; process_monitor_.SetMetricsToReturn(aggregated_process_metrics); @@ -764,7 +797,6 @@ test_ukm_recorder_.ExpectEntryMetric( entries[0], UkmEntry::kDeviceSleptDuringIntervalName, true); } -#endif // BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) #if BUILDFLAG(IS_MAC) // Verify that "_10sec" resource coalition histograms are recorded when time
diff --git a/chrome/browser/page_info/about_this_site_service_factory.cc b/chrome/browser/page_info/about_this_site_service_factory.cc index 8ade4cb..32f0042 100644 --- a/chrome/browser/page_info/about_this_site_service_factory.cc +++ b/chrome/browser/page_info/about_this_site_service_factory.cc
@@ -6,17 +6,15 @@ #include <memory> -#include "base/feature_list.h" #include "base/no_destructor.h" #include "chrome/browser/browser_process.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/page_info/chrome_about_this_site_service_client.h" +#include "chrome/browser/page_info/page_info_features.h" #include "chrome/browser/profiles/profile.h" #include "components/page_info/core/about_this_site_service.h" #include "components/page_info/core/features.h" -#include "content/public/browser/browser_task_traits.h" -#include "content/public/browser/browser_thread.h" // static page_info::AboutThisSiteService* AboutThisSiteServiceFactory::GetForProfile( @@ -48,7 +46,8 @@ return new page_info::AboutThisSiteService( std::make_unique<ChromeAboutThisSiteServiceClient>( OptimizationGuideKeyedServiceFactory::GetForProfile(profile), - profile->IsOffTheRecord(), profile->GetPrefs())); + profile->IsOffTheRecord(), profile->GetPrefs()), + page_info::IsDescriptionPlaceholderFeatureEnabled()); } bool AboutThisSiteServiceFactory::ServiceIsCreatedWithBrowserContext() const {
diff --git a/chrome/browser/page_info/about_this_site_tab_helper.cc b/chrome/browser/page_info/about_this_site_tab_helper.cc index d81cdcc..ffc9076 100644 --- a/chrome/browser/page_info/about_this_site_tab_helper.cc +++ b/chrome/browser/page_info/about_this_site_tab_helper.cc
@@ -7,6 +7,7 @@ #include "base/callback.h" #include "base/metrics/histogram_functions.h" #include "build/buildflag.h" +#include "chrome/browser/page_info/page_info_features.h" #include "chrome/browser/ui/page_info/about_this_site_side_panel.h" #include "components/optimization_guide/content/browser/optimization_guide_decider.h" #include "components/optimization_guide/core/optimization_guide_decision.h" @@ -88,7 +89,9 @@ absl::optional<AboutThisSiteMetadata> about_this_site_metadata = metadata.ParsedMetadata<AboutThisSiteMetadata>(); - auto status = ValidateMetadata(about_this_site_metadata); + auto status = + ValidateMetadata(about_this_site_metadata, + page_info::IsDescriptionPlaceholderFeatureEnabled()); base::UmaHistogramEnumeration("Privacy.AboutThisSite.PageLoadValidation", status);
diff --git a/chrome/browser/page_info/page_info_features.cc b/chrome/browser/page_info/page_info_features.cc new file mode 100644 index 0000000..daa5e4d --- /dev/null +++ b/chrome/browser/page_info/page_info_features.cc
@@ -0,0 +1,47 @@ +// 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/page_info/page_info_features.h" + +#include "base/feature_list.h" +#include "chrome/browser/browser_process.h" +#include "chrome/browser/ui/ui_features.h" +#include "components/page_info/core/features.h" + +namespace page_info { + +bool IsMoreAboutThisSiteFeatureEnabled() { +#if !BUILDFLAG(IS_ANDROID) + // MoreAbout may only be enabled when the side panel is on. + if (!base::FeatureList::IsEnabled(features::kUnifiedSidePanel)) + return false; +#endif + + if (!page_info::IsAboutThisSiteFeatureEnabled( + g_browser_process->GetApplicationLocale())) { + return false; + } + + return base::FeatureList::IsEnabled( + page_info::kPageInfoAboutThisSiteMoreInfo); +} + +bool IsDescriptionPlaceholderFeatureEnabled() { + return IsMoreAboutThisSiteFeatureEnabled() && + base::FeatureList::IsEnabled( + page_info::kPageInfoAboutThisSiteDescriptionPlaceholder); +} + +#if !BUILDFLAG(IS_ANDROID) +bool IsPersistentSidePanelEntryFeatureEnabled() { + return IsMoreAboutThisSiteFeatureEnabled() && + base::FeatureList::IsEnabled( + page_info::kAboutThisSitePersistentSidePanelEntry); +} + +const base::Feature kAboutThisSitePersistentSidePanelEntry{ + "AboutThisSitePersistentSidePanelEntry", base::FEATURE_DISABLED_BY_DEFAULT}; +#endif + +} // namespace page_info
diff --git a/chrome/browser/page_info/page_info_features.h b/chrome/browser/page_info/page_info_features.h new file mode 100644 index 0000000..4926fbc --- /dev/null +++ b/chrome/browser/page_info/page_info_features.h
@@ -0,0 +1,30 @@ +// 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_PAGE_INFO_PAGE_INFO_FEATURES_H_ +#define CHROME_BROWSER_PAGE_INFO_PAGE_INFO_FEATURES_H_ + +#include "base/feature_list.h" +namespace page_info { + +// Returns true if kPageInfoAboutThisSiteMoreInfo and dependent features are +// enabled. +bool IsMoreAboutThisSiteFeatureEnabled(); + +// Returns true if kPageInfoAboutThisSiteDescriptionPlaceholder and dependent +// features are enabled. +bool IsDescriptionPlaceholderFeatureEnabled(); + +#if !BUILDFLAG(IS_ANDROID) +// Returns true if kAboutThisSitePersistentSidePanelEntry and dependent +// features are enabled. +bool IsPersistentSidePanelEntryFeatureEnabled(); + +// Enables the persistent "About this site" entry in the side panel. +extern const base::Feature kAboutThisSitePersistentSidePanelEntry; +#endif + +} // namespace page_info + +#endif // CHROME_BROWSER_PAGE_INFO_PAGE_INFO_FEATURES_H_
diff --git a/chrome/browser/password_manager/android/password_manager_error_message_delegate.cc b/chrome/browser/password_manager/android/password_manager_error_message_delegate.cc index 23e18d6..b375ae8 100644 --- a/chrome/browser/password_manager/android/password_manager_error_message_delegate.cc +++ b/chrome/browser/password_manager/android/password_manager_error_message_delegate.cc
@@ -10,6 +10,7 @@ #include "chrome/browser/android/resource_mapper.h" #include "chrome/grit/generated_resources.h" #include "components/messages/android/message_dispatcher_bridge.h" +#include "components/password_manager/core/browser/password_manager_client.h" #include "content/public/browser/web_contents.h" #include "ui/android/window_android.h" #include "ui/aura/window.h" @@ -24,7 +25,8 @@ void PasswordManagerErrorMessageDelegate::MaybeDisplayErrorMessage( content::WebContents* web_contents, - bool save_password) { + password_manager::ErrorMessageFlowType flow_type, + base::OnceCallback<void()> dismissal_callback) { DCHECK(web_contents); if (!helper_bridge_->ShouldShowErrorUI()) @@ -32,11 +34,12 @@ DCHECK(!message_); - CreateMessage(web_contents, save_password); + CreateMessage(web_contents, flow_type); messages::MessageDispatcherBridge::Get()->EnqueueMessage( message_.get(), web_contents, messages::MessageScopeType::WEB_CONTENTS, messages::MessagePriority::kUrgent); helper_bridge_->SaveErrorUIShownTimestamp(); + dismissal_callback_ = std::move(dismissal_callback); } void PasswordManagerErrorMessageDelegate::DismissPasswordManagerErrorMessage( @@ -44,12 +47,13 @@ if (message_ != nullptr) { messages::MessageDispatcherBridge::Get()->DismissMessage(message_.get(), dismiss_reason); + std::move(dismissal_callback_).Run(); } } void PasswordManagerErrorMessageDelegate::CreateMessage( content::WebContents* web_contents, - bool save_password) { + password_manager::ErrorMessageFlowType flow_type) { messages::MessageIdentifier message_id = messages::MessageIdentifier::PASSWORD_MANAGER_ERROR; // Binding with base::Unretained(this) is safe here because @@ -68,8 +72,10 @@ &PasswordManagerErrorMessageDelegate::HandleMessageDismissed, base::Unretained(this))); - int title_message_id = save_password ? IDS_SIGN_IN_TO_SAVE_PASSWORDS - : IDS_SIGN_IN_TO_USE_PASSWORDS; + int title_message_id = + flow_type == password_manager::ErrorMessageFlowType::kSaveFlow + ? IDS_SIGN_IN_TO_SAVE_PASSWORDS + : IDS_SIGN_IN_TO_USE_PASSWORDS; message_->SetTitle(l10n_util::GetStringUTF16(title_message_id)); std::u16string description =
diff --git a/chrome/browser/password_manager/android/password_manager_error_message_delegate.h b/chrome/browser/password_manager/android/password_manager_error_message_delegate.h index f76c5908..809687c 100644 --- a/chrome/browser/password_manager/android/password_manager_error_message_delegate.h +++ b/chrome/browser/password_manager/android/password_manager_error_message_delegate.h
@@ -9,6 +9,7 @@ #include "chrome/browser/password_manager/android/password_manager_error_message_helper_bridge.h" #include "components/messages/android/message_wrapper.h" +#include "components/password_manager/core/browser/password_manager_client.h" namespace content { class WebContents; @@ -22,10 +23,12 @@ // Displays a password error message for current `web_contents` if enough // time has passed since the last error message was displayed. - // `save_password` decides whether the error message mentions the inability to - // save or use passwords. - void MaybeDisplayErrorMessage(content::WebContents* web_contents, - bool save_password); + // `ErrorMessageFlowType` decides whether the error message mentions the + // inability to save or use passwords. + void MaybeDisplayErrorMessage( + content::WebContents* web_contents, + password_manager::ErrorMessageFlowType flow_type, + base::OnceCallback<void()> dismissal_callback); void DismissPasswordManagerErrorMessage( messages::DismissReason dismiss_reason); @@ -34,8 +37,10 @@ std::unique_ptr<messages::MessageWrapper> message_; std::unique_ptr<PasswordManagerErrorMessageHelperBridge> helper_bridge_; + base::OnceCallback<void()> dismissal_callback_; - void CreateMessage(content::WebContents* web_contents, bool save_password); + void CreateMessage(content::WebContents* web_contents, + password_manager::ErrorMessageFlowType flow_type); // Following methods handle events associated with user interaction with UI. void HandleSignInButtonClicked(content::WebContents* web_contents);
diff --git a/chrome/browser/password_manager/android/password_manager_error_message_delegate_unittest.cc b/chrome/browser/password_manager/android/password_manager_error_message_delegate_unittest.cc index f821751..89d9c2a 100644 --- a/chrome/browser/password_manager/android/password_manager_error_message_delegate_unittest.cc +++ b/chrome/browser/password_manager/android/password_manager_error_message_delegate_unittest.cc
@@ -5,11 +5,13 @@ #include "chrome/browser/password_manager/android/password_manager_error_message_delegate.h" #include "base/android/jni_android.h" +#include "base/functional/callback_helpers.h" #include "base/test/metrics/histogram_tester.h" #include "chrome/browser/password_manager/android/mock_password_manager_error_message_helper_bridge.h" #include "chrome/grit/generated_resources.h" #include "chrome/test/base/chrome_render_view_host_test_harness.h" #include "components/messages/android/mock_message_dispatcher_bridge.h" +#include "components/password_manager/core/browser/password_manager_client.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/base/l10n/l10n_util.h" @@ -29,7 +31,10 @@ void SetUp() override; void TearDown() override; - void DisplayMessageAndExpectEnqueued(bool save_password); + void DisplayMessageAndExpectEnqueued( + password_manager::ErrorMessageFlowType flow_type); + + void ExpectDismissed(messages::DismissReason dismiss_reason); void DismissMessageAndExpectDismissed(messages::DismissReason dismiss_reason); @@ -73,13 +78,14 @@ } void PasswordManagerErrorMessageDelegateTest::DisplayMessageAndExpectEnqueued( - bool save_password) { + password_manager::ErrorMessageFlowType flow_type) { EXPECT_CALL(*helper_bridge_, ShouldShowErrorUI()).WillOnce(Return(true)); EXPECT_CALL(message_dispatcher_bridge_, EnqueueMessage); - delegate_->MaybeDisplayErrorMessage(web_contents(), save_password); + delegate_->MaybeDisplayErrorMessage(web_contents(), flow_type, + base::DoNothing()); } -void PasswordManagerErrorMessageDelegateTest::DismissMessageAndExpectDismissed( +void PasswordManagerErrorMessageDelegateTest::ExpectDismissed( messages::DismissReason dismiss_reason) { EXPECT_CALL(message_dispatcher_bridge_, DismissMessage) .WillOnce([](messages::MessageWrapper* message, @@ -87,6 +93,11 @@ message->HandleDismissCallback(base::android::AttachCurrentThread(), static_cast<int>(dismiss_reason)); }); +} + +void PasswordManagerErrorMessageDelegateTest::DismissMessageAndExpectDismissed( + messages::DismissReason dismiss_reason) { + ExpectDismissed(dismiss_reason); delegate_->DismissPasswordManagerErrorMessage(dismiss_reason); EXPECT_EQ(nullptr, GetMessageWrapper()); } @@ -100,7 +111,8 @@ // set correctly for "sign in to save password" message. TEST_F(PasswordManagerErrorMessageDelegateTest, MessagePropertyValuesSignInToSavePassword) { - DisplayMessageAndExpectEnqueued(/*save_password=*/true); + DisplayMessageAndExpectEnqueued( + password_manager::ErrorMessageFlowType::kSaveFlow); EXPECT_EQ(l10n_util::GetStringUTF16(IDS_SIGN_IN_TO_SAVE_PASSWORDS), GetMessageWrapper()->GetTitle()); @@ -116,7 +128,8 @@ // set correctly for "sign in to use password" message. TEST_F(PasswordManagerErrorMessageDelegateTest, MessagePropertyValuesSignInToUsePassword) { - DisplayMessageAndExpectEnqueued(/*save_password=*/false); + DisplayMessageAndExpectEnqueued( + password_manager::ErrorMessageFlowType::kFillFlow); EXPECT_EQ(l10n_util::GetStringUTF16(IDS_SIGN_IN_TO_USE_PASSWORDS), GetMessageWrapper()->GetTitle()); @@ -133,14 +146,15 @@ TEST_F(PasswordManagerErrorMessageDelegateTest, SignInOnActionClick) { base::HistogramTester histogram_tester; - DisplayMessageAndExpectEnqueued(/*save_password=*/true); + DisplayMessageAndExpectEnqueued( + password_manager::ErrorMessageFlowType::kSaveFlow); EXPECT_NE(nullptr, GetMessageWrapper()); EXPECT_CALL(*helper_bridge(), StartUpdateAccountCredentialsFlow(web_contents())); + ExpectDismissed(messages::DismissReason::PRIMARY_ACTION); // Trigger the click action on the "Sign in" button and dismiss the message. GetMessageWrapper()->HandleActionClick(base::android::AttachCurrentThread()); - DismissMessageAndExpectDismissed(messages::DismissReason::PRIMARY_ACTION); histogram_tester.ExpectUniqueSample(kErrorMessageDismissalReasonHistogramName, messages::DismissReason::PRIMARY_ACTION, @@ -152,7 +166,8 @@ TEST_F(PasswordManagerErrorMessageDelegateTest, MetricOnAutodismissTimer) { base::HistogramTester histogram_tester; - DisplayMessageAndExpectEnqueued(/*save_password=*/true); + DisplayMessageAndExpectEnqueued( + password_manager::ErrorMessageFlowType::kSaveFlow); EXPECT_NE(nullptr, GetMessageWrapper()); DismissMessageAndExpectDismissed(messages::DismissReason::TIMER); @@ -165,10 +180,13 @@ NotDisplayedWhenCondiditonNotMet) { EXPECT_CALL(*helper_bridge(), ShouldShowErrorUI()).WillOnce(Return(false)); EXPECT_CALL(message_dispatcher_bridge(), EnqueueMessage).Times(0); - delegate()->MaybeDisplayErrorMessage(web_contents(), /*save_password=*/true); + delegate()->MaybeDisplayErrorMessage( + web_contents(), password_manager::ErrorMessageFlowType::kSaveFlow, + base::DoNothing()); } TEST_F(PasswordManagerErrorMessageDelegateTest, DisplayeSavesTimestamp) { EXPECT_CALL(*helper_bridge(), SaveErrorUIShownTimestamp()); - DisplayMessageAndExpectEnqueued(/*save_password=*/true); + DisplayMessageAndExpectEnqueued( + password_manager::ErrorMessageFlowType::kSaveFlow); }
diff --git a/chrome/browser/password_manager/android/password_manager_eviction_util.cc b/chrome/browser/password_manager/android/password_manager_eviction_util.cc index e040a7d..051eb7f4 100644 --- a/chrome/browser/password_manager/android/password_manager_eviction_util.cc +++ b/chrome/browser/password_manager/android/password_manager_eviction_util.cc
@@ -5,7 +5,9 @@ #include "chrome/browser/password_manager/android/password_manager_eviction_util.h" #include "base/logging.h" +#include "base/metrics/field_trial_params.h" #include "base/metrics/histogram_functions.h" +#include "components/password_manager/core/common/password_manager_features.h" #include "components/password_manager/core/common/password_manager_pref_names.h" #include "components/prefs/pref_service.h" @@ -28,6 +30,9 @@ prefs->SetInteger(password_manager::prefs:: kUnenrolledFromGoogleMobileServicesAfterApiErrorCode, api_error_code); + prefs->SetInteger(password_manager::prefs:: + kUnenrolledFromGoogleMobileServicesWithErrorListVersion, + password_manager::features::kGmsApiErrorListVersion.Get()); // Reset migration prefs so when the user can join the experiment again, // non-syncable data and settings can be migrated to GMS Core. @@ -43,4 +48,29 @@ << api_error_code; } +bool ShouldInvalidateEviction(const PrefService* prefs) { + if (!IsCurrentUserEvicted(prefs)) + return false; + + // Configured error versions are > 0, default stored version is 0. + int stored_version = prefs->GetInteger( + password_manager::prefs:: + kUnenrolledFromGoogleMobileServicesWithErrorListVersion); + + return stored_version < + password_manager::features::kGmsApiErrorListVersion.Get(); +} + +void ReenrollCurrentUser(PrefService* prefs) { + DCHECK(prefs->GetBoolean( + password_manager::prefs::kUnenrolledFromGoogleMobileServicesDueToErrors)); + + prefs->ClearPref( + password_manager::prefs::kUnenrolledFromGoogleMobileServicesDueToErrors); + prefs->ClearPref(password_manager::prefs:: + kUnenrolledFromGoogleMobileServicesAfterApiErrorCode); + prefs->ClearPref(password_manager::prefs:: + kUnenrolledFromGoogleMobileServicesWithErrorListVersion); +} + } // namespace password_manager_upm_eviction
diff --git a/chrome/browser/password_manager/android/password_manager_eviction_util.h b/chrome/browser/password_manager/android/password_manager_eviction_util.h index 461c6d5c..45d5cea 100644 --- a/chrome/browser/password_manager/android/password_manager_eviction_util.h +++ b/chrome/browser/password_manager/android/password_manager_eviction_util.h
@@ -13,8 +13,19 @@ bool IsCurrentUserEvicted(const PrefService* prefs); // Evicts the current user and saves the provided error as eviction reason. +// The current error list version is also saved. void EvictCurrentUser(int api_error_code, PrefService* prefs); +// Checks whether the eviction status for the current user should be invalidated +// and the user should be re-enrolled to the UPM experiment. +// Returns true if the user is evicted and currently configured error list +// version is greater than the saved one. +bool ShouldInvalidateEviction(const PrefService* prefs); + +// Resets the eviction status for the current user. +// Also clears the stored eviction reason and error list version. +void ReenrollCurrentUser(PrefService* prefs); + } // namespace password_manager_upm_eviction #endif // CHROME_BROWSER_PASSWORD_MANAGER_ANDROID_PASSWORD_MANAGER_EVICTION_UTIL_H_
diff --git a/chrome/browser/password_manager/android/password_manager_eviction_util_unittest.cc b/chrome/browser/password_manager/android/password_manager_eviction_util_unittest.cc index c70516be..e452f16 100644 --- a/chrome/browser/password_manager/android/password_manager_eviction_util_unittest.cc +++ b/chrome/browser/password_manager/android/password_manager_eviction_util_unittest.cc
@@ -3,6 +3,7 @@ // found in the LICENSE file. #include "chrome/browser/password_manager/android/password_manager_eviction_util.h" +#include "base/strings/string_number_conversions.h" #include "base/test/metrics/histogram_tester.h" #include "base/test/scoped_feature_list.h" @@ -21,6 +22,16 @@ constexpr char kUnenrollmentHistogram[] = "PasswordManager.UnenrolledFromUPMDueToErrors"; +constexpr int kTestErrorListVersion = 2; + +void EnableUPMFeatureWithTestParams( + base::test::ScopedFeatureList* feature_list) { + feature_list->InitAndEnableFeatureWithParameters( + password_manager::features::kUnifiedPasswordManagerAndroid, + {{password_manager::features::kGmsApiErrorListVersion.name, + base::NumberToString(kTestErrorListVersion)}}); +} + } // namespace class PasswordManagerEvictionUtilTest : public testing::Test { @@ -44,6 +55,10 @@ password_manager::prefs:: kUnenrolledFromGoogleMobileServicesAfterApiErrorCode, 0); + test_pref_service_.registry()->RegisterIntegerPref( + password_manager::prefs:: + kUnenrolledFromGoogleMobileServicesWithErrorListVersion, + 0); test_pref_service_.registry()->RegisterIntegerPref( password_manager::prefs::kCurrentMigrationVersionToGoogleMobileServices, @@ -57,8 +72,7 @@ PasswordManagerEvictionUtilTest::~PasswordManagerEvictionUtilTest() = default; TEST_F(PasswordManagerEvictionUtilTest, EvictsUser) { - feature_list()->InitAndEnableFeature( - password_manager::features::kUnifiedPasswordManagerAndroid); + EnableUPMFeatureWithTestParams(feature_list()); pref_service()->SetInteger( password_manager::prefs::kCurrentMigrationVersionToGoogleMobileServices, @@ -80,6 +94,10 @@ password_manager::prefs:: kUnenrolledFromGoogleMobileServicesAfterApiErrorCode), static_cast<int>(AndroidBackendAPIErrorCode::kInternalError)); + EXPECT_EQ(pref_service()->GetInteger( + password_manager::prefs:: + kUnenrolledFromGoogleMobileServicesWithErrorListVersion), + kTestErrorListVersion); EXPECT_EQ(pref_service()->GetInteger( password_manager::prefs:: @@ -95,8 +113,7 @@ } TEST_F(PasswordManagerEvictionUtilTest, IndicatesEvictedUser) { - feature_list()->InitAndEnableFeature( - password_manager::features::kUnifiedPasswordManagerAndroid); + EnableUPMFeatureWithTestParams(feature_list()); pref_service()->SetBoolean( password_manager::prefs::kUnenrolledFromGoogleMobileServicesDueToErrors, @@ -113,3 +130,85 @@ EXPECT_FALSE( password_manager_upm_eviction::IsCurrentUserEvicted(pref_service())); } + +TEST_F(PasswordManagerEvictionUtilTest, ReenrollsUser) { + EnableUPMFeatureWithTestParams(feature_list()); + + pref_service()->SetBoolean( + password_manager::prefs::kUnenrolledFromGoogleMobileServicesDueToErrors, + true); + pref_service()->SetInteger( + password_manager::prefs:: + kUnenrolledFromGoogleMobileServicesAfterApiErrorCode, + static_cast<int>(AndroidBackendAPIErrorCode::kInternalError)); + pref_service()->SetInteger( + password_manager::prefs:: + kUnenrolledFromGoogleMobileServicesWithErrorListVersion, + kTestErrorListVersion); + + password_manager_upm_eviction::ReenrollCurrentUser(pref_service()); + + EXPECT_FALSE(pref_service()->GetBoolean( + password_manager::prefs::kUnenrolledFromGoogleMobileServicesDueToErrors)); + EXPECT_EQ(pref_service()->GetInteger( + password_manager::prefs:: + kUnenrolledFromGoogleMobileServicesAfterApiErrorCode), + 0); + EXPECT_EQ(pref_service()->GetInteger( + password_manager::prefs:: + kUnenrolledFromGoogleMobileServicesWithErrorListVersion), + 0); +} + +TEST_F(PasswordManagerEvictionUtilTest, + ShouldInvalidateEvictionWithOutdatedVersion) { + EnableUPMFeatureWithTestParams(feature_list()); + + pref_service()->SetBoolean( + password_manager::prefs::kUnenrolledFromGoogleMobileServicesDueToErrors, + true); + pref_service()->SetInteger( + password_manager::prefs:: + kUnenrolledFromGoogleMobileServicesAfterApiErrorCode, + static_cast<int>(AndroidBackendAPIErrorCode::kInternalError)); + pref_service()->SetInteger( + password_manager::prefs:: + kUnenrolledFromGoogleMobileServicesWithErrorListVersion, + kTestErrorListVersion - 1); + + EXPECT_TRUE( + password_manager_upm_eviction::ShouldInvalidateEviction(pref_service())); +} + +TEST_F(PasswordManagerEvictionUtilTest, + ShouldNotInvalidateEvictionWithCurrentVersion) { + EnableUPMFeatureWithTestParams(feature_list()); + + pref_service()->SetBoolean( + password_manager::prefs::kUnenrolledFromGoogleMobileServicesDueToErrors, + true); + pref_service()->SetInteger( + password_manager::prefs:: + kUnenrolledFromGoogleMobileServicesAfterApiErrorCode, + static_cast<int>(AndroidBackendAPIErrorCode::kInternalError)); + pref_service()->SetInteger( + password_manager::prefs:: + kUnenrolledFromGoogleMobileServicesWithErrorListVersion, + kTestErrorListVersion); + + EXPECT_FALSE( + password_manager_upm_eviction::ShouldInvalidateEviction(pref_service())); +} + +TEST_F(PasswordManagerEvictionUtilTest, + ShouldNotInvalidateEvictionBeforeParamsConfigured) { + feature_list()->InitAndEnableFeature( + password_manager::features::kUnifiedPasswordManagerAndroid); + + pref_service()->SetBoolean( + password_manager::prefs::kUnenrolledFromGoogleMobileServicesDueToErrors, + true); + + EXPECT_FALSE( + password_manager_upm_eviction::ShouldInvalidateEviction(pref_service())); +}
diff --git a/chrome/browser/password_manager/android/password_store_android_backend_unittest.cc b/chrome/browser/password_manager/android/password_store_android_backend_unittest.cc index d5fd5ef5..9f4caca 100644 --- a/chrome/browser/password_manager/android/password_store_android_backend_unittest.cc +++ b/chrome/browser/password_manager/android/password_store_android_backend_unittest.cc
@@ -186,6 +186,8 @@ prefs_.registry()->RegisterIntegerPref( prefs::kUnenrolledFromGoogleMobileServicesAfterApiErrorCode, 0); prefs_.registry()->RegisterIntegerPref( + prefs::kUnenrolledFromGoogleMobileServicesWithErrorListVersion, 0); + prefs_.registry()->RegisterIntegerPref( prefs::kCurrentMigrationVersionToGoogleMobileServices, 1); prefs_.registry()->RegisterDoublePref(prefs::kTimeOfLastMigrationAttempt, 20.22);
diff --git a/chrome/browser/password_manager/chrome_password_manager_client.cc b/chrome/browser/password_manager/chrome_password_manager_client.cc index 8541e0c..63eae4d 100644 --- a/chrome/browser/password_manager/chrome_password_manager_client.cc +++ b/chrome/browser/password_manager/chrome_password_manager_client.cc
@@ -449,6 +449,19 @@ } #if BUILDFLAG(IS_ANDROID) +void ChromePasswordManagerClient::ShowPasswordManagerErrorMessage( + password_manager::ErrorMessageFlowType flow_type) { + if (!password_manager_error_message_delegate_) { + password_manager_error_message_delegate_ = + std::make_unique<PasswordManagerErrorMessageDelegate>( + std::make_unique<PasswordManagerErrorMessageHelperBridgeImpl>()); + password_manager_error_message_delegate_->MaybeDisplayErrorMessage( + web_contents(), flow_type, + base::BindOnce(&ChromePasswordManagerClient::ResetErrorMessageDelegate, + base::Unretained(this))); + } +} + void ChromePasswordManagerClient::ShowTouchToFill( PasswordManagerDriver* driver, autofill::mojom::SubmissionReadinessState submission_readiness) { @@ -1687,4 +1700,10 @@ password_manager_.ResetPendingCredentials(); } +#if BUILDFLAG(IS_ANDROID) +void ChromePasswordManagerClient::ResetErrorMessageDelegate() { + password_manager_error_message_delegate_.reset(); +} +#endif + WEB_CONTENTS_USER_DATA_KEY_IMPL(ChromePasswordManagerClient);
diff --git a/chrome/browser/password_manager/chrome_password_manager_client.h b/chrome/browser/password_manager/chrome_password_manager_client.h index 4156030..21a33aeb 100644 --- a/chrome/browser/password_manager/chrome_password_manager_client.h +++ b/chrome/browser/password_manager/chrome_password_manager_client.h
@@ -46,6 +46,8 @@ #if BUILDFLAG(IS_ANDROID) #include "chrome/browser/password_manager/android/generated_password_saved_message_delegate.h" +#include "chrome/browser/password_manager/android/password_manager_error_message_delegate.h" +#include "chrome/browser/password_manager/android/password_manager_error_message_helper_bridge_impl.h" #include "chrome/browser/password_manager/android/save_update_password_message_delegate.h" #include "components/password_manager/core/browser/credential_cache.h" @@ -131,6 +133,9 @@ const url::Origin& origin, CredentialsCallback callback) override; #if BUILDFLAG(IS_ANDROID) + void ShowPasswordManagerErrorMessage( + password_manager::ErrorMessageFlowType flow_type) override; + void ShowTouchToFill( password_manager::PasswordManagerDriver* driver, autofill::mojom::SubmissionReadinessState submission_readiness) override; @@ -378,6 +383,10 @@ content::RenderFrameHost* frame_host, const gfx::RectF& bounds_in_frame_coordinates); +#if BUILDFLAG(IS_ANDROID) + void ResetErrorMessageDelegate(); +#endif + const raw_ptr<Profile> profile_; password_manager::PasswordManager password_manager_; @@ -399,6 +408,9 @@ // reset when ime finish composing text event is triggered. std::u16string last_composing_text_; + std::unique_ptr<PasswordManagerErrorMessageDelegate> + password_manager_error_message_delegate_; + SaveUpdatePasswordMessageDelegate save_update_password_message_delegate_; GeneratedPasswordSavedMessageDelegate generated_password_saved_message_delegate_;
diff --git a/chrome/browser/password_manager/password_store_backend_factory.cc b/chrome/browser/password_manager/password_store_backend_factory.cc index 14a4396..acaf910 100644 --- a/chrome/browser/password_manager/password_store_backend_factory.cc +++ b/chrome/browser/password_manager/password_store_backend_factory.cc
@@ -7,6 +7,7 @@ #include "base/trace_event/trace_event.h" #include "build/build_config.h" +#include "chrome/browser/password_manager/android/password_manager_eviction_util.h" #include "chrome/browser/password_manager/password_manager_buildflags.h" #include "components/password_manager/core/browser/login_database.h" #include "components/password_manager/core/browser/password_store_built_in_backend.h" @@ -34,6 +35,11 @@ if (PasswordStoreAndroidBackendBridge::CanCreateBackend() && base::FeatureList::IsEnabled( password_manager::features::kUnifiedPasswordManagerAndroid)) { + // Re-enrollment happens before the initial migration and any possible + // backend interactions allowing to perform proper initialization. + if (password_manager_upm_eviction::ShouldInvalidateEviction(prefs)) + password_manager_upm_eviction::ReenrollCurrentUser(prefs); + base::UmaHistogramBoolean( "PasswordManager.PasswordStore.WasEnrolledInUPMWhenBackendWasCreated", !prefs->GetBoolean(password_manager::prefs::
diff --git a/chrome/browser/preferences/android/java/src/org/chromium/chrome/browser/preferences/ChromePreferenceKeys.java b/chrome/browser/preferences/android/java/src/org/chromium/chrome/browser/preferences/ChromePreferenceKeys.java index da1e4c82..f42bcc3 100644 --- a/chrome/browser/preferences/android/java/src/org/chromium/chrome/browser/preferences/ChromePreferenceKeys.java +++ b/chrome/browser/preferences/android/java/src/org/chromium/chrome/browser/preferences/ChromePreferenceKeys.java
@@ -760,7 +760,6 @@ /** * Keys used to store user actions for behavioral targeting of showing Start surface on startup. */ - public static final String PRIMARY_ACCOUNT_SYNC = "Chrome.StartSurface.PrimaryAccountSync"; public static final String START_SHOW_ON_STARTUP = "Chrome.StartSurface.ShownOnStartup"; public static final String START_NEXT_SHOW_ON_STARTUP_DECISION_MS = "Chrome.StartSurface.ShownOnStartupDecisionMs"; @@ -1143,7 +1142,6 @@ PRICE_TRACKING_PRICE_WELCOME_MESSAGE_CARD_SHOW_COUNT, PRICE_TRACKING_TRACK_PRICES_ON_TABS, PRICE_TRACKING_USER_MANAGED_NOTIFICATIONS_TIMESTAMPS, - PRIMARY_ACCOUNT_SYNC, PRIVACY_METRICS_REPORTING_PERMITTED_BY_USER, PRIVACY_METRICS_REPORTING_PERMITTED_BY_POLICY, PROMO_IS_DISMISSED.pattern(),
diff --git a/chrome/browser/profiles/profile_manager.cc b/chrome/browser/profiles/profile_manager.cc index 0c4bdd4f..e53c5d29 100644 --- a/chrome/browser/profiles/profile_manager.cc +++ b/chrome/browser/profiles/profile_manager.cc
@@ -600,6 +600,8 @@ // static Profile* ProfileManager::GetLastUsedProfile() { ProfileManager* profile_manager = g_browser_process->profile_manager(); + +#if BUILDFLAG(IS_CHROMEOS) #if BUILDFLAG(IS_CHROMEOS_ASH) // Use default login profile if user has not logged in yet. if (!IsLoggedIn()) @@ -607,15 +609,20 @@ // CrOS multi-profiles implementation is different so GetLastUsedProfile() // has custom implementation too. - base::FilePath profile_dir; // In case of multi-profiles we ignore "last used profile" preference // since it may refer to profile that has been in use in previous session. // That profile dir may not be mounted in this session so instead return // active profile from current session. - profile_dir = ash::ProfileHelper::Get()->GetActiveUserProfileDir(); - + base::FilePath profile_dir = + ash::ProfileHelper::Get()->GetActiveUserProfileDir(); Profile* profile = profile_manager->GetProfileByPath( profile_manager->user_data_dir().Append(profile_dir)); +#else + // TODO(crbug.com/1363933): Once Lacros is launched pre-login, we should + // probably do something analogous to the !IsLoggedIn() check above. + Profile* profile = + profile_manager->GetProfile(profile_manager->GetLastUsedProfileDir()); +#endif // BUILDFLAG(IS_CHROMEOS_ASH) // Accessing a user profile before it is loaded may lead to policy exploit. // See http://crbug.com/689206. @@ -627,7 +634,7 @@ : profile; #else return profile_manager->GetProfile(profile_manager->GetLastUsedProfileDir()); -#endif +#endif // BUILDFLAG(IS_CHROMEOS) } // static
diff --git a/chrome/browser/resources/settings/privacy_page/privacy_page.html b/chrome/browser/resources/settings/privacy_page/privacy_page.html index 74a2dc4..6524365 100644 --- a/chrome/browser/resources/settings/privacy_page/privacy_page.html +++ b/chrome/browser/resources/settings/privacy_page/privacy_page.html
@@ -515,7 +515,8 @@ <div class="secondary"> $i18n{siteSettingsNotificationsDescription} </div> - <template is="dom-if" if="[[safetyCheckPermissionsEnabled_]]"> + <template is="dom-if" + if="[[safetyCheckNotificationPermissionsEnabled_]]"> <review-notification-permissions> </review-notification-permissions> </template>
diff --git a/chrome/browser/resources/settings/privacy_page/privacy_page.ts b/chrome/browser/resources/settings/privacy_page/privacy_page.ts index 9ca8401..0a396c9 100644 --- a/chrome/browser/resources/settings/privacy_page/privacy_page.ts +++ b/chrome/browser/resources/settings/privacy_page/privacy_page.ts
@@ -233,10 +233,11 @@ value: ChooserType, }, - safetyCheckPermissionsEnabled_: { + safetyCheckNotificationPermissionsEnabled_: { type: Boolean, value() { - return loadTimeData.getBoolean('safetyCheckPermissionsEnabled'); + return loadTimeData.getBoolean( + 'safetyCheckNotificationPermissionsEnabled'); }, }, }; @@ -258,7 +259,7 @@ private showPrivacyGuideEntryPoint_: boolean; private enablePrivacyGuidePage_: boolean; private isPrivacySandboxRestricted_: boolean; - private safetyCheckPermissionsEnabled_: boolean; + private safetyCheckNotificationPermissionsEnabled_: boolean; private focusConfig_: FocusConfig; private searchFilter_: string; private siteDataFilter_: string;
diff --git a/chrome/browser/resources/settings/safety_check_page/safety_check_page.html b/chrome/browser/resources/settings/safety_check_page/safety_check_page.html index 8393426..d97f5cf 100644 --- a/chrome/browser/resources/settings/safety_check_page/safety_check_page.html +++ b/chrome/browser/resources/settings/safety_check_page/safety_check_page.html
@@ -48,10 +48,13 @@ </settings-safety-check-chrome-cleaner-child> </if> </iron-collapse> - <template is="dom-if" if="[[safetyCheckPermissionsEnabled_]]" + <template is="dom-if" if="[[safetyCheckUnusedSitePermissionsEnabled_]]" restamp> <settings-safety-check-unused-site-permissions> </settings-safety-check-unused-site-permissions> + </template> + <template is="dom-if" if="[[safetyCheckNotificationPermissionsEnabled_]]" + restamp> <settings-safety-check-notification-permissions> </settings-safety-check-notification-permissions> </template>
diff --git a/chrome/browser/resources/settings/safety_check_page/safety_check_page.ts b/chrome/browser/resources/settings/safety_check_page/safety_check_page.ts index 4077939..8bad37d 100644 --- a/chrome/browser/resources/settings/safety_check_page/safety_check_page.ts +++ b/chrome/browser/resources/settings/safety_check_page/safety_check_page.ts
@@ -68,14 +68,22 @@ /** UI string to display for the parent status. */ parentDisplayString_: String, - /** - * Boolean that decides if the entry point for unused site permissions - * should be shown. - */ - safetyCheckPermissionsEnabled_: { + /** Boolean to show/hide entry point for notification permissions. */ + safetyCheckNotificationPermissionsEnabled_: { type: Boolean, value() { - return loadTimeData.getBoolean('safetyCheckPermissionsEnabled'); + return loadTimeData.getBoolean( + 'safetyCheckNotificationPermissionsEnabled'); + }, + }, + + + /** Boolean to show/hide entry point for unused site permissions. */ + safetyCheckUnusedSitePermissionsEnabled_: { + type: Boolean, + value() { + return loadTimeData.getBoolean( + 'safetyCheckUnusedSitePermissionsEnabled'); }, }, }; @@ -83,7 +91,8 @@ private parentStatus_: SafetyCheckParentStatus; private parentDisplayString_: string; - private safetyCheckPermissionsEnabled_: boolean; + private safetyCheckNotificationPermissionsEnabled_: boolean; + private safetyCheckUnusedSitePermissionsEnabled_: boolean; private safetyCheckBrowserProxy_: SafetyCheckBrowserProxy = SafetyCheckBrowserProxyImpl.getInstance(); private metricsBrowserProxy_: MetricsBrowserProxy =
diff --git a/chrome/browser/resources/webui_gallery/BUILD.gn b/chrome/browser/resources/webui_gallery/BUILD.gn index 41b6435..ad307d21 100644 --- a/chrome/browser/resources/webui_gallery/BUILD.gn +++ b/chrome/browser/resources/webui_gallery/BUILD.gn
@@ -66,6 +66,7 @@ "demos/cr_action_menu_demo.html", "demos/cr_checkbox_demo.html", "demos/cr_dialog_demo.html", + "demos/cr_icons/cr_icons_demo.html", "demos/cr_input/cr_input_demo.html", "demos/cr_radio_demo.html", "demos/cr_slider/cr_slider_demo.html",
diff --git a/chrome/browser/resources/webui_gallery/app.ts b/chrome/browser/resources/webui_gallery/app.ts index d52a165ac..2b0ef70 100644 --- a/chrome/browser/resources/webui_gallery/app.ts +++ b/chrome/browser/resources/webui_gallery/app.ts
@@ -60,6 +60,11 @@ src: 'cr_dialog_demo.html', }, { + name: 'Icons', + path: 'icons', + src: 'cr_icons/cr_icons_demo.html', + }, + { name: 'Inputs', path: 'inputs', src: 'cr_input/cr_input_demo.html',
diff --git a/chrome/browser/resources/webui_gallery/demos/cr_icons/cr_icons_demo.html b/chrome/browser/resources/webui_gallery/demos/cr_icons/cr_icons_demo.html new file mode 100644 index 0000000..557b79e --- /dev/null +++ b/chrome/browser/resources/webui_gallery/demos/cr_icons/cr_icons_demo.html
@@ -0,0 +1,12 @@ +<!doctype html> +<html> + <head> + <meta charset="utf-8"> + <title>cr-icons demo</title> + <link rel="stylesheet" href="../demo.css"> + </head> + <body> + <cr-icons-demo></cr-icons-demo> + <script src="cr_icons_demo_component.js" type="module"></script> + </body> +</html>
diff --git a/chrome/browser/resources/webui_gallery/demos/cr_icons/cr_icons_demo_component.html b/chrome/browser/resources/webui_gallery/demos/cr_icons/cr_icons_demo_component.html new file mode 100644 index 0000000..99413df --- /dev/null +++ b/chrome/browser/resources/webui_gallery/demos/cr_icons/cr_icons_demo_component.html
@@ -0,0 +1,99 @@ +<link rel="stylesheet" href="../demo.css"> +<style include="cr-icons"> + .icons { + display: grid; + font-size: 11px; + gap: 12px; + grid-auto-rows: 75px; + grid-template-columns: repeat(auto-fill, 75px); + text-align: center; + width: 100%; + } + + .icon { + align-items: center; + display: flex; + flex-direction: column; + justify-content: center; + } + + .icon iron-icon, + .icon .cr-icon { + margin-block-end: 12px; + } + + .label { + height: 30%; + } + + cr-input { + --cr-input-error-display: none; + } +</style> + +<h1>cr iron-icons</h1> +<div class="demos"> + <div>Commonly used iron-icons across WebUI built with SVG.</div> + <div class="icons" style$=" + --iron-icon-fill-color: [[iconColor_]]; + --iron-icon-height: [[iconSize_]]px; + --iron-icon-width: [[iconSize_]]px; + "> + <template is="dom-repeat" items="[[ironIcons_]]" as="icon"> + <div class="icon"> + <iron-icon icon="[[icon]]"></iron-icon> + <div class="label">[[icon]]</div> + </div> + </template> + </div> +</div> + +<h1>Custom iron-icons</h1> +<div class="demos"> + <div>An example of a custom iconset for an app using iron-iconset-svg.</div> + <iron-iconset-svg name="desserts"> + <svg> + <defs> + <g id="cake"><path d="M4 22q-.425 0-.712-.288Q3 21.425 3 21v-5q0-.825.587-1.413Q4.175 14 5 14v-4q0-.825.588-1.413Q6.175 8 7 8h4V6.55q-.45-.3-.725-.725Q10 5.4 10 4.8q0-.375.15-.738.15-.362.45-.662L12 2l1.4 1.4q.3.3.45.662.15.363.15.738 0 .6-.275 1.025-.275.425-.725.725V8h4q.825 0 1.413.587Q19 9.175 19 10v4q.825 0 1.413.587Q21 15.175 21 16v5q0 .425-.288.712Q20.425 22 20 22Zm3-8h10v-4H7Zm-2 6h14v-4H5Zm2-6h10Zm-2 6h14Zm14-6H5h14Z"></g> + </defs> + </svg> + </iron-iconset-svg> + <div class="icons" style$=" + --iron-icon-fill-color: [[iconColor_]]; + --iron-icon-height: [[iconSize_]]px; + --iron-icon-width: [[iconSize_]]px; + "> + <div class="icon"> + <iron-icon icon="desserts:cake"></iron-icon> + <div class="label">desserts:cake</div> + </div> + </div> +</div> + +<h1>cr-icons CSS classes</h1> +<div class="demos"> + <div>CSS classes to display icons, typically for cr-icon-button.</div> + <div class="icons" style$=" + --cr-icon-color: [[iconColor_]]; + --cr-icon-ripple-size: [[iconSize_]]px; + --cr-icon-size: [[iconSize_]]px; + "> + <template is="dom-repeat" items="[[crIcons_]]" as="icon"> + <div class="icon"> + <div class$="cr-icon no-overlap [[icon]]"></div> + <div class="label">.[[icon]]</div> + </div> + </template> + </div> +</div> + +<h1>Custom controls</h1> +<div class="demos"> + <cr-input type="number" min="12" max="128" value="{{iconSize_}}" + label="Icon size"></cr-input> + + <label> + <input type="color" value="[[iconColor_]]" on-input="onIconColorInput_"> + Icon fill color + </label> +</div>
diff --git a/chrome/browser/resources/webui_gallery/demos/cr_icons/cr_icons_demo_component.ts b/chrome/browser/resources/webui_gallery/demos/cr_icons/cr_icons_demo_component.ts new file mode 100644 index 0000000..80b8b9a9 --- /dev/null +++ b/chrome/browser/resources/webui_gallery/demos/cr_icons/cr_icons_demo_component.ts
@@ -0,0 +1,80 @@ +// 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 '//resources/cr_elements/cr_icons.css.js'; +import '//resources/cr_elements/cr_input/cr_input.js'; +import '//resources/cr_elements/icons.html.js'; +import '//resources/polymer/v3_0/iron-icon/iron-icon.js'; + +import {assert} from '//resources/js/assert_ts.js'; +import {IronIconsetSvgElement} from '//resources/polymer/v3_0/iron-iconset-svg/iron-iconset-svg.js'; +import {PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js'; + +import {getTemplate} from './cr_icons_demo_component.html.js'; + +class CrIconsDemoComponent extends PolymerElement { + static get is() { + return 'cr-icons-demo'; + } + + static get template() { + return getTemplate(); + } + + static get properties() { + return { + crIcons_: Array, + iconColor_: String, + iconSize_: String, + ironIcons_: Array, + }; + } + + private crIcons_: string[] = [ + 'icon-arrow-back', + 'icon-arrow-dropdown', + 'icon-cancel', + 'icon-clear', + 'icon-copy-content', + 'icon-delete-gray', + 'icon-edit', + 'icon-picture-delete', + 'icon-expand-less', + 'icon-expand-more', + 'icon-external', + 'icon-more-vert', + 'icon-refresh', + 'icon-search', + 'icon-settings', + 'icon-visibility', + 'icon-visibility-off', + 'subpage-arrow', + ]; + private iconColor_: string = '#000000'; + private iconSize_: string = '24'; + private ironIcons_: string[] = []; + + override ready() { + super.ready(); + + // Iconsets are appended to the document's head element when they are + // imported. + const crIconsSet = document.head.querySelector<IronIconsetSvgElement>( + 'iron-iconset-svg[name=cr]'); + assert(crIconsSet); + this.push('ironIcons_', ...crIconsSet.getIconNames()); + + const cr20IconsSet = document.head.querySelector<IronIconsetSvgElement>( + 'iron-iconset-svg[name=cr20]'); + assert(cr20IconsSet); + this.push('ironIcons_', ...cr20IconsSet.getIconNames()); + } + + private onIconColorInput_(e: Event) { + const color = (e.target as HTMLInputElement).value; + this.iconColor_ = color; + } +} + +customElements.define(CrIconsDemoComponent.is, CrIconsDemoComponent);
diff --git a/chrome/browser/resources/webui_gallery/webui_gallery.gni b/chrome/browser/resources/webui_gallery/webui_gallery.gni index 6efe0b1..7b049e50 100644 --- a/chrome/browser/resources/webui_gallery/webui_gallery.gni +++ b/chrome/browser/resources/webui_gallery/webui_gallery.gni
@@ -8,6 +8,7 @@ "demos/cr_a11y_announcer_demo_component.ts", "demos/cr_action_menu_demo_component.ts", "demos/cr_dialog_demo_component.ts", + "demos/cr_icons/cr_icons_demo_component.ts", "demos/cr_input/cr_input_demo_component.ts", "demos/cr_slider/cr_slider_demo_component.ts", "demos/cr_tabs/cr_tabs_demo_component.ts",
diff --git a/chrome/browser/translate/translate_frame_binder_browsertest.cc b/chrome/browser/translate/translate_frame_binder_browsertest.cc index 2e8b394..ff28939 100644 --- a/chrome/browser/translate/translate_frame_binder_browsertest.cc +++ b/chrome/browser/translate/translate_frame_binder_browsertest.cc
@@ -175,7 +175,7 @@ }; // TODO(crbug.com/1312008): Re-enable this test -#if BUILDFLAG(IS_CHROMEOS_LACROS) +#if BUILDFLAG(IS_CHROMEOS) #define MAYBE_NotBindingInFencedFrame DISABLED_NotBindingInFencedFrame #else #define MAYBE_NotBindingInFencedFrame NotBindingInFencedFrame
diff --git a/chrome/browser/ui/BUILD.gn b/chrome/browser/ui/BUILD.gn index b281f2a2..a71bc40 100644 --- a/chrome/browser/ui/BUILD.gn +++ b/chrome/browser/ui/BUILD.gn
@@ -3538,10 +3538,14 @@ "views/profiles/profile_customization_bubble_sync_controller.h", "views/profiles/profile_customization_bubble_view.cc", "views/profiles/profile_customization_bubble_view.h", + "views/profiles/profile_management_flow_controller.cc", + "views/profiles/profile_management_flow_controller.h", "views/profiles/profile_management_step_controller.cc", "views/profiles/profile_management_step_controller.h", "views/profiles/profile_menu_view.cc", "views/profiles/profile_menu_view.h", + "views/profiles/profile_picker_flow_controller.cc", + "views/profiles/profile_picker_flow_controller.h", "views/profiles/profile_picker_force_signin_dialog_delegate.cc", "views/profiles/profile_picker_force_signin_dialog_delegate.h", "views/profiles/profile_picker_force_signin_dialog_host.cc",
diff --git a/chrome/browser/ui/app_list/app_list_remove_space_browsertest.cc b/chrome/browser/ui/app_list/app_list_remove_space_browsertest.cc deleted file mode 100644 index cd2c1e5..0000000 --- a/chrome/browser/ui/app_list/app_list_remove_space_browsertest.cc +++ /dev/null
@@ -1,98 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ash/constants/ash_features.h" -#include "ash/public/cpp/accelerators.h" -#include "ash/public/cpp/pagination/pagination_model.h" -#include "ash/public/cpp/test/app_list_test_api.h" -#include "ash/public/cpp/test/shell_test_api.h" -#include "chrome/browser/extensions/extension_browsertest.h" -#include "chrome/browser/ui/app_list/app_list_client_impl.h" -#include "content/public/test/browser_test.h" - -// Verifies the compatibility between the environment with -// kLauncherRemoveEmptySpace enabled and the one with the feature flag disabled. -class AppListRemoveSpaceSyncCompatibilityTest - : public extensions::ExtensionBrowserTest { - public: - AppListRemoveSpaceSyncCompatibilityTest() = default; - AppListRemoveSpaceSyncCompatibilityTest( - const AppListRemoveSpaceSyncCompatibilityTest&) = delete; - AppListRemoveSpaceSyncCompatibilityTest& operator=( - const AppListRemoveSpaceSyncCompatibilityTest&) = delete; - ~AppListRemoveSpaceSyncCompatibilityTest() override = default; - - protected: - void SetUp() override { - // Enable the feature flag to remove extra spaces if the pre count is one. - if (GetTestPreCount() == 1) { - feature_list_.InitAndEnableFeature(ash::features::kProductivityLauncher); - } else { - feature_list_.InitAndDisableFeature(ash::features::kProductivityLauncher); - } - extensions::ExtensionBrowserTest::SetUp(); - } - - void SetUpOnMainThread() override { - ExtensionBrowserTest::SetUpOnMainThread(); - AppListClientImpl* client = AppListClientImpl::GetInstance(); - ASSERT_TRUE(client); - client->UpdateProfile(); - - // Ensure async callbacks are run. - base::RunLoop().RunUntilIdle(); - - // Run the test in tablet mode, so app list shows paged apps grid view when - // the productivity launcher is enabled. - ash::ShellTestApi().SetTabletModeEnabledForTest(true); - - // Create the app list view by triggering the accelerator to show it. - ash::AcceleratorController::Get()->PerformActionIfEnabled( - ash::TOGGLE_APP_LIST, {}); - } - - ash::AppListTestApi app_list_test_api_; - base::test::ScopedFeatureList feature_list_; -}; - -// Configure the launcher with the feature flag disabled. -IN_PROC_BROWSER_TEST_F(AppListRemoveSpaceSyncCompatibilityTest, - PRE_PRE_Basics) { - // Assume that the feature flag is disabled. - ASSERT_FALSE(ash::features::IsProductivityLauncherEnabled()); - - // Assume that there are two default apps. - ASSERT_EQ(2, app_list_test_api_.GetTopListItemCount()); - - // Add two apps. - const std::string app1_id = - LoadExtension(test_data_dir_.AppendASCII("app1"))->id(); - ASSERT_FALSE(app1_id.empty()); - const std::string app2_id = - LoadExtension(test_data_dir_.AppendASCII("app2"))->id(); - ASSERT_FALSE(app2_id.empty()); - - // Totally four items because two added apps besides two default apps. - EXPECT_EQ(4, app_list_test_api_.GetTopListItemCount()); - - // Add one page break item after app1. - app_list_test_api_.AddPageBreakItemAfterId(app1_id); - EXPECT_EQ(5, app_list_test_api_.GetTopListItemCount()); -} - -// Restart Chrome with the feature enabled. -IN_PROC_BROWSER_TEST_F(AppListRemoveSpaceSyncCompatibilityTest, PRE_Basics) { - ASSERT_TRUE(ash::features::IsProductivityLauncherEnabled()); - - // Because empty spaces are removed, there should be only one page. - EXPECT_EQ(1, app_list_test_api_.GetPaginationModel()->total_pages()); - EXPECT_EQ(4, app_list_test_api_.GetTopListItemCount()); -} - -// Restart Chrome with the feature disabled. -IN_PROC_BROWSER_TEST_F(AppListRemoveSpaceSyncCompatibilityTest, Basics) { - // The flag to remove empty spaces is turned off so there should be two pages. - EXPECT_EQ(2, app_list_test_api_.GetPaginationModel()->total_pages()); - EXPECT_EQ(5, app_list_test_api_.GetTopListItemCount()); -}
diff --git a/chrome/browser/ui/app_list/chrome_app_list_model_updater_browsertest.cc b/chrome/browser/ui/app_list/chrome_app_list_model_updater_browsertest.cc index e6b2fcb..2503e394 100644 --- a/chrome/browser/ui/app_list/chrome_app_list_model_updater_browsertest.cc +++ b/chrome/browser/ui/app_list/chrome_app_list_model_updater_browsertest.cc
@@ -154,16 +154,6 @@ ChromeAppListModelUpdaterTest, ::testing::Bool()); -// Test cases with productivity launcher enabled. -class ChromeAppListModelUpdaterLegacyLauncherTest - : public ChromeAppListModelUpdaterTestBase { - public: - ChromeAppListModelUpdaterLegacyLauncherTest() - : ChromeAppListModelUpdaterTestBase( - /*enable_productivity_launcher=*/false) {} - ~ChromeAppListModelUpdaterLegacyLauncherTest() override = default; -}; - class ChromeAppListModelUpdaterProductivityLauncherTest : public ChromeAppListModelUpdaterTestBase { public: @@ -744,40 +734,3 @@ EXPECT_FALSE(app2_item->is_new_install()); EXPECT_FALSE(folder_item->is_new_install()); } - -IN_PROC_BROWSER_TEST_F(ChromeAppListModelUpdaterLegacyLauncherTest, - PRE_PersistTrailingUserCreatedPage) { - const std::string app1_id = - LoadExtension(test_data_dir_.AppendASCII("app1"))->id(); - ASSERT_FALSE(app1_id.empty()); - const std::string app2_id = - LoadExtension(test_data_dir_.AppendASCII("app2"))->id(); - ASSERT_FALSE(app2_id.empty()); - - // Create the app list view and show the apps grid. - ash::AcceleratorController::Get()->PerformActionIfEnabled( - ash::TOGGLE_APP_LIST, {}); - ASSERT_EQ(1, app_list_test_api_.GetPaginationModel()->total_pages()); - - app_list_test_api_.GetLastItemInAppsGridView()->RequestFocus(); - - ASSERT_TRUE(ui_test_utils::SendKeyPressToWindowSync( - nullptr, ui::VKEY_DOWN, /*control=*/true, /*shift=*/false, - /*alt=*/false, /*command=*/false)); - EXPECT_EQ(2, app_list_test_api_.GetPaginationModel()->total_pages()); -} - -IN_PROC_BROWSER_TEST_F(ChromeAppListModelUpdaterLegacyLauncherTest, - PersistTrailingUserCreatedPage) { - const std::string app1_id = - LoadExtension(test_data_dir_.AppendASCII("app1"))->id(); - ASSERT_FALSE(app1_id.empty()); - const std::string app2_id = - LoadExtension(test_data_dir_.AppendASCII("app2"))->id(); - ASSERT_FALSE(app2_id.empty()); - - // Verify that the app list still has 2 pages after session restart. - ash::AcceleratorController::Get()->PerformActionIfEnabled( - ash::TOGGLE_APP_LIST, {}); - EXPECT_EQ(2, app_list_test_api_.GetPaginationModel()->total_pages()); -}
diff --git a/chrome/browser/ui/ash/holding_space/holding_space_keyed_service.cc b/chrome/browser/ui/ash/holding_space/holding_space_keyed_service.cc index 8a6f137c..447378cb 100644 --- a/chrome/browser/ui/ash/holding_space/holding_space_keyed_service.cc +++ b/chrome/browser/ui/ash/holding_space/holding_space_keyed_service.cc
@@ -449,8 +449,6 @@ // The `HoldingSpaceSuggestionsDelegate` manages file suggestions (i.e. the // files predicted to be used). - // TODO(https://crbug.com/1364240): ensure that if the feature is disabled, - // the suggestions restored from the persistence do not appear in the model. if (features::IsHoldingSpaceSuggestionsEnabled()) { delegates_.push_back(std::make_unique<HoldingSpaceSuggestionsDelegate>( this, &holding_space_model_));
diff --git a/chrome/browser/ui/ash/holding_space/holding_space_keyed_service_unittest.cc b/chrome/browser/ui/ash/holding_space/holding_space_keyed_service_unittest.cc index ec0820e..4b0271b 100644 --- a/chrome/browser/ui/ash/holding_space/holding_space_keyed_service_unittest.cc +++ b/chrome/browser/ui/ash/holding_space/holding_space_keyed_service_unittest.cc
@@ -498,13 +498,28 @@ arc::ArcServiceManager arc_service_manager_; }; -class HoldingSpaceKeyedServiceWithPredictabilityFeatureTest +class HoldingSpaceKeyedServiceWithExperimentalFeatureTest : public HoldingSpaceKeyedServiceTest, - public testing::WithParamInterface<bool> { + public testing::WithParamInterface< + std::tuple</*enable_predictability=*/bool, + /*enable_suggestion=*/bool>> { public: - HoldingSpaceKeyedServiceWithPredictabilityFeatureTest() { - scoped_feature_list_.InitWithFeatureState( - features::kHoldingSpacePredictability, GetParam()); + HoldingSpaceKeyedServiceWithExperimentalFeatureTest() { + std::vector<base::Feature> enabled_features; + std::vector<base::Feature> disabled_features; + if (std::get<0>(GetParam())) { + enabled_features.push_back(features::kHoldingSpacePredictability); + } else { + disabled_features.push_back(features::kHoldingSpacePredictability); + } + + if (std::get<1>(GetParam())) { + enabled_features.push_back(features::kHoldingSpaceSuggestions); + } else { + disabled_features.push_back(features::kHoldingSpaceSuggestions); + } + + scoped_feature_list_.InitWithFeatures(enabled_features, disabled_features); } private: @@ -512,11 +527,10 @@ }; INSTANTIATE_TEST_SUITE_P(All, - HoldingSpaceKeyedServiceWithPredictabilityFeatureTest, - ::testing::Bool()); + HoldingSpaceKeyedServiceWithExperimentalFeatureTest, + testing::Combine(testing::Bool(), testing::Bool())); -TEST_P(HoldingSpaceKeyedServiceWithPredictabilityFeatureTest, - GuestUserProfile) { +TEST_P(HoldingSpaceKeyedServiceWithExperimentalFeatureTest, GuestUserProfile) { // Construct a guest session profile. TestingProfile::Builder guest_profile_builder; guest_profile_builder.SetGuestSession(); @@ -571,7 +585,7 @@ secondary_otr_guest_profile_service); } -TEST_P(HoldingSpaceKeyedServiceWithPredictabilityFeatureTest, +TEST_P(HoldingSpaceKeyedServiceWithExperimentalFeatureTest, OffTheRecordProfile) { // Service instances should be created for on the record profiles. HoldingSpaceKeyedService* const primary_profile_service = @@ -595,7 +609,7 @@ ASSERT_FALSE(incognito_primary_profile_service); } -TEST_P(HoldingSpaceKeyedServiceWithPredictabilityFeatureTest, +TEST_P(HoldingSpaceKeyedServiceWithExperimentalFeatureTest, SecondaryUserProfile) { HoldingSpaceKeyedService* const primary_holding_space_service = HoldingSpaceKeyedServiceFactory::GetInstance()->GetService(GetProfile()); @@ -621,7 +635,7 @@ } // Verifies that updates to the holding space model are persisted. -TEST_P(HoldingSpaceKeyedServiceWithPredictabilityFeatureTest, +TEST_P(HoldingSpaceKeyedServiceWithExperimentalFeatureTest, UpdatePersistentStorage) { // Create a file system mount point. std::unique_ptr<ScopedTestMountPoint> downloads_mount = @@ -674,7 +688,7 @@ // Verifies that only finalized holding space items are persisted and that, // once finalized, previously in progress holding space items are persisted at // the appropriate index. -TEST_P(HoldingSpaceKeyedServiceWithPredictabilityFeatureTest, +TEST_P(HoldingSpaceKeyedServiceWithExperimentalFeatureTest, PersistenceOfInProgressItems) { // Create a file system mount point. std::unique_ptr<ScopedTestMountPoint> downloads_mount = @@ -802,7 +816,7 @@ // Verifies that when a file backing a holding space item is moved, the holding // space item is updated in place and persistence storage is updated. -TEST_P(HoldingSpaceKeyedServiceWithPredictabilityFeatureTest, +TEST_P(HoldingSpaceKeyedServiceWithExperimentalFeatureTest, UpdatePersistentStorageAfterMove) { // Create a file system mount point. std::unique_ptr<ScopedTestMountPoint> downloads_mount = @@ -929,7 +943,7 @@ // backing file is changed using move operation. Furthermore, verifies that // conflicts caused by moving a holding space item file to another path present // in the holding space get resolved. -TEST_P(HoldingSpaceKeyedServiceWithPredictabilityFeatureTest, +TEST_P(HoldingSpaceKeyedServiceWithExperimentalFeatureTest, UpdateItemsOverwrittenByMove) { // Create a file system mount point. std::unique_ptr<ScopedTestMountPoint> downloads_mount = @@ -1074,7 +1088,7 @@ // Verifies that the holding space model is restored from persistence. Note that // when restoring from persistence, existence of backing files is verified and // any stale holding space items are removed. -TEST_P(HoldingSpaceKeyedServiceWithPredictabilityFeatureTest, +TEST_P(HoldingSpaceKeyedServiceWithExperimentalFeatureTest, RestorePersistentStorage) { // Verify expected histograms. base::HistogramTester histogram_tester; @@ -1117,15 +1131,21 @@ persisted_holding_space_items_before_restoration.Append( fresh_holding_space_item->Serialize()); - // We expect the `fresh_holding_space_item` to still be in persistence - // after model restoration since its backing file exists. - persisted_holding_space_items_after_restoration.Append( - fresh_holding_space_item->Serialize()); + // Suggestions should not be restored if the suggestion feature is + // disabled. + if (!HoldingSpaceItem::IsSuggestion(type) || + features::IsHoldingSpaceSuggestionsEnabled()) { + // We expect the `fresh_holding_space_item` to still be in + // persistence after model restoration since its backing file + // exists. + persisted_holding_space_items_after_restoration.Append( + fresh_holding_space_item->Serialize()); - // We expect the `fresh_holding_space_item` to be restored from - // persistence since its backing file exists. - restored_holding_space_items.push_back( - std::move(fresh_holding_space_item)); + // We expect the `fresh_holding_space_item` to be restored from + // persistence since its backing file exists. + restored_holding_space_items.push_back( + std::move(fresh_holding_space_item)); + } base::FilePath file_path = downloads_mount->GetRootPath().AppendASCII( base::UnguessableToken::Create().ToString()); @@ -1184,16 +1204,21 @@ "HoldingSpace.Item.TotalCount.All", secondary_holding_space_model->items().size(), 1); for (const HoldingSpaceItem::Type type : GetHoldingSpaceItemTypes()) { + // Suggestions are not added to the model if the feature is disabled. + const bool should_restore = !HoldingSpaceItem::IsSuggestion(type) || + features::IsHoldingSpaceSuggestionsEnabled(); + const int expected_count = should_restore ? 1 : 0; + histogram_tester.ExpectBucketCount( base::StringPrintf("HoldingSpace.Item.TotalCount.%s", holding_space_util::ToString(type).c_str()), - /*sample=*/1, /*expected_count=*/1); + /*sample=*/1, expected_count); } } // Verifies that items from volumes that are not immediately mounted during // startup get restored into the holding space. -TEST_P(HoldingSpaceKeyedServiceWithPredictabilityFeatureTest, +TEST_P(HoldingSpaceKeyedServiceWithExperimentalFeatureTest, RestorePersistentStorageForDelayedVolumeMount) { // Create file system mount point. std::unique_ptr<ScopedTestMountPoint> downloads_mount = @@ -1226,16 +1251,25 @@ HoldingSpaceItem::CreateFileBackedItem( type, delayed_mount_file, GURL("filesystem:fake"), base::BindOnce(&CreateTestHoldingSpaceImage)); - // The item should be restored after delayed volume mount, and remain - // in persistent storage. persisted_holding_space_items_before_restoration.Append( delayed_holding_space_item->Serialize()); - persisted_holding_space_items_after_restoration.Append( - delayed_holding_space_item->Serialize()); - persisted_holding_space_items_after_delayed_mount.Append( - delayed_holding_space_item->Serialize()); - restored_holding_space_items.push_back( - std::move(delayed_holding_space_item)); + + // Suggestions should not be restored if the suggestion feature is + // disabled. + const bool should_restore = + !HoldingSpaceItem::IsSuggestion(type) || + features::IsHoldingSpaceSuggestionsEnabled(); + + // If an item should be restored, it should be restored after delayed + // volume mount, and remain in persistent storage. + if (should_restore) { + persisted_holding_space_items_after_restoration.Append( + delayed_holding_space_item->Serialize()); + persisted_holding_space_items_after_delayed_mount.Append( + delayed_holding_space_item->Serialize()); + restored_holding_space_items.push_back( + std::move(delayed_holding_space_item)); + } const base::FilePath non_existent_path = delayed_mount->GetRootPath().Append("non-existent"); @@ -1249,8 +1283,11 @@ // until the associated volume is mounted. persisted_holding_space_items_before_restoration.Append( non_existant_delayed_holding_space_item->Serialize()); - persisted_holding_space_items_after_restoration.Append( - non_existant_delayed_holding_space_item->Serialize()); + + if (should_restore) { + persisted_holding_space_items_after_restoration.Append( + non_existant_delayed_holding_space_item->Serialize()); + } const base::FilePath file = downloads_mount->CreateArbitraryFile(); const GURL file_system_url = GetFileSystemUrl(GetProfile(), file); @@ -1260,19 +1297,21 @@ base::BindOnce(&holding_space_util::ResolveImage, primary_holding_space_service ->thumbnail_loader_for_testing())); - - // The item should be immediately added to the model, and remain in - // the persistent storage. persisted_holding_space_items_before_restoration.Append( fresh_holding_space_item->Serialize()); - initialized_items_before_delayed_mount.push_back( - fresh_holding_space_item->id()); - persisted_holding_space_items_after_restoration.Append( - fresh_holding_space_item->Serialize()); - persisted_holding_space_items_after_delayed_mount.Append( - fresh_holding_space_item->Serialize()); - restored_holding_space_items.push_back( - std::move(fresh_holding_space_item)); + + // The item should be immediately added to the model, and remain in + // the persistent storage if it should be restored. + if (should_restore) { + initialized_items_before_delayed_mount.push_back( + fresh_holding_space_item->id()); + persisted_holding_space_items_after_restoration.Append( + fresh_holding_space_item->Serialize()); + persisted_holding_space_items_after_delayed_mount.Append( + fresh_holding_space_item->Serialize()); + restored_holding_space_items.push_back( + std::move(fresh_holding_space_item)); + } } pref_store->SetValueSilently( @@ -1350,7 +1389,7 @@ // startup get restored into the holding space - same as // RestorePersistentStorageForDelayedVolumeMount, but the volume gets mounted // while item restoration is in progress. -TEST_P(HoldingSpaceKeyedServiceWithPredictabilityFeatureTest, +TEST_P(HoldingSpaceKeyedServiceWithExperimentalFeatureTest, RestorePersistentStorageForDelayedVolumeMountDuringRestoration) { // Create file system mount point. std::unique_ptr<ScopedTestMountPoint> downloads_mount = @@ -1381,14 +1420,23 @@ HoldingSpaceItem::CreateFileBackedItem( type, delayed_mount_file, GURL("filesystem:fake"), base::BindOnce(&CreateTestHoldingSpaceImage)); - // The item should be restored after delayed volume mount, and remain - // in persistent storage. persisted_holding_space_items_before_restoration.Append( delayed_holding_space_item->Serialize()); - persisted_holding_space_items_after_delayed_mount.Append( - delayed_holding_space_item->Serialize()); - restored_holding_space_items.push_back( - std::move(delayed_holding_space_item)); + + // Suggestions should not be restored if the suggestion feature is + // disabled. + const bool should_restore = + !HoldingSpaceItem::IsSuggestion(type) || + features::IsHoldingSpaceSuggestionsEnabled(); + + // The item is restored after delayed volume mount, and remain + // in persistent storage if it should be restored. + if (should_restore) { + persisted_holding_space_items_after_delayed_mount.Append( + delayed_holding_space_item->Serialize()); + restored_holding_space_items.push_back( + std::move(delayed_holding_space_item)); + } base::FilePath non_existent_path = delayed_mount->GetRootPath().Append("non-existent"); @@ -1412,14 +1460,17 @@ primary_holding_space_service ->thumbnail_loader_for_testing())); - // The item should be immediately added to the model, and remain in - // the persistent storage. persisted_holding_space_items_before_restoration.Append( fresh_holding_space_item->Serialize()); - persisted_holding_space_items_after_delayed_mount.Append( - fresh_holding_space_item->Serialize()); - restored_holding_space_items.push_back( - std::move(fresh_holding_space_item)); + + // The item should be immediately added to the model, and remain in + // the persistent storage if it should be restored. + if (should_restore) { + persisted_holding_space_items_after_delayed_mount.Append( + fresh_holding_space_item->Serialize()); + restored_holding_space_items.push_back( + std::move(fresh_holding_space_item)); + } } pref_store->SetValueSilently( @@ -1475,7 +1526,7 @@ // Verifies that mounting volumes that contain no holding space items does not // interfere with holding space restoration. -TEST_P(HoldingSpaceKeyedServiceWithPredictabilityFeatureTest, +TEST_P(HoldingSpaceKeyedServiceWithExperimentalFeatureTest, RestorePersistentStorageWithUnrelatedVolumeMounts) { // Create file system mount point. std::unique_ptr<ScopedTestMountPoint> downloads_mount = @@ -1514,18 +1565,24 @@ primary_holding_space_service ->thumbnail_loader_for_testing())); - // The item should be immediately added to the model, and remain in - // the persistent storage. persisted_holding_space_items_before_restoration.Append( fresh_holding_space_item->Serialize()); - initialized_items_before_delayed_mount.push_back( - fresh_holding_space_item->id()); - persisted_holding_space_items_after_restoration.Append( - fresh_holding_space_item->Serialize()); - persisted_holding_space_items_after_delayed_mount.Append( - fresh_holding_space_item->Serialize()); - restored_holding_space_items.push_back( - std::move(fresh_holding_space_item)); + + // The item should be immediately added to the model, and remain in + // the persistent storage if it should be restored. + const bool should_restore = + !HoldingSpaceItem::IsSuggestion(type) || + features::IsHoldingSpaceSuggestionsEnabled(); + if (should_restore) { + initialized_items_before_delayed_mount.push_back( + fresh_holding_space_item->id()); + persisted_holding_space_items_after_restoration.Append( + fresh_holding_space_item->Serialize()); + persisted_holding_space_items_after_delayed_mount.Append( + fresh_holding_space_item->Serialize()); + restored_holding_space_items.push_back( + std::move(fresh_holding_space_item)); + } } pref_store->SetValueSilently( @@ -1593,7 +1650,7 @@ } // Tests that items from an unmounted volume get removed from the holding space. -TEST_P(HoldingSpaceKeyedServiceWithPredictabilityFeatureTest, +TEST_P(HoldingSpaceKeyedServiceWithExperimentalFeatureTest, RemoveItemsFromUnmountedVolumes) { auto test_mount_1 = std::make_unique<ScopedTestMountPoint>( "test_mount_1", storage::kFileSystemTypeLocal, @@ -1643,7 +1700,7 @@ // `kMaxFileAge`, when the predictability feature is off. // Verifies that files restored from persistence are restored, regardless of // `kMaxFileAge`, when the predictability feature is on. -TEST_P(HoldingSpaceKeyedServiceWithPredictabilityFeatureTest, +TEST_P(HoldingSpaceKeyedServiceWithExperimentalFeatureTest, RemoveOlderFilesFromPersistence) { // Create file system mount point. std::unique_ptr<ScopedTestMountPoint> downloads_mount = @@ -1677,12 +1734,22 @@ persisted_holding_space_items_before_restoration.Append( fresh_holding_space_item->Serialize()); - // Only pinned files are exempt from age checks. In this test, we - // expect all holding space items of other types to be removed from - // persistence during restoration due to being older than - // `kMaxFileAge`. - if (features::IsHoldingSpacePredictabilityEnabled() || - type == HoldingSpaceItem::Type::kPinnedFile) { + bool should_restore = false; + if (!features::IsHoldingSpaceSuggestionsEnabled() && + HoldingSpaceItem::IsSuggestion(type)) { + // Suggestion items should not be restored if the suggestion feature + // is disabled. + should_restore = false; + } else { + // Pinned files are exempt from age checks. If the predictability + // feature is disabled, we expect all holding space items of other + // types to be removed from persistence during restoration due to + // being older than `kMaxFileAge`. + should_restore = features::IsHoldingSpacePredictabilityEnabled() || + type == HoldingSpaceItem::Type::kPinnedFile; + } + + if (should_restore) { persisted_holding_space_items_after_restoration.Append( fresh_holding_space_item->Serialize()); restored_holding_space_items.push_back( @@ -1738,7 +1805,7 @@ persisted_holding_space_items_after_restoration); } -TEST_P(HoldingSpaceKeyedServiceWithPredictabilityFeatureTest, +TEST_P(HoldingSpaceKeyedServiceWithExperimentalFeatureTest, AddArcDownloadItem) { // Wait for the holding space model to attach. TestingProfile* profile = GetProfile(); @@ -1775,7 +1842,7 @@ base::FilePath("Download.png"))); } -TEST_P(HoldingSpaceKeyedServiceWithPredictabilityFeatureTest, +TEST_P(HoldingSpaceKeyedServiceWithExperimentalFeatureTest, AddInProgressDownloadItem) { // Wait for the holding space model to attach. TestingProfile* profile = GetProfile(); @@ -2043,7 +2110,7 @@ EXPECT_TRUE(BitmapsAreEqual(actual_image, expected_image)); } -TEST_P(HoldingSpaceKeyedServiceWithPredictabilityFeatureTest, RemoveAll) { +TEST_P(HoldingSpaceKeyedServiceWithExperimentalFeatureTest, RemoveAll) { // Wait for the holding space model to attach. TestingProfile* profile = GetProfile(); HoldingSpaceModelAttachedWaiter(profile).Wait(); @@ -2079,7 +2146,7 @@ EXPECT_EQ(0u, model->items().size()); } -TEST_P(HoldingSpaceKeyedServiceWithPredictabilityFeatureTest, +TEST_P(HoldingSpaceKeyedServiceWithExperimentalFeatureTest, CreateInterruptedDownloadItem) { // Wait for the holding space model to attach. TestingProfile* profile = GetProfile(); @@ -2155,7 +2222,7 @@ EXPECT_TRUE(model->items()[0]->progress().IsComplete()); } -TEST_P(HoldingSpaceKeyedServiceWithPredictabilityFeatureTest, +TEST_P(HoldingSpaceKeyedServiceWithExperimentalFeatureTest, InterruptAndResumeDownload) { // Wait for the holding space model to attach. TestingProfile* profile = GetProfile();
diff --git a/chrome/browser/ui/ash/holding_space/holding_space_persistence_delegate.cc b/chrome/browser/ui/ash/holding_space/holding_space_persistence_delegate.cc index c6ec83e..5737745 100644 --- a/chrome/browser/ui/ash/holding_space/holding_space_persistence_delegate.cc +++ b/chrome/browser/ui/ash/holding_space/holding_space_persistence_delegate.cc
@@ -4,6 +4,7 @@ #include "chrome/browser/ui/ash/holding_space/holding_space_persistence_delegate.h" +#include "ash/constants/ash_features.h" #include "ash/public/cpp/holding_space/holding_space_constants.h" #include "ash/public/cpp/holding_space/holding_space_image.h" #include "ash/public/cpp/holding_space/holding_space_item.h" @@ -131,6 +132,9 @@ void HoldingSpacePersistenceDelegate::RestoreModelFromPersistence() { DCHECK(model()->items().empty()); + // Clear suggestions before restoration if needed. + MaybeRemoveSuggestionsFromPersistence(); + const auto& persisted_holding_space_items = profile()->GetPrefs()->GetList(kPersistencePath); @@ -157,4 +161,17 @@ std::move(persistence_restored_callback_).Run(); } +void HoldingSpacePersistenceDelegate::MaybeRemoveSuggestionsFromPersistence() { + DCHECK(is_restoring_persistence()); + + if (features::IsHoldingSpaceSuggestionsEnabled()) + return; + + ListPrefUpdate update(profile()->GetPrefs(), kPersistencePath); + update->GetList().EraseIf([](const base::Value& persisted_item) { + return HoldingSpaceItem::IsSuggestion(HoldingSpaceItem::DeserializeType( + base::Value::AsDictionaryValue(persisted_item))); + }); +} + } // namespace ash
diff --git a/chrome/browser/ui/ash/holding_space/holding_space_persistence_delegate.h b/chrome/browser/ui/ash/holding_space/holding_space_persistence_delegate.h index 3825df8..4c36111 100644 --- a/chrome/browser/ui/ash/holding_space/holding_space_persistence_delegate.h +++ b/chrome/browser/ui/ash/holding_space/holding_space_persistence_delegate.h
@@ -64,6 +64,9 @@ // Restores the holding space model from persistent storage. void RestoreModelFromPersistence(); + // Removes the persisted suggestions if the suggestion feature is disabled. + void MaybeRemoveSuggestionsFromPersistence(); + // Owned by `HoldingSpaceKeyedService`. ThumbnailLoader* const thumbnail_loader_;
diff --git a/chrome/browser/ui/ash/media_client_impl.cc b/chrome/browser/ui/ash/media_client_impl.cc index 7b8737623..ca5702a 100644 --- a/chrome/browser/ui/ash/media_client_impl.cc +++ b/chrome/browser/ui/ash/media_client_impl.cc
@@ -7,11 +7,16 @@ #include <utility> #include "ash/constants/ash_features.h" +#include "ash/constants/ash_pref_names.h" #include "ash/constants/notifier_catalogs.h" #include "ash/public/cpp/media_controller.h" #include "ash/public/cpp/notification_utils.h" #include "ash/public/cpp/system/toast_data.h" #include "ash/public/cpp/system/toast_manager.h" +#include "ash/session/session_controller_impl.h" +#include "ash/shell.h" +#include "ash/system/privacy_hub/camera_privacy_switch_controller.h" +#include "ash/system/privacy_hub/privacy_hub_controller.h" #include "base/bind.h" #include "base/callback_helpers.h" #include "base/check_op.h" @@ -456,9 +461,18 @@ bool is_active) { is_camera_active_ = is_active; - if (is_active && camera_privacy_switch_state_ == - cros::mojom::CameraPrivacySwitchState::ON) { - ShowCameraOffNotification(); + if (is_active) { + if (camera_privacy_switch_state_ == + cros::mojom::CameraPrivacySwitchState::ON) { + ShowCameraOffNotification(); + } + if (!ProfileManager::GetActiveUserProfile()->GetPrefs()->GetBoolean( + ash::prefs::kUserCameraAllowed)) { + ash::Shell::Get() + ->privacy_hub_controller() + ->camera_controller() + .ShowNotification(GetNameOfAppAccessingCameraInternal()); + } } }
diff --git a/chrome/browser/ui/page_info/chrome_page_info_ui_delegate.cc b/chrome/browser/ui/page_info/chrome_page_info_ui_delegate.cc index 9e242b2b..456e160 100644 --- a/chrome/browser/ui/page_info/chrome_page_info_ui_delegate.cc +++ b/chrome/browser/ui/page_info/chrome_page_info_ui_delegate.cc
@@ -7,6 +7,7 @@ #include "base/feature_list.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" +#include "chrome/browser/page_info/page_info_features.h" #include "chrome/browser/permissions/permission_manager_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser_finder.h" @@ -126,9 +127,7 @@ void ChromePageInfoUiDelegate::OpenMoreAboutThisPageUrl( const GURL& url, const ui::Event& event) { - DCHECK(base::FeatureList::IsEnabled(features::kUnifiedSidePanel)); - DCHECK( - base::FeatureList::IsEnabled(page_info::kPageInfoAboutThisSiteMoreInfo)); + DCHECK(page_info::IsMoreAboutThisSiteFeatureEnabled()); ShowAboutThisSiteSidePanel(web_contents_, url); } #endif
diff --git a/chrome/browser/ui/profile_picker.cc b/chrome/browser/ui/profile_picker.cc index ef8276e8..a8f6b233 100644 --- a/chrome/browser/ui/profile_picker.cc +++ b/chrome/browser/ui/profile_picker.cc
@@ -119,33 +119,6 @@ } #endif -GURL ProfilePicker::Params::GetInitialURL() const { - GURL base_url = GURL(chrome::kChromeUIProfilePickerUrl); - switch (entry_point_) { - case ProfilePicker::EntryPoint::kOnStartup: { - GURL::Replacements replacements; - replacements.SetQueryStr(chrome::kChromeUIProfilePickerStartupQuery); - return base_url.ReplaceComponents(replacements); - } - case ProfilePicker::EntryPoint::kProfileMenuManageProfiles: - case ProfilePicker::EntryPoint::kOpenNewWindowAfterProfileDeletion: - case ProfilePicker::EntryPoint::kNewSessionOnExistingProcess: - case ProfilePicker::EntryPoint::kProfileLocked: - case ProfilePicker::EntryPoint::kUnableToCreateBrowser: - case ProfilePicker::EntryPoint::kBackgroundModeManager: - case ProfilePicker::EntryPoint::kProfileIdle: - return base_url; - case ProfilePicker::EntryPoint::kProfileMenuAddNewProfile: - return base_url.Resolve("new-profile"); - case ProfilePicker::EntryPoint::kLacrosSelectAvailableAccount: - return base_url.Resolve("account-selection-lacros"); - case ProfilePicker::EntryPoint::kLacrosPrimaryProfileFirstRun: - // No web UI should be displayed initially. - NOTREACHED(); - return GURL(); - } -} - bool ProfilePicker::Params::CanReusePickerWindow(const Params& other) const { #if BUILDFLAG(IS_CHROMEOS_LACROS) LOG(WARNING) << "Checking window reusability from entry point "
diff --git a/chrome/browser/ui/profile_picker.h b/chrome/browser/ui/profile_picker.h index 3e407e1..11a5ef35 100644 --- a/chrome/browser/ui/profile_picker.h +++ b/chrome/browser/ui/profile_picker.h
@@ -164,12 +164,6 @@ base::OnceClosure maybe_callback); #endif - // Returns the URL to load as initial content for the profile picker. If an - // empty URL is returned, the profile picker should not be shown until - // another explicit call with a non-empty URL given to the view - // (see `ProfilePickerView::ShowScreen()` for example) - GURL GetInitialURL() const; - // Returns whether the current profile picker window can be reused for // different parameters. If this returns false, the picker cannot be reused // and must be closed and repoen. @@ -219,10 +213,12 @@ base::OnceCallback<void(bool)> switch_finished_callback); #endif +#if BUILDFLAG(IS_CHROMEOS_LACROS) // Starts the flow to set-up a signed-in profile. `signed_in_profile` must // have an unconsented primary account. static void SwitchToSignedInFlow(absl::optional<SkColor> profile_color, Profile* signed_in_profile); +#endif // Cancel the signed-in flow and returns back to the main picker screen (if // the original EntryPoint was to open the picker). Must only be called from
diff --git a/chrome/browser/ui/tab_helpers.cc b/chrome/browser/ui/tab_helpers.cc index 640ac8142..f8ee985a 100644 --- a/chrome/browser/ui/tab_helpers.cc +++ b/chrome/browser/ui/tab_helpers.cc
@@ -49,6 +49,7 @@ #include "chrome/browser/optimization_guide/optimization_guide_keyed_service_factory.h" #include "chrome/browser/optimization_guide/optimization_guide_web_contents_observer.h" #include "chrome/browser/optimization_guide/page_content_annotations_service_factory.h" +#include "chrome/browser/page_info/page_info_features.h" #include "chrome/browser/page_load_metrics/page_load_metrics_initialize.h" #include "chrome/browser/password_manager/chrome_password_manager_client.h" #include "chrome/browser/performance_hints/performance_hints_features.h" @@ -311,8 +312,7 @@ // --- Section 1: Common tab helpers --- #if defined(TOOLKIT_VIEWS) - if (base::FeatureList::IsEnabled( - page_info::kAboutThisSitePersistentSidePanelEntry)) { + if (page_info::IsPersistentSidePanelEntryFeatureEnabled()) { auto* optimization_guide_decider = OptimizationGuideKeyedServiceFactory::GetForProfile(profile); auto* about_this_site_service =
diff --git a/chrome/browser/ui/views/frame/browser_window_factory.cc b/chrome/browser/ui/views/frame/browser_window_factory.cc index b7f804d..d32b2d3 100644 --- a/chrome/browser/ui/views/frame/browser_window_factory.cc +++ b/chrome/browser/ui/views/frame/browser_window_factory.cc
@@ -69,9 +69,6 @@ } #endif // IS_MAC - view->GetWidget()->non_client_view()->SetAccessibleName( - l10n_util::GetStringUTF16(IDS_PRODUCT_NAME)); - if (view->GetIsPictureInPictureType() && view->GetLockAspectRatio()) { gfx::SizeF aspect_ratio(view->GetInitialAspectRatio(), 1.0f); view->GetWidget()->SetAspectRatio(aspect_ratio);
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 a4a63c4d..37bbfbece 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
@@ -15,6 +15,7 @@ #include "build/build_config.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/page_info/page_info_features.h" #include "chrome/browser/privacy_sandbox/mock_privacy_sandbox_service.h" #include "chrome/browser/privacy_sandbox/privacy_sandbox_service.h" #include "chrome/browser/privacy_sandbox/privacy_sandbox_service_factory.h" @@ -743,15 +744,7 @@ class PageInfoBubbleViewAboutThisSiteBrowserTest : public InProcessBrowserTest { public: - PageInfoBubbleViewAboutThisSiteBrowserTest() { - feature_list.InitWithFeatures( - {page_info::kPageInfoAboutThisSiteEn, - page_info::kPageInfoAboutThisSiteNonEn, - page_info::kPageInfoAboutThisSiteMoreInfo, - page_info::kPageInfoAboutThisSiteDescriptionPlaceholder, - features::kUnifiedSidePanel}, - {}); - } + PageInfoBubbleViewAboutThisSiteBrowserTest() { InitFeatureList(); } void SetUp() override { https_server_.SetSSLConfig(net::EmbeddedTestServer::CERT_TEST_NAMES); @@ -761,6 +754,16 @@ InProcessBrowserTest::SetUp(); } + virtual void InitFeatureList() { + feature_list_.InitWithFeatures( + {page_info::kPageInfoAboutThisSiteEn, + page_info::kPageInfoAboutThisSiteNonEn, + page_info::kPageInfoAboutThisSiteMoreInfo, + page_info::kPageInfoAboutThisSiteDescriptionPlaceholder, + features::kUnifiedSidePanel}, + {}); + } + void SetUpOnMainThread() override { host_resolver()->AddRule("*", "127.0.0.1"); } @@ -782,16 +785,15 @@ site_info.mutable_more_about()->set_url( https_server_.GetURL("a.test", "/title2.html").spec()); EXPECT_EQ( - page_info::about_this_site_validation::ValidateSiteInfo(site_info), + page_info::about_this_site_validation::ValidateSiteInfo( + site_info, page_info::IsDescriptionPlaceholderFeatureEnabled()), AboutThisSiteStatus::kValid); return site_info; } protected: net::EmbeddedTestServer https_server_{net::EmbeddedTestServer::TYPE_HTTPS}; - - private: - base::test::ScopedFeatureList feature_list; + base::test::ScopedFeatureList feature_list_; }; IN_PROC_BROWSER_TEST_F(PageInfoBubbleViewAboutThisSiteBrowserTest, @@ -860,7 +862,8 @@ auto url = https_server_.GetURL("a.test", "/title1.html"); auto site_info = CreateValidSiteInfo(); site_info.clear_description(); - EXPECT_EQ(page_info::about_this_site_validation::ValidateSiteInfo(site_info), + EXPECT_EQ(page_info::about_this_site_validation::ValidateSiteInfo( + site_info, page_info::IsDescriptionPlaceholderFeatureEnabled()), AboutThisSiteStatus::kValid); AddHintForTesting(browser(), url, site_info); @@ -983,6 +986,60 @@ static_cast<int>(AboutThisSiteStatus::kUnknown)); } +class PageInfoBubbleViewAboutThisSiteWithoutSidePanelBrowserTest + : public PageInfoBubbleViewAboutThisSiteBrowserTest { + public: + void InitFeatureList() override { + feature_list_.InitWithFeatures( + { + page_info::kPageInfoAboutThisSiteEn, + page_info::kPageInfoAboutThisSiteNonEn, + page_info::kPageInfoAboutThisSiteMoreInfo, + page_info::kPageInfoAboutThisSiteDescriptionPlaceholder, + }, + {features::kUnifiedSidePanel}); + } + + page_info::proto::SiteInfo CreateSiteInfoWithoutDescription() { + auto site_info = CreateValidSiteInfo(); + site_info.mutable_description()->clear_description(); + return site_info; + } +}; + +IN_PROC_BROWSER_TEST_F( + PageInfoBubbleViewAboutThisSiteWithoutSidePanelBrowserTest, + AboutThisSiteInteraction) { + auto url = https_server_.GetURL("a.test", "/title1.html"); + AddHintForTesting(browser(), url, CreateValidSiteInfo()); + + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); + OpenPageInfoBubble(browser()); + + auto* page_info = PageInfoBubbleView::GetPageInfoBubbleForTesting(); + views::View* button = page_info->GetViewByID( + PageInfoViewFactory::VIEW_ID_PAGE_INFO_ABOUT_THIS_SITE_BUTTON); + ASSERT_TRUE(button); + PerformMouseClickOnView(button); + // PageInfo should stay open since the side panel is disabled. + EXPECT_TRUE(PageInfoBubbleView::GetPageInfoBubbleForTesting()); +} + +IN_PROC_BROWSER_TEST_F( + PageInfoBubbleViewAboutThisSiteWithoutSidePanelBrowserTest, + AboutThisSiteWithoutDescription) { + auto url = https_server_.GetURL("a.test", "/title1.html"); + AddHintForTesting(browser(), url, CreateSiteInfoWithoutDescription()); + + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); + OpenPageInfoBubble(browser()); + + auto* page_info = PageInfoBubbleView::GetPageInfoBubbleForTesting(); + views::View* button = page_info->GetViewByID( + PageInfoViewFactory::VIEW_ID_PAGE_INFO_ABOUT_THIS_SITE_BUTTON); + EXPECT_FALSE(button); +} + class PageInfoBubbleViewSiteSettingsBrowserTest : public InProcessBrowserTest { public: PageInfoBubbleViewSiteSettingsBrowserTest() {
diff --git a/chrome/browser/ui/views/page_info/page_info_main_view.cc b/chrome/browser/ui/views/page_info/page_info_main_view.cc index 8c76145..211f04f 100644 --- a/chrome/browser/ui/views/page_info/page_info_main_view.cc +++ b/chrome/browser/ui/views/page_info/page_info_main_view.cc
@@ -8,6 +8,7 @@ #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" +#include "chrome/browser/page_info/page_info_features.h" #include "chrome/browser/reputation/safety_tip_ui_helper.h" #include "chrome/browser/ui/layout_constants.h" #include "chrome/browser/ui/page_info/chrome_page_info_ui_delegate.h" @@ -151,7 +152,7 @@ PageInfoHoverButton>( base::BindRepeating(&PageInfoNavigationHandler::OpenCookiesPage, base::Unretained(navigation_handler_)), - icon, IDS_PAGE_INFO_COOKIES, std::u16string(), + icon, IDS_PAGE_INFO_COOKIES_HEADER, std::u16string(), PageInfoViewFactory::VIEW_ID_PAGE_INFO_LINK_OR_BUTTON_COOKIES_SUBPAGE, tooltip, std::u16string(), PageInfoViewFactory::GetOpenSubpageIcon())); @@ -576,8 +577,7 @@ PageInfoHoverButton* about_this_site_button = nullptr; - if (base::FeatureList::IsEnabled(page_info::kPageInfoAboutThisSiteMoreInfo) && - base::FeatureList::IsEnabled(features::kUnifiedSidePanel)) { + if (page_info::IsMoreAboutThisSiteFeatureEnabled()) { const auto& description = info.has_description() ? base::UTF8ToUTF16(info.description().description())
diff --git a/chrome/browser/ui/views/profiles/profile_management_flow_controller.cc b/chrome/browser/ui/views/profiles/profile_management_flow_controller.cc new file mode 100644 index 0000000..06fa88c --- /dev/null +++ b/chrome/browser/ui/views/profiles/profile_management_flow_controller.cc
@@ -0,0 +1,66 @@ +// Copyright 2022 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/views/profiles/profile_management_flow_controller.h" + +#include "chrome/browser/ui/views/profiles/profile_management_step_controller.h" +#include "chrome/browser/ui/views/profiles/profile_picker_web_contents_host.h" + +ProfileManagementFlowController::ProfileManagementFlowController( + ProfilePickerWebContentsHost* host, + Step initial_step) + : initial_step_(initial_step), host_(host) {} + +ProfileManagementFlowController::~ProfileManagementFlowController() = default; + +void ProfileManagementFlowController::Init() { + SwitchToStep(initial_step()); +} + +void ProfileManagementFlowController::SwitchToStep( + Step step, + bool reset_state, + base::OnceClosure pop_step_callback, + base::OnceCallback<void(bool)> step_switch_finished_callback) { + DCHECK_NE(Step::kUnknown, step); + DCHECK_NE(current_step_, step); + + auto* new_step_controller = initialized_steps_.at(step).get(); + DCHECK(new_step_controller); + new_step_controller->set_pop_step_callback(std::move(pop_step_callback)); + new_step_controller->Show(std::move(step_switch_finished_callback), + reset_state); + + if (initialized_steps_.contains(current_step_)) { + initialized_steps_.at(current_step_)->OnHidden(); + } + + current_step_ = step; +} + +void ProfileManagementFlowController::OnNavigateBackRequested() { + DCHECK(initialized_steps_.contains(current_step_)); + initialized_steps_.at(current_step_)->OnNavigateBackRequested(); +} + +#if BUILDFLAG(ENABLE_DICE_SUPPORT) +void ProfileManagementFlowController::OnReloadRequested() { + DCHECK(initialized_steps_.contains(current_step_)); + initialized_steps_.at(current_step_)->OnReloadRequested(); +} +#endif + +void ProfileManagementFlowController::RegisterStep( + Step step, + std::unique_ptr<ProfileManagementStepController> step_controller) { + initialized_steps_[step] = std::move(step_controller); +} + +void ProfileManagementFlowController::UnregisterStep(Step step) { + initialized_steps_.erase(step); +} + +bool ProfileManagementFlowController::IsStepInitialized(Step step) const { + return initialized_steps_.contains(step) && initialized_steps_.at(step); +}
diff --git a/chrome/browser/ui/views/profiles/profile_management_flow_controller.h b/chrome/browser/ui/views/profiles/profile_management_flow_controller.h new file mode 100644 index 0000000..c58a69e5 --- /dev/null +++ b/chrome/browser/ui/views/profiles/profile_management_flow_controller.h
@@ -0,0 +1,91 @@ +// Copyright 2022 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_VIEWS_PROFILES_PROFILE_MANAGEMENT_FLOW_CONTROLLER_H_ +#define CHROME_BROWSER_UI_VIEWS_PROFILES_PROFILE_MANAGEMENT_FLOW_CONTROLLER_H_ + +#include "base/callback.h" +#include "base/containers/flat_map.h" +#include "base/memory/raw_ptr.h" +#include "components/signin/public/base/signin_buildflags.h" + +class ProfileManagementStepController; +class ProfilePickerWebContentsHost; + +// Represents an abstract user facing flow related to profile management. +// +// A profile management flow is made of a series of steps, implemented as +// `ProfileManagementStepController`s and owned by this object. +// +// Typical usage starts with calling `Init()` on the instantiated flow, which +// will switch to the `initial_step()`. Then as the user interacts with the +// flow, this controller will handle instantiating and navigating between the +// steps. +class ProfileManagementFlowController { + public: + // TODO(https://crbug.com/1358843): Split the steps more granularly across + // logical steps instead of according to implementation details. + enum class Step { + kUnknown, + // Renders the `chrome://profile-picker` app, covering the profile picker, + // the profile type choice at the beginning of the profile creation + // flow and the account selection on Lacros. + kProfilePicker, +#if BUILDFLAG(ENABLE_DICE_SUPPORT) + // Renders the sign in screen on Dice platforms. + // TODO(https://crbug.com/1360773): Support the `kAccountSelection` step on + // Lacros. Picking an account during the `kLacrosSelectAvailableAccount` + // flow and the profile creation should be implemented as a standalone step. + kAccountSelection, +#endif + // Renders all post-sign in screens: enterprise management consent, profile + // switch, sync opt-in, etc. + kPostSignInFlow + }; + + explicit ProfileManagementFlowController(ProfilePickerWebContentsHost* host, + Step initial_step); + virtual ~ProfileManagementFlowController(); + + void Init(); + + void SwitchToStep( + Step step, + bool reset_state = false, + base::OnceClosure pop_step_callback = base::OnceClosure(), + base::OnceCallback<void(bool)> step_switch_finished_callback = + base::OnceCallback<void(bool)>()); + + void OnNavigateBackRequested(); + +#if BUILDFLAG(ENABLE_DICE_SUPPORT) + void OnReloadRequested(); +#endif + + protected: + void RegisterStep(Step step, + std::unique_ptr<ProfileManagementStepController>); + + void UnregisterStep(Step step); + + bool IsStepInitialized(Step step) const; + + Step current_step() const { return current_step_; } + + Step initial_step() const { return initial_step_; } + + ProfilePickerWebContentsHost* host() { return host_; } + + private: + Step current_step_ = Step::kUnknown; + + Step initial_step_; + + raw_ptr<ProfilePickerWebContentsHost> host_; + + base::flat_map<Step, std::unique_ptr<ProfileManagementStepController>> + initialized_steps_; +}; + +#endif // CHROME_BROWSER_UI_VIEWS_PROFILES_PROFILE_MANAGEMENT_FLOW_CONTROLLER_H_
diff --git a/chrome/browser/ui/views/profiles/profile_management_step_controller.cc b/chrome/browser/ui/views/profiles/profile_management_step_controller.cc index a2ab9de..a7db694 100644 --- a/chrome/browser/ui/views/profiles/profile_management_step_controller.cc +++ b/chrome/browser/ui/views/profiles/profile_management_step_controller.cc
@@ -98,9 +98,9 @@ private: void OnStepFinished(Profile* profile, - std::unique_ptr<content::WebContents> contents, - bool is_saml) { - std::move(signed_in_callback_).Run(profile, std::move(contents), is_saml); + bool is_saml, + std::unique_ptr<content::WebContents> contents) { + std::move(signed_in_callback_).Run(profile, is_saml, std::move(contents)); // The step controller can be destroyed when `signed_in_callback_` runs. // Don't interact with members below. } @@ -156,9 +156,7 @@ ProfileManagementStepController::CreateForDiceSignIn( ProfilePickerWebContentsHost* host, std::unique_ptr<ProfilePickerDiceSignInProvider> dice_sign_in_provider, - base::OnceCallback<void(Profile* profile, - std::unique_ptr<content::WebContents>, - bool is_saml)> signed_in_callback) { + ProfilePickerDiceSignInProvider::SignedInCallback signed_in_callback) { return std::make_unique<DiceSignInStepController>( host, std::move(dice_sign_in_provider), std::move(signed_in_callback)); }
diff --git a/chrome/browser/ui/views/profiles/profile_management_step_controller.h b/chrome/browser/ui/views/profiles/profile_management_step_controller.h index 222edc8..dcbda5d 100644 --- a/chrome/browser/ui/views/profiles/profile_management_step_controller.h +++ b/chrome/browser/ui/views/profiles/profile_management_step_controller.h
@@ -9,10 +9,12 @@ #include "components/signin/public/base/signin_buildflags.h" #include "url/gurl.h" -class Profile; -class ProfilePickerDiceSignInProvider; -class ProfilePickerWebContentsHost; +#if BUILDFLAG(ENABLE_DICE_SUPPORT) +#include "chrome/browser/ui/views/profiles/profile_picker_dice_sign_in_provider.h" +#endif + class ProfilePickerSignedInFlowController; +class ProfilePickerWebContentsHost; namespace content { class WebContents; @@ -32,9 +34,7 @@ static std::unique_ptr<ProfileManagementStepController> CreateForDiceSignIn( ProfilePickerWebContentsHost* host, std::unique_ptr<ProfilePickerDiceSignInProvider> dice_sign_in_provider, - base::OnceCallback<void(Profile* profile, - std::unique_ptr<content::WebContents>, - bool is_saml)> signed_in_callback); + ProfilePickerDiceSignInProvider::SignedInCallback signed_in_callback); #endif static std::unique_ptr<ProfileManagementStepController>
diff --git a/chrome/browser/ui/views/profiles/profile_picker_dice_sign_in_provider.cc b/chrome/browser/ui/views/profiles/profile_picker_dice_sign_in_provider.cc index 40384907..ff497c11 100644 --- a/chrome/browser/ui/views/profiles/profile_picker_dice_sign_in_provider.cc +++ b/chrome/browser/ui/views/profiles/profile_picker_dice_sign_in_provider.cc
@@ -278,5 +278,5 @@ host_->SetNativeToolbarVisible(false); contents()->SetDelegate(nullptr); identity_manager_observation_.Reset(); - std::move(callback_).Run(profile_.get(), std::move(contents_), is_saml); + std::move(callback_).Run(profile_.get(), is_saml, std::move(contents_)); }
diff --git a/chrome/browser/ui/views/profiles/profile_picker_dice_sign_in_provider.h b/chrome/browser/ui/views/profiles/profile_picker_dice_sign_in_provider.h index edc714b..b1c451b 100644 --- a/chrome/browser/ui/views/profiles/profile_picker_dice_sign_in_provider.h +++ b/chrome/browser/ui/views/profiles/profile_picker_dice_sign_in_provider.h
@@ -39,8 +39,8 @@ // casing is not needed here. using SignedInCallback = base::OnceCallback<void(Profile* profile, - std::unique_ptr<content::WebContents>, - bool is_saml)>; + bool is_saml, + std::unique_ptr<content::WebContents>)>; explicit ProfilePickerDiceSignInProvider(ProfilePickerWebContentsHost* host); ~ProfilePickerDiceSignInProvider() override;
diff --git a/chrome/browser/ui/views/profiles/profile_picker_flow_controller.cc b/chrome/browser/ui/views/profiles/profile_picker_flow_controller.cc new file mode 100644 index 0000000..5a11422 --- /dev/null +++ b/chrome/browser/ui/views/profiles/profile_picker_flow_controller.cc
@@ -0,0 +1,174 @@ +// Copyright 2022 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/views/profiles/profile_picker_flow_controller.h" + +#include "chrome/browser/signin/signin_util.h" +#include "chrome/browser/ui/views/profiles/profile_creation_signed_in_flow_controller.h" +#include "chrome/browser/ui/views/profiles/profile_management_step_controller.h" +#include "chrome/browser/ui/views/profiles/profile_picker_web_contents_host.h" +#include "chrome/common/webui_url_constants.h" + +#if BUILDFLAG(ENABLE_DICE_SUPPORT) +#include "chrome/browser/ui/views/profiles/profile_picker_dice_sign_in_provider.h" +#endif + +namespace { +// Returns the URL to load as initial content for the profile picker. If an +// empty URL is returned, the profile picker should not be shown until +// another explicit call with a non-empty URL given to the view +// (see `ProfilePickerView::ShowScreen()` for example) +GURL GetInitialURL(ProfilePicker::EntryPoint entry_point) { + GURL base_url = GURL(chrome::kChromeUIProfilePickerUrl); + switch (entry_point) { + case ProfilePicker::EntryPoint::kOnStartup: { + GURL::Replacements replacements; + replacements.SetQueryStr(chrome::kChromeUIProfilePickerStartupQuery); + return base_url.ReplaceComponents(replacements); + } + case ProfilePicker::EntryPoint::kProfileMenuManageProfiles: + case ProfilePicker::EntryPoint::kOpenNewWindowAfterProfileDeletion: + case ProfilePicker::EntryPoint::kNewSessionOnExistingProcess: + case ProfilePicker::EntryPoint::kProfileLocked: + case ProfilePicker::EntryPoint::kUnableToCreateBrowser: + case ProfilePicker::EntryPoint::kBackgroundModeManager: + case ProfilePicker::EntryPoint::kProfileIdle: + return base_url; + case ProfilePicker::EntryPoint::kProfileMenuAddNewProfile: + return base_url.Resolve("new-profile"); + case ProfilePicker::EntryPoint::kLacrosSelectAvailableAccount: + return base_url.Resolve("account-selection-lacros"); + case ProfilePicker::EntryPoint::kLacrosPrimaryProfileFirstRun: + // Should not be used for this entry point. + NOTREACHED(); + return GURL(); + } +} +} // namespace + +ProfilePickerFlowController::ProfilePickerFlowController( + ProfilePickerWebContentsHost* host, + ProfilePicker::EntryPoint entry_point) + : ProfileManagementFlowController(host, Step::kProfilePicker), + entry_point_(entry_point) { + RegisterStep(initial_step(), + ProfileManagementStepController::CreateForProfilePickerApp( + host, GetInitialURL(entry_point_))); +} + +ProfilePickerFlowController::~ProfilePickerFlowController() = default; + +#if BUILDFLAG(ENABLE_DICE_SUPPORT) +void ProfilePickerFlowController::SwitchToDiceSignIn( + absl::optional<SkColor> profile_color, + base::OnceCallback<void(bool)> switch_finished_callback) { + DCHECK_EQ(Step::kProfilePicker, current_step()); + + profile_color_ = profile_color; + if (!IsStepInitialized(Step::kAccountSelection)) { + RegisterStep( + Step::kAccountSelection, + ProfileManagementStepController::CreateForDiceSignIn( + host(), std::make_unique<ProfilePickerDiceSignInProvider>(host()), + base::BindOnce(&ProfilePickerFlowController::SwitchToPostSignIn, + // Binding as Unretained as `this` outlives the step + // controllers. + base::Unretained(this)))); + } + auto pop_closure = base::BindOnce( + &ProfilePickerFlowController::SwitchToStep, + // Binding as Unretained as `this` outlives the step + // controllers. + base::Unretained(this), Step::kProfilePicker, + /*reset_state=*/false, /*pop_step_callback=*/base::OnceClosure(), + /*step_switch_finished_callback=*/base::OnceCallback<void(bool)>()); + SwitchToStep(Step::kAccountSelection, + /*reset_state=*/false, std::move(pop_closure), + std::move(switch_finished_callback)); +} +#endif + +void ProfilePickerFlowController::SwitchToPostSignIn( + Profile* signed_in_profile, +#if BUILDFLAG(ENABLE_DICE_SUPPORT) + bool is_saml, +#endif + std::unique_ptr<content::WebContents> contents) { + DCHECK(!signin_util::IsForceSigninEnabled()); +#if BUILDFLAG(ENABLE_DICE_SUPPORT) + DCHECK_EQ(Step::kAccountSelection, current_step()); +#endif + DCHECK(signed_in_profile); + + DCHECK(!IsStepInitialized(Step::kPostSignInFlow)); + + // TODO(crbug.com/1360055): Split out the SAML flow directly from here instead + // of using `ProfileCreationSignedInFlowController` for it. + auto signed_in_flow = std::make_unique<ProfileCreationSignedInFlowController>( + host(), signed_in_profile, std::move(contents), profile_color_, +#if BUILDFLAG(ENABLE_DICE_SUPPORT) + is_saml +#else + false +#endif + ); + + weak_signed_in_flow_controller_ = signed_in_flow->GetWeakPtr(); + RegisterStep(Step::kPostSignInFlow, + ProfileManagementStepController::CreateForPostSignInFlow( + host(), std::move(signed_in_flow))); + + SwitchToStep(Step::kPostSignInFlow); + +#if BUILDFLAG(ENABLE_DICE_SUPPORT) + // If we need to go back, we should go all the way to the beginning of the + // flow and after that, recreate the account selection step to ensure no data + // leaks if we select a different account. + // We also erase the step after the switch here because it holds a + // `ScopedProfileKeepAlive` and we need the next step to register its own + // before this the account selection's is released. + UnregisterStep(Step::kAccountSelection); +#endif +} + +base::FilePath ProfilePickerFlowController::GetSwitchProfilePathOrEmpty() + const { + if (weak_signed_in_flow_controller_) { + return weak_signed_in_flow_controller_->switch_profile_path(); + } + return base::FilePath(); +} + +void ProfilePickerFlowController::CancelPostSignInFlow() { + // Triggered from either entreprise welcome or profile switch screens. + DCHECK_EQ(Step::kPostSignInFlow, current_step()); + + switch (entry_point_) { + case ProfilePicker::EntryPoint::kOnStartup: + case ProfilePicker::EntryPoint::kProfileMenuManageProfiles: + case ProfilePicker::EntryPoint::kOpenNewWindowAfterProfileDeletion: + case ProfilePicker::EntryPoint::kNewSessionOnExistingProcess: + case ProfilePicker::EntryPoint::kProfileLocked: + case ProfilePicker::EntryPoint::kUnableToCreateBrowser: + case ProfilePicker::EntryPoint::kBackgroundModeManager: + case ProfilePicker::EntryPoint::kProfileIdle: { + SwitchToStep(Step::kProfilePicker, /*reset_state=*/true); + UnregisterStep(Step::kPostSignInFlow); +#if BUILDFLAG(ENABLE_DICE_SUPPORT) + UnregisterStep(Step::kAccountSelection); +#endif + return; + } + case ProfilePicker::EntryPoint::kProfileMenuAddNewProfile: { + // This results in destroying `this`. + host()->Clear(); + return; + } + case ProfilePicker::EntryPoint::kLacrosSelectAvailableAccount: + case ProfilePicker::EntryPoint::kLacrosPrimaryProfileFirstRun: + NOTREACHED() + << "CancelPostSignInFlow() is not reachable from this entry point"; + return; + } +}
diff --git a/chrome/browser/ui/views/profiles/profile_picker_flow_controller.h b/chrome/browser/ui/views/profiles/profile_picker_flow_controller.h new file mode 100644 index 0000000..6c9a6ac --- /dev/null +++ b/chrome/browser/ui/views/profiles/profile_picker_flow_controller.h
@@ -0,0 +1,54 @@ +// Copyright 2022 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_VIEWS_PROFILES_PROFILE_PICKER_FLOW_CONTROLLER_H_ +#define CHROME_BROWSER_UI_VIEWS_PROFILES_PROFILE_PICKER_FLOW_CONTROLLER_H_ + +#include "chrome/browser/ui/profile_picker.h" +#include "chrome/browser/ui/views/profiles/profile_management_flow_controller.h" +#include "components/signin/public/base/signin_buildflags.h" +#include "third_party/abseil-cpp/absl/types/optional.h" +#include "third_party/skia/include/core/SkColor.h" + +class ProfilePickerSignedInFlowController; + +class ProfilePickerFlowController : public ProfileManagementFlowController { + public: + ProfilePickerFlowController(ProfilePickerWebContentsHost* host, + ProfilePicker::EntryPoint entry_point); + ~ProfilePickerFlowController() override; + + void SwitchToDiceSignIn( + absl::optional<SkColor> profile_color, + base::OnceCallback<void(bool)> switch_finished_callback); + + void SwitchToPostSignIn(Profile* signed_in_profile, +#if BUILDFLAG(ENABLE_DICE_SUPPORT) + bool is_saml, +#endif + std::unique_ptr<content::WebContents> contents); + + // Cancel the signed-in profile setup and returns back to the main picker + // screen (if the original EntryPoint was to open the picker). + void CancelPostSignInFlow(); + + base::FilePath GetSwitchProfilePathOrEmpty() const; + + void set_profile_color(absl::optional<SkColor> profile_color) { + profile_color_ = profile_color; + } + + private: + ProfilePicker::EntryPoint entry_point_; + absl::optional<SkColor> profile_color_ = absl::nullopt; + + // TODO(crbug.com/1359352): To be refactored out. + // This is used for `ProfilePicker::GetSwitchProfilePath()`. The information + // should ideally be provided to the handler of the profile switch page once + // its controller is created instead of relying on static calls. + base::WeakPtr<ProfilePickerSignedInFlowController> + weak_signed_in_flow_controller_; +}; + +#endif // CHROME_BROWSER_UI_VIEWS_PROFILES_PROFILE_PICKER_FLOW_CONTROLLER_H_
diff --git a/chrome/browser/ui/views/profiles/profile_picker_view.cc b/chrome/browser/ui/views/profiles/profile_picker_view.cc index 2405f8b..9b4423ae 100644 --- a/chrome/browser/ui/views/profiles/profile_picker_view.cc +++ b/chrome/browser/ui/views/profiles/profile_picker_view.cc
@@ -26,9 +26,8 @@ #include "chrome/browser/signin/signin_util.h" #include "chrome/browser/ui/color/chrome_color_id.h" #include "chrome/browser/ui/views/accelerator_table.h" -#include "chrome/browser/ui/views/profiles/profile_creation_signed_in_flow_controller.h" -#include "chrome/browser/ui/views/profiles/profile_management_step_controller.h" -#include "chrome/browser/ui/views/profiles/profile_picker_web_contents_host.h" +#include "chrome/browser/ui/views/profiles/profile_management_flow_controller.h" +#include "chrome/browser/ui/views/profiles/profile_picker_flow_controller.h" #include "chrome/browser/ui/webui/signin/profile_picker_ui.h" #include "chrome/common/pref_names.h" #include "chrome/common/webui_url_constants.h" @@ -53,7 +52,6 @@ #include "url/gurl.h" #if BUILDFLAG(ENABLE_DICE_SUPPORT) -#include "chrome/browser/ui/views/profiles/profile_picker_dice_sign_in_provider.h" #include "chrome/browser/ui/views/profiles/profile_picker_dice_sign_in_toolbar.h" #endif @@ -69,6 +67,7 @@ #if BUILDFLAG(IS_CHROMEOS_LACROS) #include "chrome/browser/ui/views/profiles/lacros_first_run_signed_in_flow_controller.h" +#include "chrome/browser/ui/views/profiles/profile_management_step_controller.h" #include "chrome/grit/generated_resources.h" #endif @@ -103,6 +102,38 @@ const raw_ptr<ProfilePickerView> profile_picker_view_; }; +// Returns whether the current flow is part of the classic profile picker flow. +// Checking this should become eventually unnecessary as flows move away from +// using static calls and global variables, and keep calls to native contained +// within their own steps. See crbug.com/1359352. +bool IsClassicProfilePickerFlow(const ProfilePicker::Params& params) { + // TODO(crbug.com/1360773): Implement more use cases outside of the classic + // profile picker flow. e.g.: kLacrosSelectAvailableAccount. + return params.entry_point() != + ProfilePicker::EntryPoint::kLacrosPrimaryProfileFirstRun; +} + +#if BUILDFLAG(IS_CHROMEOS_LACROS) +class LacrosFirstRunFlowController : public ProfileManagementFlowController { + public: + LacrosFirstRunFlowController( + ProfilePickerWebContentsHost* host, + Profile* profile, + ProfilePicker::DebugFirstRunExitedCallback first_run_exited_callback) + : ProfileManagementFlowController(host, Step::kPostSignInFlow) { + RegisterStep( + initial_step(), + ProfileManagementStepController::CreateForPostSignInFlow( + host, std::make_unique<LacrosFirstRunSignedInFlowController>( + host, profile, + content::WebContents::Create( + content::WebContents::CreateParams(profile)), + std::move(first_run_exited_callback)))); + } + ~LacrosFirstRunFlowController() override = default; +}; +#endif + } // namespace // static @@ -132,10 +163,9 @@ // static base::FilePath ProfilePicker::GetSwitchProfilePath() { - if (g_profile_picker_view && - g_profile_picker_view->weak_signed_in_flow_controller_) { - return g_profile_picker_view->weak_signed_in_flow_controller_ - ->switch_profile_path(); + if (g_profile_picker_view) { + return g_profile_picker_view->GetProfilePickerFlowController() + ->GetSwitchProfilePathOrEmpty(); } return base::FilePath(); } @@ -152,23 +182,26 @@ } #endif +#if BUILDFLAG(IS_CHROMEOS_LACROS) // static void ProfilePicker::SwitchToSignedInFlow(absl::optional<SkColor> profile_color, Profile* signed_in_profile) { if (g_profile_picker_view) { - g_profile_picker_view->profile_color_ = profile_color; + g_profile_picker_view->GetProfilePickerFlowController()->set_profile_color( + profile_color); g_profile_picker_view->SwitchToSignedInFlow( signed_in_profile, content::WebContents::Create( - content::WebContents::CreateParams(signed_in_profile)), - /*is_saml=*/false); + content::WebContents::CreateParams(signed_in_profile))); } } +#endif // static void ProfilePicker::CancelSignedInFlow() { if (g_profile_picker_view) { - g_profile_picker_view->CancelSignedInFlow(); + g_profile_picker_view->GetProfilePickerFlowController() + ->CancelPostSignInFlow(); } } @@ -585,37 +618,23 @@ views::HWNDForWidget(GetWidget())); #endif - Step initial_step = Step::kUnknown; - if (params_.entry_point() == - ProfilePicker::EntryPoint::kLacrosPrimaryProfileFirstRun) { + if (IsClassicProfilePickerFlow(params_)) { + flow_controller_ = std::make_unique<ProfilePickerFlowController>( + /*host=*/this, params_.entry_point()); + } else if (params_.entry_point() == + ProfilePicker::EntryPoint::kLacrosPrimaryProfileFirstRun) { #if BUILDFLAG(IS_CHROMEOS_LACROS) - // TODO(crbug.com/1300109): Consider some refactoring to share this - // `WebContents` for usage in this class instead of a separate `contents_`. - std::unique_ptr<content::WebContents> contents_for_signed_in_flow = - content::WebContents::Create( - content::WebContents::CreateParams(picker_profile)); - - initial_step = Step::kPostSignInFlow; - initialized_steps_[initial_step] = - ProfileManagementStepController::CreateForPostSignInFlow( - this, - std::make_unique<LacrosFirstRunSignedInFlowController>( - this, picker_profile, std::move(contents_for_signed_in_flow), - base::BindOnce(&ProfilePicker::Params::NotifyFirstRunExited, - // Unretained ok because the controller is owned - // by this through `initialized_steps_`. - base::Unretained(¶ms_)))); -#else - NOTREACHED(); + flow_controller_ = std::make_unique<LacrosFirstRunFlowController>( + /*host=*/this, picker_profile, + base::BindOnce(&ProfilePicker::Params::NotifyFirstRunExited, + // Unretained ok because the controller is owned + // by this through `initialized_steps_`. + base::Unretained(¶ms_))); #endif // BUILDFLAG(IS_CHROMEOS_LACROS) - } else { - initial_step = Step::kProfilePicker; - initialized_steps_[initial_step] = - ProfileManagementStepController::CreateForProfilePickerApp( - this, params_.GetInitialURL()); } - SwitchToStep(initial_step); + DCHECK(flow_controller_); + flow_controller_->Init(); state_ = kReady; PrefService* prefs = g_browser_process->local_state(); @@ -638,9 +657,6 @@ void ProfilePickerView::SwitchToDiceSignIn( absl::optional<SkColor> profile_color, base::OnceCallback<void(bool)> switch_finished_callback) { - DCHECK_EQ(Step::kProfilePicker, current_step_); - profile_color_ = profile_color; - // TODO(crbug.com/1360774): Consider having forced signin as separate step // controller for `Step::kAccountSelection`. if (signin_util::IsForceSigninEnabled()) { @@ -648,26 +664,8 @@ return; } - if (!initialized_steps_.contains(Step::kAccountSelection)) { - initialized_steps_[Step::kAccountSelection] = - ProfileManagementStepController::CreateForDiceSignIn( - /*host=*/this, - std::make_unique<ProfilePickerDiceSignInProvider>(this), - base::BindOnce(&ProfilePickerView::SwitchToSignedInFlow, - // Binding as Unretained as `this` outlives the step - // controllers. - base::Unretained(this))); - } - auto pop_closure = base::BindOnce( - &ProfilePickerView::SwitchToStep, - // Binding as Unretained as `this` outlives the step - // controllers. - base::Unretained(this), Step::kProfilePicker, - /*reset_state=*/false, /*pop_step_callback=*/base::OnceClosure(), - /*step_switch_finished_callback=*/base::OnceCallback<void(bool)>()); - SwitchToStep(Step::kAccountSelection, - /*reset_state=*/false, std::move(pop_closure), - std::move(switch_finished_callback)); + GetProfilePickerFlowController()->SwitchToDiceSignIn( + profile_color, std::move(switch_finished_callback)); } void ProfilePickerView::SwitchToForcedSignIn( @@ -700,75 +698,15 @@ #endif +#if BUILDFLAG(IS_CHROMEOS_LACROS) void ProfilePickerView::SwitchToSignedInFlow( Profile* signed_in_profile, - std::unique_ptr<content::WebContents> contents, - bool is_saml) { + std::unique_ptr<content::WebContents> contents) { DCHECK(!signin_util::IsForceSigninEnabled()); -#if BUILDFLAG(ENABLE_DICE_SUPPORT) - DCHECK_EQ(Step::kAccountSelection, current_step_); -#endif - DCHECK(signed_in_profile); - - DCHECK(!initialized_steps_.contains(Step::kPostSignInFlow)); - - // TODO(crbug.com/1360055): Split out the SAML flow directly from here instead - // of using `ProfileCreationSignedInFlowController` for it. - auto signed_in_flow = std::make_unique<ProfileCreationSignedInFlowController>( - /*host=*/this, signed_in_profile, std::move(contents), profile_color_, - is_saml); - - weak_signed_in_flow_controller_ = signed_in_flow->GetWeakPtr(); - initialized_steps_[Step::kPostSignInFlow] = - ProfileManagementStepController::CreateForPostSignInFlow( - this, std::move(signed_in_flow)); - - SwitchToStep(Step::kPostSignInFlow); - -#if BUILDFLAG(ENABLE_DICE_SUPPORT) - // If we need to go back, we should go all the way to the beginning of the - // flow and after that, recreate the account selection step to ensure no data - // leaks if we select a different account. - // We also erase the step after the switch here because it holds a - // `ScopedProfileKeepAlive` and we need the next step to register its own - // before this the account selection's is released. - initialized_steps_.erase(Step::kAccountSelection); -#endif + GetProfilePickerFlowController()->SwitchToPostSignIn(signed_in_profile, + std::move(contents)); } - -void ProfilePickerView::CancelSignedInFlow() { - // Triggered from either entreprise welcome or profile switch. - DCHECK_EQ(Step::kPostSignInFlow, current_step_); - - switch (params_.entry_point()) { - case ProfilePicker::EntryPoint::kOnStartup: - case ProfilePicker::EntryPoint::kProfileMenuManageProfiles: - case ProfilePicker::EntryPoint::kOpenNewWindowAfterProfileDeletion: - case ProfilePicker::EntryPoint::kNewSessionOnExistingProcess: - case ProfilePicker::EntryPoint::kProfileLocked: - case ProfilePicker::EntryPoint::kUnableToCreateBrowser: - case ProfilePicker::EntryPoint::kBackgroundModeManager: - case ProfilePicker::EntryPoint::kProfileIdle: { - SwitchToStep(Step::kProfilePicker, /*reset_state=*/true); - initialized_steps_.erase(Step::kPostSignInFlow); -#if BUILDFLAG(ENABLE_DICE_SUPPORT) - initialized_steps_.erase(Step::kAccountSelection); #endif - return; - } - case ProfilePicker::EntryPoint::kProfileMenuAddNewProfile: { - // This results in destroying `this`. - Clear(); - return; - } - case ProfilePicker::EntryPoint::kLacrosSelectAvailableAccount: - NOTREACHED() << "Signed in flow is not reachable from this entry point"; - return; - case ProfilePicker::EntryPoint::kLacrosPrimaryProfileFirstRun: - NOTREACHED() << "Signed in flow is not cancellable"; - return; - } -} void ProfilePickerView::WindowClosing() { views::WidgetDelegateView::WindowClosing(); @@ -859,8 +797,7 @@ case IDC_RELOAD: case IDC_RELOAD_BYPASSING_CACHE: case IDC_RELOAD_CLEARING_CACHE: - DCHECK(initialized_steps_.contains(current_step_)); - initialized_steps_.at(current_step_)->OnReloadRequested(); + flow_controller_->OnReloadRequested(); break; #endif @@ -908,30 +845,8 @@ std::move(navigation_finished_closure).Run(); } -void ProfilePickerView::SwitchToStep( - Step step, - bool reset_state, - base::OnceClosure pop_step_callback, - base::OnceCallback<void(bool)> step_switch_finished_callback) { - DCHECK_NE(Step::kUnknown, step); - DCHECK_NE(current_step_, step); - - auto* new_step_controller = initialized_steps_.at(step).get(); - DCHECK(new_step_controller); - new_step_controller->set_pop_step_callback(std::move(pop_step_callback)); - new_step_controller->Show(std::move(step_switch_finished_callback), - reset_state); - - if (initialized_steps_.contains(current_step_)) { - initialized_steps_.at(current_step_)->OnHidden(); - } - - current_step_ = step; -} - void ProfilePickerView::NavigateBack() { - DCHECK(initialized_steps_.contains(current_step_)); - initialized_steps_.at(current_step_)->OnNavigateBackRequested(); + flow_controller_->OnNavigateBackRequested(); } void ProfilePickerView::ConfigureAccelerators() { @@ -979,6 +894,12 @@ return params_.on_select_profile_target_url(); } +ProfilePickerFlowController* ProfilePickerView::GetProfilePickerFlowController() + const { + DCHECK(IsClassicProfilePickerFlow(params_)); + return static_cast<ProfilePickerFlowController*>(flow_controller_.get()); +} + #if BUILDFLAG(IS_CHROMEOS_LACROS) // static void ProfilePicker::NotifyAccountSelected(const std::string& gaia_id) {
diff --git a/chrome/browser/ui/views/profiles/profile_picker_view.h b/chrome/browser/ui/views/profiles/profile_picker_view.h index 19d9b8f4..8661ab7 100644 --- a/chrome/browser/ui/views/profiles/profile_picker_view.h +++ b/chrome/browser/ui/views/profiles/profile_picker_view.h
@@ -6,7 +6,6 @@ #define CHROME_BROWSER_UI_VIEWS_PROFILES_PROFILE_PICKER_VIEW_H_ #include "base/callback_forward.h" -#include "base/containers/flat_map.h" #include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" #include "base/time/time.h" @@ -29,9 +28,9 @@ #endif class Profile; -class ProfileManagementStepController; -class ProfilePickerSignedInFlowController; class ScopedProfileKeepAlive; +class ProfileManagementFlowController; +class ProfilePickerFlowController; namespace base { class FilePath; @@ -48,26 +47,6 @@ class ProfilePickerView : public views::WidgetDelegateView, public ProfilePickerWebContentsHost { public: - // TODO(https://crbug.com/1358843): Split the steps more granularly across - // logical steps instead of according to implementation details. - enum class Step { - kUnknown, - // Renders the `chrome://profile-picker` app, covering the profile picker, - // the profile type choice at the beginning of the profile creation - // flow and the account selection on Lacros. - kProfilePicker, -#if BUILDFLAG(ENABLE_DICE_SUPPORT) - // Renders the sign in screen on Dice platforms. - // TODO(https://crbug.com/1360773): Support the `kAccountSelection` step on - // Lacros. Picking an account during the `kLacrosSelectAvailableAccount` - // flow and the profile creation should be implemented as a standalone step. - kAccountSelection, -#endif - // Renders all post-sign in screens: enterprise management consent, profile - // switch, sync opt-in, etc. - kPostSignInFlow - }; - METADATA_HEADER(ProfilePickerView); ProfilePickerView(const ProfilePickerView&) = delete; @@ -176,13 +155,10 @@ Profile* new_profile); #endif +#if BUILDFLAG(IS_CHROMEOS_LACROS) void SwitchToSignedInFlow(Profile* signed_in_profile, - std::unique_ptr<content::WebContents> contents, - bool is_saml); - - // Cancel the signed-in profile setup and returns back to the main picker - // screen (if themoriginal EntryPoint was to open the picker). - void CancelSignedInFlow(); + std::unique_ptr<content::WebContents> contents); +#endif // views::WidgetDelegate: void WindowClosing() override; @@ -226,6 +202,8 @@ // profile selection instead of the new tab page. GURL GetOnSelectProfileTargetUrl() const; + ProfilePickerFlowController* GetProfilePickerFlowController() const; + #if BUILDFLAG(IS_CHROMEOS_LACROS) // Called when the user selects an account on the Lacros-specific account // selection screen. Only called for existing profiles, not as part of profile @@ -233,13 +211,6 @@ void NotifyAccountSelected(const std::string& gaia_id); #endif - void SwitchToStep( - Step step, - bool reset_state = false, - base::OnceClosure pop_step_callback = base::OnceClosure(), - base::OnceCallback<void(bool)> step_switch_finished_callback = - base::OnceCallback<void(bool)>()); - ScopedKeepAlive keep_alive_; std::unique_ptr<ScopedProfileKeepAlive> profile_keep_alive_; @@ -278,19 +249,7 @@ raw_ptr<ProfilePickerDiceSignInToolbar> toolbar_ = nullptr; #endif - Step current_step_ = Step::kUnknown; - - absl::optional<SkColor> profile_color_; - - base::flat_map<Step, std::unique_ptr<ProfileManagementStepController>> - initialized_steps_; - - // TODO(crbug.com/1359352): To be refactored out. - // This is used for `ProfilePicker::GetSwitchProfilePath()`. The information - // should ideally be provided to the handler of the profile switch page once - // its controller is created instead of relying on static calls. - base::WeakPtr<ProfilePickerSignedInFlowController> - weak_signed_in_flow_controller_; + std::unique_ptr<ProfileManagementFlowController> flow_controller_; // Creation time of the picker, to measure performance on startup. Only set // when the picker is shown on startup.
diff --git a/chrome/browser/ui/views/site_data/page_specific_site_data_dialog.cc b/chrome/browser/ui/views/site_data/page_specific_site_data_dialog.cc index 430cce7d..c3c77af 100644 --- a/chrome/browser/ui/views/site_data/page_specific_site_data_dialog.cc +++ b/chrome/browser/ui/views/site_data/page_specific_site_data_dialog.cc
@@ -10,6 +10,7 @@ #include "chrome/browser/history/history_service_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/collected_cookies_infobar_delegate.h" +#include "chrome/browser/ui/views/chrome_layout_provider.h" #include "chrome/browser/ui/views/site_data/page_specific_site_data_dialog_controller.h" #include "chrome/browser/ui/views/site_data/site_data_row_view.h" #include "chrome/grit/generated_resources.h" @@ -24,6 +25,8 @@ #include "ui/base/l10n/l10n_util.h" #include "ui/base/models/dialog_model.h" #include "ui/views/bubble/bubble_dialog_model_host.h" +#include "ui/views/layout/box_layout_view.h" +#include "ui/views/view_class_properties.h" namespace { @@ -262,6 +265,65 @@ bool status_changed_ = false; }; +class PageSpecificSiteDataSectionView : public views::BoxLayoutView { + public: + PageSpecificSiteDataSectionView( + std::vector<PageSpecificSiteDataDialogSite> sites, + PageSpecificSiteDataDialogModelDelegate* delegate) { + SetOrientation(views::BoxLayout::Orientation::kVertical); + SetCrossAxisAlignment(views::BoxLayout::CrossAxisAlignment::kStretch); + + for (const PageSpecificSiteDataDialogSite& site : sites) { + // It is safe to use base::Unretained for the delegate here because both + // the row view and the delegate are owned by the dialog and will be + // destroyed when the dialog is destroyed. + auto* const row_view = AddChildView(std::make_unique<SiteDataRowView>( + site.origin, site.setting, delegate->favicon_cache(), + base::BindRepeating( + &PageSpecificSiteDataDialogModelDelegate::DeleteStoredObjects, + base::Unretained(delegate)), + base::BindRepeating( + &PageSpecificSiteDataDialogModelDelegate::SetContentException, + base::Unretained(delegate)))); + row_view->SetProperty(views::kElementIdentifierKey, + kPageSpecificSiteDataDialogRowForTesting); + } + + empty_state_label_ = AddChildView(std::make_unique<views::Label>( + l10n_util::GetStringUTF16( + IDS_PAGE_SPECIFIC_SITE_DATA_DIALOG_EMPTY_STATE_LABEL), + views::style::CONTEXT_LABEL, views::style::STYLE_SECONDARY)); + empty_state_label_->SetHorizontalAlignment(gfx::ALIGN_LEFT); + + // Set insets to match with other views in the dialog. + auto dialog_insets = ChromeLayoutProvider::Get()->GetInsetsMetric( + views::InsetsMetric::INSETS_DIALOG); + dialog_insets.set_top(0); + dialog_insets.set_bottom(0); + empty_state_label_->SetProperty(views::kMarginsKey, dialog_insets); + + UpdateEmptyStateLabelVisibility(); + } + + // views::View: + void ChildVisibilityChanged(views::View* child) override { + UpdateEmptyStateLabelVisibility(); + } + + private: + void UpdateEmptyStateLabelVisibility() { + // If none of the children (except the empty state label) are visible, show + // a label to explain the empty state. + bool none_children_visible = + base::ranges::none_of(children(), [=](views::View* v) { + return v != empty_state_label_ && v->GetVisible(); + }); + empty_state_label_->SetVisible(none_children_visible); + } + + raw_ptr<views::Label> empty_state_label_ = nullptr; +}; + } // namespace DEFINE_ELEMENT_IDENTIFIER_VALUE(kPageSpecificSiteDataDialogRowForTesting); @@ -284,29 +346,32 @@ &PageSpecificSiteDataDialogModelDelegate::OnDialogExplicitlyClosed, base::Unretained(delegate))); + bool has_any_sections = false; auto sections = GetSections(delegate->GetAllSites(), url::Origin::Create(web_contents->GetVisibleURL())); for (const auto& section : sections) { + // If section doesn't have any sites, don't show the section. + if (section.sites.size() == 0u) + continue; + + has_any_sections = true; builder.AddParagraph( ui::DialogModelLabel(section.subtitle).set_is_secondary(), section.title); - for (const auto& site : section.sites) { - // It is safe to use base::Unretained for the delegate here because both - // the row view and the delegate are owned by the dialog and will be - // destroyed when the dialog is destroyed. - builder.AddCustomField( - CreateCustomField(std::make_unique<SiteDataRowView>( - site.origin, site.setting, delegate->favicon_cache(), - base::BindRepeating( - &PageSpecificSiteDataDialogModelDelegate::DeleteStoredObjects, - base::Unretained(delegate)), - base::BindRepeating( - &PageSpecificSiteDataDialogModelDelegate::SetContentException, - base::Unretained(delegate)))), - kPageSpecificSiteDataDialogRowForTesting); - } + builder.AddCustomField( + CreateCustomField(std::make_unique<PageSpecificSiteDataSectionView>( + section.sites, delegate))); } - // TODO(crbug.com/1344787): Build the rest of the dialog. Add action handling. + + // If there were no sections shown, show a label that explains an empty state. + if (!has_any_sections) { + builder.AddParagraph( + ui::DialogModelLabel( + l10n_util::GetStringUTF16( + IDS_PAGE_SPECIFIC_SITE_DATA_DIALOG_EMPTY_STATE_LABEL)) + .set_is_secondary()); + } + return constrained_window::ShowWebModal(builder.Build(), web_contents); }
diff --git a/chrome/browser/ui/views/web_apps/web_app_integration_browsertest.cc b/chrome/browser/ui/views/web_apps/web_app_integration_browsertest.cc index 367b925..5e0fbcbd 100644 --- a/chrome/browser/ui/views/web_apps/web_app_integration_browsertest.cc +++ b/chrome/browser/ui/views/web_apps/web_app_integration_browsertest.cc
@@ -4451,5 +4451,77 @@ WindowOptions::kBrowser, InstallMode::kWebApp); } +IN_PROC_BROWSER_TEST_F( + WebAppIntegration, + WAI_29StandaloneWindowed_24_12Standalone_7Standalone_112StandaloneNotShown_73_37Standalone_19) { + // Test contents are generated by script. Please do not modify! + // See `docs/webapps/why-is-this-test-failing.md` or + // `docs/webapps/integration-testing-framework` for more info. + // Sheriffs: Disabling this test is supported. + helper_.CreateShortcut(Site::kStandalone, WindowOptions::kWindowed); + helper_.CheckWindowCreated(); + helper_.CheckAppInListWindowed(Site::kStandalone); + helper_.CheckPlatformShortcutAndIcon(Site::kStandalone); + helper_.CheckWindowControlsOverlayToggle(Site::kStandalone, + IsShown::kNotShown); + helper_.SwitchIncognitoProfile(); + helper_.NavigateBrowser(Site::kStandalone); + helper_.CheckLaunchIconNotShown(); +} + +IN_PROC_BROWSER_TEST_F( + WebAppIntegration, + WAI_31Standalone_24_12Standalone_7Standalone_112StandaloneNotShown_73_37Standalone_19) { + // Test contents are generated by script. Please do not modify! + // See `docs/webapps/why-is-this-test-failing.md` or + // `docs/webapps/integration-testing-framework` for more info. + // Sheriffs: Disabling this test is supported. + helper_.InstallOmniboxIcon(InstallableSite::kStandalone); + helper_.CheckWindowCreated(); + helper_.CheckAppInListWindowed(Site::kStandalone); + helper_.CheckPlatformShortcutAndIcon(Site::kStandalone); + helper_.CheckWindowControlsOverlayToggle(Site::kStandalone, + IsShown::kNotShown); + helper_.SwitchIncognitoProfile(); + helper_.NavigateBrowser(Site::kStandalone); + helper_.CheckLaunchIconNotShown(); +} + +IN_PROC_BROWSER_TEST_F( + WebAppIntegration, + WAI_47Standalone_24_12Standalone_7Standalone_112StandaloneNotShown_73_37Standalone_19) { + // Test contents are generated by script. Please do not modify! + // See `docs/webapps/why-is-this-test-failing.md` or + // `docs/webapps/integration-testing-framework` for more info. + // Sheriffs: Disabling this test is supported. + helper_.InstallMenuOption(InstallableSite::kStandalone); + helper_.CheckWindowCreated(); + helper_.CheckAppInListWindowed(Site::kStandalone); + helper_.CheckPlatformShortcutAndIcon(Site::kStandalone); + helper_.CheckWindowControlsOverlayToggle(Site::kStandalone, + IsShown::kNotShown); + helper_.SwitchIncognitoProfile(); + helper_.NavigateBrowser(Site::kStandalone); + helper_.CheckLaunchIconNotShown(); +} + +IN_PROC_BROWSER_TEST_F(WebAppIntegration, WAI_73_37Standalone) { + // Test contents are generated by script. Please do not modify! + // See `docs/webapps/why-is-this-test-failing.md` or + // `docs/webapps/integration-testing-framework` for more info. + // Sheriffs: Disabling this test is supported. + helper_.SwitchIncognitoProfile(); + helper_.NavigateBrowser(Site::kStandalone); +} + +IN_PROC_BROWSER_TEST_F(WebAppIntegration, WAI_73_37NotPromotable) { + // Test contents are generated by script. Please do not modify! + // See `docs/webapps/why-is-this-test-failing.md` or + // `docs/webapps/integration-testing-framework` for more info. + // Sheriffs: Disabling this test is supported. + helper_.SwitchIncognitoProfile(); + helper_.NavigateBrowser(Site::kNotPromotable); +} + } // namespace } // namespace web_app::integration_tests
diff --git a/chrome/browser/ui/views/web_apps/web_app_integration_test_driver.cc b/chrome/browser/ui/views/web_apps/web_app_integration_test_driver.cc index 549b255..7aff2b3 100644 --- a/chrome/browser/ui/views/web_apps/web_app_integration_test_driver.cc +++ b/chrome/browser/ui/views/web_apps/web_app_integration_test_driver.cc
@@ -2595,7 +2595,8 @@ base::flat_map<Browser*, BrowserState> browser_state; auto* browser_list = BrowserList::GetInstance(); for (Browser* browser : *browser_list) { - if (browser->profile() != profile) { + if (browser->profile() != profile && + browser->profile()->GetOriginalProfile() != profile) { continue; }
diff --git a/chrome/browser/ui/webui/policy/policy_ui_handler.cc b/chrome/browser/ui/webui/policy/policy_ui_handler.cc index a9a1f037aa..d3173ed 100644 --- a/chrome/browser/ui/webui/policy/policy_ui_handler.cc +++ b/chrome/browser/ui/webui/policy/policy_ui_handler.cc
@@ -298,9 +298,13 @@ auto update_callback(base::BindRepeating(&PolicyUIHandler::SendStatus, base::Unretained(this))); - user_status_provider_->SetStatusChangeCallback(update_callback); - device_status_provider_->SetStatusChangeCallback(update_callback); - machine_status_provider_->SetStatusChangeCallback(update_callback); + + policy_status_provider_observations_.AddObservation( + user_status_provider_.get()); + policy_status_provider_observations_.AddObservation( + device_status_provider_.get()); + policy_status_provider_observations_.AddObservation( + machine_status_provider_.get()); #if BUILDFLAG(IS_WIN) && BUILDFLAG(GOOGLE_CHROME_BRANDING) updater_status_and_value_provider_ = @@ -308,7 +312,8 @@ Profile::FromWebUI(web_ui())); policy_value_provider_observations_.AddObservation( updater_status_and_value_provider_.get()); - updater_status_and_value_provider_->SetStatusChangeCallback(update_callback); + policy_status_provider_observations_.AddObservation( + updater_status_and_value_provider_.get()); #endif // BUILDFLAG(IS_WIN) && BUILDFLAG(GOOGLE_CHROME_BRANDING) pref_change_registrar_ = std::make_unique<PrefChangeRegistrar>(); @@ -356,6 +361,10 @@ SendStatus(); } +void PolicyUIHandler::OnPolicyStatusChanged() { + SendStatus(); +} + base::Value::Dict PolicyUIHandler::GetPolicyNames() { base::Value::Dict names; names.Merge(chrome_policies_value_provider_->GetNames());
diff --git a/chrome/browser/ui/webui/policy/policy_ui_handler.h b/chrome/browser/ui/webui/policy/policy_ui_handler.h index f5ce5ee..eb9045ca 100644 --- a/chrome/browser/ui/webui/policy/policy_ui_handler.h +++ b/chrome/browser/ui/webui/policy/policy_ui_handler.h
@@ -21,6 +21,7 @@ #include "chrome/browser/policy/value_provider/chrome_policies_value_provider.h" #include "chrome/browser/policy/value_provider/policy_value_provider.h" #include "components/policy/core/browser/policy_error_map.h" +#include "components/policy/core/browser/webui/policy_status_provider.h" #include "components/policy/core/common/policy_map.h" #include "components/policy/core/common/policy_namespace.h" #include "components/policy/core/common/policy_service.h" @@ -46,13 +47,10 @@ class PrefChangeRegistrar; -namespace policy { -class PolicyStatusProvider; -} - // The JavaScript message handler for the chrome://policy page. class PolicyUIHandler : public content::WebUIMessageHandler, public policy::PolicyValueProvider::Observer, + public policy::PolicyStatusProvider::Observer, public ui::SelectFileDialog::Listener { public: PolicyUIHandler(); @@ -71,6 +69,9 @@ // policy::PolicyValueProvider::Observer implementation. void OnPolicyValueChanged() override; + // policy::PolicyValueProvider::Observer implementation. + void OnPolicyStatusChanged() override; + protected: // ui::SelectFileDialog::Listener implementation. void FileSelected(const base::FilePath& path, @@ -143,6 +144,10 @@ policy::PolicyValueProvider::Observer> policy_value_provider_observations_{this}; + base::ScopedMultiSourceObservation<policy::PolicyStatusProvider, + policy::PolicyStatusProvider::Observer> + policy_status_provider_observations_{this}; + base::WeakPtrFactory<PolicyUIHandler> weak_factory_{this}; };
diff --git a/chrome/browser/ui/webui/realbox/realbox_handler.cc b/chrome/browser/ui/webui/realbox/realbox_handler.cc index ca7050e7..ac73755 100644 --- a/chrome/browser/ui/webui/realbox/realbox_handler.cc +++ b/chrome/browser/ui/webui/realbox/realbox_handler.cc
@@ -321,6 +321,9 @@ : kSearchIconResourceName); source->AddString("realboxHint", l10n_util::GetStringUTF8( IDS_GOOGLE_SEARCH_BOX_EMPTY_HINT_MD)); + source->AddBoolean( + "realboxLensSearch", + base::FeatureList::IsEnabled(ntp_features::kNtpRealboxLensSearch)); } // static
diff --git a/chrome/browser/ui/webui/settings/settings_ui.cc b/chrome/browser/ui/webui/settings/settings_ui.cc index 68d7077..e4caff4b 100644 --- a/chrome/browser/ui/webui/settings/settings_ui.cc +++ b/chrome/browser/ui/webui/settings/settings_ui.cc
@@ -433,9 +433,12 @@ "privacySandbox", IDR_SETTINGS_PRIVACY_SANDBOX_PRIVACY_SANDBOX_HTML); } - html_source->AddBoolean( - "safetyCheckPermissionsEnabled", - base::FeatureList::IsEnabled(features::kSafetyCheckPermissions)); + html_source->AddBoolean("safetyCheckNotificationPermissionsEnabled", + base::FeatureList::IsEnabled( + features::kSafetyCheckNotificationPermissions)); + html_source->AddBoolean("safetyCheckUnusedSitePermissionsEnabled", + base::FeatureList::IsEnabled( + features::kSafetyCheckUnusedSitePermissions)); // Performance AddSettingsPageUIHandler(std::make_unique<PerformanceHandler>());
diff --git a/chrome/browser/web_applications/isolated_web_apps/isolated_web_app_url_loader_factory.cc b/chrome/browser/web_applications/isolated_web_apps/isolated_web_app_url_loader_factory.cc index fbc25eb..4e6fbd8 100644 --- a/chrome/browser/web_applications/isolated_web_apps/isolated_web_app_url_loader_factory.cc +++ b/chrome/browser/web_applications/isolated_web_apps/isolated_web_app_url_loader_factory.cc
@@ -323,12 +323,9 @@ return; } - const base::FilePath web_bundle_path = - base::FilePath::FromUTF8Unsafe(content.path); - auto loader = std::make_unique<IsolatedWebAppURLLoader>( - isolated_web_app_reader_registry, web_bundle_path, - *web_bundle_id, std::move(loader_client), resource_request, + isolated_web_app_reader_registry, content.path, *web_bundle_id, + std::move(loader_client), resource_request, frame_tree_node_id_); mojo::MakeSelfOwnedReceiver( std::move(std::move(loader)),
diff --git a/chrome/browser/web_applications/isolated_web_apps/isolated_web_app_url_loader_factory_browsertest.cc b/chrome/browser/web_applications/isolated_web_apps/isolated_web_app_url_loader_factory_browsertest.cc index b9f7366..2639f790 100644 --- a/chrome/browser/web_applications/isolated_web_apps/isolated_web_app_url_loader_factory_browsertest.cc +++ b/chrome/browser/web_applications/isolated_web_apps/isolated_web_app_url_loader_factory_browsertest.cc
@@ -6,6 +6,7 @@ #include "base/callback.h" #include "base/containers/span.h" +#include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/threading/thread_restrictions.h" #include "chrome/browser/profiles/profile.h" @@ -179,8 +180,8 @@ base::FilePath bundle_path = SignAndWriteBundleToDisk(builder.CreateBundle()); std::unique_ptr<WebApp> iwa = CreateIsolatedWebApp( - GURL(kPrimaryUrl), IsolationData{IsolationData::InstalledBundle{ - .path = bundle_path.MaybeAsASCII()}}); + GURL(kPrimaryUrl), + IsolationData{IsolationData::InstalledBundle{.path = bundle_path}}); RegisterWebApp(std::move(iwa)); NavigateAndWaitForTitle(GURL(kPrimaryUrl), u"Hello Isolated Apps"); @@ -200,8 +201,8 @@ base::FilePath bundle_path = SignAndWriteBundleToDisk(builder.CreateBundle()); std::unique_ptr<WebApp> iwa = CreateIsolatedWebApp( - GURL(kPrimaryUrl), IsolationData{IsolationData::InstalledBundle{ - .path = bundle_path.MaybeAsASCII()}}); + GURL(kPrimaryUrl), + IsolationData{IsolationData::InstalledBundle{.path = bundle_path}}); RegisterWebApp(std::move(iwa)); NavigateAndWaitForTitle(GURL(kPrimaryUrl), u"title from js"); @@ -217,8 +218,8 @@ base::FilePath bundle_path = SignAndWriteBundleToDisk(builder.CreateBundle()); std::unique_ptr<WebApp> iwa = CreateIsolatedWebApp( - GURL(kPrimaryUrl), IsolationData{IsolationData::InstalledBundle{ - .path = bundle_path.MaybeAsASCII()}}); + GURL(kPrimaryUrl), + IsolationData{IsolationData::InstalledBundle{.path = bundle_path}}); RegisterWebApp(std::move(iwa)); NavigateAndWaitForError( @@ -237,8 +238,8 @@ base::FilePath bundle_path = SignAndWriteBundleToDisk(builder.CreateBundle()); std::unique_ptr<WebApp> iwa = CreateIsolatedWebApp( - GURL(kPrimaryUrl), IsolationData{IsolationData::InstalledBundle{ - .path = bundle_path.MaybeAsASCII()}}); + GURL(kPrimaryUrl), + IsolationData{IsolationData::InstalledBundle{.path = bundle_path}}); RegisterWebApp(std::move(iwa)); NavigateAndWaitForError( @@ -266,8 +267,10 @@ IsolatedWebAppURLLoaderFactoryNonExistingBundlesBrowserTest, NonExistingBundle) { std::unique_ptr<WebApp> iwa = CreateIsolatedWebApp( - GURL(kPrimaryUrl), IsolationData{IsolationData::InstalledBundle{ - .path = "/this/path/does/not/exist"}}); + GURL(kPrimaryUrl), + IsolationData{IsolationData::InstalledBundle{ + .path = + base::FilePath(FILE_PATH_LITERAL("/this/path/does/not/exist"))}}); RegisterWebApp(std::move(iwa)); NavigateAndWaitForError(url_, error_message_);
diff --git a/chrome/browser/web_applications/isolated_web_apps/isolated_web_app_url_loader_factory_unittest.cc b/chrome/browser/web_applications/isolated_web_apps/isolated_web_app_url_loader_factory_unittest.cc index 2257991..934002d 100644 --- a/chrome/browser/web_applications/isolated_web_apps/isolated_web_app_url_loader_factory_unittest.cc +++ b/chrome/browser/web_applications/isolated_web_apps/isolated_web_app_url_loader_factory_unittest.cc
@@ -231,8 +231,8 @@ auto bundle_path = CreateSignedBundleAndWriteToDisk(); std::unique_ptr<WebApp> iwa = CreateIsolatedWebApp( - kPrimaryUrl, IsolationData{IsolationData::InstalledBundle{ - .path = bundle_path.MaybeAsASCII()}}); + kPrimaryUrl, + IsolationData{IsolationData::InstalledBundle{.path = bundle_path}}); RegisterWebApp(std::move(iwa)); }
diff --git a/chrome/browser/web_applications/isolation_data.cc b/chrome/browser/web_applications/isolation_data.cc index c647163..1710a5a 100644 --- a/chrome/browser/web_applications/isolation_data.cc +++ b/chrome/browser/web_applications/isolation_data.cc
@@ -53,20 +53,21 @@ base::Value IsolationData::AsDebugValue() const { base::Value::Dict value; - absl::visit( - base::Overloaded{ - [&value](const IsolationData::InstalledBundle& bundle) { - value.SetByDottedPath("content.installed_bundle.path", bundle.path); - }, - [&value](const IsolationData::DevModeBundle& bundle) { - value.SetByDottedPath("content.dev_mode_bundle.path", bundle.path); - }, - [&value](const IsolationData::DevModeProxy& proxy) { - value.SetByDottedPath("content.dev_mode_proxy.proxy_url", - proxy.proxy_url); - }, - }, - content); + absl::visit(base::Overloaded{ + [&value](const IsolationData::InstalledBundle& bundle) { + value.SetByDottedPath("content.installed_bundle.path", + bundle.path.LossyDisplayName()); + }, + [&value](const IsolationData::DevModeBundle& bundle) { + value.SetByDottedPath("content.dev_mode_bundle.path", + bundle.path.LossyDisplayName()); + }, + [&value](const IsolationData::DevModeProxy& proxy) { + value.SetByDottedPath("content.dev_mode_proxy.proxy_url", + proxy.proxy_url); + }, + }, + content); return base::Value(std::move(value)); }
diff --git a/chrome/browser/web_applications/isolation_data.h b/chrome/browser/web_applications/isolation_data.h index e76a9cd..86cb180 100644 --- a/chrome/browser/web_applications/isolation_data.h +++ b/chrome/browser/web_applications/isolation_data.h
@@ -7,6 +7,7 @@ #include <string> +#include "base/files/file_path.h" #include "base/values.h" #include "third_party/abseil-cpp/absl/types/variant.h" @@ -19,14 +20,14 @@ bool operator==(const InstalledBundle& other) const; bool operator!=(const InstalledBundle& other) const; - std::string path; + base::FilePath path; }; struct DevModeBundle { bool operator==(const DevModeBundle& other) const; bool operator!=(const DevModeBundle& other) const; - std::string path; + base::FilePath path; }; struct DevModeProxy {
diff --git a/chrome/browser/web_applications/proto/web_app.proto b/chrome/browser/web_applications/proto/web_app.proto index 225dec7..c66be07 100644 --- a/chrome/browser/web_applications/proto/web_app.proto +++ b/chrome/browser/web_applications/proto/web_app.proto
@@ -127,14 +127,24 @@ } // Contains information specific to Isolated Web Apps. +// +// File paths are (de)serialized using Pickle to and from `base::FilePath` via +// its (de)serialization methods `base::FilePath::WriteToPickle` and +// `base::FilePath::ReadFromPickle`. Depending on the OS, file paths may either +// use `std::string` or `std::wstring` internally. The Pickle format includes a +// header representing the original data type of the file path, which means that +// it is impossible to ever accidentally deserialize a `std::wstring` into a +// `std::string` and vice versa. The (de)serialization code is also easier to +// read than manually written code that converts bytes to and from +// `std::wstring` / `std::string`. message IsolationDataProto { // Information needed to load data from an installed web bundle. message InstalledBundle { - optional string path = 1; + optional bytes path = 1; } // Information needed to load data from an installed dev mode web bundle. message DevModeBundle { - optional string path = 1; + optional bytes path = 1; } // Information needed to load data for an app using a dev mode proxy. message DevModeProxy {
diff --git a/chrome/browser/web_applications/test/web_app_test_utils.cc b/chrome/browser/web_applications/test/web_app_test_utils.cc index e889da3..d7b7d66 100644 --- a/chrome/browser/web_applications/test/web_app_test_utils.cc +++ b/chrome/browser/web_applications/test/web_app_test_utils.cc
@@ -615,9 +615,10 @@ using IsolationDataContent = decltype(IsolationData::content); constexpr size_t kNumContentTypes = absl::variant_size<IsolationDataContent>::value; + auto path = base::FilePath::FromUTF8Unsafe(seed_str); IsolationDataContent content_types[] = { - IsolationData::InstalledBundle{.path = seed_str}, - IsolationData::DevModeBundle{.path = seed_str}, + IsolationData::InstalledBundle{.path = path}, + IsolationData::DevModeBundle{.path = path}, IsolationData::DevModeProxy{.proxy_url = seed_str}, }; static_assert(std::size(content_types) == kNumContentTypes);
diff --git a/chrome/browser/web_applications/web_app_database.cc b/chrome/browser/web_applications/web_app_database.cc index 799d5ae..0a2cbf5 100644 --- a/chrome/browser/web_applications/web_app_database.cc +++ b/chrome/browser/web_applications/web_app_database.cc
@@ -11,7 +11,9 @@ #include "base/bind.h" #include "base/callback.h" #include "base/containers/contains.h" +#include "base/files/file_path.h" #include "base/functional/overloaded.h" +#include "base/pickle.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/ash/system_web_apps/types/system_web_app_type.h" #include "chrome/browser/web_applications/os_integration/web_app_file_handler_manager.h" @@ -295,6 +297,23 @@ } } +std::string FilePathToProto(const base::FilePath& path) { + base::Pickle pickle; + path.WriteToPickle(&pickle); + return std::string(static_cast<const char*>(pickle.data()), pickle.size()); +} + +absl::optional<base::FilePath> ProtoToFilePath(const std::string& bytes) { + const base::Pickle pickle(bytes.data(), bytes.size()); + base::PickleIterator pickle_iterator(pickle); + + base::FilePath path; + if (!path.ReadFromPickle(&pickle_iterator)) { + return absl::nullopt; + } + return path; +} + } // anonymous namespace WebAppDatabase::WebAppDatabase(AbstractWebAppDatabaseFactory* database_factory, @@ -739,10 +758,12 @@ absl::visit( base::Overloaded{ [&mutable_data](const IsolationData::InstalledBundle& bundle) { - mutable_data->mutable_installed_bundle()->set_path(bundle.path); + mutable_data->mutable_installed_bundle()->set_path( + FilePathToProto(bundle.path)); }, [&mutable_data](const IsolationData::DevModeBundle& bundle) { - mutable_data->mutable_dev_mode_bundle()->set_path(bundle.path); + mutable_data->mutable_dev_mode_bundle()->set_path( + FilePathToProto(bundle.path)); }, [&mutable_data](const IsolationData::DevModeProxy& proxy) { mutable_data->mutable_dev_mode_proxy()->set_proxy_url( @@ -1368,15 +1389,31 @@ if (local_data.has_isolation_data()) { switch (local_data.isolation_data().content_case()) { - case IsolationDataProto::ContentCase::kInstalledBundle: - web_app->SetIsolationData(IsolationData(IsolationData::InstalledBundle{ - .path = local_data.isolation_data().installed_bundle().path()})); + case IsolationDataProto::ContentCase::kInstalledBundle: { + absl::optional<base::FilePath> path = ProtoToFilePath( + local_data.isolation_data().installed_bundle().path()); + if (!path.has_value()) { + DLOG(ERROR) << "WebApp proto isolation_data.installed_bundle.path " + "parse error: cannot deserialize file path"; + return nullptr; + } + web_app->SetIsolationData( + IsolationData(IsolationData::InstalledBundle{.path = *path})); break; + } - case IsolationDataProto::ContentCase::kDevModeBundle: - web_app->SetIsolationData(IsolationData(IsolationData::DevModeBundle{ - .path = local_data.isolation_data().dev_mode_bundle().path()})); + case IsolationDataProto::ContentCase::kDevModeBundle: { + absl::optional<base::FilePath> path = ProtoToFilePath( + local_data.isolation_data().dev_mode_bundle().path()); + if (!path.has_value()) { + DLOG(ERROR) << "WebApp proto isolation_data.dev_mode_bundle.path " + "parse error: cannot deserialize file path"; + return nullptr; + } + web_app->SetIsolationData( + IsolationData(IsolationData::DevModeBundle{.path = *path})); break; + } case IsolationDataProto::ContentCase::kDevModeProxy: web_app->SetIsolationData(IsolationData(IsolationData::DevModeProxy{
diff --git a/chrome/browser/web_applications/web_app_database_unittest.cc b/chrome/browser/web_applications/web_app_database_unittest.cc index 42288b6f..5d70a74 100644 --- a/chrome/browser/web_applications/web_app_database_unittest.cc +++ b/chrome/browser/web_applications/web_app_database_unittest.cc
@@ -9,6 +9,7 @@ #include <utility> #include <vector> +#include "base/files/file_path.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" @@ -46,6 +47,8 @@ using ::testing::Eq; using ::testing::Field; +using ::testing::IsNull; +using ::testing::NotNull; using ::testing::Property; using ::testing::VariantWith; @@ -622,27 +625,71 @@ } TEST_F(WebAppDatabaseIsolationDataTest, SavesInstalledBundleIsolationData) { + base::FilePath path(FILE_PATH_LITERAL("bundle_path")); std::unique_ptr<WebApp> web_app = CreateIsolatedWebApp( - IsolationData(IsolationData::InstalledBundle{.path = "bundle_path"})); + IsolationData(IsolationData::InstalledBundle{.path = path})); std::unique_ptr<WebApp> protoed_web_app = ToAndFromProto(*web_app); EXPECT_THAT(*web_app, Eq(*protoed_web_app)); - EXPECT_THAT( - web_app->isolation_data()->content, - VariantWith<IsolationData::InstalledBundle>(Field( - "path", &IsolationData::InstalledBundle::path, Eq("bundle_path")))); + EXPECT_THAT(web_app->isolation_data()->content, + VariantWith<IsolationData::InstalledBundle>(Field( + "path", &IsolationData::InstalledBundle::path, Eq(path)))); +} + +TEST_F(WebAppDatabaseIsolationDataTest, + HandlesCorruptedInstalledBundleIsolationData) { + base::FilePath path(FILE_PATH_LITERAL("bundle_path")); + std::unique_ptr<WebApp> web_app = CreateIsolatedWebApp( + IsolationData(IsolationData::InstalledBundle{.path = path})); + + std::unique_ptr<WebAppProto> web_app_proto = + WebAppDatabase::CreateWebAppProto(*web_app); + ASSERT_THAT(web_app_proto, NotNull()); + + // The path is encoded with Pickle, thus setting some non-pickle data here + // should break deserialization. + web_app_proto->mutable_isolation_data() + ->mutable_installed_bundle() + ->mutable_path() + ->assign("foo"); + + std::unique_ptr<WebApp> protoed_web_app = + WebAppDatabase::CreateWebApp(*web_app_proto); + EXPECT_THAT(protoed_web_app, IsNull()); } TEST_F(WebAppDatabaseIsolationDataTest, SavesDevModeBundleIsolationData) { + base::FilePath path(FILE_PATH_LITERAL("dev_bundle_path")); std::unique_ptr<WebApp> web_app = CreateIsolatedWebApp( - IsolationData(IsolationData::DevModeBundle{.path = "dev_bundle_path"})); + IsolationData(IsolationData::DevModeBundle{.path = path})); std::unique_ptr<WebApp> protoed_web_app = ToAndFromProto(*web_app); EXPECT_THAT(*web_app, Eq(*protoed_web_app)); - EXPECT_THAT( - web_app->isolation_data()->content, - VariantWith<IsolationData::DevModeBundle>(Field( - "path", &IsolationData::DevModeBundle::path, Eq("dev_bundle_path")))); + EXPECT_THAT(web_app->isolation_data()->content, + VariantWith<IsolationData::DevModeBundle>(Field( + "path", &IsolationData::DevModeBundle::path, Eq(path)))); +} + +TEST_F(WebAppDatabaseIsolationDataTest, + HandlesCorruptedDevModeBundleIsolationData) { + base::FilePath path(FILE_PATH_LITERAL("bundle_path")); + std::unique_ptr<WebApp> web_app = CreateIsolatedWebApp( + IsolationData(IsolationData::DevModeBundle{.path = path})); + + std::unique_ptr<WebAppProto> web_app_proto = + WebAppDatabase::CreateWebAppProto(*web_app); + ASSERT_THAT(web_app_proto, NotNull()); + + // The path is encoded with Pickle, thus setting some non-pickle data here + // should break deserialization. + web_app_proto->mutable_isolation_data() + ->mutable_dev_mode_bundle() + ->mutable_path() + ->assign("foo"); + + std::unique_ptr<WebApp> protoed_web_app = + WebAppDatabase::CreateWebApp(*web_app_proto); + EXPECT_THAT(protoed_web_app, IsNull()); } TEST_F(WebAppDatabaseIsolationDataTest, SavesDevModeProxyIsolationData) {
diff --git a/chrome/browser/web_applications/web_app_install_finalizer_unittest.cc b/chrome/browser/web_applications/web_app_install_finalizer_unittest.cc index a2953bc..5d2dc44a 100644 --- a/chrome/browser/web_applications/web_app_install_finalizer_unittest.cc +++ b/chrome/browser/web_applications/web_app_install_finalizer_unittest.cc
@@ -430,7 +430,8 @@ info.start_url = GURL("https://foo.example"); info.title = u"Foo Title"; - const IsolationData isolation_data{IsolationData::DevModeBundle{.path = "p"}}; + const IsolationData isolation_data{IsolationData::DevModeBundle{ + .path = base::FilePath(FILE_PATH_LITERAL("p"))}}; WebAppInstallFinalizer::FinalizeOptions options( webapps::WebappInstallSource::EXTERNAL_POLICY); options.isolation_data = isolation_data;
diff --git a/chrome/browser/web_applications/web_app_unittest.cc b/chrome/browser/web_applications/web_app_unittest.cc index 95aa8d9..c4f8918 100644 --- a/chrome/browser/web_applications/web_app_unittest.cc +++ b/chrome/browser/web_applications/web_app_unittest.cc
@@ -312,8 +312,8 @@ TEST(WebAppTest, IsolationDataDebugValue) { WebApp app{GenerateAppId(/*manifest_id=*/absl::nullopt, GURL("https://example.com"))}; - app.SetIsolationData( - IsolationData(IsolationData::InstalledBundle{.path = "random_path"})); + app.SetIsolationData(IsolationData(IsolationData::InstalledBundle{ + .path = base::FilePath(FILE_PATH_LITERAL("random_path"))})); EXPECT_TRUE(app.isolation_data().has_value());
diff --git a/chrome/build/linux.pgo.txt b/chrome/build/linux.pgo.txt index dfd0bf68..fb518686f 100644 --- a/chrome/build/linux.pgo.txt +++ b/chrome/build/linux.pgo.txt
@@ -1 +1 @@ -chrome-linux-main-1663783183-9c32cabf46fa8298a487a7c85d3008e28b574125.profdata +chrome-linux-main-1663826101-5a76decbb0d6d11b0602413d6cb28fb51d0a30f5.profdata
diff --git a/chrome/build/mac-arm.pgo.txt b/chrome/build/mac-arm.pgo.txt index 011408b..f031ab76 100644 --- a/chrome/build/mac-arm.pgo.txt +++ b/chrome/build/mac-arm.pgo.txt
@@ -1 +1 @@ -chrome-mac-arm-main-1663718373-a9635b5325275571e41377fd03c6b3687d76af1a.profdata +chrome-mac-arm-main-1663826101-a399507d12bbeec97de84e34095ca6218625a8df.profdata
diff --git a/chrome/build/mac.pgo.txt b/chrome/build/mac.pgo.txt index 350e4aa..039643a5 100644 --- a/chrome/build/mac.pgo.txt +++ b/chrome/build/mac.pgo.txt
@@ -1 +1 @@ -chrome-mac-main-1663783183-ba7af3e2dcda9927ad42413211122a2ce2a558c9.profdata +chrome-mac-main-1663826101-396c0289365d5bcae2879fcc1aa5c1100d9065cf.profdata
diff --git a/chrome/build/win32.pgo.txt b/chrome/build/win32.pgo.txt index 38c3e8f..3064e58 100644 --- a/chrome/build/win32.pgo.txt +++ b/chrome/build/win32.pgo.txt
@@ -1 +1 @@ -chrome-win32-main-1663772376-707d803d4d37bd1d5c53983e8e7d87a0e765b5ab.profdata +chrome-win32-main-1663826101-6eeee9adb0ecdb4978c1423ef4d1b56a4c563791.profdata
diff --git a/chrome/build/win64.pgo.txt b/chrome/build/win64.pgo.txt index aa0f095c..2608ff1f 100644 --- a/chrome/build/win64.pgo.txt +++ b/chrome/build/win64.pgo.txt
@@ -1 +1 @@ -chrome-win64-main-1663793607-714c82dca7dd1c7176e7ad363a97731f5591fa80.profdata +chrome-win64-main-1663826101-ea49b7fdc41005369e173f9ce2bfec1e8a14c3bb.profdata
diff --git a/chrome/common/chrome_features.cc b/chrome/common/chrome_features.cc index dfa531b74..10fd84d42 100644 --- a/chrome/common/chrome_features.cc +++ b/chrome/common/chrome_features.cc
@@ -625,6 +625,10 @@ BASE_FEATURE(kHappinessTrackingPhotosExperience, "HappinessTrackingPhotosExperience", base::FEATURE_DISABLED_BY_DEFAULT); +// Enables the Happiness Tracking System for General Camera survey. +BASE_FEATURE(kHappinessTrackingGeneralCamera, + "HappinessTrackingGeneralCamera", + base::FEATURE_DISABLED_BY_DEFAULT); #endif // Hides the origin text from showing up briefly in WebApp windows. @@ -926,9 +930,14 @@ #endif #if !BUILDFLAG(IS_ANDROID) -// Enables permission modules on Safety Check. -BASE_FEATURE(kSafetyCheckPermissions, - "SafetyCheckPermissions", +// Enables notification permission module in Safety Check. +BASE_FEATURE(kSafetyCheckNotificationPermissions, + "SafetyCheckNotificationPermissions", + base::FEATURE_DISABLED_BY_DEFAULT); + +// Enables unused site permission module in Safety Check. +BASE_FEATURE(kSafetyCheckUnusedSitePermissions, + "SafetyCheckUnusedSitePermissions", base::FEATURE_DISABLED_BY_DEFAULT); #endif // !BUILDFLAG(IS_ANDROID)
diff --git a/chrome/common/chrome_features.h b/chrome/common/chrome_features.h index 31ed5d8d..0c198ff3 100644 --- a/chrome/common/chrome_features.h +++ b/chrome/common/chrome_features.h
@@ -372,6 +372,9 @@ COMPONENT_EXPORT(CHROME_FEATURES) BASE_DECLARE_FEATURE(kHappinessTrackingPhotosExperience); +COMPONENT_EXPORT(CHROME_FEATURES) +extern const base::Feature kHappinessTrackingGeneralCamera; + #endif COMPONENT_EXPORT(CHROME_FEATURES) BASE_DECLARE_FEATURE(kHideWebAppOriginText); @@ -538,7 +541,11 @@ #endif #if !BUILDFLAG(IS_ANDROID) -COMPONENT_EXPORT(CHROME_FEATURES) BASE_DECLARE_FEATURE(kSafetyCheckPermissions); +COMPONENT_EXPORT(CHROME_FEATURES) +BASE_DECLARE_FEATURE(kSafetyCheckNotificationPermissions); + +COMPONENT_EXPORT(CHROME_FEATURES) +BASE_DECLARE_FEATURE(kSafetyCheckUnusedSitePermissions); #endif #if BUILDFLAG(IS_CHROMEOS_ASH)
diff --git a/chrome/common/chromeos/extensions/api/diagnostics.idl b/chrome/common/chromeos/extensions/api/diagnostics.idl index e38d5d7..6f1ffc5 100644 --- a/chrome/common/chromeos/extensions/api/diagnostics.idl +++ b/chrome/common/chromeos/extensions/api/diagnostics.idl
@@ -19,10 +19,12 @@ cpu_prime_search, cpu_stress, disk_read, + dns_resolution, memory, nvme_wear_level, smartctl_check, - lan_connectivity + lan_connectivity, + signal_strength }; enum RoutineStatus { @@ -161,6 +163,8 @@ [supportsPromises] static void runDiskReadRoutine(RunDiskReadRequest request, RunRoutineCallback callback); + [supportsPromises] static void runDnsResolutionRoutine(RunRoutineCallback callback); + [supportsPromises] static void runLanConnectivityRoutine(RunRoutineCallback callback); [supportsPromises] static void runMemoryRoutine(RunRoutineCallback callback); @@ -168,6 +172,8 @@ [supportsPromises] static void runNvmeWearLevelRoutine(RunNvmeWearLevelRequest request, RunRoutineCallback callback); + [supportsPromises] static void runSignalStrengthRoutine(RunRoutineCallback callback); + [supportsPromises] static void runSmartctlCheckRoutine(RunRoutineCallback callback); }; };
diff --git a/chrome/common/pref_names.cc b/chrome/common/pref_names.cc index fc8501f..8a8bb1f 100644 --- a/chrome/common/pref_names.cc +++ b/chrome/common/pref_names.cc
@@ -904,6 +904,15 @@ const char kHatsPhotosExperienceIsSelected[] = "hats_photos_experience_is_selected"; +// An int64 pref. This is the timestamp, microseconds after epoch, that +// indicated the end of the most recent general camera survey cycle. +const char kHatsGeneralCameraSurveyCycleEndTs[] = + "hats_general_camera_cycle_end_timestamp"; + +// A boolean pref. Indicated if the device is selected for the general camera +// survey. +const char kHatsGeneralCameraIsSelected[] = "hats_general_camera_is_selected"; + // A boolean pref. Indicates if we've already shown a notification to inform the // current user about the quick unlock feature. const char kPinUnlockFeatureNotificationShown[] =
diff --git a/chrome/common/pref_names.h b/chrome/common/pref_names.h index 7d44889..99004b4 100644 --- a/chrome/common/pref_names.h +++ b/chrome/common/pref_names.h
@@ -312,6 +312,8 @@ extern const char kHatsCameraAppSurveyCycleEndTs[]; extern const char kHatsPhotosExperienceCycleEndTs[]; extern const char kHatsPhotosExperienceIsSelected[]; +extern const char kHatsGeneralCameraIsSelected[]; +extern const char kHatsGeneralCameraSurveyCycleEndTs[]; extern const char kEolStatus[]; extern const char kEndOfLifeDate[]; extern const char kEolNotificationDismissed[];
diff --git a/chrome/renderer/cart/commerce_hint_agent_browsertest.cc b/chrome/renderer/cart/commerce_hint_agent_browsertest.cc index b34cddf5..ae43d132 100644 --- a/chrome/renderer/cart/commerce_hint_agent_browsertest.cc +++ b/chrome/renderer/cart/commerce_hint_agent_browsertest.cc
@@ -504,9 +504,17 @@ ExpectUKMCount(XHREntry::kEntryName, "IsAddToCart", 1); } -#if !BUILDFLAG(IS_CHROMEOS) -// TODO(crbug/1310497): This test is flaky on ChromeOS. -IN_PROC_BROWSER_TEST_F(CommerceHintAgentTest, VisitCart) { +// TODO(https://crbug/1310497, https://crbug.com/1362442): This test is flaky +// on ChromeOS and Linux Asan. +#if BUILDFLAG(IS_CHROMEOS) +#define MAYBE_VisitCart DISABLED_VisitCart +#elif BUILDFLAG(IS_LINUX) && defined(ADDRESS_SANITIZER) +#define MAYBE_VisitCart DISABLED_VisitCart +#else +#define MAYBE_VisitCart VisitCart +#endif + +IN_PROC_BROWSER_TEST_F(CommerceHintAgentTest, MAYBE_VisitCart) { // Cannot use dummy page with zero products, or the cart would be deleted. NavigateToURL("https://www.guitarcenter.com/cart.html"); @@ -515,7 +523,6 @@ WaitForCartCount(kExpectedExample); #endif } -#endif // !BUILDFLAG(IS_CHROMEOS) // Flaky on Windows: https://crbug.com/1300332. #if BUILDFLAG(IS_WIN) @@ -547,8 +554,16 @@ WaitForUmaCount("Commerce.Carts.VisitCart", 2); } +// TODO(https://crbug.com/1362442): This test is flaky on Linux Asan. +#if BUILDFLAG(IS_LINUX) && defined(ADDRESS_SANITIZER) +#define MAYBE_VisitCart_PerDomain_FromComponent \ + DISABLED_VisitCart_PerDomain_FromComponent +#else +#define MAYBE_VisitCart_PerDomain_FromComponent \ + VisitCart_PerDomain_FromComponent +#endif IN_PROC_BROWSER_TEST_F(CommerceHintAgentTest, - VisitCart_PerDomain_FromComponent) { + MAYBE_VisitCart_PerDomain_FromComponent) { bool is_populated = commerce_hint_service_->InitializeCommerceHeuristicsForTesting( base::Version("0.0.0.1"), R"###( @@ -1300,7 +1315,8 @@ base::test::ScopedFeatureList scoped_feature_list_; }; -IN_PROC_BROWSER_TEST_F(CommerceHintCartPatternTest, VisitCart) { +// TODO(https://crbug.com/1362442): Deflake this test. +IN_PROC_BROWSER_TEST_F(CommerceHintCartPatternTest, DISABLED_VisitCart) { // The test is flaky with same-site back/forward cache, presumably because it // doesn't expect a RenderView change on same-site navigations. // TODO(https://crbug.com/1302902): Investigate and fix this.
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index 7e902164..27117a2 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -3952,7 +3952,6 @@ "../browser/speech/on_device_speech_recognizer_browsertest.cc", "../browser/support_tool/ash/ui_hierarchy_data_collector_browsertest.cc", "../browser/ui/app_list/app_list_client_impl_browsertest.cc", - "../browser/ui/app_list/app_list_remove_space_browsertest.cc", "../browser/ui/app_list/app_list_sort_browsertest.cc", "../browser/ui/app_list/app_service/app_service_app_item_browsertest.cc", "../browser/ui/app_list/arc/arc_usb_host_permission_browsertest.cc",
diff --git a/chrome/test/data/webui/settings/cr_settings_browsertest.js b/chrome/test/data/webui/settings/cr_settings_browsertest.js index 0eb15064..1145344 100644 --- a/chrome/test/data/webui/settings/cr_settings_browsertest.js +++ b/chrome/test/data/webui/settings/cr_settings_browsertest.js
@@ -353,7 +353,8 @@ get featureListInternal() { return { enabled: [ - 'features::kSafetyCheckPermissions', + 'features::kSafetyCheckUnusedSitePermissions', + 'features::kSafetyCheckNotificationPermissions', ], }; } @@ -834,7 +835,7 @@ get featureList() { return { enabled: [ - 'features::kSafetyCheckPermissions', + 'features::kSafetyCheckNotificationPermissions', ], }; }
diff --git a/chrome/test/data/webui/settings/safety_check_page_test.ts b/chrome/test/data/webui/settings/safety_check_page_test.ts index 6605d7a6..46fc8109 100644 --- a/chrome/test/data/webui/settings/safety_check_page_test.ts +++ b/chrome/test/data/webui/settings/safety_check_page_test.ts
@@ -4,10 +4,12 @@ // clang-format off import {webUIListenerCallback} from 'chrome://resources/js/cr.m.js'; +import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {HatsBrowserProxyImpl, LifetimeBrowserProxyImpl, MetricsBrowserProxyImpl, OpenWindowProxyImpl, PasswordCheckReferrer, PasswordManagerImpl, Router, routes, SafetyCheckBrowserProxy, SafetyCheckBrowserProxyImpl, SafetyCheckCallbackConstants, SafetyCheckChromeCleanerStatus, SafetyCheckExtensionsStatus, SafetyCheckIconStatus, SafetyCheckInteractions, SafetyCheckParentStatus, SafetyCheckPasswordsStatus, SafetyCheckSafeBrowsingStatus, SafetyCheckUpdatesStatus, SettingsSafetyCheckChildElement, SettingsSafetyCheckExtensionsChildElement, SettingsSafetyCheckPageElement, SettingsSafetyCheckPasswordsChildElement, SettingsSafetyCheckSafeBrowsingChildElement ,SettingsSafetyCheckUpdatesChildElement, TrustSafetyInteraction} from 'chrome://settings/settings.js'; import {assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chai_assert.js'; import {TestBrowserProxy} from 'chrome://webui-test/test_browser_proxy.js'; +import {isVisible} from 'chrome://webui-test/test_util.js'; import {TestHatsBrowserProxy} from './test_hats_browser_proxy.js'; import {TestLifetimeBrowserProxy} from './test_lifetime_browser_proxy.js'; @@ -950,3 +952,53 @@ }); }); }); + +suite('SafetyCheckPagePermissionModulesTest', function() { + let page: SettingsSafetyCheckPageElement; + const notificationElementName = + 'settings-safety-check-notification-permissions'; + const unusedSiteElementName = 'settings-safety-check-unused-site-permissions'; + + function createPage() { + document.body.innerHTML = ''; + page = document.createElement('settings-safety-check-page'); + document.body.appendChild(page); + flush(); + } + + teardown(function() { + page.remove(); + }); + + test('notificationPermissionModuleVisible', () => { + loadTimeData.overrideValues( + {safetyCheckNotificationPermissionsEnabled: true}); + createPage(); + assertTrue( + isVisible(page.shadowRoot!.querySelector(notificationElementName))); + }); + + test('notificationPermissionModuleNotVisible', () => { + loadTimeData.overrideValues( + {safetyCheckNotificationPermissionsEnabled: false}); + createPage(); + assertFalse( + isVisible(page.shadowRoot!.querySelector(notificationElementName))); + }); + + test('unusedSitePermissionsModuleVisible', () => { + loadTimeData.overrideValues( + {safetyCheckUnusedSitePermissionsEnabled: true}); + createPage(); + assertTrue( + isVisible(page.shadowRoot!.querySelector(unusedSiteElementName))); + }); + + test('unusedSitePermissionsModuleNotVisible', () => { + loadTimeData.overrideValues( + {safetyCheckUnusedSitePermissionsEnabled: false}); + createPage(); + assertFalse( + isVisible(page.shadowRoot!.querySelector(unusedSiteElementName))); + }); +});
diff --git a/chrome/test/webapps/coverage/coverage_cros.tsv b/chrome/test/webapps/coverage/coverage_cros.tsv index 8564aeb..956130e 100644 --- a/chrome/test/webapps/coverage/coverage_cros.tsv +++ b/chrome/test/webapps/coverage/coverage_cros.tsv
@@ -627,8 +627,8 @@ create_shortcut_StandaloneNestedA_Windowed🌕 manifest_update_scope_to_StandaloneNestedA_Standalone🌕 await_manifest_update_StandaloneNestedA🌕 navigate_browser_StandaloneNestedA🌕 check_launch_icon_shown🌕 install_omnibox_icon_StandaloneNestedA🌕 manifest_update_scope_to_StandaloneNestedA_Standalone🌕 await_manifest_update_StandaloneNestedA🌕 navigate_browser_StandaloneNestedA🌕 check_launch_icon_shown🌕 install_menu_option_StandaloneNestedA🌕 manifest_update_scope_to_StandaloneNestedA_Standalone🌕 await_manifest_update_StandaloneNestedA🌕 navigate_browser_StandaloneNestedA🌕 check_launch_icon_shown🌕 -switch_incognito_profile🌑 navigate_browser_Standalone🌑 check_create_shortcut_not_shown🌑 -switch_incognito_profile🌑 navigate_browser_NotPromotable🌑 check_create_shortcut_not_shown🌑 +switch_incognito_profile🌕 navigate_browser_Standalone🌕 check_create_shortcut_not_shown🌑 +switch_incognito_profile🌕 navigate_browser_NotPromotable🌕 check_create_shortcut_not_shown🌑 navigate_crashed_url🌑 check_create_shortcut_not_shown🌑 navigate_crashed_url🌑 check_install_icon_not_shown🌑 navigate_notfound_url🌕 check_create_shortcut_not_shown🌑 @@ -666,9 +666,9 @@ create_shortcut_Standalone_Windowed🌕 navigate_pwa_Standalone_MinimalUi🌕 check_app_title_Standalone_StandaloneOriginal🌑 install_omnibox_icon_Standalone🌕 navigate_pwa_Standalone_MinimalUi🌕 check_app_title_Standalone_StandaloneOriginal🌑 install_menu_option_Standalone🌕 navigate_pwa_Standalone_MinimalUi🌕 check_app_title_Standalone_StandaloneOriginal🌑 -create_shortcut_Standalone_Windowed🌕 switch_incognito_profile🌑 navigate_browser_Standalone🌑 check_launch_icon_not_shown🌑 -install_omnibox_icon_Standalone🌕 switch_incognito_profile🌑 navigate_browser_Standalone🌑 check_launch_icon_not_shown🌑 -install_menu_option_Standalone🌕 switch_incognito_profile🌑 navigate_browser_Standalone🌑 check_launch_icon_not_shown🌑 +create_shortcut_Standalone_Windowed🌕 switch_incognito_profile🌕 navigate_browser_Standalone🌕 check_launch_icon_not_shown🌕 +install_omnibox_icon_Standalone🌕 switch_incognito_profile🌕 navigate_browser_Standalone🌕 check_launch_icon_not_shown🌕 +install_menu_option_Standalone🌕 switch_incognito_profile🌕 navigate_browser_Standalone🌕 check_launch_icon_not_shown🌕 create_shortcut_Standalone_Windowed🌕 set_open_in_tab_Standalone🌓 check_app_in_list_tabbed_Standalone🌓 install_omnibox_icon_Standalone🌕 set_open_in_tab_Standalone🌓 check_app_in_list_tabbed_Standalone🌓 install_menu_option_Standalone🌕 set_open_in_tab_Standalone🌓 check_app_in_list_tabbed_Standalone🌓
diff --git a/chrome/test/webapps/coverage/coverage_linux.tsv b/chrome/test/webapps/coverage/coverage_linux.tsv index d33a805c..7edcdbb 100644 --- a/chrome/test/webapps/coverage/coverage_linux.tsv +++ b/chrome/test/webapps/coverage/coverage_linux.tsv
@@ -844,8 +844,8 @@ create_shortcut_StandaloneNestedA_Windowed🌕 manifest_update_scope_to_StandaloneNestedA_Standalone🌕 await_manifest_update_StandaloneNestedA🌕 navigate_browser_StandaloneNestedA🌕 check_launch_icon_shown🌕 install_omnibox_icon_StandaloneNestedA🌕 manifest_update_scope_to_StandaloneNestedA_Standalone🌕 await_manifest_update_StandaloneNestedA🌕 navigate_browser_StandaloneNestedA🌕 check_launch_icon_shown🌕 install_menu_option_StandaloneNestedA🌕 manifest_update_scope_to_StandaloneNestedA_Standalone🌕 await_manifest_update_StandaloneNestedA🌕 navigate_browser_StandaloneNestedA🌕 check_launch_icon_shown🌕 -switch_incognito_profile🌑 navigate_browser_Standalone🌑 check_create_shortcut_not_shown🌑 -switch_incognito_profile🌑 navigate_browser_NotPromotable🌑 check_create_shortcut_not_shown🌑 +switch_incognito_profile🌕 navigate_browser_Standalone🌕 check_create_shortcut_not_shown🌑 +switch_incognito_profile🌕 navigate_browser_NotPromotable🌕 check_create_shortcut_not_shown🌑 navigate_crashed_url🌑 check_create_shortcut_not_shown🌑 navigate_crashed_url🌑 check_install_icon_not_shown🌑 navigate_notfound_url🌕 check_create_shortcut_not_shown🌑 @@ -883,9 +883,9 @@ create_shortcut_Standalone_Windowed🌕 navigate_pwa_Standalone_MinimalUi🌕 check_app_title_Standalone_StandaloneOriginal🌑 install_omnibox_icon_Standalone🌕 navigate_pwa_Standalone_MinimalUi🌕 check_app_title_Standalone_StandaloneOriginal🌑 install_menu_option_Standalone🌕 navigate_pwa_Standalone_MinimalUi🌕 check_app_title_Standalone_StandaloneOriginal🌑 -create_shortcut_Standalone_Windowed🌕 switch_incognito_profile🌑 navigate_browser_Standalone🌑 check_launch_icon_not_shown🌑 -install_omnibox_icon_Standalone🌕 switch_incognito_profile🌑 navigate_browser_Standalone🌑 check_launch_icon_not_shown🌑 -install_menu_option_Standalone🌕 switch_incognito_profile🌑 navigate_browser_Standalone🌑 check_launch_icon_not_shown🌑 +create_shortcut_Standalone_Windowed🌕 switch_incognito_profile🌕 navigate_browser_Standalone🌕 check_launch_icon_not_shown🌕 +install_omnibox_icon_Standalone🌕 switch_incognito_profile🌕 navigate_browser_Standalone🌕 check_launch_icon_not_shown🌕 +install_menu_option_Standalone🌕 switch_incognito_profile🌕 navigate_browser_Standalone🌕 check_launch_icon_not_shown🌕 create_shortcut_Standalone_Windowed🌕 set_open_in_tab_Standalone🌓 check_app_in_list_tabbed_Standalone🌓 install_omnibox_icon_Standalone🌕 set_open_in_tab_Standalone🌓 check_app_in_list_tabbed_Standalone🌓 install_menu_option_Standalone🌕 set_open_in_tab_Standalone🌓 check_app_in_list_tabbed_Standalone🌓
diff --git a/chrome/test/webapps/coverage/coverage_mac.tsv b/chrome/test/webapps/coverage/coverage_mac.tsv index 18e423c..5733132 100644 --- a/chrome/test/webapps/coverage/coverage_mac.tsv +++ b/chrome/test/webapps/coverage/coverage_mac.tsv
@@ -844,8 +844,8 @@ create_shortcut_StandaloneNestedA_Windowed🌕 manifest_update_scope_to_StandaloneNestedA_Standalone🌕 await_manifest_update_StandaloneNestedA🌕 navigate_browser_StandaloneNestedA🌕 check_launch_icon_shown🌕 install_omnibox_icon_StandaloneNestedA🌕 manifest_update_scope_to_StandaloneNestedA_Standalone🌕 await_manifest_update_StandaloneNestedA🌕 navigate_browser_StandaloneNestedA🌕 check_launch_icon_shown🌕 install_menu_option_StandaloneNestedA🌕 manifest_update_scope_to_StandaloneNestedA_Standalone🌕 await_manifest_update_StandaloneNestedA🌕 navigate_browser_StandaloneNestedA🌕 check_launch_icon_shown🌕 -switch_incognito_profile🌑 navigate_browser_Standalone🌑 check_create_shortcut_not_shown🌑 -switch_incognito_profile🌑 navigate_browser_NotPromotable🌑 check_create_shortcut_not_shown🌑 +switch_incognito_profile🌕 navigate_browser_Standalone🌕 check_create_shortcut_not_shown🌑 +switch_incognito_profile🌕 navigate_browser_NotPromotable🌕 check_create_shortcut_not_shown🌑 navigate_crashed_url🌑 check_create_shortcut_not_shown🌑 navigate_crashed_url🌑 check_install_icon_not_shown🌑 navigate_notfound_url🌕 check_create_shortcut_not_shown🌑 @@ -883,9 +883,9 @@ create_shortcut_Standalone_Windowed🌕 navigate_pwa_Standalone_MinimalUi🌕 check_app_title_Standalone_StandaloneOriginal🌑 install_omnibox_icon_Standalone🌕 navigate_pwa_Standalone_MinimalUi🌕 check_app_title_Standalone_StandaloneOriginal🌑 install_menu_option_Standalone🌕 navigate_pwa_Standalone_MinimalUi🌕 check_app_title_Standalone_StandaloneOriginal🌑 -create_shortcut_Standalone_Windowed🌕 switch_incognito_profile🌑 navigate_browser_Standalone🌑 check_launch_icon_not_shown🌑 -install_omnibox_icon_Standalone🌕 switch_incognito_profile🌑 navigate_browser_Standalone🌑 check_launch_icon_not_shown🌑 -install_menu_option_Standalone🌕 switch_incognito_profile🌑 navigate_browser_Standalone🌑 check_launch_icon_not_shown🌑 +create_shortcut_Standalone_Windowed🌕 switch_incognito_profile🌕 navigate_browser_Standalone🌕 check_launch_icon_not_shown🌕 +install_omnibox_icon_Standalone🌕 switch_incognito_profile🌕 navigate_browser_Standalone🌕 check_launch_icon_not_shown🌕 +install_menu_option_Standalone🌕 switch_incognito_profile🌕 navigate_browser_Standalone🌕 check_launch_icon_not_shown🌕 create_shortcut_Standalone_Windowed🌕 set_open_in_tab_Standalone🌓 check_app_in_list_tabbed_Standalone🌓 install_omnibox_icon_Standalone🌕 set_open_in_tab_Standalone🌓 check_app_in_list_tabbed_Standalone🌓 install_menu_option_Standalone🌕 set_open_in_tab_Standalone🌓 check_app_in_list_tabbed_Standalone🌓
diff --git a/chrome/test/webapps/coverage/coverage_win.tsv b/chrome/test/webapps/coverage/coverage_win.tsv index 02d35702..dfddcb91 100644 --- a/chrome/test/webapps/coverage/coverage_win.tsv +++ b/chrome/test/webapps/coverage/coverage_win.tsv
@@ -844,8 +844,8 @@ create_shortcut_StandaloneNestedA_Windowed🌕 manifest_update_scope_to_StandaloneNestedA_Standalone🌕 await_manifest_update_StandaloneNestedA🌕 navigate_browser_StandaloneNestedA🌕 check_launch_icon_shown🌕 install_omnibox_icon_StandaloneNestedA🌕 manifest_update_scope_to_StandaloneNestedA_Standalone🌕 await_manifest_update_StandaloneNestedA🌕 navigate_browser_StandaloneNestedA🌕 check_launch_icon_shown🌕 install_menu_option_StandaloneNestedA🌕 manifest_update_scope_to_StandaloneNestedA_Standalone🌕 await_manifest_update_StandaloneNestedA🌕 navigate_browser_StandaloneNestedA🌕 check_launch_icon_shown🌕 -switch_incognito_profile🌑 navigate_browser_Standalone🌑 check_create_shortcut_not_shown🌑 -switch_incognito_profile🌑 navigate_browser_NotPromotable🌑 check_create_shortcut_not_shown🌑 +switch_incognito_profile🌕 navigate_browser_Standalone🌕 check_create_shortcut_not_shown🌑 +switch_incognito_profile🌕 navigate_browser_NotPromotable🌕 check_create_shortcut_not_shown🌑 navigate_crashed_url🌑 check_create_shortcut_not_shown🌑 navigate_crashed_url🌑 check_install_icon_not_shown🌑 navigate_notfound_url🌕 check_create_shortcut_not_shown🌑 @@ -883,9 +883,9 @@ create_shortcut_Standalone_Windowed🌕 navigate_pwa_Standalone_MinimalUi🌕 check_app_title_Standalone_StandaloneOriginal🌑 install_omnibox_icon_Standalone🌕 navigate_pwa_Standalone_MinimalUi🌕 check_app_title_Standalone_StandaloneOriginal🌑 install_menu_option_Standalone🌕 navigate_pwa_Standalone_MinimalUi🌕 check_app_title_Standalone_StandaloneOriginal🌑 -create_shortcut_Standalone_Windowed🌕 switch_incognito_profile🌑 navigate_browser_Standalone🌑 check_launch_icon_not_shown🌑 -install_omnibox_icon_Standalone🌕 switch_incognito_profile🌑 navigate_browser_Standalone🌑 check_launch_icon_not_shown🌑 -install_menu_option_Standalone🌕 switch_incognito_profile🌑 navigate_browser_Standalone🌑 check_launch_icon_not_shown🌑 +create_shortcut_Standalone_Windowed🌕 switch_incognito_profile🌕 navigate_browser_Standalone🌕 check_launch_icon_not_shown🌕 +install_omnibox_icon_Standalone🌕 switch_incognito_profile🌕 navigate_browser_Standalone🌕 check_launch_icon_not_shown🌕 +install_menu_option_Standalone🌕 switch_incognito_profile🌕 navigate_browser_Standalone🌕 check_launch_icon_not_shown🌕 create_shortcut_Standalone_Windowed🌕 set_open_in_tab_Standalone🌓 check_app_in_list_tabbed_Standalone🌓 install_omnibox_icon_Standalone🌕 set_open_in_tab_Standalone🌓 check_app_in_list_tabbed_Standalone🌓 install_menu_option_Standalone🌕 set_open_in_tab_Standalone🌓 check_app_in_list_tabbed_Standalone🌓
diff --git a/chrome/test/webapps/data/actions.md b/chrome/test/webapps/data/actions.md index 1fd4b86..2377a6ba 100644 --- a/chrome/test/webapps/data/actions.md +++ b/chrome/test/webapps/data/actions.md
@@ -86,7 +86,7 @@ | check_app_in_list_not_locally_installed | Site | | 45 | Implemented | Find the app in the app list (chrome://apps) and check that the given app is in the app list and is not installed. This means the icon is grey, and right clicking on it provides an 'install' option. Win/Mac/Linux only. | | | check_app_not_in_list | Site | | 15 | Implemented | Check that the given app is NOT in the app list. On desktop, this is chrome://apps, and on ChromeOS, this is the app drawer. | | | check_app_title | Site, Title | | 79 | Implemented | Check that the app title is correct | finnur@ | -| check_app_in_list_icon_correct | Site | | 75 | Not Implemented | Find the app in the app list (on desktop, this is chrome://apps, and on ChromeOS, this is the app drawer). Check that the icon for the given app in the app list is correct. | P2 (dmurph modified - should be easy to fetch icon using web request for chrome://app-icon/<app-id>/<dip> I believe) | +| check_app_in_list_icon_correct | Site | | 75 | Implemented | Find the app in the app list (on desktop, this is chrome://apps, and on ChromeOS, this is the app drawer). Check that the icon for the given app in the app list is correct. | P2 (fetch icon using web request for chrome://app-icon/<app-id>/<icon-size>) | | check_theme_color | Site | | 76 | Not Implemented | Asserts that the theme color of the given app window is correct. | P3 | | # Misc UX | | check_browser_navigation_is_app_settings | Site | | 109 | Implemented | Check the current browser navigation is chrome://app-settings/<app-id> | phillis@ | @@ -142,7 +142,7 @@ | switch_profile_clients | ProfileClient | | 40 | Implemented | Switch to a different instance of chrome signed in to the same profile | | | sync_turn_off | | | 41 | Implemented | Turn chrome sync off for "Apps": chrome://settings/syncSetup/advanced | | | sync_turn_on | | | 42 | Implemented | Turn chrome sync on for "Apps": chrome://settings/syncSetup/advanced | | -| switch_incognito_profile | | | 73 | Not Implemented | Switch to using incognito mode | P2 | +| switch_incognito_profile | | | 73 | Implemented | Switch to using incognito mode | P2 | | # File handling | | check_site_handles_file | Site, FileExtension | | 118 | Not Implemented | | | | check_site_not_handles_file | Site, FileExtension | | 122 | Not Implemented | | |
diff --git a/chrome/test/webapps/data/framework_supported_actions.csv b/chrome/test/webapps/data/framework_supported_actions.csv index a8ff3cd..445c492 100644 --- a/chrome/test/webapps/data/framework_supported_actions.csv +++ b/chrome/test/webapps/data/framework_supported_actions.csv
@@ -1,4 +1,5 @@ # Action base name, Mac,Win,Lin,Cros +check_app_in_list_icon_correct, 🌕, 🌕, 🌕, 🌕, check_app_in_list_not_locally_installed, 🌓, 🌓, 🌓, 🌓, check_app_in_list_tabbed, 🌓, 🌓, 🌓, 🌓, check_app_in_list_windowed, 🌓, 🌓, 🌓, 🌓, @@ -43,6 +44,7 @@ open_in_chrome, 🌕, 🌕, 🌕, 🌕, set_open_in_tab, 🌓, 🌓, 🌓, 🌓, set_open_in_window, 🌓, 🌓, 🌓, 🌓, +switch_incognito_profile, 🌕, 🌕, 🌕, 🌕, switch_profile_clients, 🌕, 🌕, 🌕, 🌕, sync_turn_off, 🌕, 🌕, 🌕, 🌕, sync_turn_on, 🌕, 🌕, 🌕, 🌕,
diff --git a/chrome/updater/app/app_install.cc b/chrome/updater/app/app_install.cc index dc8ba41..c51c24b 100644 --- a/chrome/updater/app/app_install.cc +++ b/chrome/updater/app/app_install.cc
@@ -66,8 +66,6 @@ void InstallAppOffline(const std::string& app_id, const std::string& app_name, - const base::FilePath& offline_dir, - bool enterprise, base::OnceCallback<void(int)> callback) override { base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(std::move(callback), 0)); @@ -115,7 +113,8 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(base::ThreadTaskRunnerHandle::IsSet()); - const TagParsingResult tag_parsing_result = GetTagArgs(); + const TagParsingResult tag_parsing_result = + GetTagArgsForCommandLine(GetCommandLineLegacyCompatible()); // A tag parsing error is handled as an fatal error. if (tag_parsing_result.error != tagging::ErrorCode::kSuccess) { @@ -280,11 +279,11 @@ const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess(); if (cmd_line->HasSwitch(kOfflineDirSwitch)) { // Presence of "offlinedir" in command line indicates this is an offline - // install. + // install. Note the check here is compatible with legacy command line + // because `base::CommandLine::HasSwitch()` recognizes switches that + // begin with '/' on Windows. app_install_controller_->InstallAppOffline( - app_id_, app_name_, cmd_line->GetSwitchValuePath(kOfflineDirSwitch), - cmd_line->HasSwitch(kEnterpriseSwitch), - base::BindOnce(&AppInstall::Shutdown, this)); + app_id_, app_name_, base::BindOnce(&AppInstall::Shutdown, this)); } else { app_install_controller_->InstallApp(
diff --git a/chrome/updater/app/app_install.h b/chrome/updater/app/app_install.h index f65c491..19f2307 100644 --- a/chrome/updater/app/app_install.h +++ b/chrome/updater/app/app_install.h
@@ -15,7 +15,6 @@ #include "chrome/updater/splash_screen.h" namespace base { -class FilePath; class Version; } @@ -39,8 +38,6 @@ virtual void InstallAppOffline(const std::string& app_id, const std::string& app_name, - const base::FilePath& offline_dir, - bool enterprise, base::OnceCallback<void(int)> callback) = 0; protected:
diff --git a/chrome/updater/test/integration_tests_impl.cc b/chrome/updater/test/integration_tests_impl.cc index a18a839..d94a14e3 100644 --- a/chrome/updater/test/integration_tests_impl.cc +++ b/chrome/updater/test/integration_tests_impl.cc
@@ -7,6 +7,7 @@ #include <cstdint> #include <cstdlib> #include <memory> +#include <set> #include <string> #include <utility> #include <vector> @@ -665,20 +666,20 @@ .is_null()); } -std::vector<base::FilePath::StringType> GetTestProcessNames() { +std::set<base::FilePath::StringType> GetTestProcessNames() { #if BUILDFLAG(IS_MAC) return { - GetExecutableRelativePath().value(), - GetSetupExecutablePath().value(), + GetExecutableRelativePath().BaseName().value(), + GetSetupExecutablePath().BaseName().value(), }; #elif BUILDFLAG(IS_WIN) return { - GetExecutableRelativePath().value(), - GetSetupExecutablePath().value(), + GetExecutableRelativePath().BaseName().value(), + GetSetupExecutablePath().BaseName().value(), kTestProcessExecutableName, []() { const base::FilePath test_executable = - base::FilePath::FromASCII(kExecutableName); + base::FilePath::FromASCII(kExecutableName).BaseName(); return base::StrCat({test_executable.RemoveExtension().value(), base::ASCIIToWide(kExecutableSuffix), test_executable.Extension()});
diff --git a/chrome/updater/test/integration_tests_impl.h b/chrome/updater/test/integration_tests_impl.h index a695872..bd0e054 100644 --- a/chrome/updater/test/integration_tests_impl.h +++ b/chrome/updater/test/integration_tests_impl.h
@@ -5,6 +5,7 @@ #ifndef CHROME_UPDATER_TEST_INTEGRATION_TESTS_IMPL_H_ #define CHROME_UPDATER_TEST_INTEGRATION_TESTS_IMPL_H_ +#include <set> #include <string> #include "base/callback_forward.h" @@ -39,7 +40,7 @@ base::FilePath GetSetupExecutablePath(); // Returns the names for processes which may be running during unit tests. -std::vector<base::FilePath::StringType> GetTestProcessNames(); +std::set<base::FilePath::StringType> GetTestProcessNames(); // Ensures test processes are not running after the function is called. void CleanProcesses();
diff --git a/chrome/updater/update_service_impl.cc b/chrome/updater/update_service_impl.cc index c82fd55c..9c3d888 100644 --- a/chrome/updater/update_service_impl.cc +++ b/chrome/updater/update_service_impl.cc
@@ -590,8 +590,9 @@ state_update.Run(state); VLOG(1) << app_id << " installation completed: " << result.error; - // TODO(crbug.com/1286574): Perform post-install actions, such as - // send pings (if `enterprise` is not set in install_settings). + // TODO(crbug.com/1286574, crbug.com/1286581): Perform post-install + // actions, such as send pings (if `enterprise` is not set in + // install_settings) with the given `sessionid`. std::move(callback).Run(result.error == 0 ? Result::kSuccess : Result::kInstallFailed);
diff --git a/chrome/updater/util.cc b/chrome/updater/util.cc index 404f9aad..8481ba3 100644 --- a/chrome/updater/util.cc +++ b/chrome/updater/util.cc
@@ -190,19 +190,14 @@ } TagParsingResult GetTagArgs() { -#if BUILDFLAG(IS_WIN) - TagParsingResult result = - GetTagArgsForCommandLine(*base::CommandLine::ForCurrentProcess()); - - return result.tag_args ? result - : GetTagArgsFromLegacyCommandLine(::GetCommandLine()); -#else return GetTagArgsForCommandLine(*base::CommandLine::ForCurrentProcess()); -#endif } -absl::optional<tagging::AppArgs> GetAppArgs(const std::string& app_id) { - const absl::optional<tagging::TagArgs> tag_args = GetTagArgs().tag_args; +absl::optional<tagging::AppArgs> GetAppArgsForCommandLine( + const base::CommandLine& command_line, + const std::string& app_id) { + const absl::optional<tagging::TagArgs> tag_args = + GetTagArgsForCommandLine(command_line).tag_args; if (!tag_args || tag_args->apps.empty()) return absl::nullopt; @@ -215,8 +210,16 @@ : absl::nullopt; } -std::string GetDecodedInstallDataFromAppArgs(const std::string& app_id) { - const absl::optional<tagging::AppArgs> app_args = GetAppArgs(app_id); +absl::optional<tagging::AppArgs> GetAppArgs(const std::string& app_id) { + return GetAppArgsForCommandLine(*base::CommandLine::ForCurrentProcess(), + app_id); +} + +std::string GetDecodedInstallDataFromAppArgsForCommandLine( + const base::CommandLine& command_line, + const std::string& app_id) { + const absl::optional<tagging::AppArgs> app_args = + GetAppArgsForCommandLine(command_line, app_id); if (!app_args) return std::string(); @@ -232,11 +235,24 @@ return decoded_installer_data; } -std::string GetInstallDataIndexFromAppArgs(const std::string& app_id) { - const absl::optional<tagging::AppArgs> app_args = GetAppArgs(app_id); +std::string GetDecodedInstallDataFromAppArgs(const std::string& app_id) { + return GetDecodedInstallDataFromAppArgsForCommandLine( + *base::CommandLine::ForCurrentProcess(), app_id); +} + +std::string GetInstallDataIndexFromAppArgsForCommandLine( + const base::CommandLine& command_line, + const std::string& app_id) { + const absl::optional<tagging::AppArgs> app_args = + GetAppArgsForCommandLine(command_line, app_id); return app_args ? app_args->install_data_index : std::string(); } +std::string GetInstallDataIndexFromAppArgs(const std::string& app_id) { + return GetInstallDataIndexFromAppArgsForCommandLine( + *base::CommandLine::ForCurrentProcess(), app_id); +} + base::CommandLine MakeElevated(base::CommandLine command_line) { #if BUILDFLAG(IS_MAC) command_line.PrependWrapper("/usr/bin/sudo"); @@ -316,6 +332,18 @@ kUpdaterVersionUtf16}); } +base::CommandLine GetCommandLineLegacyCompatible() { + absl::optional<base::CommandLine> cmd_line = + CommandLineForLegacyFormat(::GetCommandLine()); + return cmd_line ? *cmd_line : *base::CommandLine::ForCurrentProcess(); +} + +#else // BUILDFLAG(IS_WIN) + +base::CommandLine GetCommandLineLegacyCompatible() { + return *base::CommandLine::ForCurrentProcess(); +} + #endif // BUILDFLAG(IS_WIN) absl::optional<base::FilePath> WriteInstallerDataToTempFile(
diff --git a/chrome/updater/util.h b/chrome/updater/util.h index f131e91..444b7b4 100644 --- a/chrome/updater/util.h +++ b/chrome/updater/util.h
@@ -109,23 +109,25 @@ absl::optional<tagging::TagArgs> tag_args; tagging::ErrorCode error = tagging::ErrorCode::kSuccess; }; + TagParsingResult GetTagArgsForCommandLine( const base::CommandLine& command_line); - -#if BUILDFLAG(IS_WIN) -// Gets tag value from command line in legacy format. This is for handoff -// requests from legacy updaters. -// The function must take a raw command line string because `base::CommandLine` -// re-orders the switches and loses the positional information. -TagParsingResult GetTagArgsFromLegacyCommandLine(const std::wstring& cmd_line); -#endif - TagParsingResult GetTagArgs(); // Returns the arguments corresponding to `app_id` from the command line tag. +absl::optional<tagging::AppArgs> GetAppArgsForCommandLine( + const base::CommandLine& command_line, + const std::string& app_id); absl::optional<tagging::AppArgs> GetAppArgs(const std::string& app_id); +std::string GetDecodedInstallDataFromAppArgsForCommandLine( + const base::CommandLine& command_line, + const std::string& app_id); std::string GetDecodedInstallDataFromAppArgs(const std::string& app_id); + +std::string GetInstallDataIndexFromAppArgsForCommandLine( + const base::CommandLine& command_line, + const std::string& app_id); std::string GetInstallDataIndexFromAppArgs(const std::string& app_id); // Returns true if the user running the updater also owns the `path`. @@ -191,16 +193,19 @@ // For instance: "ChromiumUpdater Task System 92.0.0.1". std::wstring GetTaskDisplayName(UpdaterScope scope); -// Returns the value associated with the given switch when they are specified in -// the legacy updater command line format. Example: +// Parses the command line string in legacy format into `base::CommandLine`. +// The string must be in format like: // program.exe /switch1 value1 /switch2 /switch3 value3 -// The equivalent Chromium format is: -// program.exe --switch1=value1 --switch2 --switch3=value3 -std::string GetSwitchValueInLegacyFormat(const std::wstring& command_line, - const std::wstring& switch_name); +// Returns empty if a Chromium style switch is found. +absl::optional<base::CommandLine> CommandLineForLegacyFormat( + const std::wstring& cmd_string); #endif // BUILDFLAG(IS_WIN) +// Returns the command line for current process, either in legacy style, or +// in Chromium style. +base::CommandLine GetCommandLineLegacyCompatible(); + // Writes the provided string prefixed with the UTF8 byte order mark to a // temporary file. The temporary file is created in the specified `directory`. absl::optional<base::FilePath> WriteInstallerDataToTempFile(
diff --git a/chrome/updater/util_win.cc b/chrome/updater/util_win.cc index 8f74f4f5..5711348 100644 --- a/chrome/updater/util_win.cc +++ b/chrome/updater/util_win.cc
@@ -23,47 +23,51 @@ namespace updater { -std::string GetSwitchValueInLegacyFormat(const std::wstring& command_line, - const std::wstring& switch_name) { +absl::optional<base::CommandLine> CommandLineForLegacyFormat( + const std::wstring& cmd_string) { wchar_t** args = nullptr; int num_args = 0; - args = ::CommandLineToArgvW(command_line.c_str(), &num_args); + args = ::CommandLineToArgvW(cmd_string.c_str(), &num_args); - auto is_switch = [](const std::wstring& arg) { - return !arg.empty() && arg.at(0) == u'/'; + auto is_switch = [](const std::wstring& arg) { return arg[0] == L'-'; }; + + auto is_legacy_switch = [](const std::wstring& arg) { + return arg[0] == L'/'; }; - // For switch to have a value in legacy format, the switch name cannot be - // the last argument. - const int last_arg_to_check = num_args - 1; - for (int i = 0; i < last_arg_to_check; ++i) { - const std::wstring current_switch(args[i]); - if (base::EqualsCaseInsensitiveASCII(current_switch, - base::StrCat({L"/", switch_name})) && - !is_switch(args[i + 1])) { - return base::WideToASCII(args[i + 1]); + + // First argument is the program. + base::CommandLine command_line(base::FilePath{args[0]}); + + for (int i = 1; i < num_args; ++i) { + const std::wstring next_arg = i < num_args - 1 ? args[i + 1] : L""; + + if (is_switch(args[i]) || is_switch(next_arg)) { + // Won't parse Chromium-style command line. + return absl::nullopt; + } + + if (!is_legacy_switch(args[i])) { + // This is a bare argument. + command_line.AppendArg(base::WideToASCII(args[i])); + continue; + } + + const std::string switch_name = base::WideToASCII(&args[i][1]); + if (switch_name.empty()) { + VLOG(1) << "Empty switch in command line: [" << cmd_string << "]"; + return absl::nullopt; + } + + if (is_legacy_switch(next_arg) || next_arg.empty()) { + command_line.AppendSwitch(switch_name); + } else { + // Next argument is the value for this switch. + command_line.AppendSwitchNative(switch_name, next_arg); + ++i; } } - return std::string(); -} - -TagParsingResult GetTagArgsFromLegacyCommandLine( - const std::wstring& command_line) { - std::string tag = GetSwitchValueInLegacyFormat( - command_line, base::ASCIIToWide(kHandoffSwitch)); - - if (tag.empty()) - return {}; - - tagging::TagArgs tag_args; - const tagging::ErrorCode error = - tagging::Parse(tag, - GetSwitchValueInLegacyFormat( - command_line, base::ASCIIToWide(kAppArgsSwitch)), - &tag_args); - VLOG_IF(1, error != tagging::ErrorCode::kSuccess) - << "Legacy tag parsing returned " << error << "."; - return {tag_args, error}; + return command_line; } absl::optional<base::FilePath> GetBaseInstallDirectory(UpdaterScope scope) {
diff --git a/chrome/updater/util_win_unittest.cc b/chrome/updater/util_win_unittest.cc index ca6a31d..5ba7761 100644 --- a/chrome/updater/util_win_unittest.cc +++ b/chrome/updater/util_win_unittest.cc
@@ -5,33 +5,27 @@ #include "chrome/updater/util.h" #include <string> +#include <vector> #include "chrome/updater/tag.h" #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/abseil-cpp/absl/types/optional.h" namespace updater { -TEST(UtilTest, GetSwitchValueInLegacyFormat) { - const std::wstring command_line = - L"program.exe /handoff " - L"\"&appid={8a69}&appname=Google Chrome&needsadmin=true&lang=en\" " - L"/interactive /sessionid {123-456}"; - EXPECT_EQ(GetSwitchValueInLegacyFormat(command_line, L"handoff"), - "&appid={8a69}&appname=Google Chrome&needsadmin=true&lang=en"); - EXPECT_TRUE( - GetSwitchValueInLegacyFormat(command_line, L"interactive").empty()); - EXPECT_EQ(GetSwitchValueInLegacyFormat(command_line, L"sessionid"), - "{123-456}"); - EXPECT_TRUE( - GetSwitchValueInLegacyFormat(command_line, L"none_exist_switch").empty()); -} - -TEST(UtilTest, GetTagArgsFromLegacyCommandLine) { - TagParsingResult result = GetTagArgsFromLegacyCommandLine( +TEST(UtilTest, CommandLineForLegacyFormat) { + absl::optional<base::CommandLine> cmd_line = CommandLineForLegacyFormat( L"program.exe /handoff \"appguid={8a69}&appname=Chrome\" /appargs " L"\"&appguid={8a69}" L"&installerdata=%7B%22homepage%22%3A%22http%3A%2F%2Fwww.google.com%\" " L"/silent /sessionid {123-456}"); + + EXPECT_TRUE(cmd_line); + EXPECT_EQ(cmd_line->GetSwitchValueASCII("handoff"), + "appguid={8a69}&appname=Chrome"); + EXPECT_TRUE(cmd_line->HasSwitch("silent")); + EXPECT_EQ(cmd_line->GetSwitchValueASCII("sessionid"), "{123-456}"); + TagParsingResult result = GetTagArgsForCommandLine(*cmd_line); EXPECT_EQ(result.error, tagging::ErrorCode::kSuccess); EXPECT_EQ(result.tag_args->apps.size(), size_t{1}); EXPECT_EQ(result.tag_args->apps[0].app_id, "{8a69}"); @@ -40,4 +34,26 @@ "%7B%22homepage%22%3A%22http%3A%2F%2Fwww.google.com%"); } +TEST(UtilTest, CommandLineForLegacyFormat_Mixed) { + absl::optional<base::CommandLine> cmd_line = CommandLineForLegacyFormat( + L"program.exe --handoff \"appguid={8a69}&appname=Chrome\"" + L"/silent /sessionid {123-456}"); + + EXPECT_FALSE(cmd_line); +} + +TEST(UtilTest, CommandLineForLegacyFormat_WithArgs) { + absl::optional<base::CommandLine> cmd_line = CommandLineForLegacyFormat( + L"program.exe arg1 /SWITCH1 value1 \"arg2 with space\" /Switch2 /s3"); + + EXPECT_TRUE(cmd_line); + EXPECT_EQ(cmd_line->GetArgs(), + std::vector<std::wstring>({L"arg1", L"arg2 with space"})); + EXPECT_EQ(cmd_line->GetSwitchValueASCII("switch1"), "value1"); + EXPECT_TRUE(cmd_line->HasSwitch("switch2")); + EXPECT_TRUE(cmd_line->GetSwitchValueASCII("switch2").empty()); + EXPECT_TRUE(cmd_line->HasSwitch("s3")); + EXPECT_TRUE(cmd_line->GetSwitchValueASCII("s3").empty()); +} + } // namespace updater
diff --git a/chrome/updater/win/app_install_controller.cc b/chrome/updater/win/app_install_controller.cc index ab112d1..afb88220 100644 --- a/chrome/updater/win/app_install_controller.cc +++ b/chrome/updater/win/app_install_controller.cc
@@ -548,8 +548,6 @@ void InstallAppOffline(const std::string& app_id, const std::string& app_name, - const base::FilePath& offline_dir, - bool enterprise, base::OnceCallback<void(int)> callback) override; private: @@ -582,8 +580,7 @@ void DoInstallApp(); void DoInstallAppOffline(const base::FilePath& installer_path, const std::string& install_args, - const std::string& install_data, - bool enterprise); + const std::string& install_data); void InstallComplete(UpdateService::Result result); void HandleInstallResult(const UpdateService::UpdateState& update_state); @@ -696,8 +693,6 @@ void AppInstallControllerImpl::InstallAppOffline( const std::string& app_id, const std::string& app_name, - const base::FilePath& offline_dir, - bool enterprise, base::OnceCallback<void(int)> callback) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(base::ThreadTaskRunnerHandle::IsSet()); @@ -709,51 +704,52 @@ ui_task_runner_->PostTaskAndReply( FROM_HERE, base::BindOnce(&AppInstallControllerImpl::InitializeUI, this), base::BindOnce( - [](scoped_refptr<AppInstallControllerImpl> self, - const base::FilePath& offline_dir, bool enterprise) { + [](scoped_refptr<AppInstallControllerImpl> self) { base::ThreadPool::PostTaskAndReplyWithResult( FROM_HERE, {base::MayBlock()}, base::BindOnce( - [](const base::FilePath& offline_dir, - const std::string& app_id) { + [](const std::string& app_id) { + const base::CommandLine cmd_line = + GetCommandLineLegacyCompatible(); // Parse the offline manifest to get the install // command and install data. base::FilePath installer_path; std::string install_args; std::string install_data; ReadInstallCommandFromManifest( - offline_dir, app_id, - GetInstallDataIndexFromAppArgs(app_id), + cmd_line.GetSwitchValuePath(kOfflineDirSwitch), + app_id, + GetInstallDataIndexFromAppArgsForCommandLine(cmd_line, + app_id), installer_path, install_args, install_data); const std::string client_install_data = - GetDecodedInstallDataFromAppArgs(app_id); + GetDecodedInstallDataFromAppArgsForCommandLine( + cmd_line, app_id); return std::make_tuple(installer_path, install_args, client_install_data.empty() ? install_data : client_install_data); }, - offline_dir, self->app_id_), + self->app_id_), base::BindOnce( [](scoped_refptr<AppInstallControllerImpl> self, - bool enterprise, const std::tuple<base::FilePath /*installer_path*/, std::string /*arguments*/, std::string /*install_data*/>& result) { - self->DoInstallAppOffline( - std::get<0>(result), std::get<1>(result), - std::get<2>(result), enterprise); + self->DoInstallAppOffline(std::get<0>(result), + std::get<1>(result), + std::get<2>(result)); }, - self, enterprise)); + self)); }, - base::WrapRefCounted(this), offline_dir, enterprise)); + base::WrapRefCounted(this))); } void AppInstallControllerImpl::DoInstallAppOffline( const base::FilePath& installer_path, const std::string& install_args, - const std::string& install_data, - bool enterprise) { + const std::string& install_data) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // At this point, the UI has been initialized, which means the UI can be // used from now on as an observer of the application install. The task @@ -769,8 +765,12 @@ // TODO(crbug.com/1286581): fine-tune installation behavior by serializing // other related command line options, such as "/sessionid <sid>" into // `install_settings`. + base::CommandLine cmd_line = GetCommandLineLegacyCompatible(); base::Value::Dict install_settings_dict; - install_settings_dict.Set(kEnterpriseSwitch, enterprise); + install_settings_dict.Set(kEnterpriseSwitch, + cmd_line.HasSwitch(kEnterpriseSwitch)); + install_settings_dict.Set(kSessionIdSwitch, + cmd_line.GetSwitchValueASCII(kSessionIdSwitch)); std::string install_settings; if (!JSONStringValueSerializer(&install_settings) @@ -778,11 +778,13 @@ VLOG(1) << "Failed to serialize install settings."; } - absl::optional<tagging::TagArgs> tag_args = GetTagArgs().tag_args; + absl::optional<tagging::TagArgs> tag_args = + GetTagArgsForCommandLine(cmd_line).tag_args; RegistrationRequest request; request.app_id = app_id_; - absl::optional<tagging::AppArgs> app_args = GetAppArgs(app_id_); + absl::optional<tagging::AppArgs> app_args = + GetAppArgsForCommandLine(cmd_line, app_id_); if (app_args) request.ap = app_args->ap; if (tag_args)
diff --git a/chrome/updater/win/manifest_util.cc b/chrome/updater/win/manifest_util.cc index 360dea8..cf816f238 100644 --- a/chrome/updater/win/manifest_util.cc +++ b/chrome/updater/win/manifest_util.cc
@@ -80,6 +80,11 @@ base::FilePath& installer_path, std::string& install_args, std::string& install_data) { + if (offline_dir.empty()) { + VLOG(1) << "Unexpected: offline install without an offline directory."; + return; + } + std::unique_ptr<ProtocolParserXML> manifest_parser = ParseOfflineManifest(offline_dir, app_id); if (!manifest_parser) {
diff --git a/chrome/utility/services.cc b/chrome/utility/services.cc index b82daa0..9dfa783 100644 --- a/chrome/utility/services.cc +++ b/chrome/utility/services.cc
@@ -411,7 +411,7 @@ auto RunLibassistantService( mojo::PendingReceiver<chromeos::libassistant::mojom::LibassistantService> receiver) { - return std::make_unique<chromeos::libassistant::LibassistantService>( + return std::make_unique<ash::libassistant::LibassistantService>( std::move(receiver)); } #endif // BUILDFLAG(ENABLE_CROS_LIBASSISTANT)
diff --git a/chromeos/ash/components/dbus/userdataauth/fake_install_attributes_client.cc b/chromeos/ash/components/dbus/userdataauth/fake_install_attributes_client.cc index 3bc0bdc..b9dc3054 100644 --- a/chromeos/ash/components/dbus/userdataauth/fake_install_attributes_client.cc +++ b/chromeos/ash/components/dbus/userdataauth/fake_install_attributes_client.cc
@@ -56,11 +56,6 @@ InstallAttributesGetCallback callback) { NOTIMPLEMENTED(); } -void FakeInstallAttributesClient::InstallAttributesSet( - const ::user_data_auth::InstallAttributesSetRequest& request, - InstallAttributesSetCallback callback) { - NOTIMPLEMENTED(); -} void FakeInstallAttributesClient::InstallAttributesFinalize( const ::user_data_auth::InstallAttributesFinalizeRequest& request, InstallAttributesFinalizeCallback callback) {
diff --git a/chromeos/ash/components/dbus/userdataauth/fake_install_attributes_client.h b/chromeos/ash/components/dbus/userdataauth/fake_install_attributes_client.h index e67dcd4..6a7471ed 100644 --- a/chromeos/ash/components/dbus/userdataauth/fake_install_attributes_client.h +++ b/chromeos/ash/components/dbus/userdataauth/fake_install_attributes_client.h
@@ -33,9 +33,6 @@ void InstallAttributesGet( const ::user_data_auth::InstallAttributesGetRequest& request, InstallAttributesGetCallback callback) override; - void InstallAttributesSet( - const ::user_data_auth::InstallAttributesSetRequest& request, - InstallAttributesSetCallback callback) override; void InstallAttributesFinalize( const ::user_data_auth::InstallAttributesFinalizeRequest& request, InstallAttributesFinalizeCallback callback) override;
diff --git a/chromeos/ash/components/dbus/userdataauth/install_attributes_client.cc b/chromeos/ash/components/dbus/userdataauth/install_attributes_client.cc index 54a4e2da..e6cd2d6 100644 --- a/chromeos/ash/components/dbus/userdataauth/install_attributes_client.cc +++ b/chromeos/ash/components/dbus/userdataauth/install_attributes_client.cc
@@ -86,14 +86,6 @@ std::move(callback)); } - void InstallAttributesSet( - const ::user_data_auth::InstallAttributesSetRequest& request, - InstallAttributesSetCallback callback) override { - CallProtoMethod(::user_data_auth::kInstallAttributesSet, - ::user_data_auth::kInstallAttributesInterface, request, - std::move(callback)); - } - void InstallAttributesFinalize( const ::user_data_auth::InstallAttributesFinalizeRequest& request, InstallAttributesFinalizeCallback callback) override {
diff --git a/chromeos/ash/components/dbus/userdataauth/install_attributes_client.h b/chromeos/ash/components/dbus/userdataauth/install_attributes_client.h index 5153ae17..00757cb 100644 --- a/chromeos/ash/components/dbus/userdataauth/install_attributes_client.h +++ b/chromeos/ash/components/dbus/userdataauth/install_attributes_client.h
@@ -66,11 +66,6 @@ const ::user_data_auth::InstallAttributesGetRequest& request, InstallAttributesGetCallback callback) = 0; - // Set an install attribute. - virtual void InstallAttributesSet( - const ::user_data_auth::InstallAttributesSetRequest& request, - InstallAttributesSetCallback callback) = 0; - // Finalizes the install attribute. virtual void InstallAttributesFinalize( const ::user_data_auth::InstallAttributesFinalizeRequest& request,
diff --git a/chromeos/ash/components/dbus/userdataauth/install_attributes_client_unittest.cc b/chromeos/ash/components/dbus/userdataauth/install_attributes_client_unittest.cc index 094993ff..b310322 100644 --- a/chromeos/ash/components/dbus/userdataauth/install_attributes_client_unittest.cc +++ b/chromeos/ash/components/dbus/userdataauth/install_attributes_client_unittest.cc
@@ -180,9 +180,6 @@ ::user_data_auth::kInstallAttributesGet) { writer.AppendProtoAsArrayOfBytes(expected_install_attributes_get_reply_); } else if (method_call->GetMember() == - ::user_data_auth::kInstallAttributesSet) { - writer.AppendProtoAsArrayOfBytes(expected_install_attributes_set_reply_); - } else if (method_call->GetMember() == ::user_data_auth::kInstallAttributesFinalize) { writer.AppendProtoAsArrayOfBytes( expected_install_attributes_finalize_reply_); @@ -268,19 +265,6 @@ ASSERT_EQ(result_reply, absl::nullopt); } -TEST_F(InstallAttributesClientTest, InstallAttributesSet) { - expected_install_attributes_set_reply_.set_error( - user_data_auth::CryptohomeErrorCode::CRYPTOHOME_ERROR_TPM_DEFEND_LOCK); - absl::optional<::user_data_auth::InstallAttributesSetReply> result_reply; - - client_->InstallAttributesSet(::user_data_auth::InstallAttributesSetRequest(), - CreateCopyCallback(&result_reply)); - base::RunLoop().RunUntilIdle(); - ASSERT_NE(result_reply, absl::nullopt); - EXPECT_TRUE(ProtobufEquals(result_reply.value(), - expected_install_attributes_set_reply_)); -} - TEST_F(InstallAttributesClientTest, InstallAttributesFinalize) { expected_install_attributes_finalize_reply_.set_error( user_data_auth::CryptohomeErrorCode::CRYPTOHOME_ERROR_TPM_DEFEND_LOCK);
diff --git a/chromeos/ash/services/assistant/libassistant_service_host_impl.cc b/chromeos/ash/services/assistant/libassistant_service_host_impl.cc index 8309d87bc..8d913834 100644 --- a/chromeos/ash/services/assistant/libassistant_service_host_impl.cc +++ b/chromeos/ash/services/assistant/libassistant_service_host_impl.cc
@@ -35,9 +35,8 @@ std::move(receiver)); } else { DCHECK(!libassistant_service_); - libassistant_service_ = - std::make_unique<chromeos::libassistant::LibassistantService>( - std::move(receiver)); + libassistant_service_ = std::make_unique<libassistant::LibassistantService>( + std::move(receiver)); } }
diff --git a/chromeos/ash/services/assistant/libassistant_service_host_impl.h b/chromeos/ash/services/assistant/libassistant_service_host_impl.h index d00f89a..c02fde3 100644 --- a/chromeos/ash/services/assistant/libassistant_service_host_impl.h +++ b/chromeos/ash/services/assistant/libassistant_service_host_impl.h
@@ -12,13 +12,13 @@ #include "chromeos/ash/components/assistant/buildflags.h" #include "chromeos/ash/services/assistant/libassistant_service_host.h" -namespace chromeos { +namespace ash { + namespace libassistant { class LibassistantService; -} // namespace libassistant -} // namespace chromeos +} -namespace ash::assistant { +namespace assistant { // Host class controlling the lifetime of the Libassistant service. // The implementation will be stubbed out in the unbranded build. @@ -38,11 +38,12 @@ private: #if BUILDFLAG(ENABLE_CROS_LIBASSISTANT) SEQUENCE_CHECKER(sequence_checker_); - std::unique_ptr<chromeos::libassistant::LibassistantService> - libassistant_service_ GUARDED_BY_CONTEXT(sequence_checker_); + std::unique_ptr<libassistant::LibassistantService> libassistant_service_ + GUARDED_BY_CONTEXT(sequence_checker_); #endif }; -} // namespace ash::assistant +} // namespace assistant +} // namespace ash #endif // CHROMEOS_ASH_SERVICES_ASSISTANT_LIBASSISTANT_SERVICE_HOST_IMPL_H_
diff --git a/chromeos/ash/services/libassistant/abortable_task_list.cc b/chromeos/ash/services/libassistant/abortable_task_list.cc index 798eccf..372a11dd 100644 --- a/chromeos/ash/services/libassistant/abortable_task_list.cc +++ b/chromeos/ash/services/libassistant/abortable_task_list.cc
@@ -6,8 +6,7 @@ #include <algorithm> -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { AbortableTaskList::AbortableTaskList() = default; AbortableTaskList::~AbortableTaskList() { @@ -38,5 +37,4 @@ tasks_.end()); } -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant
diff --git a/chromeos/ash/services/libassistant/abortable_task_list.h b/chromeos/ash/services/libassistant/abortable_task_list.h index c69ddce..9296d31 100644 --- a/chromeos/ash/services/libassistant/abortable_task_list.h +++ b/chromeos/ash/services/libassistant/abortable_task_list.h
@@ -8,8 +8,7 @@ #include <memory> #include <vector> -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { class AbortableTask { public: @@ -49,7 +48,6 @@ std::vector<std::unique_ptr<AbortableTask>> tasks_; }; -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant #endif // CHROMEOS_ASH_SERVICES_LIBASSISTANT_ABORTABLE_TASK_LIST_H_
diff --git a/chromeos/ash/services/libassistant/audio_input_controller.cc b/chromeos/ash/services/libassistant/audio_input_controller.cc index 1246b0ce..d02d0c1 100644 --- a/chromeos/ash/services/libassistant/audio_input_controller.cc +++ b/chromeos/ash/services/libassistant/audio_input_controller.cc
@@ -6,8 +6,10 @@ #include "base/notreached.h" -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { + +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom = ::chromeos::libassistant::mojom; AudioInputController::AudioInputController() = default; @@ -63,5 +65,4 @@ return audio_input_provider().GetAudioInput(); } -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant
diff --git a/chromeos/ash/services/libassistant/audio_input_controller.h b/chromeos/ash/services/libassistant/audio_input_controller.h index a7b4790..9fe9a188 100644 --- a/chromeos/ash/services/libassistant/audio_input_controller.h +++ b/chromeos/ash/services/libassistant/audio_input_controller.h
@@ -12,13 +12,12 @@ #include "mojo/public/cpp/bindings/pending_remote.h" #include "mojo/public/cpp/bindings/receiver.h" -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { // Implementation of |mojom::AudioInputController| that will forward all calls // to a Libassistant V1 |assistant_client::AudioInputProvider| implementation. class COMPONENT_EXPORT(LIBASSISTANT_SERVICE) AudioInputController - : public mojom::AudioInputController { + : public chromeos::libassistant::mojom::AudioInputController { public: using Resolution = assistant_client::ConversationStateListener::Resolution; @@ -27,8 +26,9 @@ AudioInputController& operator=(AudioInputController&) = delete; ~AudioInputController() override; - void Bind(mojo::PendingReceiver<mojom::AudioInputController> receiver, - mojom::PlatformDelegate* platform_delegate); + void Bind(mojo::PendingReceiver< + chromeos::libassistant::mojom::AudioInputController> receiver, + chromeos::libassistant::mojom::PlatformDelegate* platform_delegate); // mojom::AudioInputController implementation: void SetMicOpen(bool mic_open) override; @@ -36,7 +36,7 @@ void SetDeviceId(const absl::optional<std::string>& device_id) override; void SetHotwordDeviceId( const absl::optional<std::string>& device_id) override; - void SetLidState(mojom::LidState new_state) override; + void SetLidState(chromeos::libassistant::mojom::LidState new_state) override; void OnConversationTurnStarted() override; // Invoked when the current conversation turn has finished. @@ -49,11 +49,11 @@ private: AudioInputImpl& audio_input(); - mojo::Receiver<mojom::AudioInputController> receiver_{this}; + mojo::Receiver<chromeos::libassistant::mojom::AudioInputController> receiver_{ + this}; AudioInputProviderImpl audio_input_provider_; }; -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant #endif // CHROMEOS_ASH_SERVICES_LIBASSISTANT_AUDIO_INPUT_CONTROLLER_H_
diff --git a/chromeos/ash/services/libassistant/audio_input_controller_unittest.cc b/chromeos/ash/services/libassistant/audio_input_controller_unittest.cc index 610e514..1922222 100644 --- a/chromeos/ash/services/libassistant/audio_input_controller_unittest.cc +++ b/chromeos/ash/services/libassistant/audio_input_controller_unittest.cc
@@ -24,13 +24,14 @@ #include "testing/gtest/include/gtest/gtest.h" #include "third_party/abseil-cpp/absl/types/optional.h" -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { namespace { -using mojom::LidState; +using ::chromeos::libassistant::mojom::LidState; using testing::_; using Resolution = assistant_client::ConversationStateListener::Resolution; +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom = ::chromeos::libassistant::mojom; constexpr char kNormalDeviceId[] = "normal-device-id"; constexpr char kHotwordDeviceId[] = "hotword-device-id"; @@ -592,5 +593,4 @@ EXPECT_EQ(GetOpenDeviceId(), kHotwordDeviceId); } -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant
diff --git a/chromeos/ash/services/libassistant/authentication_state_observer_unittest.cc b/chromeos/ash/services/libassistant/authentication_state_observer_unittest.cc index 3aadce3..c3701c93 100644 --- a/chromeos/ash/services/libassistant/authentication_state_observer_unittest.cc +++ b/chromeos/ash/services/libassistant/authentication_state_observer_unittest.cc
@@ -12,8 +12,10 @@ #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { + +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom = ::chromeos::libassistant::mojom; namespace { @@ -22,12 +24,12 @@ // enum that defines these, and we don't want to hard code this list in the // test. std::vector<int> GetAuthenticationErrorCodes() { - const int kMinErrorCode = assistant::GetLowestErrorCode(); - const int kMaxErrorCode = assistant::GetHighestErrorCode(); + const int kMinErrorCode = chromeos::assistant::GetLowestErrorCode(); + const int kMaxErrorCode = chromeos::assistant::GetHighestErrorCode(); std::vector<int> result; for (int code = kMinErrorCode; code <= kMaxErrorCode; ++code) { - if (assistant::IsAuthError(code)) + if (chromeos::assistant::IsAuthError(code)) result.push_back(code); } @@ -118,7 +120,7 @@ // check to ensure these are not authentication errors. for (int code : non_authentication_errors) - ASSERT_FALSE(assistant::IsAuthError(code)); + ASSERT_FALSE(chromeos::assistant::IsAuthError(code)); // Run the actual unittest for (int code : GetAuthenticationErrorCodes()) { @@ -131,5 +133,4 @@ } } -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant
diff --git a/chromeos/ash/services/libassistant/callback_utils.h b/chromeos/ash/services/libassistant/callback_utils.h index 3a2d4251..b586ff16 100644 --- a/chromeos/ash/services/libassistant/callback_utils.h +++ b/chromeos/ash/services/libassistant/callback_utils.h
@@ -12,8 +12,7 @@ #include "base/memory/scoped_refptr.h" #include "base/threading/sequenced_task_runner_handle.h" -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { namespace internal { @@ -163,12 +162,6 @@ return BindToCurrentSequenceRepeating(callback); } -} // namespace libassistant -} // namespace chromeos - -// TODO(https://crbug.com/1164001): remove when it moved to ash. -namespace ash::libassistant { -using ::chromeos::libassistant::ToStdFunction; -} +} // namespace ash::libassistant #endif // CHROMEOS_ASH_SERVICES_LIBASSISTANT_CALLBACK_UTILS_H_
diff --git a/chromeos/ash/services/libassistant/chromium_api_delegate.cc b/chromeos/ash/services/libassistant/chromium_api_delegate.cc index 413b92889..0f01968 100644 --- a/chromeos/ash/services/libassistant/chromium_api_delegate.cc +++ b/chromeos/ash/services/libassistant/chromium_api_delegate.cc
@@ -9,8 +9,7 @@ #include "base/task/single_thread_task_runner.h" #include "services/network/public/cpp/shared_url_loader_factory.h" -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { ChromiumApiDelegate::ChromiumApiDelegate( std::unique_ptr<network::PendingSharedURLLoaderFactory> @@ -24,5 +23,4 @@ return &http_connection_factory_; } -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant
diff --git a/chromeos/ash/services/libassistant/chromium_api_delegate.h b/chromeos/ash/services/libassistant/chromium_api_delegate.h index f218921..be3b9c8e 100644 --- a/chromeos/ash/services/libassistant/chromium_api_delegate.h +++ b/chromeos/ash/services/libassistant/chromium_api_delegate.h
@@ -14,8 +14,7 @@ class PendingSharedURLLoaderFactory; } // namespace network -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { class ChromiumHttpConnectionFactory; @@ -39,7 +38,6 @@ ChromiumHttpConnectionFactory http_connection_factory_; }; -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant #endif // CHROMEOS_ASH_SERVICES_LIBASSISTANT_CHROMIUM_API_DELEGATE_H_
diff --git a/chromeos/ash/services/libassistant/chromium_http_connection.cc b/chromeos/ash/services/libassistant/chromium_http_connection.cc index ae4fbcb..089cd55a 100644 --- a/chromeos/ash/services/libassistant/chromium_http_connection.cc +++ b/chromeos/ash/services/libassistant/chromium_http_connection.cc
@@ -32,8 +32,7 @@ return; \ } -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { namespace { @@ -412,5 +411,4 @@ return new ChromiumHttpConnection(url_loader_factory_->Clone(), delegate); } -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant
diff --git a/chromeos/ash/services/libassistant/chromium_http_connection.h b/chromeos/ash/services/libassistant/chromium_http_connection.h index 7a21a64..2a1fe5a 100644 --- a/chromeos/ash/services/libassistant/chromium_http_connection.h +++ b/chromeos/ash/services/libassistant/chromium_http_connection.h
@@ -27,8 +27,7 @@ class PendingSharedURLLoaderFactory; } // namespace network -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { // Implements libassistant's HttpConnection. class ChromiumHttpConnection @@ -151,7 +150,6 @@ scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_; }; -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant #endif // CHROMEOS_ASH_SERVICES_LIBASSISTANT_CHROMIUM_HTTP_CONNECTION_H_
diff --git a/chromeos/ash/services/libassistant/constants.cc b/chromeos/ash/services/libassistant/constants.cc index 4db2a55..f81c14f5 100644 --- a/chromeos/ash/services/libassistant/constants.cc +++ b/chromeos/ash/services/libassistant/constants.cc
@@ -13,8 +13,7 @@ #define LIBASSISTANT_V1_NAME "libassistant.so" #define LIBASSISTANT_V2_NAME "libassistant_v2.so" -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { #if BUILDFLAG(IS_CHROMEOS_DEVICE) const base::FilePath::CharType kAssistantBaseDirPath[] = @@ -42,5 +41,4 @@ FILE_PATH_LITERAL(LIBASSISTANT_V2_NAME); #endif -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant
diff --git a/chromeos/ash/services/libassistant/constants.h b/chromeos/ash/services/libassistant/constants.h index 2a6c8022..59bbf2e 100644 --- a/chromeos/ash/services/libassistant/constants.h +++ b/chromeos/ash/services/libassistant/constants.h
@@ -8,8 +8,7 @@ #include "base/component_export.h" #include "base/files/file_path.h" -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { // A directory to save Assistant config files. COMPONENT_EXPORT(LIBASSISTANT_CONSTANTS) @@ -27,7 +26,6 @@ COMPONENT_EXPORT(LIBASSISTANT_CONSTANTS) extern const base::FilePath::CharType kLibAssistantV2DlcPath[]; -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant #endif // CHROMEOS_ASH_SERVICES_LIBASSISTANT_CONSTANTS_H_
diff --git a/chromeos/ash/services/libassistant/conversation_controller.cc b/chromeos/ash/services/libassistant/conversation_controller.cc index 7ae8334..6c650e5 100644 --- a/chromeos/ash/services/libassistant/conversation_controller.cc +++ b/chromeos/ash/services/libassistant/conversation_controller.cc
@@ -22,12 +22,13 @@ #include "mojo/public/cpp/bindings/pending_receiver.h" #include "ui/base/l10n/l10n_util.h" -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { using assistant::AssistantInteractionMetadata; using assistant::AssistantInteractionType; using assistant::AssistantQuerySource; +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom = ::chromeos::libassistant::mojom; namespace { @@ -45,7 +46,7 @@ // Helper function to convert |action::Suggestion| to |AssistantSuggestion|. std::vector<assistant::AssistantSuggestion> ToAssistantSuggestion( - const std::vector<assistant::action::Suggestion>& suggestions) { + const std::vector<chromeos::assistant::action::Suggestion>& suggestions) { std::vector<assistant::AssistantSuggestion> result; for (const auto& suggestion : suggestions) { assistant::AssistantSuggestion assistant_suggestion; @@ -61,7 +62,7 @@ // Helper function to convert |action::Notification| to |AssistantNotification|. chromeos::assistant::AssistantNotification ToAssistantNotification( - const assistant::action::Notification& notification) { + const chromeos::assistant::action::Notification& notification) { chromeos::assistant::AssistantNotification assistant_notification; assistant_notification.title = notification.title; assistant_notification.message = notification.text; @@ -201,9 +202,10 @@ ConversationController::ConversationController() : receiver_(this), events_observer_(std::make_unique<GrpcEventsObserver>(this)), - action_module_(std::make_unique<assistant::action::CrosActionModule>( - assistant::features::IsAppSupportEnabled(), - assistant::features::IsWaitSchedulingEnabled())), + action_module_( + std::make_unique<chromeos::assistant::action::CrosActionModule>( + assistant::features::IsAppSupportEnabled(), + assistant::features::IsWaitSchedulingEnabled())), mojom_task_runner_(base::SequencedTaskRunnerHandle::Get()) { action_module_->AddObserver(this); } @@ -483,7 +485,7 @@ // Called from Libassistant thread. void ConversationController::OnShowSuggestions( - const std::vector<assistant::action::Suggestion>& suggestions) { + const std::vector<chromeos::assistant::action::Suggestion>& suggestions) { ENSURE_MOJOM_THREAD(&ConversationController::OnShowSuggestions, suggestions); for (auto& observer : observers_) @@ -552,7 +554,7 @@ // Called from Libassistant thread. void ConversationController::OnShowNotification( - const assistant::action::Notification& notification) { + const chromeos::assistant::action::Notification& notification) { ENSURE_MOJOM_THREAD(&ConversationController::OnShowNotification, notification); @@ -580,5 +582,4 @@ stop_interaction_closure_->callback().Run(); } -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant
diff --git a/chromeos/ash/services/libassistant/conversation_controller.h b/chromeos/ash/services/libassistant/conversation_controller.h index 59357e0..3b72ab66 100644 --- a/chromeos/ash/services/libassistant/conversation_controller.h +++ b/chromeos/ash/services/libassistant/conversation_controller.h
@@ -11,8 +11,6 @@ #include "base/component_export.h" #include "base/sequence_checker.h" #include "chromeos/ash/services/assistant/public/cpp/conversation_observer.h" -// TODO(https://crbug.com/1164001): move to forward declaration -#include "chromeos/ash/services/libassistant/grpc/assistant_client.h" #include "chromeos/ash/services/libassistant/grpc/assistant_client_observer.h" #include "chromeos/ash/services/libassistant/public/cpp/assistant_notification.h" #include "chromeos/ash/services/libassistant/public/mojom/authentication_state_observer.mojom.h" @@ -23,17 +21,18 @@ #include "mojo/public/cpp/bindings/receiver.h" #include "mojo/public/cpp/bindings/remote_set.h" -namespace chromeos { -namespace assistant { -namespace action { +namespace chromeos::assistant::action { class CrosActionModule; -} // namespace action -} // namespace assistant +} + +namespace ash { + +class AssistantClient; namespace libassistant { class COMPONENT_EXPORT(LIBASSISTANT_SERVICE) ConversationController - : public mojom::ConversationController, + : public chromeos::libassistant::mojom::ConversationController, public AssistantClientObserver, public chromeos::assistant::action::AssistantActionObserver, public chromeos::assistant::ConversationObserver { @@ -48,8 +47,10 @@ ~ConversationController() override; void Bind( - mojo::PendingReceiver<mojom::ConversationController> receiver, - mojo::PendingRemote<mojom::NotificationDelegate> notification_delegate); + mojo::PendingReceiver< + chromeos::libassistant::mojom::ConversationController> receiver, + mojo::PendingRemote<chromeos::libassistant::mojom::NotificationDelegate> + notification_delegate); void AddActionObserver( chromeos::assistant::action::AssistantActionObserver* observer); @@ -77,7 +78,8 @@ void DismissNotification(AssistantNotification notification) override; void SendAssistantFeedback(const AssistantFeedback& feedback) override; void AddRemoteObserver( - mojo::PendingRemote<mojom::ConversationObserver> observer) override; + mojo::PendingRemote<chromeos::libassistant::mojom::ConversationObserver> + observer) override; // chromeos::assistant::action::AssistantActionObserver: void OnShowHtml(const std::string& html_content, @@ -85,14 +87,15 @@ void OnShowText(const std::string& text) override; void OnShowContextualQueryFallback() override; void OnShowSuggestions( - const std::vector<assistant::action::Suggestion>& suggestions) override; + const std::vector<chromeos::assistant::action::Suggestion>& suggestions) + override; void OnOpenUrl(const std::string& url, bool in_background) override; void OnOpenAndroidApp( const chromeos::assistant::AndroidAppInfo& app_info, const chromeos::assistant::InteractionInfo& interaction) override; void OnScheduleWait(int id, int time_ms) override; void OnShowNotification( - const assistant::action::Notification& notification) override; + const chromeos::assistant::action::Notification& notification) override; // chromeos::assistant::ConversationObserver: void OnInteractionStarted( @@ -101,11 +104,12 @@ void OnInteractionFinished( chromeos::assistant::AssistantInteractionResolution resolution) override; - const mojo::RemoteSet<mojom::ConversationObserver>* conversation_observers() { + const mojo::RemoteSet<chromeos::libassistant::mojom::ConversationObserver>* + conversation_observers() { return &observers_; } - assistant::action::CrosActionModule* action_module() { + chromeos::assistant::action::CrosActionModule* action_module() { return action_module_.get(); } @@ -114,11 +118,14 @@ void MaybeStopPreviousInteraction(); - mojo::Receiver<mojom::ConversationController> receiver_; - mojo::RemoteSet<mojom::ConversationObserver> observers_; - mojo::RemoteSet<mojom::AuthenticationStateObserver> + mojo::Receiver<chromeos::libassistant::mojom::ConversationController> + receiver_; + mojo::RemoteSet<chromeos::libassistant::mojom::ConversationObserver> + observers_; + mojo::RemoteSet<chromeos::libassistant::mojom::AuthenticationStateObserver> authentication_state_observers_; - mojo::Remote<mojom::NotificationDelegate> notification_delegate_; + mojo::Remote<chromeos::libassistant::mojom::NotificationDelegate> + notification_delegate_; // Owned by ServiceController. // Set in `OnAssistantClientCreated()` and unset in @@ -130,7 +137,7 @@ bool requests_are_allowed_ = false; std::unique_ptr<GrpcEventsObserver> events_observer_; - std::unique_ptr<assistant::action::CrosActionModule> action_module_; + std::unique_ptr<chromeos::assistant::action::CrosActionModule> action_module_; std::unique_ptr<base::CancelableOnceClosure> stop_interaction_closure_; base::TimeDelta stop_interaction_delay_ = base::Milliseconds(500); @@ -140,6 +147,6 @@ }; } // namespace libassistant -} // namespace chromeos +} // namespace ash #endif // CHROMEOS_ASH_SERVICES_LIBASSISTANT_CONVERSATION_CONTROLLER_H_
diff --git a/chromeos/ash/services/libassistant/conversation_controller_unittest.cc b/chromeos/ash/services/libassistant/conversation_controller_unittest.cc index 05af46f..9659b73 100644 --- a/chromeos/ash/services/libassistant/conversation_controller_unittest.cc +++ b/chromeos/ash/services/libassistant/conversation_controller_unittest.cc
@@ -10,16 +10,16 @@ #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { namespace { class AssistantClientMock : public FakeAssistantClient { public: - AssistantClientMock( - std::unique_ptr<assistant::FakeAssistantManager> assistant_manager, - assistant::FakeAssistantManagerInternal* assistant_manager_internal) + AssistantClientMock(std::unique_ptr<chromeos::assistant::FakeAssistantManager> + assistant_manager, + chromeos::assistant::FakeAssistantManagerInternal* + assistant_manager_internal) : FakeAssistantClient(std::move(assistant_manager), assistant_manager_internal) {} ~AssistantClientMock() override = default; @@ -112,5 +112,4 @@ controller().StartEditReminderInteraction("client-id"); } -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant
diff --git a/chromeos/ash/services/libassistant/conversation_observer_unittest.cc b/chromeos/ash/services/libassistant/conversation_observer_unittest.cc index baa3df2..9d64820 100644 --- a/chromeos/ash/services/libassistant/conversation_observer_unittest.cc +++ b/chromeos/ash/services/libassistant/conversation_observer_unittest.cc
@@ -17,8 +17,10 @@ #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { + +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom = ::chromeos::libassistant::mojom; namespace { @@ -26,7 +28,7 @@ class CrosActionModuleHelper { public: explicit CrosActionModuleHelper( - assistant::action::CrosActionModule* action_module) + chromeos::assistant::action::CrosActionModule* action_module) : action_module_(*action_module) {} CrosActionModuleHelper(const CrosActionModuleHelper&) = delete; CrosActionModuleHelper& operator=(const CrosActionModuleHelper&) = delete; @@ -43,7 +45,7 @@ } void ShowSuggestions( - const std::vector<assistant::action::Suggestion>& suggestions) { + const std::vector<chromeos::assistant::action::Suggestion>& suggestions) { for (auto* observer : action_observers()) observer->OnShowSuggestions(suggestions); } @@ -54,7 +56,7 @@ } void OpenAndroidApp(const assistant::AndroidAppInfo& app_info) { - assistant::InteractionInfo info{}; + chromeos::assistant::InteractionInfo info{}; for (auto* observer : action_observers()) observer->OnOpenAndroidApp(app_info, info); } @@ -65,12 +67,12 @@ } private: - const std::vector<assistant::action::AssistantActionObserver*>& + const std::vector<chromeos::assistant::action::AssistantActionObserver*>& action_observers() { return action_module_.GetActionObserversForTesting(); } - const assistant::action::CrosActionModule& action_module_; + const chromeos::assistant::action::CrosActionModule& action_module_; }; class ConversationObserverMock : public mojom::ConversationObserver { @@ -132,7 +134,7 @@ controller().OnAssistantClientRunning(&service_tester_.assistant_client()); action_module_helper_ = std::make_unique<CrosActionModuleHelper>( - static_cast<assistant::action::CrosActionModule*>( + static_cast<chromeos::assistant::action::CrosActionModule*>( service_tester_.assistant_manager_internal().action_module())); } @@ -218,7 +220,7 @@ const std::string fake_text = "text"; const std::string fake_icon_url = "https://icon-url/"; const std::string fake_action_url = "https://action-url/"; - std::vector<assistant::action::Suggestion> fake_suggestions{ + std::vector<chromeos::assistant::action::Suggestion> fake_suggestions{ {fake_text, fake_icon_url, fake_action_url}}; EXPECT_CALL(observer_mock(), OnSuggestionsResponse) @@ -271,5 +273,4 @@ observer_mock().FlushForTesting(); } -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant
diff --git a/chromeos/ash/services/libassistant/conversation_state_listener_impl.cc b/chromeos/ash/services/libassistant/conversation_state_listener_impl.cc index 69c50a9..5c45b71 100644 --- a/chromeos/ash/services/libassistant/conversation_state_listener_impl.cc +++ b/chromeos/ash/services/libassistant/conversation_state_listener_impl.cc
@@ -11,8 +11,10 @@ #include "chromeos/ash/services/libassistant/public/mojom/speech_recognition_observer.mojom.h" #include "chromeos/assistant/internal/libassistant/shared_headers.h" -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { + +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom = ::chromeos::libassistant::mojom; namespace { @@ -140,5 +142,4 @@ observer->OnInteractionFinished(resolution); } -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant
diff --git a/chromeos/ash/services/libassistant/conversation_state_listener_impl.h b/chromeos/ash/services/libassistant/conversation_state_listener_impl.h index 89e6e9eb..870dbbe 100644 --- a/chromeos/ash/services/libassistant/conversation_state_listener_impl.h +++ b/chromeos/ash/services/libassistant/conversation_state_listener_impl.h
@@ -21,8 +21,7 @@ } // namespace libassistant } // namespace chromeos -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { class AudioInputController; @@ -31,9 +30,10 @@ public AssistantClientObserver { public: ConversationStateListenerImpl( - mojo::RemoteSet<mojom::SpeechRecognitionObserver>* + mojo::RemoteSet<chromeos::libassistant::mojom::SpeechRecognitionObserver>* speech_recognition_observers, - const mojo::RemoteSet<mojom::ConversationObserver>* + const mojo::RemoteSet< + chromeos::libassistant::mojom::ConversationObserver>* conversation_observers, AudioInputController* audio_input_controller); ConversationStateListenerImpl(const ConversationStateListenerImpl&) = delete; @@ -58,11 +58,12 @@ assistant::AssistantInteractionResolution resolution); // Owned by |LibassistantService|. - mojo::RemoteSet<mojom::SpeechRecognitionObserver>& + mojo::RemoteSet<chromeos::libassistant::mojom::SpeechRecognitionObserver>& speech_recognition_observers_; // Owned by |ConversationController|. - const mojo::RemoteSet<mojom::ConversationObserver>& conversation_observers_; + const mojo::RemoteSet<chromeos::libassistant::mojom::ConversationObserver>& + conversation_observers_; AudioInputController* const audio_input_controller_ = nullptr; @@ -75,7 +76,6 @@ base::WeakPtrFactory<ConversationStateListenerImpl> weak_factory_{this}; }; -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant #endif // CHROMEOS_ASH_SERVICES_LIBASSISTANT_CONVERSATION_STATE_LISTENER_IMPL_H_
diff --git a/chromeos/ash/services/libassistant/device_settings_controller.cc b/chromeos/ash/services/libassistant/device_settings_controller.cc index 7d43d528..186afe3 100644 --- a/chromeos/ash/services/libassistant/device_settings_controller.cc +++ b/chromeos/ash/services/libassistant/device_settings_controller.cc
@@ -23,8 +23,10 @@ using chromeos::libassistant::mojom::DeviceSettingsDelegate; using chromeos::libassistant::mojom::GetBrightnessResultPtr; -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { + +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom = ::chromeos::libassistant::mojom; namespace { // A macro which ensures we are running on the main thread. @@ -313,12 +315,11 @@ return; } - std::vector<assistant::DeviceSetting> result = + std::vector<chromeos::assistant::DeviceSetting> result = GetSupportedDeviceSettings(args); - auto interaction_proto = - chromeos::libassistant::CreateGetDeviceSettingInteraction(interaction_id, - result); + auto interaction_proto = ash::libassistant::CreateGetDeviceSettingInteraction( + interaction_id, result); ::assistant::api::VoicelessOptions options; options.set_is_user_initiated(true); @@ -356,5 +357,4 @@ settings_.push_back(std::move(setting)); } -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant
diff --git a/chromeos/ash/services/libassistant/device_settings_controller.h b/chromeos/ash/services/libassistant/device_settings_controller.h index 892523e..8a9d88ae 100644 --- a/chromeos/ash/services/libassistant/device_settings_controller.h +++ b/chromeos/ash/services/libassistant/device_settings_controller.h
@@ -12,8 +12,6 @@ #include "base/component_export.h" #include "base/memory/weak_ptr.h" #include "base/task/sequenced_task_runner.h" -// TODO(https://crbug.com/1164001): move to forward declaration -#include "chromeos/ash/services/libassistant/grpc/assistant_client.h" #include "chromeos/ash/services/libassistant/grpc/assistant_client_observer.h" #include "chromeos/ash/services/libassistant/public/mojom/device_settings_delegate.mojom.h" #include "chromeos/assistant/internal/action/assistant_action_observer.h" @@ -35,9 +33,9 @@ } // namespace assistant } // namespace chromeos -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { +class AssistantClient; class Setting; class DeviceSettingsController @@ -49,7 +47,9 @@ DeviceSettingsController& operator=(DeviceSettingsController&) = delete; ~DeviceSettingsController() override; - void Bind(mojo::PendingRemote<mojom::DeviceSettingsDelegate> delegate); + void Bind( + mojo::PendingRemote<chromeos::libassistant::mojom::DeviceSettingsDelegate> + delegate); // chromeos::assistant::action::AssistantActionObserver implementation: void OnModifyDeviceSetting( @@ -74,12 +74,11 @@ std::vector<std::unique_ptr<Setting>> settings_; AssistantClient* assistant_client_ = nullptr; - mojo::Remote<mojom::DeviceSettingsDelegate> remote_; + mojo::Remote<chromeos::libassistant::mojom::DeviceSettingsDelegate> remote_; scoped_refptr<base::SequencedTaskRunner> mojom_task_runner_; base::WeakPtrFactory<DeviceSettingsController> weak_factory_{this}; }; -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant #endif // CHROMEOS_ASH_SERVICES_LIBASSISTANT_DEVICE_SETTINGS_CONTROLLER_H_
diff --git a/chromeos/ash/services/libassistant/device_settings_controller_unittest.cc b/chromeos/ash/services/libassistant/device_settings_controller_unittest.cc index db6b031..23889aa 100644 --- a/chromeos/ash/services/libassistant/device_settings_controller_unittest.cc +++ b/chromeos/ash/services/libassistant/device_settings_controller_unittest.cc
@@ -35,8 +35,7 @@ } // namespace assistant } // namespace chromeos -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { namespace { @@ -53,6 +52,8 @@ using ::testing::FloatNear; using ::testing::Return; using ::testing::StrictMock; +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom = ::chromeos::libassistant::mojom; constexpr char kWiFi[] = "WIFI"; constexpr char kBluetooth[] = "BLUETOOTH"; @@ -279,5 +280,4 @@ ModifySetting(args); } -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant
diff --git a/chromeos/ash/services/libassistant/display_connection.cc b/chromeos/ash/services/libassistant/display_connection.cc index 2e4e855..e972c64 100644 --- a/chromeos/ash/services/libassistant/display_connection.cc +++ b/chromeos/ash/services/libassistant/display_connection.cc
@@ -12,8 +12,7 @@ #include "chromeos/ash/services/libassistant/grpc/assistant_client.h" #include "chromeos/assistant/internal/proto/shared/proto/v2/display_interface.pb.h" -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { DisplayConnection::DisplayConnection(DisplayConnectionObserver* observer, bool feedback_ui_enabled) @@ -143,5 +142,4 @@ MEDIA_SESSION_DETECTION_DISABLED_SCREEN_CONTEXT); } -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant
diff --git a/chromeos/ash/services/libassistant/display_connection.h b/chromeos/ash/services/libassistant/display_connection.h index 43502ef..e4a656b9 100644 --- a/chromeos/ash/services/libassistant/display_connection.h +++ b/chromeos/ash/services/libassistant/display_connection.h
@@ -8,16 +8,15 @@ #include <string> #include "base/task/sequenced_task_runner.h" -// TODO(https://crbug.com/1164001): move to forward declaration -#include "chromeos/ash/services/libassistant/grpc/assistant_client.h" #include "chromeos/ash/services/libassistant/grpc/external_services/grpc_services_observer.h" #include "chromeos/ash/services/libassistant/public/cpp/android_app_info.h" #include "chromeos/assistant/internal/libassistant/shared_headers.h" #include "chromeos/assistant/internal/proto/assistant/display_connection.pb.h" #include "chromeos/assistant/internal/proto/shared/proto/v2/delegate/event_handler_interface.pb.h" -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { + +class AssistantClient; class DisplayConnectionObserver { public: @@ -81,7 +80,6 @@ scoped_refptr<base::SequencedTaskRunner> task_runner_; }; -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant #endif // CHROMEOS_ASH_SERVICES_LIBASSISTANT_DISPLAY_CONNECTION_H_
diff --git a/chromeos/ash/services/libassistant/display_controller.cc b/chromeos/ash/services/libassistant/display_controller.cc index a319faf..d8461f3 100644 --- a/chromeos/ash/services/libassistant/display_controller.cc +++ b/chromeos/ash/services/libassistant/display_controller.cc
@@ -16,8 +16,10 @@ #include "chromeos/assistant/internal/libassistant/shared_headers.h" #include "chromeos/assistant/internal/proto/shared/proto/v2/internal_options.pb.h" -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { + +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom = ::chromeos::libassistant::mojom; namespace { // A macro which ensures we are running on the main thread. @@ -123,7 +125,7 @@ } auto interaction_proto = - chromeos::libassistant::CreateVerifyProviderResponseInteraction( + ash::libassistant::CreateVerifyProviderResponseInteraction( interaction.interaction_id, result_apps_info); ::assistant::api::VoicelessOptions options; @@ -152,5 +154,4 @@ return assistant::AppStatus::kUnavailable; } -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant
diff --git a/chromeos/ash/services/libassistant/display_controller.h b/chromeos/ash/services/libassistant/display_controller.h index 62b404b9..dc154cf 100644 --- a/chromeos/ash/services/libassistant/display_controller.h +++ b/chromeos/ash/services/libassistant/display_controller.h
@@ -28,23 +28,25 @@ } // namespace assistant } // namespace chromeos -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { class DisplayConnection; class DisplayController - : public mojom::DisplayController, + : public chromeos::libassistant::mojom::DisplayController, public AssistantClientObserver, public chromeos::assistant::action::AssistantActionObserver { public: - explicit DisplayController(mojo::RemoteSet<mojom::SpeechRecognitionObserver>* - speech_recognition_observers); + explicit DisplayController( + mojo::RemoteSet<chromeos::libassistant::mojom::SpeechRecognitionObserver>* + speech_recognition_observers); DisplayController(const DisplayController&) = delete; DisplayController& operator=(const DisplayController&) = delete; ~DisplayController() override; - void Bind(mojo::PendingReceiver<mojom::DisplayController> receiver); + void Bind( + mojo::PendingReceiver<chromeos::libassistant::mojom::DisplayController> + receiver); void SetActionModule( chromeos::assistant::action::CrosActionModule* action_module); @@ -73,12 +75,13 @@ chromeos::assistant::AppStatus GetAndroidAppStatus( const std::string& package_name); - mojo::Receiver<mojom::DisplayController> receiver_{this}; + mojo::Receiver<chromeos::libassistant::mojom::DisplayController> receiver_{ + this}; std::unique_ptr<EventObserver> event_observer_; std::unique_ptr<DisplayConnection> display_connection_; // Owned by |LibassistantService|. - mojo::RemoteSet<mojom::SpeechRecognitionObserver>& + mojo::RemoteSet<chromeos::libassistant::mojom::SpeechRecognitionObserver>& speech_recognition_observers_; AssistantClient* assistant_client_ = nullptr; @@ -95,7 +98,6 @@ base::WeakPtrFactory<DisplayController> weak_factory_{this}; }; -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant #endif // CHROMEOS_ASH_SERVICES_LIBASSISTANT_DISPLAY_CONTROLLER_H_
diff --git a/chromeos/ash/services/libassistant/display_controller_unittest.cc b/chromeos/ash/services/libassistant/display_controller_unittest.cc index e39aee3b..970256a 100644 --- a/chromeos/ash/services/libassistant/display_controller_unittest.cc +++ b/chromeos/ash/services/libassistant/display_controller_unittest.cc
@@ -12,13 +12,14 @@ #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { namespace { using chromeos::assistant::AndroidAppInfo; using chromeos::assistant::InteractionInfo; +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom = ::chromeos::libassistant::mojom; constexpr int kSampleInteractionId = 123; constexpr char kSampleUserId[] = "user-id"; @@ -26,9 +27,10 @@ class AssistantClientMock : public FakeAssistantClient { public: - AssistantClientMock( - std::unique_ptr<assistant::FakeAssistantManager> assistant_manager, - assistant::FakeAssistantManagerInternal* assistant_manager_internal) + AssistantClientMock(std::unique_ptr<chromeos::assistant::FakeAssistantManager> + assistant_manager, + chromeos::assistant::FakeAssistantManagerInternal* + assistant_manager_internal) : FakeAssistantClient(std::move(assistant_manager), assistant_manager_internal) {} ~AssistantClientMock() override = default; @@ -96,5 +98,4 @@ controller()->OnVerifyAndroidApp({app_info}, interaction); } -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant
diff --git a/chromeos/ash/services/libassistant/fake_auth_provider.cc b/chromeos/ash/services/libassistant/fake_auth_provider.cc index f3190b7..8fa3a78 100644 --- a/chromeos/ash/services/libassistant/fake_auth_provider.cc +++ b/chromeos/ash/services/libassistant/fake_auth_provider.cc
@@ -4,8 +4,7 @@ #include "chromeos/ash/services/libassistant/fake_auth_provider.h" -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { std::string FakeAuthProvider::GetAuthClientId() { return "kFakeClientId"; @@ -43,5 +42,4 @@ void FakeAuthProvider::Reset() {} -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant
diff --git a/chromeos/ash/services/libassistant/fake_auth_provider.h b/chromeos/ash/services/libassistant/fake_auth_provider.h index ccb4fcc..cc3c466 100644 --- a/chromeos/ash/services/libassistant/fake_auth_provider.h +++ b/chromeos/ash/services/libassistant/fake_auth_provider.h
@@ -10,8 +10,7 @@ #include <string> #include <vector> -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { // ChromeOS does not use auth manager, so we don't yet need to implement a // real auth provider. @@ -45,7 +44,6 @@ void Reset() override; }; -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant #endif // CHROMEOS_ASH_SERVICES_LIBASSISTANT_FAKE_AUTH_PROVIDER_H_
diff --git a/chromeos/ash/services/libassistant/file_provider_impl.cc b/chromeos/ash/services/libassistant/file_provider_impl.cc index 74fe5731..5e611b47 100644 --- a/chromeos/ash/services/libassistant/file_provider_impl.cc +++ b/chromeos/ash/services/libassistant/file_provider_impl.cc
@@ -9,8 +9,7 @@ #include "chromeos/ash/services/libassistant/util.h" #include "ui/base/resource/resource_bundle.h" -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { namespace { constexpr int kReadFileSizeLimitInBytes = 10 * 1024 * 1024; @@ -98,5 +97,4 @@ return true; } -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant
diff --git a/chromeos/ash/services/libassistant/file_provider_impl.h b/chromeos/ash/services/libassistant/file_provider_impl.h index cb8881df..90ee747 100644 --- a/chromeos/ash/services/libassistant/file_provider_impl.h +++ b/chromeos/ash/services/libassistant/file_provider_impl.h
@@ -10,8 +10,7 @@ #include "base/files/file_path.h" #include "chromeos/assistant/internal/libassistant/shared_headers.h" -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { class FileProviderImpl : public assistant_client::FileProvider { public: @@ -36,7 +35,6 @@ const base::FilePath root_path_; }; -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant #endif // CHROMEOS_ASH_SERVICES_LIBASSISTANT_FILE_PROVIDER_IMPL_H_
diff --git a/chromeos/ash/services/libassistant/grpc/assistant_client_v1.cc b/chromeos/ash/services/libassistant/grpc/assistant_client_v1.cc index ca0efb7..09120b1 100644 --- a/chromeos/ash/services/libassistant/grpc/assistant_client_v1.cc +++ b/chromeos/ash/services/libassistant/grpc/assistant_client_v1.cc
@@ -45,13 +45,6 @@ using ::assistant::api::events::SpeakerIdEnrollmentEvent; using ::assistant::ui::SettingsUiUpdate; using assistant_client::SpeakerIdEnrollmentUpdate; -using ::chromeos::libassistant::AdaptCallback; -using ::chromeos::libassistant::BindToCurrentSequence; -using ::chromeos::libassistant::BindToCurrentSequenceRepeating; -using ::chromeos::libassistant::PopulateInternalOptionsFromProto; -using ::chromeos::libassistant::PopulateVoicelessOptionsFromProto; -using ::chromeos::libassistant::ToStdFunction; -using ::chromeos::libassistant::ToStdFunctionRepeating; // A macro which ensures we are running on the calling sequence. #define ENSURE_CALLING_SEQUENCE(method, ...) \ @@ -111,7 +104,7 @@ auto* options = assistant_manager_internal->CreateDefaultInternalOptions(); auto proto = chromeos::assistant::CreateInternalOptionsProto( locale, spoken_feedback_enabled); - PopulateInternalOptionsFromProto(proto, options); + chromeos::libassistant::PopulateInternalOptionsFromProto(proto, options); chromeos::assistant::SetDarkModeEnabledForV1(options, dark_mode_enabled); chromeos::assistant::SetTimezoneOverrideForV1(options); @@ -468,7 +461,8 @@ const ::assistant::api::VoicelessOptions& options, base::OnceCallback<void(bool)> on_done) { assistant_client::VoicelessOptions voiceless_options; - PopulateVoicelessOptionsFromProto(options, &voiceless_options); + chromeos::libassistant::PopulateVoicelessOptionsFromProto(options, + &voiceless_options); assistant_manager_internal()->SendVoicelessInteraction( interaction.SerializeAsString(), description, voiceless_options, [callback = std::move(on_done)](bool result) mutable {
diff --git a/chromeos/ash/services/libassistant/libassistant_factory.h b/chromeos/ash/services/libassistant/libassistant_factory.h index f660cd6..8b6cae6 100644 --- a/chromeos/ash/services/libassistant/libassistant_factory.h +++ b/chromeos/ash/services/libassistant/libassistant_factory.h
@@ -15,8 +15,7 @@ class AssistantManagerInternal; } // namespace assistant_client -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { // Factory class that creates the main actual Libassistant classes. // Can be replaced with a fake for unittests. @@ -32,12 +31,6 @@ assistant_client::AssistantManager* assistant_manager) = 0; }; -} // namespace libassistant -} // namespace chromeos - -// TODO(https://crbug.com/1164001): remove when it moved to ash. -namespace ash::libassistant { -using ::chromeos::libassistant::LibassistantFactory; -} +} // namespace ash::libassistant #endif // CHROMEOS_ASH_SERVICES_LIBASSISTANT_LIBASSISTANT_FACTORY_H_
diff --git a/chromeos/ash/services/libassistant/libassistant_loader_impl.cc b/chromeos/ash/services/libassistant/libassistant_loader_impl.cc index f898548..edb9427 100644 --- a/chromeos/ash/services/libassistant/libassistant_loader_impl.cc +++ b/chromeos/ash/services/libassistant/libassistant_loader_impl.cc
@@ -22,7 +22,7 @@ #include "chromeos/ash/services/libassistant/constants.h" #include "third_party/cros_system_api/dbus/dlcservice/dbus-constants.h" -namespace chromeos::libassistant { +namespace ash::libassistant { namespace { @@ -212,6 +212,10 @@ return instance.get(); } +} // namespace ash::libassistant + +namespace chromeos::libassistant { + // static void LibassistantLoader::Load(LoadCallback callback) { LibassistantLoaderImpl::GetInstance()->Load(std::move(callback));
diff --git a/chromeos/ash/services/libassistant/libassistant_loader_impl.h b/chromeos/ash/services/libassistant/libassistant_loader_impl.h index 638eec2..435ff3c6f 100644 --- a/chromeos/ash/services/libassistant/libassistant_loader_impl.h +++ b/chromeos/ash/services/libassistant/libassistant_loader_impl.h
@@ -17,7 +17,7 @@ #include "net/base/backoff_entry.h" #include "third_party/abseil-cpp/absl/types/optional.h" -namespace chromeos::libassistant { +namespace ash::libassistant { using EntryPoint = assistant_client::internal_api::LibassistantEntrypoint; @@ -71,6 +71,11 @@ base::WeakPtrFactory<LibassistantLoaderImpl> weak_factory_{this}; }; -} // namespace chromeos::libassistant +} // namespace ash::libassistant + +// TODO(https://crbug.com/1164001): remove when the migration is finished. +namespace chromeos::libassistant { +using ::ash::libassistant::LibassistantLoaderImpl; +} #endif // /CHROMEOS_SERVICES_LIBASSISTANT_PUBLIC_CPP_LIBASSISTANT_LOADER_H_
diff --git a/chromeos/ash/services/libassistant/libassistant_loader_impl_unittest.cc b/chromeos/ash/services/libassistant/libassistant_loader_impl_unittest.cc index 888869a3..d13381b 100644 --- a/chromeos/ash/services/libassistant/libassistant_loader_impl_unittest.cc +++ b/chromeos/ash/services/libassistant/libassistant_loader_impl_unittest.cc
@@ -13,8 +13,7 @@ #include "chromeos/ash/services/assistant/public/cpp/features.h" #include "testing/gtest/include/gtest/gtest.h" -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { class LibassistantLoaderImplTest : public ::testing::Test { public: @@ -52,7 +51,7 @@ TEST_F(LibassistantLoaderImplTest, ShouldRunCallbackWithDlcFeature) { feature_list_.InitAndEnableFeature( - chromeos::assistant::features::kEnableLibAssistantDlc); + assistant::features::kEnableLibAssistantDlc); auto* loader = LibassistantLoaderImpl::GetInstance(); EXPECT_TRUE(loader); @@ -79,5 +78,4 @@ DlcserviceClient::Shutdown(); } -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant
diff --git a/chromeos/ash/services/libassistant/libassistant_sandbox_hook.cc b/chromeos/ash/services/libassistant/libassistant_sandbox_hook.cc index 24e18c8..54abe2dd 100644 --- a/chromeos/ash/services/libassistant/libassistant_sandbox_hook.cc +++ b/chromeos/ash/services/libassistant/libassistant_sandbox_hook.cc
@@ -17,8 +17,7 @@ using sandbox::syscall_broker::BrokerFilePermission; using sandbox::syscall_broker::MakeBrokerCommandSet; -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { namespace { @@ -77,5 +76,4 @@ return true; } -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant
diff --git a/chromeos/ash/services/libassistant/libassistant_sandbox_hook.h b/chromeos/ash/services/libassistant/libassistant_sandbox_hook.h index 9ea35d3..783395d 100644 --- a/chromeos/ash/services/libassistant/libassistant_sandbox_hook.h +++ b/chromeos/ash/services/libassistant/libassistant_sandbox_hook.h
@@ -7,12 +7,10 @@ #include "sandbox/policy/linux/sandbox_linux.h" -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { bool LibassistantPreSandboxHook(sandbox::policy::SandboxLinux::Options options); -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant #endif // CHROMEOS_ASH_SERVICES_LIBASSISTANT_LIBASSISTANT_SANDBOX_HOOK_H_
diff --git a/chromeos/ash/services/libassistant/libassistant_service.cc b/chromeos/ash/services/libassistant/libassistant_service.cc index 31832b4..1a7f2c77 100644 --- a/chromeos/ash/services/libassistant/libassistant_service.cc +++ b/chromeos/ash/services/libassistant/libassistant_service.cc
@@ -16,8 +16,10 @@ #include "chromeos/ash/services/libassistant/public/mojom/speech_recognition_observer.mojom.h" #include "chromeos/assistant/internal/libassistant/shared_headers.h" -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { + +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom = ::chromeos::libassistant::mojom; namespace { @@ -32,7 +34,7 @@ // LibassistantFactory implementation: std::unique_ptr<assistant_client::AssistantManager> CreateAssistantManager( const std::string& lib_assistant_config) override { - if (!chromeos::assistant::features::IsLibAssistantDlcEnabled()) { + if (!assistant::features::IsLibAssistantDlcEnabled()) { return base::WrapUnique(assistant_client::AssistantManager::Create( platform_api_, lib_assistant_config)); } @@ -45,7 +47,7 @@ assistant_client::AssistantManagerInternal* UnwrapAssistantManagerInternal( assistant_client::AssistantManager* assistant_manager) override { - if (!chromeos::assistant::features::IsLibAssistantDlcEnabled()) { + if (!assistant::features::IsLibAssistantDlcEnabled()) { return assistant_client::UnwrapAssistantManagerInternal( assistant_manager); } @@ -160,5 +162,4 @@ conversation_controller_.AddAuthenticationStateObserver(std::move(observer)); } -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant
diff --git a/chromeos/ash/services/libassistant/libassistant_service.h b/chromeos/ash/services/libassistant/libassistant_service.h index 9fef28e6..0456e68 100644 --- a/chromeos/ash/services/libassistant/libassistant_service.h +++ b/chromeos/ash/services/libassistant/libassistant_service.h
@@ -26,14 +26,14 @@ #include "mojo/public/cpp/bindings/receiver.h" #include "mojo/public/cpp/bindings/remote_set.h" -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { class COMPONENT_EXPORT(LIBASSISTANT_SERVICE) LibassistantService - : public mojom::LibassistantService { + : public chromeos::libassistant::mojom::LibassistantService { public: explicit LibassistantService( - mojo::PendingReceiver<mojom::LibassistantService> receiver, + mojo::PendingReceiver<chromeos::libassistant::mojom::LibassistantService> + receiver, // Allows to inject a custom instance during unittests. std::unique_ptr<LibassistantFactory> factory = nullptr); LibassistantService(LibassistantService&) = delete; @@ -42,25 +42,40 @@ // mojom::LibassistantService implementation: void Bind( - mojo::PendingReceiver<mojom::AudioInputController> audio_input_controller, - mojo::PendingReceiver<mojom::ConversationController> + mojo::PendingReceiver<chromeos::libassistant::mojom::AudioInputController> + audio_input_controller, + mojo::PendingReceiver< + chromeos::libassistant::mojom::ConversationController> conversation_controller, - mojo::PendingReceiver<mojom::DisplayController> display_controller, - mojo::PendingReceiver<mojom::MediaController> media_controller, - mojo::PendingReceiver<mojom::ServiceController> service_controller, - mojo::PendingReceiver<mojom::SettingsController> settings_controller, - mojo::PendingReceiver<mojom::SpeakerIdEnrollmentController> + mojo::PendingReceiver<chromeos::libassistant::mojom::DisplayController> + display_controller, + mojo::PendingReceiver<chromeos::libassistant::mojom::MediaController> + media_controller, + mojo::PendingReceiver<chromeos::libassistant::mojom::ServiceController> + service_controller, + mojo::PendingReceiver<chromeos::libassistant::mojom::SettingsController> + settings_controller, + mojo::PendingReceiver< + chromeos::libassistant::mojom::SpeakerIdEnrollmentController> speaker_id_enrollment_controller, - mojo::PendingReceiver<mojom::TimerController> timer_controller, - mojo::PendingRemote<mojom::AudioOutputDelegate> audio_output_delegate, - mojo::PendingRemote<mojom::DeviceSettingsDelegate> + mojo::PendingReceiver<chromeos::libassistant::mojom::TimerController> + timer_controller, + mojo::PendingRemote<chromeos::libassistant::mojom::AudioOutputDelegate> + audio_output_delegate, + mojo::PendingRemote<chromeos::libassistant::mojom::DeviceSettingsDelegate> device_settings_delegate, - mojo::PendingRemote<mojom::MediaDelegate> media_delegate, - mojo::PendingRemote<mojom::NotificationDelegate> notification_delegate, - mojo::PendingRemote<mojom::PlatformDelegate> platform_delegate, - mojo::PendingRemote<mojom::TimerDelegate> timer_delegate) override; + mojo::PendingRemote<chromeos::libassistant::mojom::MediaDelegate> + media_delegate, + mojo::PendingRemote<chromeos::libassistant::mojom::NotificationDelegate> + notification_delegate, + mojo::PendingRemote<chromeos::libassistant::mojom::PlatformDelegate> + platform_delegate, + mojo::PendingRemote<chromeos::libassistant::mojom::TimerDelegate> + timer_delegate) override; void AddSpeechRecognitionObserver( - mojo::PendingRemote<mojom::SpeechRecognitionObserver> observer) override; + mojo::PendingRemote< + chromeos::libassistant::mojom::SpeechRecognitionObserver> observer) + override; void AddAuthenticationStateObserver( mojo::PendingRemote< chromeos::libassistant::mojom::AuthenticationStateObserver> observer) @@ -73,10 +88,11 @@ ServiceController& service_controller() { return service_controller_; } private: - mojo::Receiver<mojom::LibassistantService> receiver_; - mojo::Remote<mojom::PlatformDelegate> platform_delegate_; + mojo::Receiver<chromeos::libassistant::mojom::LibassistantService> receiver_; + mojo::Remote<chromeos::libassistant::mojom::PlatformDelegate> + platform_delegate_; - mojo::RemoteSet<mojom::SpeechRecognitionObserver> + mojo::RemoteSet<chromeos::libassistant::mojom::SpeechRecognitionObserver> speech_recognition_observers_; // These controllers are part of the platform api which is called from @@ -99,12 +115,6 @@ TimerController timer_controller_; }; -} // namespace libassistant -} // namespace chromeos - -// TODO(https://crbug.com/1164001): remove when it moved to ash. -namespace ash::libassistant { -using ::chromeos::libassistant::LibassistantService; -} +} // namespace ash::libassistant #endif // CHROMEOS_ASH_SERVICES_LIBASSISTANT_LIBASSISTANT_SERVICE_H_
diff --git a/chromeos/ash/services/libassistant/media_controller.cc b/chromeos/ash/services/libassistant/media_controller.cc index 3067638..f597add 100644 --- a/chromeos/ash/services/libassistant/media_controller.cc +++ b/chromeos/ash/services/libassistant/media_controller.cc
@@ -15,8 +15,7 @@ #include "chromeos/assistant/internal/util_headers.h" #include "chromeos/services/assistant/public/shared/utils.h" -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { namespace { @@ -33,6 +32,8 @@ using chromeos::assistant::AndroidAppInfo; using chromeos::assistant::shared::PlayMediaArgs; +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom = ::chromeos::libassistant::mojom; // A macro which ensures we are running on the mojom thread. #define ENSURE_MOJOM_THREAD(method, ...) \ @@ -255,5 +256,4 @@ assistant_client->AddMediaActionFallbackEventObserver(events_observer_.get()); } -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant
diff --git a/chromeos/ash/services/libassistant/media_controller.h b/chromeos/ash/services/libassistant/media_controller.h index 9278b005..481e5e50 100644 --- a/chromeos/ash/services/libassistant/media_controller.h +++ b/chromeos/ash/services/libassistant/media_controller.h
@@ -11,10 +11,9 @@ #include "mojo/public/cpp/bindings/receiver.h" #include "mojo/public/cpp/bindings/remote.h" -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { -class MediaController : public mojom::MediaController, +class MediaController : public chromeos::libassistant::mojom::MediaController, public AssistantClientObserver { public: MediaController(); @@ -22,13 +21,16 @@ MediaController& operator=(const MediaController&) = delete; ~MediaController() override; - void Bind(mojo::PendingReceiver<mojom::MediaController> receiver, - mojo::PendingRemote<mojom::MediaDelegate> delegate); + void Bind(mojo::PendingReceiver< + chromeos::libassistant::mojom::MediaController> receiver, + mojo::PendingRemote<chromeos::libassistant::mojom::MediaDelegate> + delegate); // mojom::MediaController implementation: void ResumeInternalMediaPlayer() override; void PauseInternalMediaPlayer() override; - void SetExternalPlaybackState(mojom::MediaStatePtr state) override; + void SetExternalPlaybackState( + chromeos::libassistant::mojom::MediaStatePtr state) override; // AssistantClientObserver implementation: void OnAssistantClientRunning(AssistantClient* assistant_client) override; @@ -38,12 +40,12 @@ AssistantClient* assistant_client_ = nullptr; - mojo::Receiver<mojom::MediaController> receiver_{this}; - mojo::Remote<mojom::MediaDelegate> delegate_; + mojo::Receiver<chromeos::libassistant::mojom::MediaController> receiver_{ + this}; + mojo::Remote<chromeos::libassistant::mojom::MediaDelegate> delegate_; std::unique_ptr<GrpcEventsObserver> events_observer_; }; -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant #endif // CHROMEOS_ASH_SERVICES_LIBASSISTANT_MEDIA_CONTROLLER_H_
diff --git a/chromeos/ash/services/libassistant/media_controller_unittest.cc b/chromeos/ash/services/libassistant/media_controller_unittest.cc index 371bf10f..f7e9facc 100644 --- a/chromeos/ash/services/libassistant/media_controller_unittest.cc +++ b/chromeos/ash/services/libassistant/media_controller_unittest.cc
@@ -16,8 +16,7 @@ #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { namespace { @@ -25,7 +24,10 @@ using ProtoAndroidAppInfo = chromeos::assistant::shared::AndroidAppInfo; using AndroidAppInfo = chromeos::assistant::AndroidAppInfo; using chromeos::assistant::shared::PlayMediaArgs; -using mojom::PlaybackState; +using ::chromeos::libassistant::mojom::PlaybackState; + +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom = ::chromeos::libassistant::mojom; #define EXPECT_NO_CALLS(args...) EXPECT_CALL(args).Times(0); @@ -366,5 +368,4 @@ play_media_args.SerializeAsString()); FlushMojomPipes(); } -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant
diff --git a/chromeos/ash/services/libassistant/network_provider_impl.cc b/chromeos/ash/services/libassistant/network_provider_impl.cc index 531a384..264c6c93 100644 --- a/chromeos/ash/services/libassistant/network_provider_impl.cc +++ b/chromeos/ash/services/libassistant/network_provider_impl.cc
@@ -18,8 +18,11 @@ using ConnectionStateType = chromeos::network_config::mojom::ConnectionStateType; -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { + +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom = ::chromeos::libassistant::mojom; +namespace network_config = ::chromeos::network_config; NetworkProviderImpl::NetworkProviderImpl() : connection_status_(ConnectionStatus::UNKNOWN) {} @@ -62,5 +65,4 @@ return nullptr; } -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant
diff --git a/chromeos/ash/services/libassistant/network_provider_impl.h b/chromeos/ash/services/libassistant/network_provider_impl.h index 621c2d2..eb278ae1 100644 --- a/chromeos/ash/services/libassistant/network_provider_impl.h +++ b/chromeos/ash/services/libassistant/network_provider_impl.h
@@ -13,12 +13,11 @@ #include "mojo/public/cpp/bindings/receiver.h" #include "mojo/public/cpp/bindings/remote.h" -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { class COMPONENT_EXPORT(ASSISTANT_SERVICE) NetworkProviderImpl : public assistant_client::NetworkProvider, - public network_config::CrosNetworkConfigObserver { + public chromeos::network_config::CrosNetworkConfigObserver { public: NetworkProviderImpl(); @@ -27,7 +26,8 @@ ~NetworkProviderImpl() override; - void Initialize(mojom::PlatformDelegate* platform_delegate); + void Initialize( + chromeos::libassistant::mojom::PlatformDelegate* platform_delegate); // assistant_client::NetworkProvider: ConnectionStatus GetConnectionStatus() override; @@ -35,18 +35,17 @@ // network_config::CrosNetworkConfigObserver: void OnActiveNetworksChanged( - std::vector<network_config::mojom::NetworkStatePropertiesPtr> networks) - override; + std::vector<chromeos::network_config::mojom::NetworkStatePropertiesPtr> + networks) override; private: ConnectionStatus connection_status_; - mojo::Receiver<network_config::mojom::CrosNetworkConfigObserver> receiver_{ - this}; - mojo::Remote<network_config::mojom::CrosNetworkConfig> + mojo::Receiver<chromeos::network_config::mojom::CrosNetworkConfigObserver> + receiver_{this}; + mojo::Remote<chromeos::network_config::mojom::CrosNetworkConfig> cros_network_config_remote_; }; -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant #endif // CHROMEOS_ASH_SERVICES_LIBASSISTANT_NETWORK_PROVIDER_IMPL_H_
diff --git a/chromeos/ash/services/libassistant/network_provider_impl_unittest.cc b/chromeos/ash/services/libassistant/network_provider_impl_unittest.cc index 4fa7a45..3cc74503 100644 --- a/chromeos/ash/services/libassistant/network_provider_impl_unittest.cc +++ b/chromeos/ash/services/libassistant/network_provider_impl_unittest.cc
@@ -13,11 +13,10 @@ #include "chromeos/services/network_config/public/mojom/network_types.mojom-forward.h" #include "testing/gtest/include/gtest/gtest.h" -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { -using network_config::mojom::ConnectionStateType; -using network_config::mojom::NetworkStatePropertiesPtr; +using ::chromeos::network_config::mojom::ConnectionStateType; +using ::chromeos::network_config::mojom::NetworkStatePropertiesPtr; using ConnectionStatus = NetworkProviderImpl::ConnectionStatus; class AssistantNetworkProviderImplTest : public ::testing::Test { @@ -43,7 +42,7 @@ NetworkStatePropertiesPtr CreateNetworkState( ConnectionStateType connection_type) const { NetworkStatePropertiesPtr network_state = - network_config::mojom::NetworkStateProperties::New(); + chromeos::network_config::mojom::NetworkStateProperties::New(); network_state->connection_state = connection_type; return network_state; } @@ -109,5 +108,4 @@ network_provider_.GetConnectionStatus()); } -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant
diff --git a/chromeos/ash/services/libassistant/notification_delegate_unittest.cc b/chromeos/ash/services/libassistant/notification_delegate_unittest.cc index fb8ec6a..7598ed4 100644 --- a/chromeos/ash/services/libassistant/notification_delegate_unittest.cc +++ b/chromeos/ash/services/libassistant/notification_delegate_unittest.cc
@@ -11,8 +11,10 @@ #include "chromeos/assistant/internal/test_support/fake_assistant_manager_internal.h" #include "testing/gmock/include/gmock/gmock.h" -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { + +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom = ::chromeos::libassistant::mojom; namespace { @@ -50,24 +52,25 @@ class CrosActionModuleHelper { public: explicit CrosActionModuleHelper( - assistant::action::CrosActionModule* action_module) + chromeos::assistant::action::CrosActionModule* action_module) : action_module_(*action_module) {} CrosActionModuleHelper(const CrosActionModuleHelper&) = delete; CrosActionModuleHelper& operator=(const CrosActionModuleHelper&) = delete; ~CrosActionModuleHelper() = default; - void ShowNotification(const assistant::action::Notification& notification) { + void ShowNotification( + const chromeos::assistant::action::Notification& notification) { for (auto* observer : action_observers()) observer->OnShowNotification(notification); } private: - const std::vector<assistant::action::AssistantActionObserver*>& + const std::vector<chromeos::assistant::action::AssistantActionObserver*>& action_observers() { return action_module_.GetActionObserversForTesting(); } - const assistant::action::CrosActionModule& action_module_; + const chromeos::assistant::action::CrosActionModule& action_module_; }; } // namespace @@ -84,7 +87,7 @@ service_tester_.GetNotificationDelegatePendingReceiver()); service_tester_.Start(); action_module_helper_ = std::make_unique<CrosActionModuleHelper>( - static_cast<assistant::action::CrosActionModule*>( + static_cast<chromeos::assistant::action::CrosActionModule*>( service_tester_.assistant_manager_internal().action_module())); service_tester_.service() @@ -111,7 +114,7 @@ }; TEST_F(NotificationDelegateTest, ShouldInvokeAddOrUpdateNotification) { - assistant::action::Notification input_notification{ + chromeos::assistant::action::Notification input_notification{ /*title=*/"title", /*text=*/"text", /*action_url=*/"https://action-url/", @@ -165,5 +168,4 @@ delegate_mock().FlushForTesting(); } -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant
diff --git a/chromeos/ash/services/libassistant/platform_api.cc b/chromeos/ash/services/libassistant/platform_api.cc index f35dfcf..5a9ffdb 100644 --- a/chromeos/ash/services/libassistant/platform_api.cc +++ b/chromeos/ash/services/libassistant/platform_api.cc
@@ -13,8 +13,10 @@ #include "chromeos/ash/services/libassistant/system_provider_impl.h" #include "media/audio/audio_device_description.h" -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { + +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom = ::chromeos::libassistant::mojom; PlatformApi::PlatformApi() : audio_output_provider_(std::make_unique<AudioOutputProviderImpl>( @@ -85,5 +87,4 @@ audio_output_provider_->UnBindAudioDecoderFactory(); } -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant
diff --git a/chromeos/ash/services/libassistant/platform_api.h b/chromeos/ash/services/libassistant/platform_api.h index 2ce5bbf..2ded58ec 100644 --- a/chromeos/ash/services/libassistant/platform_api.h +++ b/chromeos/ash/services/libassistant/platform_api.h
@@ -7,8 +7,6 @@ #include <memory> -// TODO(https://crbug.com/1164001): move to forward declaration -#include "chromeos/ash/services/libassistant/audio/audio_output_provider_impl.h" #include "chromeos/ash/services/libassistant/grpc/assistant_client_observer.h" #include "chromeos/ash/services/libassistant/network_provider_impl.h" #include "chromeos/ash/services/libassistant/public/mojom/audio_output_delegate.mojom.h" @@ -16,9 +14,9 @@ #include "chromeos/assistant/internal/libassistant/shared_headers.h" #include "mojo/public/cpp/bindings/pending_remote.h" -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { +class AudioOutputProviderImpl; class FakeAuthProvider; class FileProviderImpl; class NetworkProviderImpl; @@ -36,8 +34,9 @@ ~PlatformApi() override; void Bind( - mojo::PendingRemote<mojom::AudioOutputDelegate> audio_output_delegate, - mojom::PlatformDelegate* platform_delegate); + mojo::PendingRemote<chromeos::libassistant::mojom::AudioOutputDelegate> + audio_output_delegate, + chromeos::libassistant::mojom::PlatformDelegate* platform_delegate); PlatformApi& SetAudioInputProvider(assistant_client::AudioInputProvider*); @@ -64,7 +63,6 @@ std::unique_ptr<SystemProviderImpl> system_provider_; }; -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant #endif // CHROMEOS_ASH_SERVICES_LIBASSISTANT_PLATFORM_API_H_
diff --git a/chromeos/ash/services/libassistant/power_manager_provider_impl.cc b/chromeos/ash/services/libassistant/power_manager_provider_impl.cc index 7acb6f6..3c77682 100644 --- a/chromeos/ash/services/libassistant/power_manager_provider_impl.cc +++ b/chromeos/ash/services/libassistant/power_manager_provider_impl.cc
@@ -13,8 +13,7 @@ #include "mojo/public/cpp/bindings/remote.h" #include "services/device/public/mojom/wake_lock_provider.mojom.h" -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { namespace { @@ -104,7 +103,8 @@ DVLOG(1) << __func__; DCHECK(main_thread_task_runner_->RunsTasksInCurrentSequence()); - auto timer = std::make_unique<NativeTimer>(kTag + base::NumberToString(id)); + auto timer = + std::make_unique<chromeos::NativeTimer>(kTag + base::NumberToString(id)); // Once the timer is created successfully, start the timer and store // associated data. The stored |callback| will be called in // |OnTimerFiredOnMainThread|. @@ -197,5 +197,4 @@ timers_.erase(id); } -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant
diff --git a/chromeos/ash/services/libassistant/power_manager_provider_impl.h b/chromeos/ash/services/libassistant/power_manager_provider_impl.h index 2b60744..ce1e681d 100644 --- a/chromeos/ash/services/libassistant/power_manager_provider_impl.h +++ b/chromeos/ash/services/libassistant/power_manager_provider_impl.h
@@ -18,8 +18,7 @@ #include "mojo/public/cpp/bindings/remote.h" #include "services/device/public/mojom/wake_lock.mojom.h" -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { // Implementation of power management features for libassistant. // @@ -61,8 +60,8 @@ } private: - using CallbackAndTimer = - std::pair<assistant_client::Callback0, std::unique_ptr<NativeTimer>>; + using CallbackAndTimer = std::pair<assistant_client::Callback0, + std::unique_ptr<chromeos::NativeTimer>>; // Returns time ticks from boot including time ticks during sleeping. base::TimeTicks GetCurrentBootTime(); @@ -117,7 +116,6 @@ base::WeakPtrFactory<PowerManagerProviderImpl> weak_factory_; }; -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant #endif // CHROMEOS_ASH_SERVICES_LIBASSISTANT_POWER_MANAGER_PROVIDER_IMPL_H_
diff --git a/chromeos/ash/services/libassistant/power_manager_provider_impl_unittest.cc b/chromeos/ash/services/libassistant/power_manager_provider_impl_unittest.cc index 842b770..184164e 100644 --- a/chromeos/ash/services/libassistant/power_manager_provider_impl_unittest.cc +++ b/chromeos/ash/services/libassistant/power_manager_provider_impl_unittest.cc
@@ -11,8 +11,7 @@ #include "services/device/public/cpp/test/test_wake_lock_provider.h" #include "testing/gtest/include/gtest/gtest.h" -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { namespace { @@ -54,7 +53,7 @@ void SetUp() override { chromeos::PowerManagerClient::InitializeFake(); - FakePowerManagerClient::Get()->set_tick_clock( + chromeos::FakePowerManagerClient::Get()->set_tick_clock( task_environment_.GetMockTickClock()); power_manager_provider_impl_ = std::make_unique<PowerManagerProviderImpl>(); power_manager_provider_impl_->set_tick_clock_for_testing( @@ -166,5 +165,4 @@ CheckAddWakeAlarmAndExpiration(kAlarmRelativeTimeMs, kAlarmMaxDelayMs)); } -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant
diff --git a/chromeos/ash/services/libassistant/public/cpp/libassistant_loader.h b/chromeos/ash/services/libassistant/public/cpp/libassistant_loader.h index bb03c34..02b746a 100644 --- a/chromeos/ash/services/libassistant/public/cpp/libassistant_loader.h +++ b/chromeos/ash/services/libassistant/public/cpp/libassistant_loader.h
@@ -24,4 +24,9 @@ } // namespace chromeos::libassistant +// TODO(https://crbug.com/1164001): remove when it moved to ash. +namespace ash::libassistant { +using ::chromeos::libassistant::LibassistantLoader; +} + #endif // CHROMEOS_ASH_SERVICES_LIBASSISTANT_PUBLIC_CPP_LIBASSISTANT_LOADER_H_
diff --git a/chromeos/ash/services/libassistant/service_controller.cc b/chromeos/ash/services/libassistant/service_controller.cc index b840215..e0eb3f4 100644 --- a/chromeos/ash/services/libassistant/service_controller.cc +++ b/chromeos/ash/services/libassistant/service_controller.cc
@@ -19,12 +19,13 @@ #include "services/network/public/cpp/cross_thread_pending_shared_url_loader_factory.h" #include "services/network/public/cpp/wrapper_shared_url_loader_factory.h" -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { namespace { -using mojom::ServiceState; +using ::chromeos::libassistant::mojom::ServiceState; +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom = ::chromeos::libassistant::mojom; // A macro which ensures we are running on the mojom thread. #define ENSURE_MOJOM_THREAD(method, ...) \ @@ -344,5 +345,4 @@ CreatePendingURLLoaderFactory(std::move(url_loader_factory_remote))); } -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant
diff --git a/chromeos/ash/services/libassistant/service_controller.h b/chromeos/ash/services/libassistant/service_controller.h index 5e7a546..277d475c 100644 --- a/chromeos/ash/services/libassistant/service_controller.h +++ b/chromeos/ash/services/libassistant/service_controller.h
@@ -19,8 +19,7 @@ #include "mojo/public/cpp/bindings/receiver.h" #include "mojo/public/cpp/bindings/remote_set.h" -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { class ChromiumApiDelegate; class LibassistantFactory; @@ -28,7 +27,7 @@ // Component managing the lifecycle of Libassistant, // exposing methods to start/stop and configure Libassistant. class COMPONENT_EXPORT(LIBASSISTANT_SERVICE) ServiceController - : public mojom::ServiceController, + : public chromeos::libassistant::mojom::ServiceController, public ServicesStatusObserver { public: explicit ServiceController(LibassistantFactory* factory); @@ -36,18 +35,22 @@ ServiceController& operator=(ServiceController&) = delete; ~ServiceController() override; - void Bind(mojo::PendingReceiver<mojom::ServiceController> receiver, - mojom::SettingsController* settings_controller); + void Bind( + mojo::PendingReceiver<chromeos::libassistant::mojom::ServiceController> + receiver, + chromeos::libassistant::mojom::SettingsController* settings_controller); // mojom::ServiceController implementation: - void Initialize(mojom::BootupConfigPtr libassistant_config, - mojo::PendingRemote<network::mojom::URLLoaderFactory> - url_loader_factory) override; + void Initialize( + chromeos::libassistant::mojom::BootupConfigPtr libassistant_config, + mojo::PendingRemote<network::mojom::URLLoaderFactory> url_loader_factory) + override; void Start() override; void Stop() override; void ResetAllDataAndStop() override; void AddAndFireStateObserver( - mojo::PendingRemote<mojom::StateObserver> observer) override; + mojo::PendingRemote<chromeos::libassistant::mojom::StateObserver> + observer) override; // ServicesStatusObserver implementation: void OnServicesStatusChanged(ServicesStatus status) override; @@ -71,25 +74,30 @@ // Will be invoked when Libassistant services are started. void OnServicesBootingUp(); - void SetStateAndInformObservers(mojom::ServiceState new_state); + void SetStateAndInformObservers( + chromeos::libassistant::mojom::ServiceState new_state); void CreateAndRegisterChromiumApiDelegate( mojo::PendingRemote<network::mojom::URLLoaderFactory> url_loader_factory); void CreateChromiumApiDelegate( mojo::PendingRemote<network::mojom::URLLoaderFactory> url_loader_factory); - mojom::ServiceState state_ = mojom::ServiceState::kStopped; + chromeos::libassistant::mojom::ServiceState state_ = + chromeos::libassistant::mojom::ServiceState::kStopped; // Called during |Initialize| to apply boot configuration. - mojom::SettingsController* settings_controller_ = nullptr; + chromeos::libassistant::mojom::SettingsController* settings_controller_ = + nullptr; LibassistantFactory& libassistant_factory_; std::unique_ptr<AssistantClient> assistant_client_; std::unique_ptr<ChromiumApiDelegate> chromium_api_delegate_; - mojo::Receiver<mojom::ServiceController> receiver_{this}; - mojo::RemoteSet<mojom::StateObserver> state_observers_; + mojo::Receiver<chromeos::libassistant::mojom::ServiceController> receiver_{ + this}; + mojo::RemoteSet<chromeos::libassistant::mojom::StateObserver> + state_observers_; base::ObserverList<AssistantClientObserver> assistant_client_observers_; base::WeakPtrFactory<ServiceController> weak_factory_{this}; @@ -101,7 +109,6 @@ &ServiceController::AddAndFireAssistantClientObserver, &ServiceController::RemoveAssistantClientObserver>; -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant #endif // CHROMEOS_ASH_SERVICES_LIBASSISTANT_SERVICE_CONTROLLER_H_
diff --git a/chromeos/ash/services/libassistant/service_controller_unittest.cc b/chromeos/ash/services/libassistant/service_controller_unittest.cc index 1ef2d92..87c55ca 100644 --- a/chromeos/ash/services/libassistant/service_controller_unittest.cc +++ b/chromeos/ash/services/libassistant/service_controller_unittest.cc
@@ -26,12 +26,14 @@ #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { + +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom = ::chromeos::libassistant::mojom; namespace { -using mojom::ServiceState; +using ::chromeos::libassistant::mojom::ServiceState; using ::testing::StrictMock; #define EXPECT_NO_CALLS(args...) EXPECT_CALL(args).Times(0) @@ -233,8 +235,9 @@ }; } // namespace +} // namespace ash::libassistant -namespace mojom { +namespace chromeos::libassistant::mojom { void PrintTo(const ServiceState state, std::ostream* stream) { switch (state) { @@ -251,7 +254,9 @@ *stream << "INVALID ServiceState (" << static_cast<int>(state) << ")"; } -} // namespace mojom +} // namespace chromeos::libassistant::mojom + +namespace ash::libassistant { TEST_F(AssistantServiceControllerTest, StateShouldStartAsStopped) { Initialize(); @@ -663,5 +668,4 @@ Initialize(std::move(bootup_config)); } -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant
diff --git a/chromeos/ash/services/libassistant/settings_controller.cc b/chromeos/ash/services/libassistant/settings_controller.cc index b5601a7..119a9db 100644 --- a/chromeos/ash/services/libassistant/settings_controller.cc +++ b/chromeos/ash/services/libassistant/settings_controller.cc
@@ -22,17 +22,11 @@ #include "chromeos/assistant/internal/proto/shared/proto/v2/display_interface.pb.h" #include "third_party/icu/source/common/unicode/locid.h" -namespace chromeos { +namespace ash::libassistant { // TODO(https://crbug.com/1164001): remove after migrating to ash. -namespace assistant { -using ::ash::assistant::AssistantDevice; -using ::ash::assistant::AssistantDeviceSettings; -using ::ash::assistant::AssistantDeviceSettingsUpdate; -using ::ash::assistant::SettingsUiUpdate; -} // namespace assistant +namespace mojom = ::chromeos::libassistant::mojom; -namespace libassistant { namespace { // Each authentication token exists of a [gaia_id, access_token] tuple. @@ -413,5 +407,4 @@ spoken_feedback_enabled_.reset(); } -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant
diff --git a/chromeos/ash/services/libassistant/settings_controller.h b/chromeos/ash/services/libassistant/settings_controller.h index 32f0c23..656d29a2 100644 --- a/chromeos/ash/services/libassistant/settings_controller.h +++ b/chromeos/ash/services/libassistant/settings_controller.h
@@ -14,22 +14,25 @@ #include "chromeos/ash/services/libassistant/public/mojom/settings_controller.mojom.h" #include "mojo/public/cpp/bindings/receiver.h" -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { -class SettingsController : public AssistantClientObserver, - public mojom::SettingsController { +class SettingsController + : public AssistantClientObserver, + public chromeos::libassistant::mojom::SettingsController { public: SettingsController(); SettingsController(const SettingsController&) = delete; SettingsController& operator=(const SettingsController&) = delete; ~SettingsController() override; - void Bind(mojo::PendingReceiver<mojom::SettingsController> receiver); + void Bind( + mojo::PendingReceiver<chromeos::libassistant::mojom::SettingsController> + receiver); // mojom::SettingsController implementation: void SetAuthenticationTokens( - std::vector<mojom::AuthenticationTokenPtr> tokens) override; + std::vector<chromeos::libassistant::mojom::AuthenticationTokenPtr> tokens) + override; void SetListeningEnabled(bool value) override; void SetLocale(const std::string& value) override; void SetSpokenFeedbackEnabled(bool value) override; @@ -53,7 +56,9 @@ // must be updated. void UpdateListeningEnabled(absl::optional<bool> listening_enabled); void UpdateAuthenticationTokens( - const absl::optional<std::vector<mojom::AuthenticationTokenPtr>>& tokens); + const absl::optional< + std::vector<chromeos::libassistant::mojom::AuthenticationTokenPtr>>& + tokens); void UpdateInternalOptions(const absl::optional<std::string>& locale, absl::optional<bool> spoken_feedback_enabled, absl::optional<bool> dark_mode_enabled); @@ -78,13 +83,14 @@ absl::optional<bool> dark_mode_enabled_; absl::optional<bool> listening_enabled_; absl::optional<std::string> locale_; - absl::optional<std::vector<mojom::AuthenticationTokenPtr>> + absl::optional< + std::vector<chromeos::libassistant::mojom::AuthenticationTokenPtr>> authentication_tokens_; - mojo::Receiver<mojom::SettingsController> receiver_{this}; + mojo::Receiver<chromeos::libassistant::mojom::SettingsController> receiver_{ + this}; }; -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant #endif // CHROMEOS_ASH_SERVICES_LIBASSISTANT_SETTINGS_CONTROLLER_H_
diff --git a/chromeos/ash/services/libassistant/settings_controller_unittest.cc b/chromeos/ash/services/libassistant/settings_controller_unittest.cc index bff9210..9946810c 100644 --- a/chromeos/ash/services/libassistant/settings_controller_unittest.cc +++ b/chromeos/ash/services/libassistant/settings_controller_unittest.cc
@@ -13,8 +13,7 @@ #include "testing/gtest/include/gtest/gtest.h" #include "third_party/icu/source/common/unicode/locid.h" -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { namespace { @@ -22,6 +21,8 @@ #define IGNORE_CALLS(args...) EXPECT_CALL(args).Times(testing::AnyNumber()); // The auth tokens are pairs of <user, token> using AuthTokens = std::vector<std::pair<std::string, std::string>>; +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom = ::chromeos::libassistant::mojom; std::vector<mojom::AuthenticationTokenPtr> ToVector( mojom::AuthenticationTokenPtr token) { @@ -32,9 +33,10 @@ class AssistantClientMock : public FakeAssistantClient { public: - AssistantClientMock( - std::unique_ptr<assistant::FakeAssistantManager> assistant_manager, - assistant::FakeAssistantManagerInternal* assistant_manager_internal) + AssistantClientMock(std::unique_ptr<chromeos::assistant::FakeAssistantManager> + assistant_manager, + chromeos::assistant::FakeAssistantManagerInternal* + assistant_manager_internal) : FakeAssistantClient(std::move(assistant_manager), assistant_manager_internal) {} ~AssistantClientMock() override = default; @@ -101,9 +103,9 @@ assistant_manager_internal_ = nullptr; auto assistant_manager = - std::make_unique<assistant::FakeAssistantManager>(); - assistant_manager_internal_ = std::make_unique< - testing::StrictMock<assistant::FakeAssistantManagerInternal>>(); + std::make_unique<chromeos::assistant::FakeAssistantManager>(); + assistant_manager_internal_ = std::make_unique<testing::StrictMock< + chromeos::assistant::FakeAssistantManagerInternal>>(); assistant_client_ = std::make_unique<AssistantClientMock>( std::move(assistant_manager), assistant_manager_internal_.get()); } @@ -114,7 +116,7 @@ base::test::SingleThreadTaskEnvironment environment_; SettingsController controller_; - std::unique_ptr<assistant::FakeAssistantManagerInternal> + std::unique_ptr<chromeos::assistant::FakeAssistantManagerInternal> assistant_manager_internal_; std::unique_ptr<AssistantClientMock> assistant_client_; }; @@ -431,5 +433,4 @@ DestroyLibassistant(); } -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant
diff --git a/chromeos/ash/services/libassistant/speaker_id_enrollment_controller.cc b/chromeos/ash/services/libassistant/speaker_id_enrollment_controller.cc index d60fab23..3d0cef3 100644 --- a/chromeos/ash/services/libassistant/speaker_id_enrollment_controller.cc +++ b/chromeos/ash/services/libassistant/speaker_id_enrollment_controller.cc
@@ -14,10 +14,11 @@ #include "chromeos/assistant/internal/proto/shared/proto/v2/speaker_id_enrollment_interface.pb.h" #include "mojo/public/cpp/bindings/remote.h" -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { using ::assistant::api::OnSpeakerIdEnrollmentEventRequest; +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom = ::chromeos::libassistant::mojom; //////////////////////////////////////////////////////////////////////////////// // GetStatusWaiter @@ -228,5 +229,4 @@ pending_response_waiters_.AbortAll(); } -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant
diff --git a/chromeos/ash/services/libassistant/speaker_id_enrollment_controller.h b/chromeos/ash/services/libassistant/speaker_id_enrollment_controller.h index ccbcf5f..dbf2101 100644 --- a/chromeos/ash/services/libassistant/speaker_id_enrollment_controller.h +++ b/chromeos/ash/services/libassistant/speaker_id_enrollment_controller.h
@@ -6,35 +6,37 @@ #define CHROMEOS_ASH_SERVICES_LIBASSISTANT_SPEAKER_ID_ENROLLMENT_CONTROLLER_H_ #include "chromeos/ash/services/libassistant/abortable_task_list.h" -// TODO(https://crbug.com/1164001): move to forward declaration -#include "chromeos/ash/services/libassistant/grpc/assistant_client.h" #include "chromeos/ash/services/libassistant/grpc/assistant_client_observer.h" #include "chromeos/ash/services/libassistant/public/mojom/audio_input_controller.mojom-forward.h" #include "chromeos/ash/services/libassistant/public/mojom/speaker_id_enrollment_controller.mojom.h" #include "mojo/public/cpp/bindings/receiver.h" -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { + +class AssistantClient; class SpeakerIdEnrollmentController - : public mojom::SpeakerIdEnrollmentController, + : public chromeos::libassistant::mojom::SpeakerIdEnrollmentController, public AssistantClientObserver { public: explicit SpeakerIdEnrollmentController( - mojom::AudioInputController* audio_input); + chromeos::libassistant::mojom::AudioInputController* audio_input); SpeakerIdEnrollmentController(const SpeakerIdEnrollmentController&) = delete; SpeakerIdEnrollmentController& operator=( const SpeakerIdEnrollmentController&) = delete; ~SpeakerIdEnrollmentController() override; - void Bind(mojo::PendingReceiver<mojom::SpeakerIdEnrollmentController> + void Bind(mojo::PendingReceiver< + chromeos::libassistant::mojom::SpeakerIdEnrollmentController> pending_receiver); // mojom::SpeakerIdEnrollmentController implementation: void StartSpeakerIdEnrollment( const std::string& user_gaia_id, bool skip_cloud_enrollment, - ::mojo::PendingRemote<mojom::SpeakerIdEnrollmentClient> client) override; + ::mojo::PendingRemote< + chromeos::libassistant::mojom::SpeakerIdEnrollmentClient> client) + override; void StopSpeakerIdEnrollment() override; void GetSpeakerIdEnrollmentStatus( const std::string& user_gaia_id, @@ -48,8 +50,9 @@ class EnrollmentSession; class GetStatusWaiter; - mojo::Receiver<mojom::SpeakerIdEnrollmentController> receiver_{this}; - mojom::AudioInputController* const audio_input_; + mojo::Receiver<chromeos::libassistant::mojom::SpeakerIdEnrollmentController> + receiver_{this}; + chromeos::libassistant::mojom::AudioInputController* const audio_input_; std::unique_ptr<EnrollmentSession> active_enrollment_session_; // Contains all pending callbacks for GetSpeakerIdEnrollmentStatus requests. @@ -58,7 +61,6 @@ AssistantClient* assistant_client_ = nullptr; }; -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant #endif // CHROMEOS_ASH_SERVICES_LIBASSISTANT_SPEAKER_ID_ENROLLMENT_CONTROLLER_H_
diff --git a/chromeos/ash/services/libassistant/speaker_id_enrollment_controller_unittest.cc b/chromeos/ash/services/libassistant/speaker_id_enrollment_controller_unittest.cc index 51be267..ebdb977 100644 --- a/chromeos/ash/services/libassistant/speaker_id_enrollment_controller_unittest.cc +++ b/chromeos/ash/services/libassistant/speaker_id_enrollment_controller_unittest.cc
@@ -12,8 +12,7 @@ #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { namespace { using assistant_client::SpeakerIdEnrollmentStatus; @@ -23,6 +22,8 @@ SpeakerIdEnrollmentController::GetSpeakerIdEnrollmentStatusCallback; using ::testing::NiceMock; using ::testing::StrictMock; +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom = ::chromeos::libassistant::mojom; class SpeakerIdEnrollmentClientMock : public mojom::SpeakerIdEnrollmentClient { public: @@ -66,7 +67,8 @@ LibassistantServiceTester& service_tester() { return service_tester_; } - assistant::FakeAssistantManagerInternal& assistant_manager_internal() { + chromeos::assistant::FakeAssistantManagerInternal& + assistant_manager_internal() { return service_tester().assistant_manager_internal(); } @@ -240,5 +242,4 @@ FlushForTesting(); } -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant
diff --git a/chromeos/ash/services/libassistant/speech_recognition_observer_unittest.cc b/chromeos/ash/services/libassistant/speech_recognition_observer_unittest.cc index c06befd..8a905b3 100644 --- a/chromeos/ash/services/libassistant/speech_recognition_observer_unittest.cc +++ b/chromeos/ash/services/libassistant/speech_recognition_observer_unittest.cc
@@ -14,8 +14,7 @@ #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { namespace { @@ -23,6 +22,8 @@ assistant_client::ConversationStateListener::RecognitionState; using RecognitionResult = assistant_client::ConversationStateListener::RecognitionResult; +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom = ::chromeos::libassistant::mojom; std::string CreateDisplayAssistantEvent(float speech_level) { ::assistant::display::AssistantEvent result; @@ -142,5 +143,4 @@ RecognitionState::FINAL_RESULT, recognition_result); observer_mock().FlushForTesting(); } -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant
diff --git a/chromeos/ash/services/libassistant/system_provider_impl.cc b/chromeos/ash/services/libassistant/system_provider_impl.cc index 10c8fdc..bd03605 100644 --- a/chromeos/ash/services/libassistant/system_provider_impl.cc +++ b/chromeos/ash/services/libassistant/system_provider_impl.cc
@@ -11,8 +11,7 @@ #include "base/system/sys_info.h" #include "chromeos/ash/services/libassistant/power_manager_provider_impl.h" -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { SystemProviderImpl::SystemProviderImpl( std::unique_ptr<PowerManagerProviderImpl> power_manager_provider) @@ -73,5 +72,4 @@ battery_monitor_.FlushForTesting(); // IN-TEST } -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant
diff --git a/chromeos/ash/services/libassistant/system_provider_impl.h b/chromeos/ash/services/libassistant/system_provider_impl.h index bb121b1..b3854047 100644 --- a/chromeos/ash/services/libassistant/system_provider_impl.h +++ b/chromeos/ash/services/libassistant/system_provider_impl.h
@@ -16,8 +16,7 @@ #include "services/device/public/mojom/battery_monitor.mojom.h" #include "services/device/public/mojom/battery_status.mojom.h" -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { class PowerManagerProviderImpl; @@ -56,7 +55,6 @@ device::mojom::BatteryStatusPtr current_battery_status_; }; -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant #endif // CHROMEOS_ASH_SERVICES_LIBASSISTANT_SYSTEM_PROVIDER_IMPL_H_
diff --git a/chromeos/ash/services/libassistant/system_provider_impl_unittest.cc b/chromeos/ash/services/libassistant/system_provider_impl_unittest.cc index aa2a322c..c9f0a10 100644 --- a/chromeos/ash/services/libassistant/system_provider_impl_unittest.cc +++ b/chromeos/ash/services/libassistant/system_provider_impl_unittest.cc
@@ -14,8 +14,7 @@ #include "services/device/public/mojom/battery_monitor.mojom.h" #include "testing/gtest/include/gtest/gtest.h" -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { class FakeBatteryMonitor : device::mojom::BatteryMonitor { public: @@ -106,5 +105,4 @@ EXPECT_EQ(state.charge_percentage, 100); } -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant
diff --git a/chromeos/ash/services/libassistant/timer_controller.cc b/chromeos/ash/services/libassistant/timer_controller.cc index 5640e49..9b13b56e 100644 --- a/chromeos/ash/services/libassistant/timer_controller.cc +++ b/chromeos/ash/services/libassistant/timer_controller.cc
@@ -13,8 +13,10 @@ #include "chromeos/ash/services/libassistant/public/cpp/assistant_timer.h" #include "chromeos/assistant/internal/proto/shared/proto/v2/delegate/event_handler_interface.pb.h" -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { + +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom = ::chromeos::libassistant::mojom; //////////////////////////////////////////////////////////////////////////////// // TimerListener @@ -141,5 +143,4 @@ } } -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant
diff --git a/chromeos/ash/services/libassistant/timer_controller.h b/chromeos/ash/services/libassistant/timer_controller.h index b017cf1..597ad97 100644 --- a/chromeos/ash/services/libassistant/timer_controller.h +++ b/chromeos/ash/services/libassistant/timer_controller.h
@@ -13,10 +13,9 @@ #include "mojo/public/cpp/bindings/receiver.h" #include "mojo/public/cpp/bindings/remote.h" -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { -class TimerController : public mojom::TimerController, +class TimerController : public chromeos::libassistant::mojom::TimerController, public AssistantClientObserver { public: TimerController(); @@ -24,8 +23,10 @@ TimerController& operator=(const TimerController&) = delete; ~TimerController() override; - void Bind(mojo::PendingReceiver<mojom::TimerController> receiver, - mojo::PendingRemote<mojom::TimerDelegate> delegate); + void Bind(mojo::PendingReceiver< + chromeos::libassistant::mojom::TimerController> receiver, + mojo::PendingRemote<chromeos::libassistant::mojom::TimerDelegate> + delegate); // mojom::TimerController implementation: void AddTimeToTimer(const std::string& id, @@ -48,10 +49,11 @@ // in OnDestroyingAssistantClient(). AssistantClient* assistant_client_ = nullptr; - mojo::Receiver<mojom::TimerController> receiver_{this}; - mojo::Remote<mojom::TimerDelegate> delegate_; + mojo::Receiver<chromeos::libassistant::mojom::TimerController> receiver_{ + this}; + mojo::Remote<chromeos::libassistant::mojom::TimerDelegate> delegate_; }; -} // namespace libassistant -} // namespace chromeos + +} // namespace ash::libassistant #endif // CHROMEOS_ASH_SERVICES_LIBASSISTANT_TIMER_CONTROLLER_H_
diff --git a/chromeos/ash/services/libassistant/timer_controller_unittest.cc b/chromeos/ash/services/libassistant/timer_controller_unittest.cc index a4a39d5..853625bd 100644 --- a/chromeos/ash/services/libassistant/timer_controller_unittest.cc +++ b/chromeos/ash/services/libassistant/timer_controller_unittest.cc
@@ -14,13 +14,14 @@ #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { namespace { using ::chromeos::assistant::AssistantTimerState; using ::testing::Invoke; +// TODO(https://crbug.com/1164001): remove after migrating to ash. +namespace mojom = ::chromeos::libassistant::mojom; // Adds an AlarmTimerEvent of the given |type| to |events|. void AddAlarmTimerEvent(std::vector<assistant_client::AlarmTimerEvent>* events, @@ -77,7 +78,7 @@ void Init() { auto assistant_manager = - std::make_unique<assistant::FakeAssistantManager>(); + std::make_unique<chromeos::assistant::FakeAssistantManager>(); auto* assistant_manager_internal = &assistant_manager->assistant_manager_internal(); assistant_client_ = std::make_unique<FakeAssistantClient>( @@ -102,8 +103,8 @@ TimerController& controller() { return controller_; } - assistant::FakeAlarmTimerManager& fake_alarm_timer_manager() { - return *static_cast<assistant::FakeAlarmTimerManager*>( + chromeos::assistant::FakeAlarmTimerManager& fake_alarm_timer_manager() { + return *static_cast<chromeos::assistant::FakeAlarmTimerManager*>( assistant_client_->assistant_manager_internal() ->GetAlarmTimerManager()); } @@ -185,5 +186,4 @@ controller().ResumeTimer("timer-id"); } -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant
diff --git a/chromeos/ash/services/libassistant/util.cc b/chromeos/ash/services/libassistant/util.cc index 6e9d53e..254caa40 100644 --- a/chromeos/ash/services/libassistant/util.cc +++ b/chromeos/ash/services/libassistant/util.cc
@@ -33,8 +33,7 @@ using chromeos::assistant::shared::SettingInfo; using chromeos::assistant::shared::VerifyProviderClientOpResult; -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { namespace { @@ -181,16 +180,18 @@ absl::optional<std::string> version = chromeos::version_loader::GetVersion( chromeos::version_loader::VERSION_FULL); device.SetKey("embedder_build_info", Value(version.value_or("0.0.0.0"))); - device.SetKey("model_id", Value(assistant::kModelId)); + device.SetKey("model_id", Value(chromeos::assistant::kModelId)); device.SetKey("model_revision", Value(1)); config.SetKey("device", std::move(device)); // Enables Libassistant gRPC server for V2. - if (chromeos::assistant::features::IsLibAssistantV2Enabled()) { + if (assistant::features::IsLibAssistantV2Enabled()) { const bool is_chromeos_device = base::SysInfo::IsRunningOnChromeOS(); const std::string server_addresses = - assistant::GetLibassistantServiceAddress(is_chromeos_device) + "," + - assistant::GetHttpConnectionServiceAddress(is_chromeos_device); + chromeos::assistant::GetLibassistantServiceAddress(is_chromeos_device) + + "," + + chromeos::assistant::GetHttpConnectionServiceAddress( + is_chromeos_device); Value libas_server(Type::DICTIONARY); libas_server.SetKey("libas_server_address", Value(server_addresses)); @@ -324,7 +325,7 @@ return V1InteractionBuilder() .SetInResponseTo(interaction_id) .SetStatusCodeFromEntityFound(any_provider_available) - .AddResult(assistant::kResultKeyVerifyProvider, result_proto) + .AddResult(chromeos::assistant::kResultKeyVerifyProvider, result_proto) .Proto(); } @@ -341,7 +342,8 @@ return V1InteractionBuilder() .SetInResponseTo(interaction_id) .SetStatusCode(ResponseCode::OK) - .AddResult(/*key=*/assistant::kResultKeyGetDeviceSettings, result_proto) + .AddResult(/*key=*/chromeos::assistant::kResultKeyGetDeviceSettings, + result_proto) .Proto(); } @@ -350,12 +352,12 @@ const std::string& consistent_token, const std::string& opaque_token, const int action_index) { - auto request_param = assistant::CreateNotificationRequestParam( + auto request_param = chromeos::assistant::CreateNotificationRequestParam( notification_id, consistent_token, opaque_token, action_index); return V1InteractionBuilder() - .SetClientInputName(assistant::kClientInputRequestNotification) - .AddClientInputParams(assistant::kNotificationRequestParamsKey, + .SetClientInputName(chromeos::assistant::kClientInputRequestNotification) + .AddClientInputParams(chromeos::assistant::kNotificationRequestParamsKey, request_param) .Proto(); } @@ -365,22 +367,23 @@ const std::string& consistent_token, const std::string& opaque_token, const std::vector<std::string>& grouping_keys) { - auto dismiss_param = assistant::CreateNotificationDismissedParam( + auto dismiss_param = chromeos::assistant::CreateNotificationDismissedParam( notification_id, consistent_token, opaque_token, grouping_keys); return V1InteractionBuilder() - .SetClientInputName(assistant::kClientInputDismissNotification) - .AddClientInputParams(assistant::kNotificationDismissParamsKey, + .SetClientInputName(chromeos::assistant::kClientInputDismissNotification) + .AddClientInputParams(chromeos::assistant::kNotificationDismissParamsKey, dismiss_param) .Proto(); } Interaction CreateEditReminderInteraction(const std::string& reminder_id) { - auto intent_input = assistant::CreateEditReminderParam(reminder_id); + auto intent_input = chromeos::assistant::CreateEditReminderParam(reminder_id); return V1InteractionBuilder() - .SetClientInputName(assistant::kClientInputEditReminder) - .AddClientInputParams(assistant::kEditReminderParamsKey, intent_input) + .SetClientInputName(chromeos::assistant::kClientInputEditReminder) + .AddClientInputParams(chromeos::assistant::kEditReminderParamsKey, + intent_input) .Proto(); } @@ -396,25 +399,25 @@ bool assistant_debug_info_allowed, const std::string& feedback_description, const std::string& screenshot_png) { - auto feedback_arg = assistant::CreateFeedbackParam( + auto feedback_arg = chromeos::assistant::CreateFeedbackParam( assistant_debug_info_allowed, feedback_description, screenshot_png); return V1InteractionBuilder() - .SetClientInputName(assistant::kClientInputText) - .AddClientInputParams( - assistant::kTextParamsKey, - assistant::CreateTextParam(assistant::kFeedbackText)) - .AddClientInputParams(assistant::kFeedbackParamsKey, feedback_arg) + .SetClientInputName(chromeos::assistant::kClientInputText) + .AddClientInputParams(chromeos::assistant::kTextParamsKey, + chromeos::assistant::CreateTextParam( + chromeos::assistant::kFeedbackText)) + .AddClientInputParams(chromeos::assistant::kFeedbackParamsKey, + feedback_arg) .Proto(); } Interaction CreateTextQueryInteraction(const std::string& query) { return V1InteractionBuilder() - .SetClientInputName(assistant::kClientInputText) - .AddClientInputParams(assistant::kTextParamsKey, - assistant::CreateTextParam(query)) + .SetClientInputName(chromeos::assistant::kClientInputText) + .AddClientInputParams(chromeos::assistant::kTextParamsKey, + chromeos::assistant::CreateTextParam(query)) .Proto(); } -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant
diff --git a/chromeos/ash/services/libassistant/util.h b/chromeos/ash/services/libassistant/util.h index 2f31175..146949b 100644 --- a/chromeos/ash/services/libassistant/util.h +++ b/chromeos/ash/services/libassistant/util.h
@@ -26,8 +26,7 @@ } // namespace assistant } // namespace chromeos -namespace chromeos { -namespace libassistant { +namespace ash::libassistant { // Creates the configuration for libassistant. std::string CreateLibAssistantConfig( @@ -74,7 +73,6 @@ ::assistant::api::Interaction CreateTextQueryInteraction( const std::string& query); -} // namespace libassistant -} // namespace chromeos +} // namespace ash::libassistant #endif // CHROMEOS_ASH_SERVICES_LIBASSISTANT_UTIL_H_
diff --git a/chromeos/crosapi/mojom/diagnostics_service.mojom b/chromeos/crosapi/mojom/diagnostics_service.mojom index aa4834c..bfb423c 100644 --- a/chromeos/crosapi/mojom/diagnostics_service.mojom +++ b/chromeos/crosapi/mojom/diagnostics_service.mojom
@@ -16,7 +16,7 @@ // Interface for exposing diagnostics service. Implemented in ash-chrome. // -// Next ID: 17 +// Next ID: 19 [Stable, Uuid="14bc6194-c059-4048-9bea-ca6823eeda82", RenamedFrom="ash.health.mojom.DiagnosticsService"] interface DiagnosticsService { @@ -268,11 +268,32 @@ // * |response| - contains a unique identifier and status for the created // routine. RunLanConnectivityRoutine@16() => (DiagnosticsRunRoutineResponse response); + + // TODO(b/245293243): Rephrase to express sufficiency instead of necessity. + // Requests that the DnsResolution routine is created and started on the + // platform. This routine checks whether a DNS resolution can be completed + // successfully. This routine is only available if GetAvailableRoutines + // returned kDnsResolution. + // + // The response: + // * |response| - contains a unique identifier and status for the created + // routine. + RunDnsResolutionRoutine@17() => (DiagnosticsRunRoutineResponse response); + + // Requests that the SignalStrength routine is created and started on the + // platform. This routine checks whether there is an acceptable signal + // strength on wireless networks. This routine is only available if + // GetAvailableRoutines returned kSignalStrength. + // + // The response: + // * |response| - contains a unique identifier and status for the created + // routine. + RunSignalStrengthRoutine@18() => (DiagnosticsRunRoutineResponse response); }; // Enumeration of each of the diagnostics routines the platform may support. // -// Next ID: 16 +// Next ID: 18 [Stable, Extensible, RenamedFrom="ash.health.mojom.DiagnosticRoutineEnum"] enum DiagnosticsRoutineEnum { [Default] kUnknown = 15, @@ -291,6 +312,8 @@ kBatteryCharge = 12, kMemory = 13, kLanConnectivity = 14, + kDnsResolution = 16, + kSignalStrength = 17, }; // Enumeration of each of the possible statuses for a diagnostics routine.
diff --git a/components/accuracy_tips/accuracy_service.cc b/components/accuracy_tips/accuracy_service.cc index f81bca7..2875b3b 100644 --- a/components/accuracy_tips/accuracy_service.cc +++ b/components/accuracy_tips/accuracy_service.cc
@@ -234,16 +234,16 @@ ukm::SourceId ukm_source_id, AccuracyTipInteraction interaction) { DCHECK(ui_task_runner_->RunsTasksInCurrentSequence()); - ListPrefUpdate update(pref_service_, - GetPreviousInteractionsPrefName(disable_ui_)); - base::Value* interaction_list = update.Get(); - interaction_list->Append(static_cast<int>(interaction)); + ScopedListPrefUpdate update(pref_service_, + GetPreviousInteractionsPrefName(disable_ui_)); + base::Value::List& interaction_list = update.Get(); + interaction_list.Append(static_cast<int>(interaction)); // Record metrics. base::UmaHistogramEnumeration("Privacy.AccuracyTip.AccuracyTipInteraction", interaction); base::UmaHistogramCounts100("Privacy.AccuracyTip.NumDialogsShown", - interaction_list->GetList().size()); + interaction_list.size()); ukm::builders::AccuracyTipDialog ukm_builder(ukm_source_id); ukm_builder.SetInteraction(static_cast<int>(interaction)); @@ -256,7 +256,7 @@ const std::string suffix = GetHistogramSuffix(interaction); base::UmaHistogramCounts100("Privacy.AccuracyTip.NumDialogsShown." + suffix, - interaction_list->GetList().size()); + interaction_list.size()); base::UmaHistogramMediumTimes( "Privacy.AccuracyTip.AccuracyTipTimeOpen." + suffix, time_open); }
diff --git a/components/autofill/OWNERS b/components/autofill/OWNERS index e256481a..be2829f 100644 --- a/components/autofill/OWNERS +++ b/components/autofill/OWNERS
@@ -3,3 +3,4 @@ koerber@google.com schwering@google.com kolos@chromium.org +fleimgruber@google.com
diff --git a/components/autofill/core/browser/browser_autofill_manager.cc b/components/autofill/core/browser/browser_autofill_manager.cc index 89f0787b..2e9e5e7 100644 --- a/components/autofill/core/browser/browser_autofill_manager.cc +++ b/components/autofill/core/browser/browser_autofill_manager.cc
@@ -422,6 +422,16 @@ return sanitized_value; } +base::StringPiece RenderFormDataActionToString( + mojom::RendererFormDataAction action) { + switch (action) { + case mojom::RendererFormDataAction::kFill: + return "fill"; + case mojom::RendererFormDataAction::kPreview: + return "preview"; + } +} + } // namespace BrowserAutofillManager::FillingContext::FillingContext( @@ -1968,6 +1978,7 @@ DCHECK(autofill_field); LogBuffer buffer(IsLoggingActive(log_manager())); + LOG_AF(buffer) << "action: " << RenderFormDataActionToString(action); LOG_AF(buffer) << "is credit card section: " << is_credit_card << Br{}; LOG_AF(buffer) << "is refill: " << is_refill << Br{}; LOG_AF(buffer) << *form_structure << Br{};
diff --git a/components/autofill_assistant/android/internal/java/res/drawable/autofill_assistant_rounded_corner_background.xml b/components/autofill_assistant/android/internal/java/res/drawable/autofill_assistant_rounded_corner_background.xml index 146e416b..e037afe 100644 --- a/components/autofill_assistant/android/internal/java/res/drawable/autofill_assistant_rounded_corner_background.xml +++ b/components/autofill_assistant/android/internal/java/res/drawable/autofill_assistant_rounded_corner_background.xml
@@ -9,5 +9,5 @@ <corners android:radius="4dp" /> <solid - android:color="@color/blue_when_enabled_list" /> + android:color="@color/default_text_color_accent1_tint_list" /> </shape> \ No newline at end of file
diff --git a/components/autofill_assistant/android/internal/java/res/layout/autofill_assistant_button_filled.xml b/components/autofill_assistant/android/internal/java/res/layout/autofill_assistant_button_filled.xml index 572a4c5..c3e4184 100644 --- a/components/autofill_assistant/android/internal/java/res/layout/autofill_assistant_button_filled.xml +++ b/components/autofill_assistant/android/internal/java/res/layout/autofill_assistant_button_filled.xml
@@ -11,10 +11,11 @@ android:layout_height="wrap_content" android:gravity="center_vertical" android:minHeight="@dimen/min_touch_target_size" - app:chipColor="@color/filled_button_bg" + app:chipColor="?attr/globalFilledButtonBgColor" app:rippleColor="@color/filled_button_ripple_color" app:cornerRadius="@dimen/autofill_assistant_button_corner_radius" app:primaryTextAppearance="@style/TextAppearance.Button.Text.Filled" + app:buttonTextColor="?attr/globalFilledButtonTextColor" app:iconWidth="24dp" app:iconHeight="24dp" app:chipBorderWidth="@dimen/autofill_assistant_filled_button_border_width"
diff --git a/components/autofill_assistant/android/internal/java/res/values-v17/attrs.xml b/components/autofill_assistant/android/internal/java/res/values-v17/attrs.xml index 5ebbdf18..e86a10e3 100644 --- a/components/autofill_assistant/android/internal/java/res/values-v17/attrs.xml +++ b/components/autofill_assistant/android/internal/java/res/values-v17/attrs.xml
@@ -29,6 +29,7 @@ <attr name="iconHeight" format="reference|dimension"/> <attr name="primaryTextAppearance" format="reference"/> <attr name="secondaryTextAppearance" format="reference"/> + <attr name="buttonTextColor" format="reference"/> <attr name="rippleColor"/> <attr name="chipBorderWidth" format="reference"/> <attr name="verticalInset"/>
diff --git a/components/autofill_assistant/android/java/src/org/chromium/components/autofill_assistant/carousel/ButtonView.java b/components/autofill_assistant/android/java/src/org/chromium/components/autofill_assistant/carousel/ButtonView.java index fa945d8..02e1461 100644 --- a/components/autofill_assistant/android/java/src/org/chromium/components/autofill_assistant/carousel/ButtonView.java +++ b/components/autofill_assistant/android/java/src/org/chromium/components/autofill_assistant/carousel/ButtonView.java
@@ -16,10 +16,12 @@ import android.widget.LinearLayout; import android.widget.TextView; +import androidx.annotation.ColorRes; import androidx.annotation.DrawableRes; import androidx.annotation.IdRes; import androidx.annotation.Px; import androidx.annotation.StyleRes; +import androidx.core.content.ContextCompat; import androidx.core.view.ViewCompat; import org.chromium.base.ApiCompatibilityUtils; @@ -80,6 +82,8 @@ R.styleable.ButtonView_primaryTextAppearance, R.style.TextAppearance_ChipText); mSecondaryTextAppearanceId = a.getResourceId( R.styleable.ButtonView_secondaryTextAppearance, R.style.TextAppearance_ChipText); + @ColorRes + int textColorRes = a.getResourceId(R.styleable.ButtonView_buttonTextColor, -1); int borderWidth = a.getResourceId(R.styleable.ButtonView_chipBorderWidth, R.dimen.chip_border_width); int verticalInset = a.getDimensionPixelSize(R.styleable.ButtonView_verticalInset, @@ -99,6 +103,9 @@ R.layout.autofill_assistant_button_text_view, /* root= */ null); ApiCompatibilityUtils.setTextAppearance(mPrimaryText, primaryTextAppearance); + if (textColorRes != -1) { + mPrimaryText.setTextColor(ContextCompat.getColorStateList(getContext(), textColorRes)); + } ViewCompat.setPaddingRelative(mPrimaryText, ViewUtils.dpToPx(context, 4), 0, 0, 0); addView(mPrimaryText); setPrimaryTextMargins(4);
diff --git a/components/autofill_assistant/android/java/src/org/chromium/components/autofill_assistant/header/AssistantStepProgressBar.java b/components/autofill_assistant/android/java/src/org/chromium/components/autofill_assistant/header/AssistantStepProgressBar.java index 87ab035..5fdf7f3d 100644 --- a/components/autofill_assistant/android/java/src/org/chromium/components/autofill_assistant/header/AssistantStepProgressBar.java +++ b/components/autofill_assistant/android/java/src/org/chromium/components/autofill_assistant/header/AssistantStepProgressBar.java
@@ -41,7 +41,7 @@ // animation starts scaling and after a while the alpha changes. private static final int PULSING_ALPHA_CHANGE_DELAY_MS = 300; private static final int PULSING_RESTART_DELAY_MS = 2_000; - private static final int COLOR_LIST = R.color.blue_when_enabled_list; + private static final int COLOR_LIST = R.color.default_text_color_accent1_tint_list; private static final int ERROR_COLOR_LIST = R.color.default_red; private static class IconViewHolder { @@ -302,6 +302,7 @@ line.setBackground(ApiCompatibilityUtils.getDrawable(context.getResources(), R.drawable.autofill_assistant_rounded_corner_background)); + line.setBackgroundTintList(ContextCompat.getColorStateList(context, COLOR_LIST)); line.setEnabled(false); } @@ -313,6 +314,7 @@ R.drawable.autofill_assistant_rounded_corner_background)); line.setTag(AssistantTagsForTesting.PROGRESSBAR_LINE_FOREGROUND_TAG); + line.setBackgroundTintList(ContextCompat.getColorStateList(context, COLOR_LIST)); line.setEnabled(true); line.setScaleX(0f);
diff --git a/components/page_info/core/about_this_site_service.cc b/components/page_info/core/about_this_site_service.cc index a95876a..eb6f4127 100644 --- a/components/page_info/core/about_this_site_service.cc +++ b/components/page_info/core/about_this_site_service.cc
@@ -39,8 +39,10 @@ kMaxValue = kDismissed }; -AboutThisSiteService::AboutThisSiteService(std::unique_ptr<Client> client) - : client_(std::move(client)) {} +AboutThisSiteService::AboutThisSiteService(std::unique_ptr<Client> client, + bool allow_missing_description) + : client_(std::move(client)), + allow_missing_description_(allow_missing_description) {} absl::optional<proto::SiteInfo> AboutThisSiteService::GetAboutThisSiteInfo( const GURL& url, @@ -54,7 +56,7 @@ decision == OptimizationGuideDecision::kUnknown ? AboutThisSiteStatus::kUnknown : about_this_site_validation::ValidateMetadata( - about_this_site_metadata); + about_this_site_metadata, allow_missing_description_); base::UmaHistogramEnumeration("Security.PageInfo.AboutThisSiteStatus", status); RecordAboutThisSiteInteraction( @@ -84,8 +86,7 @@ if (kShowSampleContent.Get()) { page_info::proto::SiteInfo site_info; if (url == GURL("https://example.com")) { - if (!base::FeatureList::IsEnabled( - kPageInfoAboutThisSiteDescriptionPlaceholder)) { + if (!allow_missing_description_) { auto* description = site_info.mutable_description(); description->set_name("Example website"); description->set_subtitle("Website");
diff --git a/components/page_info/core/about_this_site_service.h b/components/page_info/core/about_this_site_service.h index 6cab9ea3..bf83f8e 100644 --- a/components/page_info/core/about_this_site_service.h +++ b/components/page_info/core/about_this_site_service.h
@@ -56,7 +56,8 @@ kMaxValue = kOpenedDirectlyFromSidePanel }; - explicit AboutThisSiteService(std::unique_ptr<Client> client); + explicit AboutThisSiteService(std::unique_ptr<Client> client, + bool allow_missing_description); ~AboutThisSiteService() override; AboutThisSiteService(const AboutThisSiteService&) = delete; @@ -75,6 +76,7 @@ private: std::unique_ptr<Client> client_; base::flat_set<url::Origin> dismissed_banners_; + const bool allow_missing_description_; base::WeakPtrFactory<AboutThisSiteService> weak_ptr_factory_{this}; };
diff --git a/components/page_info/core/about_this_site_service_unittest.cc b/components/page_info/core/about_this_site_service_unittest.cc index c754bc2..b5a43ed 100644 --- a/components/page_info/core/about_this_site_service_unittest.cc +++ b/components/page_info/core/about_this_site_service_unittest.cc
@@ -89,7 +89,8 @@ auto client_mock = std::make_unique<testing::StrictMock<MockAboutThisSiteServiceClient>>(); client_ = client_mock.get(); - service_ = std::make_unique<AboutThisSiteService>(std::move(client_mock)); + service_ = std::make_unique<AboutThisSiteService>( + std::move(client_mock), /*allow_missing_description*/ false); } MockAboutThisSiteServiceClient* client() { return client_; }
diff --git a/components/page_info/core/about_this_site_validation.cc b/components/page_info/core/about_this_site_validation.cc index 2a4b221..f2ba291 100644 --- a/components/page_info/core/about_this_site_validation.cc +++ b/components/page_info/core/about_this_site_validation.cc
@@ -64,7 +64,8 @@ return AboutThisSiteStatus::kValid; } -AboutThisSiteStatus ValidateSiteInfo(const proto::SiteInfo& site_info) { +AboutThisSiteStatus ValidateSiteInfo(const proto::SiteInfo& site_info, + bool allow_missing_description) { if (!site_info.has_description() && !site_info.has_first_seen() && !site_info.has_more_about()) return AboutThisSiteStatus::kEmptySiteInfo; @@ -74,9 +75,7 @@ if (site_info.has_description()) { status = ValidateDescription(site_info.description()); } else { - if (!base::FeatureList::IsEnabled(kPageInfoAboutThisSiteMoreInfo) || - !base::FeatureList::IsEnabled( - kPageInfoAboutThisSiteDescriptionPlaceholder)) + if (!allow_missing_description) return AboutThisSiteStatus::kMissingDescription; } @@ -102,12 +101,13 @@ } AboutThisSiteStatus ValidateMetadata( - const absl::optional<proto::AboutThisSiteMetadata>& metadata) { + const absl::optional<proto::AboutThisSiteMetadata>& metadata, + bool allow_missing_description) { if (!metadata) return AboutThisSiteStatus::kNoResult; if (!metadata->has_site_info()) return AboutThisSiteStatus::kMissingSiteInfo; - return ValidateSiteInfo(metadata->site_info()); + return ValidateSiteInfo(metadata->site_info(), allow_missing_description); } } // namespace about_this_site_validation
diff --git a/components/page_info/core/about_this_site_validation.h b/components/page_info/core/about_this_site_validation.h index 4989180..8161cc99 100644 --- a/components/page_info/core/about_this_site_validation.h +++ b/components/page_info/core/about_this_site_validation.h
@@ -38,14 +38,16 @@ }; AboutThisSiteStatus ValidateMetadata( - const absl::optional<proto::AboutThisSiteMetadata>& metadata); + const absl::optional<proto::AboutThisSiteMetadata>& metadata, + bool allow_missing_description); AboutThisSiteStatus ValidateSource(const proto::Hyperlink& link); AboutThisSiteStatus ValidateDescription( const proto::SiteDescription& description); AboutThisSiteStatus ValidateFirstSeen(const proto::SiteFirstSeen& first_seen); AboutThisSiteStatus ValidateMoreAbout(const proto::MoreAbout& more_about); -AboutThisSiteStatus ValidateSiteInfo(const proto::SiteInfo& site_info); +AboutThisSiteStatus ValidateSiteInfo(const proto::SiteInfo& site_info, + bool allow_missing_description); } // namespace about_this_site_validation } // namespace page_info
diff --git a/components/page_info/core/about_this_site_validation_unittest.cc b/components/page_info/core/about_this_site_validation_unittest.cc index cd065bc..7c558cc 100644 --- a/components/page_info/core/about_this_site_validation_unittest.cc +++ b/components/page_info/core/about_this_site_validation_unittest.cc
@@ -53,22 +53,26 @@ // Tests that correct proto messages are accepted. TEST(AboutThisSiteValidation, ValidateProtos) { auto metadata = GetSampleMetaData(); - EXPECT_EQ(ValidateMetadata(metadata), AboutThisSiteStatus::kValid); + EXPECT_EQ(ValidateMetadata(metadata, /*allow_missing_description=*/false), + AboutThisSiteStatus::kValid); // The proto should still be valid without a timestamp. metadata.mutable_site_info()->clear_first_seen(); - EXPECT_EQ(ValidateMetadata(metadata), AboutThisSiteStatus::kValid); + EXPECT_EQ(ValidateMetadata(metadata, /*allow_missing_description=*/false), + AboutThisSiteStatus::kValid); } TEST(AboutThisSiteValidation, InvalidSiteInfoProto) { proto::AboutThisSiteMetadata metadata; - EXPECT_EQ(ValidateMetadata(metadata), AboutThisSiteStatus::kMissingSiteInfo); + EXPECT_EQ(ValidateMetadata(metadata, /*allow_missing_description=*/false), + AboutThisSiteStatus::kMissingSiteInfo); metadata.mutable_site_info(); - EXPECT_EQ(ValidateMetadata(metadata), AboutThisSiteStatus::kEmptySiteInfo); + EXPECT_EQ(ValidateMetadata(metadata, /*allow_missing_description=*/false), + AboutThisSiteStatus::kEmptySiteInfo); metadata = GetSampleMetaData(); metadata.mutable_site_info()->clear_description(); - EXPECT_EQ(ValidateMetadata(metadata), + EXPECT_EQ(ValidateMetadata(metadata, /*allow_missing_description=*/false), AboutThisSiteStatus::kMissingDescription); } @@ -102,39 +106,11 @@ // Test that a proto with only a more_about section is invalid unless both // kPageInfoAboutThisSiteMoreInfo and // kPageInfoAboutThisSiteDescriptionPlaceholder are enabled. + EXPECT_EQ(ValidateSiteInfo(site_info, /*allow_missing_description=*/false), + AboutThisSiteStatus::kMissingDescription); - { - base::test::ScopedFeatureList features; - features.InitWithFeatures({}, - {kPageInfoAboutThisSiteMoreInfo, - kPageInfoAboutThisSiteDescriptionPlaceholder}); - EXPECT_EQ(ValidateSiteInfo(site_info), - AboutThisSiteStatus::kMissingDescription); - } - - { - base::test::ScopedFeatureList features; - features.InitWithFeatures({kPageInfoAboutThisSiteMoreInfo}, - {kPageInfoAboutThisSiteDescriptionPlaceholder}); - EXPECT_EQ(ValidateSiteInfo(site_info), - AboutThisSiteStatus::kMissingDescription); - } - - { - base::test::ScopedFeatureList features; - features.InitWithFeatures({kPageInfoAboutThisSiteDescriptionPlaceholder}, - {kPageInfoAboutThisSiteMoreInfo}); - EXPECT_EQ(ValidateSiteInfo(site_info), - AboutThisSiteStatus::kMissingDescription); - } - - { - base::test::ScopedFeatureList features; - features.InitWithFeatures({kPageInfoAboutThisSiteMoreInfo, - kPageInfoAboutThisSiteDescriptionPlaceholder}, - {}); - EXPECT_EQ(ValidateSiteInfo(site_info), AboutThisSiteStatus::kValid); - } + EXPECT_EQ(ValidateSiteInfo(site_info, /*allow_missing_description=*/true), + AboutThisSiteStatus::kValid); } TEST(AboutThisSiteValidation, InvalidSource) { @@ -178,12 +154,14 @@ AboutThisSiteStatus::kInvalidMoreAbout); } -TEST(AboutThisSiteValidation, MissingMoreAbout_FeatureEDisabled) { +TEST(AboutThisSiteValidation, MissingMoreAbout_FeatureDisabled) { proto::AboutThisSiteMetadata meta_data = GetSampleMetaData(); - EXPECT_EQ(ValidateMetadata(meta_data), AboutThisSiteStatus::kValid); + EXPECT_EQ(ValidateMetadata(meta_data, /*allow_missing_description=*/true), + AboutThisSiteStatus::kValid); meta_data.mutable_site_info()->clear_more_about(); - EXPECT_EQ(ValidateMetadata(meta_data), AboutThisSiteStatus::kValid); + EXPECT_EQ(ValidateMetadata(meta_data, /*allow_missing_description=*/true), + AboutThisSiteStatus::kValid); } TEST(AboutThisSiteValidation, MissingMoreAbout_FeatureEnabled) { @@ -191,10 +169,11 @@ features.InitAndEnableFeature(kPageInfoAboutThisSiteMoreInfo); proto::AboutThisSiteMetadata meta_data = GetSampleMetaData(); - EXPECT_EQ(ValidateMetadata(meta_data), AboutThisSiteStatus::kValid); + EXPECT_EQ(ValidateMetadata(meta_data, /*allow_missing_description=*/true), + AboutThisSiteStatus::kValid); meta_data.mutable_site_info()->clear_more_about(); - EXPECT_EQ(ValidateMetadata(meta_data), + EXPECT_EQ(ValidateMetadata(meta_data, /*allow_missing_description=*/true), AboutThisSiteStatus::kMissingMoreAbout); }
diff --git a/components/page_info/core/features.cc b/components/page_info/core/features.cc index 4d13323..f889b41 100644 --- a/components/page_info/core/features.cc +++ b/components/page_info/core/features.cc
@@ -44,9 +44,6 @@ "PageInfoAboutThisSiteDescriptionPlaceholder", base::FEATURE_DISABLED_BY_DEFAULT}; -const base::Feature kAboutThisSitePersistentSidePanelEntry{ - "AboutThisSitePersistentSidePanelEntry", base::FEATURE_DISABLED_BY_DEFAULT}; - #if !BUILDFLAG(IS_ANDROID) const base::Feature kPageInfoHistoryDesktop{"PageInfoHistoryDesktop", base::FEATURE_DISABLED_BY_DEFAULT};
diff --git a/components/page_info/core/features.h b/components/page_info/core/features.h index 5161bc10..24a7d6d 100644 --- a/components/page_info/core/features.h +++ b/components/page_info/core/features.h
@@ -32,15 +32,16 @@ extern const base::FeatureParam<bool> kShowSampleContent; // Shows a link with more info about a site in PageInfo. +// Use page_info::IsAboutThisSiteFeatureEnabled() instead of checking this flag +// directly. extern const base::Feature kPageInfoAboutThisSiteMoreInfo; // Shows a placeholder when a description is missing. Only enable in combination // with kPageInfoAboutThisSiteMoreInfo. +// Use page_info::IsDescriptionPlaceholderEnabled() instead of checking this +// flag directly. extern const base::Feature kPageInfoAboutThisSiteDescriptionPlaceholder; -// Enables the persistent "About this site" entry in the side panel. -extern const base::Feature kAboutThisSitePersistentSidePanelEntry; - #if !BUILDFLAG(IS_ANDROID) // Enables the history section for Page Info on desktop. extern const base::Feature kPageInfoHistoryDesktop;
diff --git a/components/page_info_strings.grdp b/components/page_info_strings.grdp index 71da16a..37f24ee 100644 --- a/components/page_info_strings.grdp +++ b/components/page_info_strings.grdp
@@ -709,37 +709,37 @@ </message> <!-- Cookies subpage --> - <message name="IDS_PAGE_INFO_COOKIES_HEADER" desc="The header label of cookies subpage in Page Info bubble." translateable="false"> + <message name="IDS_PAGE_INFO_COOKIES_HEADER" desc="The header label of cookies subpage in Page Info bubble."> Cookies and site data </message> - <message name="IDS_PAGE_INFO_COOKIES_DESCRIPTION" desc="The descritpion of cookies in Cookies Subpage with placeholder for link to settings." translateable="false"> + <message name="IDS_PAGE_INFO_COOKIES_DESCRIPTION" desc="The descritpion of cookies in Cookies Subpage with placeholder for link to settings."> Cookies and other site data are used to remember you, for example to sign you in or to personalize ads. To manage cookies for all sites, see <ph name="SETTINGS">$1<ex>Settings</ex></ph>. </message> - <message name="IDS_PAGE_INFO_COOKIES_SETTINGS_LINK" desc="The text of the link to cookies settings." translateable="false"> + <message name="IDS_PAGE_INFO_COOKIES_SETTINGS_LINK" desc="The text of the link to cookies settings."> Settings </message> - <message name="IDS_PAGE_INFO_BLOCK_THIRD_PARTY_COOKIES_TITLE" desc="The title on the blocking third-party cookies toggle in cookies subpage." translateable="false"> + <message name="IDS_PAGE_INFO_BLOCK_THIRD_PARTY_COOKIES_TITLE" desc="The title on the blocking third-party cookies toggle in cookies subpage."> Block third-party cookies </message> - <message name="IDS_PAGE_INFO_BLOCK_THIRD_PARTY_COOKIES_TOGGLE_TOOLTIP" desc="The tooltip on the blocking third-party cookies toggle in cookies subpage." translateable="false"> + <message name="IDS_PAGE_INFO_BLOCK_THIRD_PARTY_COOKIES_TOGGLE_TOOLTIP" desc="The tooltip on the blocking third-party cookies toggle in cookies subpage. It is only used by screen reader so no screenshot for that."> Block third-party cookies </message> - <message name="IDS_PAGE_INFO_BLOCK_THIRD_PARTY_COOKIES_MANAGED_BY_SETTINGS_TOOLTIP" desc="The tooltip on the blocking third-party cookies icon in cookies subpage if blocking is explicitly set by user in cookies settings." translateable="false"> + <message name="IDS_PAGE_INFO_BLOCK_THIRD_PARTY_COOKIES_MANAGED_BY_SETTINGS_TOOLTIP" desc="The tooltip on the blocking third-party cookies icon in cookies subpage if blocking is explicitly set by user in cookies settings."> Managed by cookies settings </message> - <message name="IDS_PAGE_INFO_COOKIES_BLOCKED_SITES_COUNT" desc="The label of the count for sites that have blocked access to cookies on the page. This text will be shown on the blocking third-party cookies toggle." translateable="false"> - {NUM_COOKIES, plural, =0 {No sites} =1 {1 site} other {# sites}} blocked + <message name="IDS_PAGE_INFO_COOKIES_BLOCKED_SITES_COUNT" desc="The label of the count for sites that have blocked access to cookies on the page. This text will be shown on the blocking third-party cookies toggle."> + {NUM_COOKIES, plural, =0 {No sites blocked} =1 {1 site blocked} other {# sites blocked}} </message> - <message name="IDS_PAGE_INFO_COOKIES_BLOCKED_SITES_COUNT_WHEN_FPS_BLOCKED" desc="The label of the count for sites that have blocked access to cookies on the page when fps is blocked. This text will be shown on the blocking third-party cookies toggle." translateable="false"> - {NUM_COOKIES, plural, =0 {No sites} =1 {1 site} other {# sites}} blocked, including related sites + <message name="IDS_PAGE_INFO_COOKIES_BLOCKED_SITES_COUNT_WHEN_FPS_BLOCKED" desc="The label of the count for sites that have blocked access to cookies on the page when fps is blocked. This text will be shown on the blocking third-party cookies toggle."> + {NUM_COOKIES, plural, =0 {No sites blocked, including related sites} =1 {1 site blocked, including related sites} other {# sites blocked, including related sites}} </message> - <message name="IDS_PAGE_INFO_COOKIES_ALLOWED_SITES_COUNT" desc="The label of the count for sites with allowed cookies on the page. This text will be shown on the cookies dialog button." translateable="false"> - {NUM_COOKIES, plural,=0 {No sites} =1 {1 site} other {# sites}} allowed + <message name="IDS_PAGE_INFO_COOKIES_ALLOWED_SITES_COUNT" desc="The label of the count for sites with allowed cookies on the page. This text will be shown on the cookies dialog button."> + {NUM_COOKIES, plural, =0 {No sites allowed} =1 {1 site allowed} other {# sites allowed}} </message> - <message name="IDS_PAGE_INFO_COOKIES_DIALOG_BUTTON_TITLE" desc="The title on the button opening cookies in use dialog in cookies subpage." translateable="false"> + <message name="IDS_PAGE_INFO_COOKIES_DIALOG_BUTTON_TITLE" desc="The title on the button opening cookies in use dialog in cookies subpage."> Manage cookies and site data </message> - <message name="IDS_PAGE_INFO_COOKIES_DIALOG_BUTTON_TOOLTIP" desc="The text of the tooltip on the button opening cookies in use dialog in cookies subpage." translateable="false"> + <message name="IDS_PAGE_INFO_COOKIES_DIALOG_BUTTON_TOOLTIP" desc="The text of the tooltip on the button opening cookies in use dialog in cookies subpage."> Show cookies </message> <message name="IDS_PAGE_INFO_FPS_BUTTON_TOOLTIP" desc="The tooltip of first-party sets button in cookies subpage, which opens 'All Sites' settings page with a filter for this sets' pages." translateable="false"> @@ -749,7 +749,7 @@ See sites related to <ph name="SET_OWNER">$1<ex>gannett.com</ex></ph> </message> <message name="IDS_PAGE_INFO_FPS_BUTTON_SUBTITLE" desc="The subtitle of first-party sets button in cookies subpage with placeholder for name of the owner of this set." translateable="false"> - <ph name="SET_OWNER">$1<ex>gannett.com</ex></ph> says these sites are related + This site is in <ph name="SET_OWNER">$1<ex>gannett.com</ex></ph>'s group of sites that can see your activity in the group </message> <!-- History strings -->
diff --git a/components/page_info_strings_grdp/IDS_PAGE_INFO_BLOCK_THIRD_PARTY_COOKIES_MANAGED_BY_SETTINGS_TOOLTIP.png.sha1 b/components/page_info_strings_grdp/IDS_PAGE_INFO_BLOCK_THIRD_PARTY_COOKIES_MANAGED_BY_SETTINGS_TOOLTIP.png.sha1 new file mode 100644 index 0000000..487da69 --- /dev/null +++ b/components/page_info_strings_grdp/IDS_PAGE_INFO_BLOCK_THIRD_PARTY_COOKIES_MANAGED_BY_SETTINGS_TOOLTIP.png.sha1
@@ -0,0 +1 @@ +fb0d3c415768ac25459eb55c88a4eb3ee968b85a \ No newline at end of file
diff --git a/components/page_info_strings_grdp/IDS_PAGE_INFO_BLOCK_THIRD_PARTY_COOKIES_TITLE.png.sha1 b/components/page_info_strings_grdp/IDS_PAGE_INFO_BLOCK_THIRD_PARTY_COOKIES_TITLE.png.sha1 new file mode 100644 index 0000000..fbb6d07 --- /dev/null +++ b/components/page_info_strings_grdp/IDS_PAGE_INFO_BLOCK_THIRD_PARTY_COOKIES_TITLE.png.sha1
@@ -0,0 +1 @@ +fec756acb19721d0b51e261d70be0f2ec7e6bfee \ No newline at end of file
diff --git a/components/page_info_strings_grdp/IDS_PAGE_INFO_BLOCK_THIRD_PARTY_COOKIES_TOGGLE_TOOLTIP.png.sha1 b/components/page_info_strings_grdp/IDS_PAGE_INFO_BLOCK_THIRD_PARTY_COOKIES_TOGGLE_TOOLTIP.png.sha1 new file mode 100644 index 0000000..589f0f1 --- /dev/null +++ b/components/page_info_strings_grdp/IDS_PAGE_INFO_BLOCK_THIRD_PARTY_COOKIES_TOGGLE_TOOLTIP.png.sha1
@@ -0,0 +1 @@ +7d166033bbb1c31b66aaeafaa938dfb6bdcf82e4 \ No newline at end of file
diff --git a/components/page_info_strings_grdp/IDS_PAGE_INFO_COOKIES_ALLOWED_SITES_COUNT.png.sha1 b/components/page_info_strings_grdp/IDS_PAGE_INFO_COOKIES_ALLOWED_SITES_COUNT.png.sha1 new file mode 100644 index 0000000..589f0f1 --- /dev/null +++ b/components/page_info_strings_grdp/IDS_PAGE_INFO_COOKIES_ALLOWED_SITES_COUNT.png.sha1
@@ -0,0 +1 @@ +7d166033bbb1c31b66aaeafaa938dfb6bdcf82e4 \ No newline at end of file
diff --git a/components/page_info_strings_grdp/IDS_PAGE_INFO_COOKIES_BLOCKED_SITES_COINT_WHEN_FPS_BLOCKED.png.sha1 b/components/page_info_strings_grdp/IDS_PAGE_INFO_COOKIES_BLOCKED_SITES_COINT_WHEN_FPS_BLOCKED.png.sha1 new file mode 100644 index 0000000..589f0f1 --- /dev/null +++ b/components/page_info_strings_grdp/IDS_PAGE_INFO_COOKIES_BLOCKED_SITES_COINT_WHEN_FPS_BLOCKED.png.sha1
@@ -0,0 +1 @@ +7d166033bbb1c31b66aaeafaa938dfb6bdcf82e4 \ No newline at end of file
diff --git a/components/page_info_strings_grdp/IDS_PAGE_INFO_COOKIES_BLOCKED_SITES_COUNT.png.sha1 b/components/page_info_strings_grdp/IDS_PAGE_INFO_COOKIES_BLOCKED_SITES_COUNT.png.sha1 new file mode 100644 index 0000000..fbb6d07 --- /dev/null +++ b/components/page_info_strings_grdp/IDS_PAGE_INFO_COOKIES_BLOCKED_SITES_COUNT.png.sha1
@@ -0,0 +1 @@ +fec756acb19721d0b51e261d70be0f2ec7e6bfee \ No newline at end of file
diff --git a/components/page_info_strings_grdp/IDS_PAGE_INFO_COOKIES_BLOCKED_SITES_COUNT_WHEN_FPS_BLOCKED.png.sha1 b/components/page_info_strings_grdp/IDS_PAGE_INFO_COOKIES_BLOCKED_SITES_COUNT_WHEN_FPS_BLOCKED.png.sha1 new file mode 100644 index 0000000..589f0f1 --- /dev/null +++ b/components/page_info_strings_grdp/IDS_PAGE_INFO_COOKIES_BLOCKED_SITES_COUNT_WHEN_FPS_BLOCKED.png.sha1
@@ -0,0 +1 @@ +7d166033bbb1c31b66aaeafaa938dfb6bdcf82e4 \ No newline at end of file
diff --git a/components/page_info_strings_grdp/IDS_PAGE_INFO_COOKIES_DESCRIPTION.png.sha1 b/components/page_info_strings_grdp/IDS_PAGE_INFO_COOKIES_DESCRIPTION.png.sha1 new file mode 100644 index 0000000..589f0f1 --- /dev/null +++ b/components/page_info_strings_grdp/IDS_PAGE_INFO_COOKIES_DESCRIPTION.png.sha1
@@ -0,0 +1 @@ +7d166033bbb1c31b66aaeafaa938dfb6bdcf82e4 \ No newline at end of file
diff --git a/components/page_info_strings_grdp/IDS_PAGE_INFO_COOKIES_DIALOG_BUTTON_TITLE.png.sha1 b/components/page_info_strings_grdp/IDS_PAGE_INFO_COOKIES_DIALOG_BUTTON_TITLE.png.sha1 new file mode 100644 index 0000000..589f0f1 --- /dev/null +++ b/components/page_info_strings_grdp/IDS_PAGE_INFO_COOKIES_DIALOG_BUTTON_TITLE.png.sha1
@@ -0,0 +1 @@ +7d166033bbb1c31b66aaeafaa938dfb6bdcf82e4 \ No newline at end of file
diff --git a/components/page_info_strings_grdp/IDS_PAGE_INFO_COOKIES_DIALOG_BUTTON_TOOLTIP.png.sha1 b/components/page_info_strings_grdp/IDS_PAGE_INFO_COOKIES_DIALOG_BUTTON_TOOLTIP.png.sha1 new file mode 100644 index 0000000..ea9eef58 --- /dev/null +++ b/components/page_info_strings_grdp/IDS_PAGE_INFO_COOKIES_DIALOG_BUTTON_TOOLTIP.png.sha1
@@ -0,0 +1 @@ +a1a3d7b9ee1177c3a7f5ec4e8d0de47c90ffd5a4 \ No newline at end of file
diff --git a/components/page_info_strings_grdp/IDS_PAGE_INFO_COOKIES_HEADER.png.sha1 b/components/page_info_strings_grdp/IDS_PAGE_INFO_COOKIES_HEADER.png.sha1 new file mode 100644 index 0000000..589f0f1 --- /dev/null +++ b/components/page_info_strings_grdp/IDS_PAGE_INFO_COOKIES_HEADER.png.sha1
@@ -0,0 +1 @@ +7d166033bbb1c31b66aaeafaa938dfb6bdcf82e4 \ No newline at end of file
diff --git a/components/page_info_strings_grdp/IDS_PAGE_INFO_COOKIES_SETTINGS_LINK.png.sha1 b/components/page_info_strings_grdp/IDS_PAGE_INFO_COOKIES_SETTINGS_LINK.png.sha1 new file mode 100644 index 0000000..589f0f1 --- /dev/null +++ b/components/page_info_strings_grdp/IDS_PAGE_INFO_COOKIES_SETTINGS_LINK.png.sha1
@@ -0,0 +1 @@ +7d166033bbb1c31b66aaeafaa938dfb6bdcf82e4 \ No newline at end of file
diff --git a/components/password_manager/core/browser/fake_form_fetcher.cc b/components/password_manager/core/browser/fake_form_fetcher.cc index 4c28c04..3bce855 100644 --- a/components/password_manager/core/browser/fake_form_fetcher.cc +++ b/components/password_manager/core/browser/fake_form_fetcher.cc
@@ -117,4 +117,15 @@ for (Consumer& consumer : consumers_) consumer.OnFetchCompleted(); } + +absl::optional<PasswordStoreBackendError> +FakeFormFetcher::GetProfileStoreBackendError() const { + return profile_store_backend_error_; +} + +void FakeFormFetcher::SetProfileStoreBackendError( + absl::optional<PasswordStoreBackendError> error) { + profile_store_backend_error_ = error; +} + } // namespace password_manager
diff --git a/components/password_manager/core/browser/fake_form_fetcher.h b/components/password_manager/core/browser/fake_form_fetcher.h index ba82a8a0..f3d8ab46 100644 --- a/components/password_manager/core/browser/fake_form_fetcher.h +++ b/components/password_manager/core/browser/fake_form_fetcher.h
@@ -54,6 +54,8 @@ const PasswordForm* GetPreferredMatch() const override; // Returns a new FakeFormFetcher. std::unique_ptr<FormFetcher> Clone() override; + absl::optional<PasswordStoreBackendError> GetProfileStoreBackendError() + const override; void set_stats(const std::vector<InteractionsStats>& stats) { state_ = State::NOT_WAITING; @@ -78,6 +80,9 @@ void NotifyFetchCompleted(); + void SetProfileStoreBackendError( + absl::optional<PasswordStoreBackendError> error); + private: base::ObserverList<Consumer> consumers_; State state_ = State::NOT_WAITING; @@ -90,6 +95,7 @@ std::vector<const PasswordForm*> insecure_credentials_; const PasswordForm* preferred_match_ = nullptr; bool is_blocklisted_ = false; + absl::optional<PasswordStoreBackendError> profile_store_backend_error_; }; } // namespace password_manager
diff --git a/components/password_manager/core/browser/form_fetcher.h b/components/password_manager/core/browser/form_fetcher.h index 9c3d5eaa..f917a71 100644 --- a/components/password_manager/core/browser/form_fetcher.h +++ b/components/password_manager/core/browser/form_fetcher.h
@@ -12,6 +12,7 @@ #include "base/observer_list_types.h" #include "components/autofill/core/common/gaia_id_hash.h" #include "components/password_manager/core/browser/password_form.h" +#include "components/password_manager/core/browser/password_store_util.h" namespace password_manager { @@ -106,6 +107,11 @@ // Creates a copy of |*this| with contains the same credentials without the // need for calling Fetch(). virtual std::unique_ptr<FormFetcher> Clone() = 0; + + // Returns an error if it occurred during login retrieval from the + // profile store. + virtual absl::optional<PasswordStoreBackendError> + GetProfileStoreBackendError() const = 0; }; } // namespace password_manager
diff --git a/components/password_manager/core/browser/form_fetcher_impl.cc b/components/password_manager/core/browser/form_fetcher_impl.cc index 589037a..2cc9fd5 100644 --- a/components/password_manager/core/browser/form_fetcher_impl.cc +++ b/components/password_manager/core/browser/form_fetcher_impl.cc
@@ -11,6 +11,7 @@ #include "base/check_op.h" #include "base/containers/contains.h" +#include "base/notreached.h" #include "base/observer_list.h" #include "build/build_config.h" #include "components/autofill/core/common/save_password_progress_logger.h" @@ -21,6 +22,7 @@ #include "components/password_manager/core/browser/password_manager_client.h" #include "components/password_manager/core/browser/password_manager_util.h" #include "components/password_manager/core/browser/password_store_interface.h" +#include "components/password_manager/core/browser/password_store_util.h" #include "components/password_manager/core/browser/psl_matching_helper.h" #include "components/password_manager/core/browser/smart_bubble_stats_store.h" #include "components/password_manager/core/browser/statistics_table.h" @@ -233,10 +235,16 @@ result->insecure_credentials_ = MakeCopies(insecure_credentials_); result->state_ = state_; result->need_to_refetch_ = need_to_refetch_; + result->profile_store_backend_error_ = profile_store_backend_error_; return result; } +absl::optional<PasswordStoreBackendError> +FormFetcherImpl::GetProfileStoreBackendError() const { + return profile_store_backend_error_; +} + void FormFetcherImpl::FindMatchesAndNotifyConsumers( std::vector<std::unique_ptr<PasswordForm>> results) { DCHECK_EQ(State::WAITING, state_); @@ -292,6 +300,25 @@ void FormFetcherImpl::OnGetPasswordStoreResultsFrom( PasswordStoreInterface* store, std::vector<std::unique_ptr<PasswordForm>> results) { + NOTIMPLEMENTED(); +} + +void FormFetcherImpl::OnGetPasswordStoreResultsOrErrorFrom( + PasswordStoreInterface* store, + FormFetcherImpl::FormsOrError results_or_error) { + // TODO(https://crbug.com/1365324): Handle errors coming from the account + // store. + if (store == client_->GetProfilePasswordStore()) { + profile_store_backend_error_.reset(); + if (absl::holds_alternative<PasswordStoreBackendError>(results_or_error)) { + profile_store_backend_error_ = + absl::get<PasswordStoreBackendError>(results_or_error); + } + } + + std::vector<std::unique_ptr<PasswordForm>> results = + GetLoginsOrEmptyListOnFailure(std::move(results_or_error)); + DCHECK_EQ(State::WAITING, state_); DCHECK_GT(wait_counter_, 0);
diff --git a/components/password_manager/core/browser/form_fetcher_impl.h b/components/password_manager/core/browser/form_fetcher_impl.h index 387a784..29c50423 100644 --- a/components/password_manager/core/browser/form_fetcher_impl.h +++ b/components/password_manager/core/browser/form_fetcher_impl.h
@@ -58,6 +58,8 @@ const std::vector<const PasswordForm*>& GetBestMatches() const override; const PasswordForm* GetPreferredMatch() const override; std::unique_ptr<FormFetcher> Clone() override; + absl::optional<PasswordStoreBackendError> GetProfileStoreBackendError() + const override; protected: // Actually finds best matches and notifies consumers. @@ -104,6 +106,9 @@ PasswordStoreInterface* store, std::vector<std::unique_ptr<PasswordForm>> results) override; void OnGetSiteStatistics(std::vector<InteractionsStats> stats) override; + void OnGetPasswordStoreResultsOrErrorFrom( + PasswordStoreInterface* store, + FormsOrError results_or_error) override; // HttpPasswordStoreMigrator::Consumer: void ProcessMigratedForms( @@ -145,6 +150,10 @@ // remove themselves from the list during their destruction. base::ObserverList<FormFetcher::Consumer> consumers_; + // Holds an error if it occurred during login retrieval from the + // PasswordStore. + absl::optional<PasswordStoreBackendError> profile_store_backend_error_; + base::WeakPtrFactory<FormFetcherImpl> weak_ptr_factory_{this}; };
diff --git a/components/password_manager/core/browser/form_fetcher_impl_unittest.cc b/components/password_manager/core/browser/form_fetcher_impl_unittest.cc index 3398475..6437bc3 100644 --- a/components/password_manager/core/browser/form_fetcher_impl_unittest.cc +++ b/components/password_manager/core/browser/form_fetcher_impl_unittest.cc
@@ -24,6 +24,7 @@ #include "components/password_manager/core/browser/password_form.h" #include "components/password_manager/core/browser/password_manager_test_utils.h" #include "components/password_manager/core/browser/password_store_interface.h" +#include "components/password_manager/core/browser/password_store_util.h" #include "components/password_manager/core/browser/statistics_table.h" #include "components/password_manager/core/browser/stub_credentials_filter.h" #include "components/password_manager/core/browser/stub_password_manager_client.h" @@ -302,8 +303,8 @@ } void DeliverPasswordStoreResults( - std::vector<std::unique_ptr<PasswordForm>> profile_store_results, - std::vector<std::unique_ptr<PasswordForm>> account_store_results) { + PasswordStoreConsumer::FormsOrError profile_store_results, + PasswordStoreConsumer::FormsOrError account_store_results) { store_consumer()->OnGetPasswordStoreResultsOrErrorFrom( profile_mock_store_.get(), std::move(profile_store_results)); if (account_mock_store_) { @@ -1273,4 +1274,33 @@ Pointee(account_form_insecure_credential))); } +TEST_P(FormFetcherImplTest, BackendErrorResetsOnNewFetch) { + ASSERT_EQ(form_fetcher_->GetProfileStoreBackendError(), absl::nullopt); + + Fetch(); + + PasswordStoreBackendError error_results = PasswordStoreBackendError( + PasswordStoreBackendErrorType::kAuthErrorResolvable, + PasswordStoreBackendErrorRecoveryType::kRecoverable); + DeliverPasswordStoreResults( + /*profile_store_results=*/std::move(error_results), + /*account_store_results=*/{}); + + EXPECT_EQ(form_fetcher_->GetProfileStoreBackendError().value(), + PasswordStoreBackendError( + PasswordStoreBackendErrorType::kAuthErrorResolvable, + PasswordStoreBackendErrorRecoveryType::kRecoverable)); + + Fetch(); + + PasswordForm form = CreateNonFederated(); + std::vector<std::unique_ptr<PasswordForm>> form_results; + form_results.push_back(std::make_unique<PasswordForm>(form)); + + DeliverPasswordStoreResults(/*profile_store_results=*/std::move(form_results), + /*account_store_results=*/{}); + + EXPECT_EQ(form_fetcher_->GetProfileStoreBackendError(), absl::nullopt); +} + } // namespace password_manager
diff --git a/components/password_manager/core/browser/password_form_manager.cc b/components/password_manager/core/browser/password_form_manager.cc index 1f6cdafb..dd6885f 100644 --- a/components/password_manager/core/browser/password_form_manager.cc +++ b/components/password_manager/core/browser/password_form_manager.cc
@@ -34,10 +34,13 @@ #include "components/password_manager/core/browser/password_manager_driver.h" #include "components/password_manager/core/browser/password_manager_metrics_util.h" #include "components/password_manager/core/browser/password_manager_util.h" +#include "components/password_manager/core/browser/password_store_backend_error.h" #include "components/password_manager/core/browser/possible_username_data.h" #include "components/password_manager/core/browser/psl_matching_helper.h" #include "components/password_manager/core/browser/statistics_table.h" #include "components/password_manager/core/common/password_manager_features.h" +#include "components/password_manager/core/common/password_manager_pref_names.h" +#include "components/prefs/pref_service.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "google_apis/gaia/core_account_id.h" #include "third_party/abseil-cpp/absl/types/optional.h" @@ -113,6 +116,24 @@ message); } +#if BUILDFLAG(IS_ANDROID) +bool IsCurrentUserEvicted(PasswordManagerClient* client) { + return client->GetPrefs()->GetBoolean( + password_manager::prefs::kUnenrolledFromGoogleMobileServicesDueToErrors); +} + +bool ShouldShowErrorMessage( + absl::optional<PasswordStoreBackendError> backend_error, + PasswordManagerClient* client) { + return backend_error.has_value() && + backend_error.value().type == + PasswordStoreBackendErrorType::kAuthErrorResolvable && + !IsCurrentUserEvicted(client) && + base::FeatureList::IsEnabled( + password_manager::features::kUnifiedPasswordManagerErrorMessages); +} +#endif + } // namespace PasswordFormManager::PasswordFormManager( @@ -657,6 +678,25 @@ newly_blocklisted_ = false; autofills_left_ = kMaxTimesAutofill; +#if BUILDFLAG(IS_ANDROID) + absl::optional<PasswordStoreBackendError> backend_error = + form_fetcher_->GetProfileStoreBackendError(); + if (ShouldShowErrorMessage(backend_error, client_)) { + // If there is no FormData, this is an http authentication form. We don't + // show the message for it because it would be hidden behind a sign in + // dialog and the user could miss it. + if (observed_form() != nullptr) { + std::unique_ptr<PasswordForm> password_form = + parser_.Parse(*observed_form(), FormDataParser::Mode::kFilling); + client_->ShowPasswordManagerErrorMessage( + password_form->IsLikelySignupForm() || + password_form->IsLikelyChangePasswordForm() + ? password_manager::ErrorMessageFlowType::kSaveFlow + : password_manager::ErrorMessageFlowType::kFillFlow); + } + } +#endif + if (IsCredentialAPISave()) { // This is saving with credential API, there is no form to fill, so no // filling required.
diff --git a/components/password_manager/core/browser/password_form_manager_unittest.cc b/components/password_manager/core/browser/password_form_manager_unittest.cc index 9e49c78..ccc1fa37 100644 --- a/components/password_manager/core/browser/password_form_manager_unittest.cc +++ b/components/password_manager/core/browser/password_form_manager_unittest.cc
@@ -32,10 +32,12 @@ #include "components/autofill/core/common/unique_ids.h" #include "components/password_manager/core/browser/fake_form_fetcher.h" #include "components/password_manager/core/browser/field_info_manager.h" +#include "components/password_manager/core/browser/leak_detection_dialog_utils.h" #include "components/password_manager/core/browser/mock_password_change_success_tracker.h" #include "components/password_manager/core/browser/mock_webauthn_credentials_delegate.h" #include "components/password_manager/core/browser/password_form.h" #include "components/password_manager/core/browser/password_form_manager_for_ui.h" +#include "components/password_manager/core/browser/password_manager_client.h" #include "components/password_manager/core/browser/password_manager_metrics_util.h" #include "components/password_manager/core/browser/password_manager_util.h" #include "components/password_manager/core/browser/password_save_manager_impl.h" @@ -184,6 +186,12 @@ GetWebAuthnCredentialsDelegateForDriver, (PasswordManagerDriver*), (override)); +#if BUILDFLAG(IS_ANDROID) + MOCK_METHOD(void, + ShowPasswordManagerErrorMessage, + (password_manager::ErrorMessageFlowType), + (override)); +#endif }; void CheckPendingCredentials(const PasswordForm& expected, @@ -338,6 +346,11 @@ true); pref_service_.registry()->RegisterStringPref( autofill::prefs::kAutofillUploadEncodingSeed, "seed"); +#if BUILDFLAG(IS_ANDROID) + pref_service_.registry()->RegisterBooleanPref( + password_manager::prefs::kUnenrolledFromGoogleMobileServicesDueToErrors, + false); +#endif #if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN) pref_service_.registry()->RegisterBooleanPref( password_manager::prefs::kBiometricAuthenticationBeforeFilling, true); @@ -2758,6 +2771,72 @@ 1); } +#if BUILDFLAG(IS_ANDROID) +TEST_P(PasswordFormManagerTest, ClientShouldShowErrorMessage) { + base::test::ScopedFeatureList feature_list; + feature_list.InitAndEnableFeature( + features::kUnifiedPasswordManagerErrorMessages); + fetcher_->SetProfileStoreBackendError(PasswordStoreBackendError( + PasswordStoreBackendErrorType::kAuthErrorResolvable, + PasswordStoreBackendErrorRecoveryType::kRecoverable)); + + EXPECT_CALL(client_, ShowPasswordManagerErrorMessage); + fetcher_->NotifyFetchCompleted(); +} + +TEST_P(PasswordFormManagerTest, + ClientShouldNotShowErrorMessageWhenFeatureIsDisabled) { + base::test::ScopedFeatureList feature_list; + feature_list.InitAndDisableFeature( + features::kUnifiedPasswordManagerErrorMessages); + fetcher_->SetProfileStoreBackendError(PasswordStoreBackendError( + PasswordStoreBackendErrorType::kAuthErrorResolvable, + PasswordStoreBackendErrorRecoveryType::kRecoverable)); + + EXPECT_CALL(client_, ShowPasswordManagerErrorMessage).Times(0); + fetcher_->NotifyFetchCompleted(); +} + +TEST_P(PasswordFormManagerTest, + ClientShouldNotShowErrorMessageWhenThereIsNoError) { + base::test::ScopedFeatureList feature_list; + feature_list.InitAndEnableFeature( + features::kUnifiedPasswordManagerErrorMessages); + fetcher_->SetProfileStoreBackendError(absl::nullopt); + + EXPECT_CALL(client_, ShowPasswordManagerErrorMessage).Times(0); + fetcher_->NotifyFetchCompleted(); +} + +TEST_P(PasswordFormManagerTest, + ClientShouldNotShowErrorMessageWhenErrorIsNotAuthError) { + base::test::ScopedFeatureList feature_list; + feature_list.InitAndEnableFeature( + features::kUnifiedPasswordManagerErrorMessages); + fetcher_->SetProfileStoreBackendError(PasswordStoreBackendError( + PasswordStoreBackendErrorType::kUncategorized, + PasswordStoreBackendErrorRecoveryType::kUnspecified)); + + EXPECT_CALL(client_, ShowPasswordManagerErrorMessage).Times(0); + fetcher_->NotifyFetchCompleted(); +} + +TEST_P(PasswordFormManagerTest, ClientShouldNotShowErrorMessageWhenUnenrolled) { + base::test::ScopedFeatureList feature_list; + feature_list.InitAndEnableFeature( + features::kUnifiedPasswordManagerErrorMessages); + client_.GetPrefs()->SetBoolean( + password_manager::prefs::kUnenrolledFromGoogleMobileServicesDueToErrors, + true); + fetcher_->SetProfileStoreBackendError(PasswordStoreBackendError( + PasswordStoreBackendErrorType::kAuthErrorResolvable, + PasswordStoreBackendErrorRecoveryType::kRecoverable)); + + EXPECT_CALL(client_, ShowPasswordManagerErrorMessage).Times(0); + fetcher_->NotifyFetchCompleted(); +} +#endif + INSTANTIATE_TEST_SUITE_P(All, PasswordFormManagerTest, testing::Values(false, true));
diff --git a/components/password_manager/core/browser/password_manager.cc b/components/password_manager/core/browser/password_manager.cc index 2e2dbce..a79d76e 100644 --- a/components/password_manager/core/browser/password_manager.cc +++ b/components/password_manager/core/browser/password_manager.cc
@@ -289,6 +289,8 @@ prefs::kUnenrolledFromGoogleMobileServicesDueToErrors, false); registry->RegisterIntegerPref( prefs::kUnenrolledFromGoogleMobileServicesAfterApiErrorCode, 0); + registry->RegisterIntegerPref( + prefs::kUnenrolledFromGoogleMobileServicesWithErrorListVersion, 0); registry->RegisterStringPref(prefs::kUPMErrorUIShownTimestamp, "0"); #endif // Preferences for |PasswordChangeSuccessTracker|.
diff --git a/components/password_manager/core/browser/password_manager_client.cc b/components/password_manager/core/browser/password_manager_client.cc index b17709c..47bd4bee 100644 --- a/components/password_manager/core/browser/password_manager_client.cc +++ b/components/password_manager/core/browser/password_manager_client.cc
@@ -33,6 +33,9 @@ } #if BUILDFLAG(IS_ANDROID) +void PasswordManagerClient::ShowPasswordManagerErrorMessage( + ErrorMessageFlowType flow_type) {} + void PasswordManagerClient::ShowTouchToFill( PasswordManagerDriver* driver, autofill::mojom::SubmissionReadinessState submission_readiness) {}
diff --git a/components/password_manager/core/browser/password_manager_client.h b/components/password_manager/core/browser/password_manager_client.h index 77e455e..d78d5d2 100644 --- a/components/password_manager/core/browser/password_manager_client.h +++ b/components/password_manager/core/browser/password_manager_client.h
@@ -99,6 +99,8 @@ kAccountPasswordsActiveNormalEncryption }; +enum class ErrorMessageFlowType { kSaveFlow, kFillFlow }; + // An abstraction of operations that depend on the embedders (e.g. Chrome) // environment. PasswordManagerClient is instantiated once per WebContents. // Main frame w.r.t WebContents refers to the primary main frame so usages of @@ -190,6 +192,10 @@ CredentialsCallback callback) = 0; #if BUILDFLAG(IS_ANDROID) + // Shows the error message that suggests the user to sign in to "save" or + // "use" passwords, depending on the |flow_type|. + virtual void ShowPasswordManagerErrorMessage(ErrorMessageFlowType flow_type); + // Instructs the client to show the Touch To Fill UI. virtual void ShowTouchToFill( PasswordManagerDriver* driver,
diff --git a/components/password_manager/core/common/password_manager_features.cc b/components/password_manager/core/common/password_manager_features.cc index ba0852e..1c9c98e4 100644 --- a/components/password_manager/core/common/password_manager_features.cc +++ b/components/password_manager/core/common/password_manager_features.cc
@@ -301,6 +301,12 @@ // is lower than 'kMigrationVersion' passwords will be re-uploaded. extern const base::FeatureParam<int> kMigrationVersion = { &kUnifiedPasswordManagerAndroid, "migration_version", 1}; + +// Current version of the GMS Core API errors lists. Users save this value on +// eviction due to error and will only be re-enrolled to the experiment if the +// configured version is greater than the saved one. +extern const base::FeatureParam<int> kGmsApiErrorListVersion = { + &kUnifiedPasswordManagerAndroid, "api_error_list_version", 0}; #endif // Field trial identifier for password generation requirements.
diff --git a/components/password_manager/core/common/password_manager_features.h b/components/password_manager/core/common/password_manager_features.h index 5578628..817d2b9 100644 --- a/components/password_manager/core/common/password_manager_features.h +++ b/components/password_manager/core/common/password_manager_features.h
@@ -101,6 +101,7 @@ #if BUILDFLAG(IS_ANDROID) extern const base::FeatureParam<int> kMigrationVersion; +extern const base::FeatureParam<int> kGmsApiErrorListVersion; constexpr base::FeatureParam<UpmExperimentVariation>::Option kUpmExperimentVariationOption[] = { {UpmExperimentVariation::kEnableForSyncingUsers, "0"},
diff --git a/components/password_manager/core/common/password_manager_pref_names.cc b/components/password_manager/core/common/password_manager_pref_names.cc index 374e06548..4a32fa36 100644 --- a/components/password_manager/core/common/password_manager_pref_names.cc +++ b/components/password_manager/core/common/password_manager_pref_names.cc
@@ -40,6 +40,8 @@ "unenrolled_from_google_mobile_services_due_to_errors"; const char kUnenrolledFromGoogleMobileServicesAfterApiErrorCode[] = "unenrolled_from_google_mobile_services_after_api_error_code"; +const char kUnenrolledFromGoogleMobileServicesWithErrorListVersion[] = + "unenrolled_from_google_mobile_services_with_error_list_version"; const char kUPMErrorUIShownTimestamp[] = "profile.upm_error_ui_shown_timestamp"; #endif
diff --git a/components/password_manager/core/common/password_manager_pref_names.h b/components/password_manager/core/common/password_manager_pref_names.h index 65787f7f..a4a3456 100644 --- a/components/password_manager/core/common/password_manager_pref_names.h +++ b/components/password_manager/core/common/password_manager_pref_names.h
@@ -98,6 +98,12 @@ // |kUnenrolledFromGoogleMobileServicesDueToErrors| is true. extern const char kUnenrolledFromGoogleMobileServicesAfterApiErrorCode[]; +// Integer value indicating the version of the ignored/retriable error list +// during the last unenrollment from the UPM experience. User will not be +// re-enrolled if this value is set and is not less than the in the current +// error list version. +extern const char kUnenrolledFromGoogleMobileServicesWithErrorListVersion[]; + // Timestamp at which the last UPM error message was shown to the user in // milliseconds since UNIX epoch (used in Java). // This is needed to ensure that the UI is prompted only once per given
diff --git a/components/policy/core/browser/webui/policy_status_provider.cc b/components/policy/core/browser/webui/policy_status_provider.cc index 9aea28ad..4fd54f0 100644 --- a/components/policy/core/browser/webui/policy_status_provider.cc +++ b/components/policy/core/browser/webui/policy_status_provider.cc
@@ -65,12 +65,14 @@ PolicyStatusProvider::~PolicyStatusProvider() = default; -void PolicyStatusProvider::SetStatusChangeCallback( - const base::RepeatingClosure& callback) { - callback_ = callback; +void PolicyStatusProvider::AddObserver(Observer* observer) { + observers_.AddObserver(observer); } -// static +void PolicyStatusProvider::RemoveObserver(Observer* observer) { + observers_.RemoveObserver(observer); +} + base::Value::Dict PolicyStatusProvider::GetStatus() { // This method is called when the client is not enrolled. // Thus return an empty dictionary. @@ -78,8 +80,8 @@ } void PolicyStatusProvider::NotifyStatusChange() { - if (callback_) - callback_.Run(); + for (auto& observer : observers_) + observer.OnPolicyStatusChanged(); } // static
diff --git a/components/policy/core/browser/webui/policy_status_provider.h b/components/policy/core/browser/webui/policy_status_provider.h index d9a3569a..6300c8b 100644 --- a/components/policy/core/browser/webui/policy_status_provider.h +++ b/components/policy/core/browser/webui/policy_status_provider.h
@@ -8,6 +8,8 @@ #include <memory> #include "base/callback_helpers.h" +#include "base/observer_list.h" +#include "base/observer_list_types.h" #include "base/time/clock.h" #include "base/time/time.h" #include "base/values.h" @@ -33,14 +35,16 @@ // actual policies themselves. class POLICY_EXPORT PolicyStatusProvider { public: + class Observer : public base::CheckedObserver { + public: + virtual void OnPolicyStatusChanged() = 0; + }; + PolicyStatusProvider(); PolicyStatusProvider(const PolicyStatusProvider&) = delete; PolicyStatusProvider& operator=(const PolicyStatusProvider&) = delete; virtual ~PolicyStatusProvider(); - // Sets a callback to invoke upon status changes. - virtual void SetStatusChangeCallback(const base::RepeatingClosure& callback); - // Returns a dictionary with metadata about policies. virtual base::Value::Dict GetStatus(); @@ -53,6 +57,9 @@ static base::ScopedClosureRunner OverrideClockForTesting( base::Clock* clock_for_testing); + void AddObserver(Observer* observer); + void RemoveObserver(Observer* observer); + protected: void NotifyStatusChange(); static std::u16string GetPolicyStatusFromStore(const CloudPolicyStore*, @@ -60,7 +67,7 @@ static std::u16string GetTimeSinceLastActionString(base::Time); private: - base::RepeatingClosure callback_; + base::ObserverList<Observer, /*check_empty=*/true> observers_; }; } // namespace policy
diff --git a/components/policy/resources/templates/common_schemas.yaml b/components/policy/resources/templates/common_schemas.yaml index fa12ef3..9342882 100644 --- a/components/policy/resources/templates/common_schemas.yaml +++ b/components/policy/resources/templates/common_schemas.yaml
@@ -187,14 +187,6 @@ - FINGERPRINT type: string type: array -QuickUnlockModeWhitelist: - items: - enum: - - all - - PIN - - FINGERPRINT - type: string - type: array Time: description: Time interpreted in local wall-clock 24h format. properties: @@ -218,13 +210,6 @@ minimum: 0 type: integer type: object -UsbDeviceId: - properties: - product_id: - type: integer - vendor_id: - type: integer - type: object UsbDeviceIdInclusive: properties: product_id:
diff --git a/components/policy/resources/templates/device_policy_proto_map.yaml b/components/policy/resources/templates/device_policy_proto_map.yaml index fc79562..52769e10 100644 --- a/components/policy/resources/templates/device_policy_proto_map.yaml +++ b/components/policy/resources/templates/device_policy_proto_map.yaml
@@ -1,6 +1,5 @@ # Mapping between device policies and fields in chrome_device_policy.proto. # Code for these policies can be generated. Add new device policies here! - AllowKioskAppControlChromeVersion: allow_kiosk_app_control_chrome_version.allow_kiosk_app_control_chrome_version AttestationEnabledForDevice: attestation_settings.attestation_enabled AttestationForContentProtectionEnabled: attestation_settings.content_protection_enabled @@ -111,6 +110,7 @@ DeviceRebootOnShutdown: reboot_on_shutdown.reboot_on_shutdown DeviceRebootOnUserSignout: device_reboot_on_user_signout.reboot_on_signout_mode DeviceReleaseLtsTag: release_channel.release_lts_tag +DeviceReportXDREvents: device_report_xdr_events.enabled DeviceRestrictedManagedGuestSessionEnabled: device_restricted_managed_guest_session_enabled.enabled DeviceRollbackAllowedMilestones: auto_update_settings.rollback_allowed_milestones DeviceRollbackToTargetVersion: auto_update_settings.rollback_to_target_version
diff --git a/components/policy/resources/templates/legacy_device_policy_proto_map.yaml b/components/policy/resources/templates/legacy_device_policy_proto_map.yaml index 6800135..b4c5772e 100644 --- a/components/policy/resources/templates/legacy_device_policy_proto_map.yaml +++ b/components/policy/resources/templates/legacy_device_policy_proto_map.yaml
@@ -7,8 +7,8 @@ # Add removed policies mapping here. -'': - - device_reporting.report_running_kiosk_app +? '' +: - device_reporting.report_running_kiosk_app - camera_enabled.camera_enabled - auto_update_settings.target_version_display_name
diff --git a/components/policy/resources/templates/policies.yaml b/components/policy/resources/templates/policies.yaml index 4b88f6b8..38e1973 100644 --- a/components/policy/resources/templates/policies.yaml +++ b/components/policy/resources/templates/policies.yaml
@@ -27,11 +27,11 @@ 26: AuthSchemes 27: DisableAuthNegotiateCnameLookup 28: EnableAuthNegotiatePort - 29: AuthServerWhitelist - 30: AuthNegotiateDelegateWhitelist + 29: '' + 30: '' 31: GSSAPILibraryName - 32: ExtensionInstallBlacklist - 33: ExtensionInstallWhitelist + 32: '' + 33: '' 34: ExtensionInstallForcelist 35: ShowHomeButton 36: DeveloperToolsDisabled @@ -101,8 +101,8 @@ 100: ImportSearchEngine 101: ImportSavedPasswords 102: AutoSelectCertificateForUrls - 103: URLBlacklist - 104: URLWhitelist + 103: '' + 104: '' 105: NotificationsAllowedForUrls 106: NotificationsBlockedForUrls 107: OpenNetworkConfiguration @@ -120,7 +120,7 @@ 119: ReportDeviceVersionInfo 120: ReportDeviceActivityTimes 121: ReportDeviceBootMode - 122: DeviceUserWhitelist + 122: '' 123: DeviceAllowNewUsers 124: DeviceGuestModeEnabled 125: DeviceShowUserNamesOnSignin @@ -199,7 +199,7 @@ 198: IdleWarningDelayBattery 199: DeviceVariationsRestrictParameter 200: AttestationEnabledForUser - 201: AttestationExtensionWhitelist + 201: '' 202: DeviceLocalAccountAutoLoginBailoutEnabled 203: AllowScreenWakeLocks 204: '' @@ -249,8 +249,8 @@ 248: ReportDeviceUsers 249: UserAvatarImage 250: DeviceLocalAccountPromptForNetworkWhenOffline - 251: NativeMessagingBlacklist - 252: NativeMessagingWhitelist + 251: '' + 252: '' 253: NativeMessagingUserLevelHosts 254: SAMLOfflineSigninTimeLimit 255: VirtualKeyboardEnabled @@ -320,7 +320,7 @@ 319: AllowKioskAppControlChromeVersion 320: DefaultWebBluetoothGuardSetting 321: LoginAuthenticationBehavior - 322: UsbDetachableWhitelist + 322: '' 323: DeviceAllowBluetooth 324: SuppressUnsupportedOSWarning 325: DeviceQuirksDownloadEnabled @@ -350,7 +350,7 @@ 349: ReportArcStatusEnabled 350: NativePrinters 351: NetworkThrottlingEnabled - 352: QuickUnlockModeWhitelist + 352: '' 353: QuickUnlockTimeout 354: PinUnlockMinimumLength 355: PinUnlockMaximumLength @@ -375,19 +375,19 @@ 374: DeviceEcryptfsMigrationStrategy 375: SafeBrowsingForTrustedSourcesEnabled 376: EcryptfsMigrationStrategy - 377: NoteTakingAppsLockScreenWhitelist + 377: '' 378: CastReceiverEnabled 379: CastReceiverName 380: DeviceOffHours 381: CloudPolicyOverridesPlatformPolicy 382: NativePrintersBulkConfiguration - 383: NativePrintersBulkAccessMode - 384: NativePrintersBulkBlacklist - 385: NativePrintersBulkWhitelist + 383: '' + 384: '' + 385: '' 386: DeviceNativePrinters - 387: DeviceNativePrintersAccessMode - 388: DeviceNativePrintersBlacklist - 389: DeviceNativePrintersWhitelist + 387: '' + 388: '' + 389: '' 390: TPMFirmwareUpdateSettings 391: RunAllFlashInAllowMode 392: AutofillCreditCardEnabled @@ -420,7 +420,7 @@ 419: RelaunchNotification 420: RelaunchNotificationPeriod 421: VirtualMachinesAllowed - 422: SafeBrowsingWhitelistDomains + 422: '' 423: PasswordProtectionLoginURLs 424: PasswordProtectionChangePasswordURL 425: DeviceMachinePasswordChangeRate @@ -429,7 +429,7 @@ 428: MachineLevelUserCloudPolicyEnrollmentToken 429: SafeBrowsingExtendedReportingEnabled 430: AutoplayAllowed - 431: AutoplayWhitelist + 431: '' 432: TabUnderAllowed 433: UserNativePrintersAllowed 434: DefaultWebUsbGuardSetting @@ -534,7 +534,7 @@ 533: AllowPopupsDuringPageUnload 534: RemoteAccessHostAllowFileTransfer 535: DeviceWilcoDtcConfiguration - 536: SpellcheckLanguageBlacklist + 536: '' 537: DeviceWiFiAllowed 538: DevicePowerPeakShiftEnabled 539: DevicePowerPeakShiftBatteryThreshold @@ -629,7 +629,7 @@ 628: DeviceLoginScreenScreenMagnifierType 629: CorsMitigationList 630: CorsLegacyModeEnabled - 631: ExternalPrintServersWhitelist + 631: '' 632: ExternalProtocolDialogShowAlwaysOpenCheckbox 633: DefaultInsecureContentSetting 634: InsecureContentAllowedForUrls @@ -656,13 +656,13 @@ 655: PrimaryMouseButtonSwitch 656: ReportDeviceCpuInfo 657: DeviceLoginScreenPrimaryMouseButtonSwitch - 658: PerAppTimeLimitsWhitelist + 658: '' 659: AccessibilityShortcutsEnabled 660: ReportDeviceGraphicsStatus 661: DeviceLoginScreenAccessibilityShortcutsEnabled 662: LocalDiscoveryEnabled 663: ChromeVariations - 664: PrintingAPIExtensionsWhitelist + 664: '' 665: ReportDeviceCrashReportInfo 666: ScreenCaptureAllowed 667: AdvancedProtectionDeepScanningEnabled @@ -1008,7 +1008,16 @@ 1007: DevicePrintingClientNameTemplate 1008: ReportDeviceSignalStrengthEventDrivenTelemetry 1009: BatterySaverModeAvailability + 1010: TabDiscardingExceptions + 1011: AssistantWebEnabled + 1012: LacrosDataBackwardMigrationMode + 1013: StrictMimetypeCheckForWorkerScriptsEnabled + 1014: RecoveryFactorBehavior + 1015: CalendarIntegrationEnabled + 1016: DeviceReportXDREvents + 1017: TrashEnabled 1018: ShoppingListEnabled + 1019: DeskAPIThirdPartyAccessEnabled atomic_groups: 1: Homepage 2: RemoteAccess
diff --git a/components/policy/resources/templates/policy_definitions/Crostini/CrostiniArcAdbSideloadingAllowed.yaml b/components/policy/resources/templates/policy_definitions/Crostini/CrostiniArcAdbSideloadingAllowed.yaml index 1fab1e2..8301d74c 100644 --- a/components/policy/resources/templates/policy_definitions/Crostini/CrostiniArcAdbSideloadingAllowed.yaml +++ b/components/policy/resources/templates/policy_definitions/Crostini/CrostiniArcAdbSideloadingAllowed.yaml
@@ -22,7 +22,7 @@ name: Allow value: 1 owners: -- janagrill@chromium.org +- janagrill@google.com - okalitova@chromium.org schema: enum:
diff --git a/components/policy/resources/templates/policy_definitions/Crostini/DeviceCrostiniArcAdbSideloadingAllowed.yaml b/components/policy/resources/templates/policy_definitions/Crostini/DeviceCrostiniArcAdbSideloadingAllowed.yaml index 1824977..405ab357 100644 --- a/components/policy/resources/templates/policy_definitions/Crostini/DeviceCrostiniArcAdbSideloadingAllowed.yaml +++ b/components/policy/resources/templates/policy_definitions/Crostini/DeviceCrostiniArcAdbSideloadingAllowed.yaml
@@ -25,7 +25,7 @@ name: AllowForAffiliatedUsers value: 2 owners: -- janagrill@chromium.org +- janagrill@google.com - okalitova@chromium.org schema: enum:
diff --git a/components/policy/resources/templates/policy_definitions/DateAndTime/CalendarIntegrationEnabled.yaml b/components/policy/resources/templates/policy_definitions/DateAndTime/CalendarIntegrationEnabled.yaml new file mode 100644 index 0000000..4c530a6 --- /dev/null +++ b/components/policy/resources/templates/policy_definitions/DateAndTime/CalendarIntegrationEnabled.yaml
@@ -0,0 +1,29 @@ +caption: Enable <ph name="GOOGLE_CALENDAR_NAME">Google Calendar</ph> Integration +default: true +default_for_enterprise_users: false +desc: |- + Enable <ph name="GOOGLE_CALENDAR_NAME">Google Calendar</ph> integration which allows <ph name="PRODUCT_OS_NAME">$2<ex>Google ChromeOS</ex></ph> users to fetch events from <ph name="GOOGLE_CALENDAR_NAME">Google Calendar</ph> to populate <ph name="PRODUCT_OS_NAME">$2<ex>Google ChromeOS</ex></ph> calendar widget in system status bar. + + If this policy is enabled, <ph name="PRODUCT_OS_NAME">$2<ex>Google ChromeOS</ex></ph> device can retrieve <ph name="GOOGLE_CALENDAR_NAME">Google Calendar</ph> events to populate <ph name="PRODUCT_OS_NAME">$2<ex>Google ChromeOS</ex></ph> calendar widget in system status bar for the logged in user. + + If this policy is disabled, <ph name="PRODUCT_OS_NAME">$2<ex>Google ChromeOS</ex></ph> device cannot retrieve <ph name="GOOGLE_CALENDAR_NAME">Google Calendar</ph> events to populate <ph name="PRODUCT_OS_NAME">$2<ex>Google ChromeOS</ex></ph> calendar widget in system status bar for the logged in user. + + If this policy is left unset, the <ph name="GOOGLE_CALENDAR_NAME">Google Calendar</ph> feature is disabled by default for enterprise users. +example_value: true +features: + dynamic_refresh: true + per_profile: true +future_on: +- chrome_os +items: +- caption: Enable <ph name="GOOGLE_CALENDAR_NAME">Google Calendar</ph> Integration. + value: true +- caption: Disable <ph name="GOOGLE_CALENDAR_NAME">Google Calendar</ph> Integration. + value: false +owners: +- ramyagopalan@google.com +- jiamingc@google.com +schema: + type: boolean +tags: [] +type: main
diff --git a/components/policy/resources/templates/policy_definitions/DateAndTime/policy_atomic_groups.yaml b/components/policy/resources/templates/policy_definitions/DateAndTime/policy_atomic_groups.yaml index 3e5dd679..667bf1c 100644 --- a/components/policy/resources/templates/policy_definitions/DateAndTime/policy_atomic_groups.yaml +++ b/components/policy/resources/templates/policy_definitions/DateAndTime/policy_atomic_groups.yaml
@@ -1,5 +1,6 @@ DateAndTime: caption: Date and time policies: + - CalendarIntegrationEnabled - SystemTimezone - SystemTimezoneAutomaticDetection
diff --git a/components/policy/resources/templates/policy_definitions/Extensions/BlockExternalExtensions.yaml b/components/policy/resources/templates/policy_definitions/Extensions/BlockExternalExtensions.yaml index ba8f8483..7f724d4 100644 --- a/components/policy/resources/templates/policy_definitions/Extensions/BlockExternalExtensions.yaml +++ b/components/policy/resources/templates/policy_definitions/Extensions/BlockExternalExtensions.yaml
@@ -1,12 +1,9 @@ caption: Blocks external extensions from being installed -desc: |- -Controls external extensions installation. - -Setting this policy to Enabled blocks external extensions from being installed. - -Setting this policy to Disabled or leaving it unset allows external extensions to be installed. - -External extensions and their installation are documented at https://developer.chrome.com/apps/external_extensions. +desc: "Controls external extensions installation.\n\n Setting this policy to\ + \ Enabled blocks external extensions from being installed.\n\n Setting this\ + \ policy to Disabled or leaving it unset allows external extensions to be installed.\n\ + \n External extensions and their installation are documented at https://developer.chrome.com/apps/external_extensions.\n\ + \ " example_value: true features: dynamic_refresh: false
diff --git a/components/policy/resources/templates/policy_definitions/Extensions/ExtensionInstallForcelist.yaml b/components/policy/resources/templates/policy_definitions/Extensions/ExtensionInstallForcelist.yaml index f8567e9..8091186f 100644 --- a/components/policy/resources/templates/policy_definitions/Extensions/ExtensionInstallForcelist.yaml +++ b/components/policy/resources/templates/policy_definitions/Extensions/ExtensionInstallForcelist.yaml
@@ -1,4 +1,5 @@ -arc_support: Android apps can be force-installed from the Google Admin console using Google Play. They do not use this policy. +arc_support: Android apps can be force-installed from the Google Admin console using + Google Play. They do not use this policy. caption: Configure the list of force-installed apps and extensions desc: |- Setting the policy specifies a list of apps and extensions that install silently, without user interaction, and which users can't uninstall or turn off. Permissions are granted implicitly, including for the enterprise.deviceAttributes and enterprise.platformKeys extension APIs. (These 2 APIs aren't available to apps and extensions that aren't force-installed.)
diff --git a/components/policy/resources/templates/policy_definitions/Extensions/policy_atomic_groups.yaml b/components/policy/resources/templates/policy_definitions/Extensions/policy_atomic_groups.yaml index 01cff1d..0f93084f 100644 --- a/components/policy/resources/templates/policy_definitions/Extensions/policy_atomic_groups.yaml +++ b/components/policy/resources/templates/policy_definitions/Extensions/policy_atomic_groups.yaml
@@ -3,8 +3,6 @@ policies: - ExtensionInstallAllowlist - ExtensionInstallBlocklist - - ExtensionInstallBlacklist - - ExtensionInstallWhitelist - ExtensionInstallForcelist - ExtensionInstallSources - ExtensionAllowedTypes
diff --git a/components/policy/resources/templates/policy_definitions/FirstPartySets/FirstPartySetsOverrides.yaml b/components/policy/resources/templates/policy_definitions/FirstPartySets/FirstPartySetsOverrides.yaml index d767224..4ff45bad 100644 --- a/components/policy/resources/templates/policy_definitions/FirstPartySets/FirstPartySetsOverrides.yaml +++ b/components/policy/resources/templates/policy_definitions/FirstPartySets/FirstPartySetsOverrides.yaml
@@ -35,23 +35,23 @@ This policy is available only on Windows instances that are joined to a <ph name="MS_AD_NAME">Microsoft® Active Directory®</ph> domain or Windows 10 Pro or Enterprise instances that are enrolled for device management, and macOS instances that are managed via MDM or joined to a domain via MCX. example_value: additions: - - ccTLDs: - https://member2.test: - - https://member2.com - members: - - https://member2.test - owner: https://owner2.test + - associatedSites: + - https://associate2.test + ccTLDs: + https://associate2.test: + - https://associate2.com + primary: https://primary2.test serviceSites: - - https://owner2-content.test + - https://associate2-content.test replacements: - - ccTLDs: - https://owner1.test: - - https://owner1.co.uk - members: - - https://member1.test - owner: https://owner1.test + - associatedSites: + - https://associate1.test + ccTLDs: + https://associate1.test: + - https://associate1.co.uk + primary: https://primary1.test serviceSites: - - https://owner1-content.test + - https://associate1-content.test features: dynamic_refresh: false per_profile: true @@ -69,49 +69,49 @@ additions: items: properties: + associatedSites: + items: + type: string + type: array ccTLDs: additionalProperties: items: type: string type: array type: object - members: - items: - type: string - type: array - owner: + primary: type: string serviceSites: items: type: string type: array required: - - owner - - members + - primary + - associatedSites type: object type: array replacements: items: properties: + associatedSites: + items: + type: string + type: array ccTLDs: additionalProperties: items: type: string type: array type: object - members: - items: - type: string - type: array - owner: + primary: type: string serviceSites: items: type: string type: array required: - - owner - - members + - primary + - associatedSites type: object type: array type: object
diff --git a/components/policy/resources/templates/policy_definitions/GoogleAssistant/AssistantWebEnabled.yaml b/components/policy/resources/templates/policy_definitions/GoogleAssistant/AssistantWebEnabled.yaml new file mode 100644 index 0000000..ad2d5d59 --- /dev/null +++ b/components/policy/resources/templates/policy_definitions/GoogleAssistant/AssistantWebEnabled.yaml
@@ -0,0 +1,36 @@ +caption: Allow using <ph name="ASSISTANT_PRODUCT_NAME">Google Assistant</ph> on the + web, e.g. to enable changing passwords automatically +default: null +desc: |- + Setting the policy to Enabled allows users to use <ph name="ASSISTANT_PRODUCT_NAME">Google Assistant</ph> on the web, e.g. for faster checkout and password changes. Using <ph name="ASSISTANT_PRODUCT_NAME">Google Assistant</ph> requires additional user consent and <ph name="ASSISTANT_PRODUCT_NAME">Google Assistant</ph> will only run if users choose to give this consent, even if the policy is set to Enabled. + + Setting the policy to Disabled means users cannot use <ph name="ASSISTANT_PRODUCT_NAME">Google Assistant</ph> on the web. + + If the policy is not set, the user can turn off <ph name="ASSISTANT_PRODUCT_NAME">Google Assistant</ph>. +example_value: true +features: + can_be_recommended: false + dynamic_refresh: true + per_profile: true +future_on: +- fuchsia +items: +- caption: Allow using <ph name="ASSISTANT_PRODUCT_NAME">Google Assistant</ph> on + the web + value: true +- caption: Do not allow using <ph name="ASSISTANT_PRODUCT_NAME">Google Assistant</ph> + on the web + value: false +- caption: Allow the user to decide + value: null +owners: +- file://components/autofill_assistant/OWNERS +- brunobraga@google.com +- jkeitel@google.com +schema: + type: boolean +supported_on: +- chrome.*:107- +- chrome_os:107- +tags: [] +type: main
diff --git a/components/policy/resources/templates/policy_definitions/Miscellaneous/BuiltinCertificateVerifierEnabled.yaml b/components/policy/resources/templates/policy_definitions/Miscellaneous/BuiltinCertificateVerifierEnabled.yaml index f133255f..09db200c 100644 --- a/components/policy/resources/templates/policy_definitions/Miscellaneous/BuiltinCertificateVerifierEnabled.yaml +++ b/components/policy/resources/templates/policy_definitions/Miscellaneous/BuiltinCertificateVerifierEnabled.yaml
@@ -1,17 +1,13 @@ caption: Determines whether the built-in certificate verifier will be used to verify server certificates default: null -desc: "When this setting is enabled, <ph name=\"PRODUCT_NAME\">$1<ex>Google Chrome</ex></ph>\ - \ will perform verification of server certificates using the built-in certificate\ - \ verifier.\n When this setting is disabled, <ph name=\"PRODUCT_NAME\">$1<ex>Google\ - \ Chrome</ex></ph> will perform verification of server certificates using the legacy\ - \ certificate verifier provided by the platform, unless <ph name=\"CHROME_ROOT_STORE_ENABLED_POLICY_NAME\"\ - >ChromeRootStoreEnabled</ph> is enabled.\n When this setting is not set, the\ - \ built-in or the legacy certificate verifier may be used.\n\n This policy\ - \ is planned to be removed in <ph name=\"PRODUCT_NAME\">$1<ex>Google Chrome</ex></ph>\ - \ for <ph name=\"MAC_OS_NAME\">macOS</ph> version 107, when support for the legacy\ - \ certificate verifier on <ph name=\"MAC_OS_NAME\">macOS</ph> is planned to be removed.\n\ - \ " +deprecated: true +desc: |- + This policy is no longer supported, however the related policy <ph name="CHROME_ROOT_STORE_ENABLED_POLICY_NAME">ChromeRootStoreEnabled</ph> may be supported on certain platforms. + + When this setting is enabled, <ph name="PRODUCT_NAME">$1<ex>Google Chrome</ex></ph> will perform verification of server certificates using the built-in certificate verifier. + When this setting is disabled, <ph name="PRODUCT_NAME">$1<ex>Google Chrome</ex></ph> will perform verification of server certificates using the legacy certificate verifier provided by the platform, unless <ph name="CHROME_ROOT_STORE_ENABLED_POLICY_NAME">ChromeRootStoreEnabled</ph> is enabled. + When this setting is not set, the built-in or the legacy certificate verifier may be used. example_value: false features: dynamic_refresh: false @@ -31,6 +27,6 @@ supported_on: - chrome_os:77-83 - chrome.linux:79-83 -- chrome.mac:83- +- chrome.mac:83-106 tags: [] type: main
diff --git a/components/policy/resources/templates/policy_definitions/Miscellaneous/ChromeOsLockOnIdleSuspend.yaml b/components/policy/resources/templates/policy_definitions/Miscellaneous/ChromeOsLockOnIdleSuspend.yaml index 6ed524e..f68db25 100644 --- a/components/policy/resources/templates/policy_definitions/Miscellaneous/ChromeOsLockOnIdleSuspend.yaml +++ b/components/policy/resources/templates/policy_definitions/Miscellaneous/ChromeOsLockOnIdleSuspend.yaml
@@ -5,6 +5,8 @@ Devices will lock when the lid is closed except if they are docked (using an external monitor). In such a case, the device will not lock when the lid closes, but will lock if the external monitor is removed and the lid is still closed. + Until <ph name="PRODUCT_OS_NAME">$2<ex>Google ChromeOS</ex></ph> M106, this policy would only lock the device when it suspends. From M106 onwards, this policy will lock the device when it suspends or the lid is closed. + By setting this policy to true, and <ph name="LID_CLOSE_ACTION_POLICY_NAME">LidCloseAction</ph> to <ph name="LID_CLOSE_ACTION_ENUM_DO_NOTHING">LidCloseActionDoNothing</ph>, a device will lock when the lid is closed, but will only suspend if and when configured to do so in <ph name="POWER_MANAGEMENT_IDLE_SETTINGS_POLICY_NAME">PowerManagementIdleSettings</ph>. Setting the policy to Disabled means users are not asked for a password to unlock the device.
diff --git a/components/policy/resources/templates/policy_definitions/Miscellaneous/ChromeRootStoreEnabled.yaml b/components/policy/resources/templates/policy_definitions/Miscellaneous/ChromeRootStoreEnabled.yaml index 25b33ba..eacb4f1 100644 --- a/components/policy/resources/templates/policy_definitions/Miscellaneous/ChromeRootStoreEnabled.yaml +++ b/components/policy/resources/templates/policy_definitions/Miscellaneous/ChromeRootStoreEnabled.yaml
@@ -1,19 +1,19 @@ caption: Determines whether the Chrome Root Store and built-in certificate verifier will be used to verify server certificates default: null -desc: "When this setting is enabled, <ph name=\"PRODUCT_NAME\">$1<ex>Google Chrome</ex></ph>\ - \ will perform verification of server certificates using the built-in certificate\ - \ verifier with the Chrome Root Store as the source of public trust.\n When\ - \ this setting is disabled, <ph name=\"PRODUCT_NAME\">$1<ex>Google Chrome</ex></ph>\ - \ will not use the Chrome Root Store. Verification may use the system certificate\ - \ verifier, or the builtin verifier if the <ph name=\"BUILT_IN_CERTIFICATE_VERIFIER_ENABLED_POLICY_NAME\"\ - >BuiltinCertificateVerifierEnabled</ph> policy is available and not disabled.\n\ - \ When this setting is not set, the Chrome Root Store or system provided roots\ - \ may be used.\n\n This policy is planned to be removed in <ph name=\"PRODUCT_NAME\"\ - >$1<ex>Google Chrome</ex></ph> for <ph name=\"MS_WIN_NAME\">Microsoft® Windows®</ph>\ - \ and <ph name=\"MAC_OS_NAME\">macOS</ph> version 111, when support for using the\ - \ platform supplied certificate verifier and roots are planned to be removed.\n\ - \ " +desc: |- +When this policy is set to enabled, <ph name="PRODUCT_NAME">$1<ex>Google +Chrome</ex></ph> will perform verification of server certificates using the built-in +certificate verifier with the Chrome Root Store as the source of public trust. +When this policy is set to disabled, <ph name="PRODUCT_NAME">$1<ex>Google +Chrome</ex></ph> will use the system certificate verifier and system root certificates. +When this policy is not set, the Chrome Root Store or system provided roots +may be used. + +This policy is planned to be removed in <ph name="PRODUCT_NAME">$1<ex>Google Chrome</ex></ph> +for <ph name="MS_WIN_NAME">Microsoft® Windows®</ph> and <ph name="MAC_OS_NAME">macOS</ph> version 111, +when support for using the platform supplied certificate verifier and roots are planned to be removed. + example_value: false features: dynamic_refresh: false
diff --git a/components/policy/resources/templates/policy_definitions/Miscellaneous/DeskAPIThirdPartyAccessEnabled.yaml b/components/policy/resources/templates/policy_definitions/Miscellaneous/DeskAPIThirdPartyAccessEnabled.yaml new file mode 100644 index 0000000..5ee327f --- /dev/null +++ b/components/policy/resources/templates/policy_definitions/Miscellaneous/DeskAPIThirdPartyAccessEnabled.yaml
@@ -0,0 +1,24 @@ +caption: Enable Desk API for third-party ChromeOS control +default: false +desc: |- +Setting the policy to Enabled allows third-party web applications to use Desk +API to control ChromeOS desks. If the policy is not set or disabled, the Desk API +will be unavailable. +example_value: true +features: + dynamic_refresh: true + per_profile: true +future_on: +- chrome_os +items: +- caption: Enable Desk API for third-party ChromeOS control + value: true +- caption: Do not enable Desk API for third-party ChromeOS control + value: false +owners: +- aprilzhou@google.com +- yzd@google.com +schema: + type: boolean +tags: [] +type: main
diff --git a/components/policy/resources/templates/policy_definitions/Miscellaneous/DeviceLoginScreenContextAwareAccessSignalsAllowlist.yaml b/components/policy/resources/templates/policy_definitions/Miscellaneous/DeviceLoginScreenContextAwareAccessSignalsAllowlist.yaml index 72a9d28..77beb0e 100644 --- a/components/policy/resources/templates/policy_definitions/Miscellaneous/DeviceLoginScreenContextAwareAccessSignalsAllowlist.yaml +++ b/components/policy/resources/templates/policy_definitions/Miscellaneous/DeviceLoginScreenContextAwareAccessSignalsAllowlist.yaml
@@ -21,8 +21,6 @@ features: cloud_only: true dynamic_refresh: true -future_on: -- chrome_os owners: - lmasopust@google.com - rodmartin@google.com @@ -31,5 +29,7 @@ items: type: string type: array +supported_on: +- chrome_os:108- tags: [] type: list
diff --git a/components/policy/resources/templates/policy_definitions/Miscellaneous/DeviceShowLowDiskSpaceNotification.yaml b/components/policy/resources/templates/policy_definitions/Miscellaneous/DeviceShowLowDiskSpaceNotification.yaml index 922988a..34f5424 100644 --- a/components/policy/resources/templates/policy_definitions/Miscellaneous/DeviceShowLowDiskSpaceNotification.yaml +++ b/components/policy/resources/templates/policy_definitions/Miscellaneous/DeviceShowLowDiskSpaceNotification.yaml
@@ -23,7 +23,7 @@ only 1 user value: false owners: -- vsavu@chromium.org +- vsavu@google.com schema: type: boolean supported_on:
diff --git a/components/policy/resources/templates/policy_definitions/Miscellaneous/LacrosDataBackwardMigrationMode.yaml b/components/policy/resources/templates/policy_definitions/Miscellaneous/LacrosDataBackwardMigrationMode.yaml new file mode 100644 index 0000000..9cfcc33e --- /dev/null +++ b/components/policy/resources/templates/policy_definitions/Miscellaneous/LacrosDataBackwardMigrationMode.yaml
@@ -0,0 +1,49 @@ +caption: Choose what happens with user data after <ph name="LACROS_NAME">Lacros</ph> + is disabled +default: none +desc: |- + This setting decides how much user data is kept after <ph name="LACROS_NAME">Lacros</ph> is disabled. + + If the policy is set to <ph name="LACROS_BACKWARD_MIGRATION_NONE">none</ph>, backward data migration is not performed. + + If the policy is set to <ph name="LACROS_BACKWARD_MIGRATION_KEEP_NONE">keep_none</ph>, all user data is removed. This is the safest option. + + If the policy is set to <ph name="LACROS_BACKWARD_MIGRATION_KEEP_SAFE_DATA">keep_safe_data</ph>, most user data is removed. Only browser independent files are kept (such as Downloads). + + If the policy is set to <ph name="LACROS_BACKWARD_MIGRATION_KEEP_ALL">keep_all</ph>, all user data is kept. This option has a high risk of failure, requiring a powerwash to recover. +example_value: keep_all +features: + dynamic_refresh: false + per_profile: false +future_on: +- chrome_os +items: +- caption: After <ph name="LACROS_NAME">Lacros</ph> is disabled, data migration is + not performed. The <ph name="LACROS_NAME">Lacros</ph> folder is removed and users + continue using the remaining data. + name: none + value: none +- caption: After <ph name="LACROS_NAME">Lacros</ph> is disabled, all user data is + removed on next login. + name: keep_none + value: keep_none +- caption: After <ph name="LACROS_NAME">Lacros</ph> is disabled, we attempt to keep + as much user data as possible, while removing all browser data. + name: keep_safe_data + value: keep_safe_data +- caption: After <ph name="LACROS_NAME">Lacros</ph> is disabled, we attempt to migrate + all data. + name: keep_all + value: keep_all +owners: +- janagrill@google.com +- vsavu@google.com +schema: + enum: + - none + - keep_none + - keep_safe_data + - keep_all + type: string +tags: [] +type: string-enum
diff --git a/components/policy/resources/templates/policy_definitions/Miscellaneous/OnFileTransferEnterpriseConnector.yaml b/components/policy/resources/templates/policy_definitions/Miscellaneous/OnFileTransferEnterpriseConnector.yaml index c33f2f0..f428d6c 100644 --- a/components/policy/resources/templates/policy_definitions/Miscellaneous/OnFileTransferEnterpriseConnector.yaml +++ b/components/policy/resources/templates/policy_definitions/Miscellaneous/OnFileTransferEnterpriseConnector.yaml
@@ -63,8 +63,6 @@ cloud_only: true dynamic_refresh: true per_profile: false -future_on: -- chrome_os owners: - sseckler@google.com - rogerta@chromium.org @@ -104,5 +102,7 @@ type: string type: object type: array +supported_on: +- chrome_os:108- tags: [] type: dict
diff --git a/components/policy/resources/templates/policy_definitions/Miscellaneous/OnPrintEnterpriseConnector.yaml b/components/policy/resources/templates/policy_definitions/Miscellaneous/OnPrintEnterpriseConnector.yaml index 36d07aa..f708e97 100644 --- a/components/policy/resources/templates/policy_definitions/Miscellaneous/OnPrintEnterpriseConnector.yaml +++ b/components/policy/resources/templates/policy_definitions/Miscellaneous/OnPrintEnterpriseConnector.yaml
@@ -54,8 +54,6 @@ dynamic_refresh: true per_profile: true future_on: -- chrome.* -- chrome_os - fuchsia owners: - file://chrome/browser/enterprise/connectors/OWNERS @@ -136,5 +134,8 @@ type: object type: object type: array +supported_on: +- chrome.*:106- +- chrome_os:106- tags: [] type: dict
diff --git a/components/policy/resources/templates/policy_definitions/Miscellaneous/PersistentQuotaEnabled.yaml b/components/policy/resources/templates/policy_definitions/Miscellaneous/PersistentQuotaEnabled.yaml index 5022d3e..a1a35618 100644 --- a/components/policy/resources/templates/policy_definitions/Miscellaneous/PersistentQuotaEnabled.yaml +++ b/components/policy/resources/templates/policy_definitions/Miscellaneous/PersistentQuotaEnabled.yaml
@@ -1,5 +1,6 @@ caption: Force persistent quota to be enabled default: false +deprecated: true desc: "Starting in M106 persistent quota will no longer be supported. This policy\ \ will re-enable persistent quota functionality until M107.\n\n If this policy\ \ is set to enabled, webkitRequestFileSystem with persistent type will operate with\
diff --git a/components/policy/resources/templates/policy_definitions/Miscellaneous/PolicyScopeDetection.yaml b/components/policy/resources/templates/policy_definitions/Miscellaneous/PolicyScopeDetection.yaml index a35776a..c3f4c9d 100644 --- a/components/policy/resources/templates/policy_definitions/Miscellaneous/PolicyScopeDetection.yaml +++ b/components/policy/resources/templates/policy_definitions/Miscellaneous/PolicyScopeDetection.yaml
@@ -1,5 +1,6 @@ caption: Allow policy scope detection on <ph name="MAC_OS_NAME">macOS</ph> default: true +deprecated: true desc: " Controls whether browser can detect mandatory policy scope on <ph name=\"\ MAC_OS_NAME\">macOS</ph> or not.\n\n If the policy is set to Enabled or not\ \ set, each policy's scope will be determined by the scope of <ph name=\"MAC_OS_NAME\"\
diff --git a/components/policy/resources/templates/policy_definitions/Miscellaneous/PrefixedStorageInfoEnabled.yaml b/components/policy/resources/templates/policy_definitions/Miscellaneous/PrefixedStorageInfoEnabled.yaml index c47291a2..d549cba3 100644 --- a/components/policy/resources/templates/policy_definitions/Miscellaneous/PrefixedStorageInfoEnabled.yaml +++ b/components/policy/resources/templates/policy_definitions/Miscellaneous/PrefixedStorageInfoEnabled.yaml
@@ -1,7 +1,7 @@ caption: Re-enable the deprecated window.webkitStorageInfo API default: false -desc: "Starting in M106, the non-standard API window.webkitStorageInfo will be removed.\n\ - \ This policy re-enables the API until M107.\n If this policy is set to\ +desc: "Non-standard API window.webkitStorageInfo is deprecated and is planned for\ + \ removal.\n This policy re-enables the API.\n If this policy is set to\ \ Enabled, the window.webkitStorageInfo API will be available.\n If this policy\ \ is set to Disabled or not set, the window.webkitStorageInfo API will be unavailable.\n\ \ " @@ -22,8 +22,8 @@ schema: type: boolean supported_on: -- chrome.*:106-107 -- chrome_os:106-107 -- android:106-107 +- chrome.*:106- +- chrome_os:106- +- android:106- tags: [] type: main
diff --git a/components/policy/resources/templates/policy_definitions/Miscellaneous/ShoppingListEnabled.yaml b/components/policy/resources/templates/policy_definitions/Miscellaneous/ShoppingListEnabled.yaml new file mode 100644 index 0000000..181c5de --- /dev/null +++ b/components/policy/resources/templates/policy_definitions/Miscellaneous/ShoppingListEnabled.yaml
@@ -0,0 +1,31 @@ +caption: Allow the shopping list feature to be enabled +default: true +desc: "This policy controls the availability of the shopping list feature.\n \ + \ If enabled, users will be presented with UI to track the price of the product\ + \ displayed on the current page. The tracked product will be shown in the bookmarks\ + \ side panel.\n If this policy is set to Enabled or not set, the shopping list\ + \ feature will be available to users.\n If this policy is set to Disabled,\ + \ the shopping list feature will be unavailable.\n " +example_value: true +features: + dynamic_refresh: true + per_profile: true +future_on: +- ios +items: +- caption: The shopping list feature will be available to users. + value: true +- caption: The shopping list feature will not be available to users. + value: false +owners: +- aymana@chromium.org +- mdjones@chromium.org +- chrome-shopping-eng@google.com +schema: + type: boolean +supported_on: +- chrome.*:107- +- chrome_os:107- +- android:107- +tags: [] +type: main
diff --git a/components/policy/resources/templates/policy_definitions/Miscellaneous/SpellcheckLanguageBlacklist.yaml b/components/policy/resources/templates/policy_definitions/Miscellaneous/SpellcheckLanguageBlacklist.yaml deleted file mode 100644 index c2a1b2d2..0000000 --- a/components/policy/resources/templates/policy_definitions/Miscellaneous/SpellcheckLanguageBlacklist.yaml +++ /dev/null
@@ -1,35 +0,0 @@ -caption: Force disable spellcheck languages -deprecated: true -desc: |- - This policy is deprecated, please use <ph name="SPELLCHECK_LANGUAGE_BLOCKLIST_POLICY_NAME">SpellcheckLanguageBlocklist</ph> instead. - - Force-disables spellcheck languages. Unrecognized languages in that list will be ignored. - - If you enable this policy, spellcheck will be disabled for the languages specified. The user can still enable or disable spellcheck for languages not in the list. - - If you do not set this policy, or disable it, there will be no change to the user's spellcheck preferences. - - If the <ph name="SPELLCHECK_ENABLED_POLICY_NAME">SpellcheckEnabled</ph> policy is set to false, this policy will have no effect. - - If a language is included in both this policy and the <ph name="SPELLCHECK_LANGUAGE_POLICY_NAME">SpellcheckLanguage</ph> policy, the latter is prioritized and the spellcheck language will be enabled. - - The currently supported languages are: af, bg, ca, cs, da, de, el, en-AU, en-CA, en-GB, en-US, es, es-419, es-AR, es-ES, es-MX, es-US, et, fa, fo, fr, he, hi, hr, hu, id, it, ko, lt, lv, nb, nl, pl, pt-BR, pt-PT, ro, ru, sh, sk, sl, sq, sr, sv, ta, tg, tr, uk, vi. -example_value: -- fr -- es -features: - can_be_recommended: false - dynamic_refresh: true - per_profile: true -owners: -- gujen@google.com -schema: - items: - type: string - type: array -supported_on: -- chrome.win:75-100 -- chrome.linux:75-100 -- chrome_os:75-100 -tags: [] -type: list
diff --git a/components/policy/resources/templates/policy_definitions/Miscellaneous/StrictMimetypeCheckForWorkerScriptsEnabled.yaml b/components/policy/resources/templates/policy_definitions/Miscellaneous/StrictMimetypeCheckForWorkerScriptsEnabled.yaml new file mode 100644 index 0000000..2fa0033 --- /dev/null +++ b/components/policy/resources/templates/policy_definitions/Miscellaneous/StrictMimetypeCheckForWorkerScriptsEnabled.yaml
@@ -0,0 +1,44 @@ +caption: Enable strict MIME type checking for worker scripts +default: true +desc: "This policy enables strict MIME type checking for worker scripts.\n\n \ + \ When enabled or unset, then worker scripts will use strict MIME type checking\ + \ for JavaScript, which is the new default behaviour. Worker scripts with legacy\ + \ MIME types will be rejected.\n\n When disabled, then worker scripts will\ + \ use lax MIME type checking, so that worker scripts with legacy MIME types, e.g.\ + \ <ph name=\"MIMETYPE_TEXT_ASCII\">text/ascii</ph>, will continue to be loaded and\ + \ executed.\n\n Browsers traditionally used lax MIME type checking, so that\ + \ resources with a number of legacy MIME types were supported. E.g. for JavaScript\ + \ resources, <ph name=\"MIMETYPE_TEXT_ASCII\">text/ascii</ph> is a legacy supported\ + \ MIME type. This may cause security issues, by allowing to load resources as scripts\ + \ that were never intended to be used as such. Chrome will transition to use strict\ + \ MIME type checking in the near future. The enabled policy will track the default\ + \ behaviour. Disabling this policy allows administrators to retain the legacy behaviour,\ + \ if desired.\n\n See https://html.spec.whatwg.org/multipage/scripting.html#scriptingLanguage\ + \ for details about JavaScript / ECMAScript media types.\n " +example_value: false +features: + dynamic_refresh: true + per_profile: true +future_on: +- fuchsia +items: +- caption: Scripts for workers (Web Workers, Service Workers, etc.) require a JavaScript + MIME type, like <ph name="MIMETYPE_TEXT_JAVASCRIPT">text/javascript</ph>. Worker + scripts with legacy MIME types, like <ph name="MIMETYPE_TEXT_ASCII">text/ascii</ph>, + will be rejected. + value: true +- caption: Scripts for workers (Web Workers, Service Workers, etc.) use lax MIME type + checking. Worker scripts with legacy MIME types, like <ph name="MIMETYPE_TEXT_ASCII">text/ascii</ph>, + will work. + value: false +owners: +- vogelheim@chromium.org +- chrome-security-owp-team@google.com +schema: + type: boolean +supported_on: +- chrome.*:107- +- chrome_os:107- +- android:107- +tags: [] +type: main
diff --git a/components/policy/resources/templates/policy_definitions/Miscellaneous/TabDiscardingExceptions.yaml b/components/policy/resources/templates/policy_definitions/Miscellaneous/TabDiscardingExceptions.yaml new file mode 100644 index 0000000..c50c6d670 --- /dev/null +++ b/components/policy/resources/templates/policy_definitions/Miscellaneous/TabDiscardingExceptions.yaml
@@ -0,0 +1,25 @@ +caption: URL pattern Exceptions to tab discarding +desc: "This policy makes it so that any URL matching one or more of the patterns it\ + \ specifies (using the <ph name=\"URL_BLOCKLIST_POLICY_NAME\">URLBlocklist</ph>\ + \ filter format) will never be discarded by the browser.\n This applies to\ + \ memory pressure and high efficiency mode discarding.\n A discarded page is\ + \ unloaded and its resources fully reclaimed. The tab its associated with remains\ + \ in the tabstrip, but making it visible will trigger a full reload.\n " +example_value: +- example.com +- https://* +- '*' +features: + dynamic_refresh: true + per_profile: true +future_on: +- chrome.* +owners: +- anthonyvd@chromium.org +- file://components/performance_manager/OWNERS +schema: + items: + type: string + type: array +tags: [] +type: list
diff --git a/components/policy/resources/templates/policy_definitions/Miscellaneous/TrashEnabled.yaml b/components/policy/resources/templates/policy_definitions/Miscellaneous/TrashEnabled.yaml new file mode 100644 index 0000000..137eb85 --- /dev/null +++ b/components/policy/resources/templates/policy_definitions/Miscellaneous/TrashEnabled.yaml
@@ -0,0 +1,25 @@ +caption: Enable capability to send files to the Trash (on supported filesystems) in + the <ph name="PRODUCT_OS_NAME">$2<ex>Google ChromeOS</ex></ph> Files app +default: true +desc: |- + Setting the policy to True allows users of <ph name="PRODUCT_OS_NAME">$2<ex>Google ChromeOS</ex></ph> Files app to see a Trash bin and files under My files and Downloads (including their user created descendants) will be sent there on deletion. + + If the policy is set to False the files that previously resided in trash will still be available by showing hidden files and finding the .Trash directory under My files or Downloads. +example_value: true +features: + dynamic_refresh: true + per_profile: true +future_on: +- chrome_os +items: +- caption: Trash is enabled for the user. + value: true +- caption: Trash is disabled for the user. + value: false +owners: +- file://ui/file_manager/OWNERS +- benreich@chromium.org +schema: + type: boolean +tags: [] +type: main
diff --git a/components/policy/resources/templates/policy_definitions/Miscellaneous/URLBlacklist.yaml b/components/policy/resources/templates/policy_definitions/Miscellaneous/URLBlacklist.yaml deleted file mode 100644 index f08e9fb..0000000 --- a/components/policy/resources/templates/policy_definitions/Miscellaneous/URLBlacklist.yaml +++ /dev/null
@@ -1,39 +0,0 @@ -arc_support: Android apps may voluntarily choose to honor this list. You cannot force - them to honor it. -caption: Block access to a list of URLs -deprecated: true -desc: |- - This policy is deprecated, please use the '<ph name="URL_BLOCKLIST_POLICY_NAME">URLBlocklist</ph>' policy instead. - - Setting the policy prevents webpages with prohibited URLs from loading. It provides a list of URL patterns that specify forbidden URLs. Leaving the policy unset means no URLs are prohibited in the browser. Format the URL pattern according to this format ( https://www.chromium.org/administrators/url-blocklist-filter-format ). Up to 1,000 exceptions can be defined in <ph name="URL_ALLOWLIST_POLICY_NAME">URLAllowlist</ph>. - - From <ph name="PRODUCT_NAME">$1<ex>Google Chrome</ex></ph> version 73, you can block javascript://* URLs. However, it affects only JavaScript entered in the address bar (or, for example, bookmarklets). In-page JavaScript URLs with dynamically loaded data aren't subject to this policy. For example, if you block example.com/abc, then example.com can still load example.com/abc using XMLHTTPRequest. - - Note: Blocking internal chrome://* URLs can lead to unexpected errors. -example_value: -- example.com -- https://ssl.server.com -- hosting.com/bad_path -- https://server:8080/path -- .exact.hostname.com -- file://* -- custom_scheme:* -- '*' -features: - dynamic_refresh: true - per_profile: true -owners: -- file://components/policy/resources/OWNERS -- hendrich@chromium.org -schema: - items: - type: string - type: array -supported_on: -- chrome.*:15-100 -- chrome_os:15-100 -- android:30-100 -- webview_android:47-100 -tags: -- filtering -type: list
diff --git a/components/policy/resources/templates/policy_definitions/Miscellaneous/URLWhitelist.yaml b/components/policy/resources/templates/policy_definitions/Miscellaneous/URLWhitelist.yaml deleted file mode 100644 index ba9cb093..0000000 --- a/components/policy/resources/templates/policy_definitions/Miscellaneous/URLWhitelist.yaml +++ /dev/null
@@ -1,37 +0,0 @@ -arc_support: Android apps may voluntarily choose to honor this list. You cannot force - them to honor it. -caption: Allow access to a list of URLs -deprecated: true -desc: |- - This policy is deprecated, please use the '<ph name="URL_ALLOWLIST_POLICY_NAME">URLAllowlist</ph>' policy instead. - - Setting the policy provides access to the listed URLs, as exceptions to the URL blocklist. See that policy's description for the format of entries of this list. For example, setting <ph name="URL_BLOCKLIST_POLICY_NAME">URLBlocklist</ph> to * will block all requests, and you can use this policy to allow access to a limited list of URLs. Use it to open exceptions to certain schemes, subdomains of other domains, ports, or specific paths, using the format specified at ( https://www.chromium.org/administrators/url-blocklist-filter-format ). The most specific filter determines if a URL is blocked or allowed. The allowlist takes precedence over blocklist. This policy is limited to 1,000 entries. - - This policy also allows enabling the automatic invocation by the browser of external application registered as protocol handlers for the listed protocols like "tel:" or "ssh:". - - Leaving the policy unset allows no exceptions. - - On <ph name="MS_WIN_NAME">Microsoft® Windows®</ph>, this functionality is only available on instances that are joined to a <ph name="MS_AD_NAME">Microsoft® Active Directory®</ph> domain, running on Windows 10 Pro, or enrolled in <ph name="CHROME_BROWSER_CLOUD_MANAGEMENT_NAME">Chrome Browser Cloud Management</ph>. On <ph name="MAC_OS_NAME">macOS</ph>, this functionality is only available on instances that are managed via MDM, or joined to a domain via MCX. -example_value: -- example.com -- https://ssl.server.com -- hosting.com/good_path -- https://server:8080/path -- .exact.hostname.com -features: - dynamic_refresh: true - per_profile: true -owners: -- file://components/policy/resources/OWNERS -- hendrich@chromium.org -schema: - items: - type: string - type: array -supported_on: -- chrome.*:15-100 -- chrome_os:15-100 -- android:30-100 -- webview_android:47-100 -tags: [] -type: list
diff --git a/components/policy/resources/templates/policy_definitions/Miscellaneous/UrlKeyedAnonymizedDataCollectionEnabled.yaml b/components/policy/resources/templates/policy_definitions/Miscellaneous/UrlKeyedAnonymizedDataCollectionEnabled.yaml index b9d68638..22b5683 100644 --- a/components/policy/resources/templates/policy_definitions/Miscellaneous/UrlKeyedAnonymizedDataCollectionEnabled.yaml +++ b/components/policy/resources/templates/policy_definitions/Miscellaneous/UrlKeyedAnonymizedDataCollectionEnabled.yaml
@@ -4,7 +4,7 @@ Setting the policy to Disabled results in no URL-keyed anonymized data collection. - If you set the policy, users can't change. If not set, then URL-keyed anonymized data collection at first, but users can change it. + If this policy is left unset, the user will be able to change this setting manually. example_value: true features: dynamic_refresh: true
diff --git a/components/policy/resources/templates/policy_definitions/Miscellaneous/WebAppInstallForceList.yaml b/components/policy/resources/templates/policy_definitions/Miscellaneous/WebAppInstallForceList.yaml index af8631e..ab0908dc 100644 --- a/components/policy/resources/templates/policy_definitions/Miscellaneous/WebAppInstallForceList.yaml +++ b/components/policy/resources/templates/policy_definitions/Miscellaneous/WebAppInstallForceList.yaml
@@ -5,7 +5,7 @@ Each list item of the policy is an object with a mandatory member: <ph name="URL_LABEL">url</ph> (the URL of the web app to install) - and 5 optional members: + and 6 optional members: - <ph name="DEFAULT_LAUNCH_CONTAINER_LABEL">default_launch_container</ph> (for how the web app opens—a new tab is the default) @@ -37,6 +37,16 @@ hash of the icon file. Currently only supported on <ph name="PRODUCT_OS_NAME">$2<ex>Google ChromeOS</ex></ph>.) + - <ph name="INSTALL_AS_SHORTCUT_LABEL">install_as_shortcut</ph> + (Starting with <ph name="PRODUCT_NAME">$1<ex>Google Chrome</ex></ph> + version 107). If enabled the given <ph name="URL_LABEL">url</ph> + will be installed as a shortcut, as if done via the "Create Shortcut..." + option in the desktop browser GUI. + Note that when installed as a shortcut it won't be updated if the + manifest in <ph name="URL_LABEL">url</ph> changes. + If disabled or unset, the web app at the given + <ph name="URL_LABEL">url</ph> will be installed normally. + See <ph name="PINNED_LAUNCHER_APPS_POLICY_NAME">PinnedLauncherApps</ph> for pinning apps to the <ph name="PRODUCT_OS_NAME">$2<ex>Google ChromeOS</ex></ph> shelf. example_value: - create_desktop_shortcut: true @@ -47,9 +57,10 @@ - default_launch_container: window fallback_app_name: Editor url: https://docs.google.com/editor -- custom_name: Spreadsheets +- custom_name: My important document default_launch_container: window - url: https://docs.google.com/sheets + install_as_shortcut: true + url: https://docs.google.com/document/d/ds187akjqih89 - custom_icon: hash: c28f469c450e9ab2b86ea47038d2b324c6ad3b1e9a4bd8960da13214afd0ca38 url: https://mydomain.example.com/sunny_icon.png @@ -87,6 +98,8 @@ type: string fallback_app_name: type: string + install_as_shortcut: + type: boolean url: type: string required:
diff --git a/components/policy/resources/templates/policy_definitions/Miscellaneous/WebSQLNonSecureContextEnabled.yaml b/components/policy/resources/templates/policy_definitions/Miscellaneous/WebSQLNonSecureContextEnabled.yaml index 8a4c352c..df214f5 100644 --- a/components/policy/resources/templates/policy_definitions/Miscellaneous/WebSQLNonSecureContextEnabled.yaml +++ b/components/policy/resources/templates/policy_definitions/Miscellaneous/WebSQLNonSecureContextEnabled.yaml
@@ -1,9 +1,9 @@ caption: Force WebSQL in non-secure contexts to be enabled. default: false desc: |- - WebSQL in non-secure contexts is off by default as of M107 and will be fully removed in M110. - If this policy is set to false or unset, WebSQL in non-secure contexts will remain on until the end of M106, then off from M107. - If this policy is set to true, WebSQL in non-secure contexts will be enabled. + WebSQL in non-secure contexts is on by default as of M105, but can be disabled via Chrome flag. + If this policy is set to false or unset, WebSQL in non-secure contexts can be disabled. + If this policy is set to true, WebSQL cannot be disabled. example_value: true features: dynamic_refresh: false @@ -21,8 +21,8 @@ schema: type: boolean supported_on: -- android:105-110 -- chrome.*:105-110 -- chrome_os:105-110 +- android:105- +- chrome.*:105- +- chrome_os:105- tags: [] type: main
diff --git a/components/policy/resources/templates/policy_definitions/NativeMessaging/policy_atomic_groups.yaml b/components/policy/resources/templates/policy_definitions/NativeMessaging/policy_atomic_groups.yaml index 48b2f8ec..0687d60 100644 --- a/components/policy/resources/templates/policy_definitions/NativeMessaging/policy_atomic_groups.yaml +++ b/components/policy/resources/templates/policy_definitions/NativeMessaging/policy_atomic_groups.yaml
@@ -1,8 +1,6 @@ NativeMessaging: caption: Native messaging policies: - - NativeMessagingBlacklist - NativeMessagingBlocklist - NativeMessagingAllowlist - - NativeMessagingWhitelist - NativeMessagingUserLevelHosts
diff --git a/components/policy/resources/templates/policy_definitions/PluginVm/PluginVmDataCollectionAllowed.yaml b/components/policy/resources/templates/policy_definitions/PluginVm/PluginVmDataCollectionAllowed.yaml index 2890a8059..c3adcec 100644 --- a/components/policy/resources/templates/policy_definitions/PluginVm/PluginVmDataCollectionAllowed.yaml +++ b/components/policy/resources/templates/policy_definitions/PluginVm/PluginVmDataCollectionAllowed.yaml
@@ -10,7 +10,7 @@ per_profile: false owners: - okalitova@chromium.org -- janagrill@chromium.org +- janagrill@google.com schema: type: boolean supported_on:
diff --git a/components/policy/resources/templates/policy_definitions/PluginVm/PluginVmRequiredFreeDiskSpace.yaml b/components/policy/resources/templates/policy_definitions/PluginVm/PluginVmRequiredFreeDiskSpace.yaml index da2d2d84..c27cde9 100644 --- a/components/policy/resources/templates/policy_definitions/PluginVm/PluginVmRequiredFreeDiskSpace.yaml +++ b/components/policy/resources/templates/policy_definitions/PluginVm/PluginVmRequiredFreeDiskSpace.yaml
@@ -10,7 +10,7 @@ per_profile: false owners: - okalitova@chromium.org -- janagrill@chromium.org +- janagrill@google.com schema: maximum: 1000 minimum: 0
diff --git a/components/policy/resources/templates/policy_definitions/PluginVm/UserPluginVmAllowed.yaml b/components/policy/resources/templates/policy_definitions/PluginVm/UserPluginVmAllowed.yaml index 877a9af..d187073 100644 --- a/components/policy/resources/templates/policy_definitions/PluginVm/UserPluginVmAllowed.yaml +++ b/components/policy/resources/templates/policy_definitions/PluginVm/UserPluginVmAllowed.yaml
@@ -12,7 +12,7 @@ per_profile: false owners: - okalitova@chromium.org -- janagrill@chromium.org +- janagrill@google.com schema: type: boolean supported_on:
diff --git a/components/policy/resources/templates/policy_definitions/Printing/DevicePrintingClientNameTemplate.yaml b/components/policy/resources/templates/policy_definitions/Printing/DevicePrintingClientNameTemplate.yaml index 036bbf2..c75ab16f 100644 --- a/components/policy/resources/templates/policy_definitions/Printing/DevicePrintingClientNameTemplate.yaml +++ b/components/policy/resources/templates/policy_definitions/Printing/DevicePrintingClientNameTemplate.yaml
@@ -1,27 +1,28 @@ -caption: Printing 'client-name' IPP attribute template +caption: Template for the <ph name="CLIENT_NAME_IPP_ATTRIBUTE">'client-name'</ph> + <ph name="INTERNET_PRINTING_PROTOCOL">Internet Printing Protocol</ph> <ph name="IPP_ATTRIBUTE">attribute</ph> desc: "This policy controls the value of the <ph name=\"CLIENT_INFO_IPP_ATTRIBUTE\"\ - >'client-info'</ph> IPP (Internet Printing Protocol) attribute in print jobs.\n\n\ - \ Setting the policy to a string has the effect of adding an additional <ph\ - \ name=\"CLIENT_INFO_IPP_ATTRIBUTE\">'client-info'</ph> item to every print job.\ - \ The <ph name=\"CLIENT_NAME_IPP_ATTRIBUTE\">'client-name'</ph> member of the added\ - \ <ph name=\"CLIENT_INFO_IPP_ATTRIBUTE\">'client-info'</ph> item will be set to\ - \ the value of the policy after substitution of variables.\n\n Supported variables\ - \ are <ph name=\"DIRECTORY_ID_PLACEHOLDER\">${DEVICE_DIRECTORY_ID}</ph>, <ph name=\"\ - SERIAL_NUMBER_PLACEHOLDER\">${DEVICE_SERIAL_NUMBER}</ph>, <ph name=\"ASSET_ID_PLACEHOLDER\"\ - >${DEVICE_ASSET_ID}</ph>, <ph name=\"ANNOTATED_LOCATION_PLACEHOLDER\">${DEVICE_ANNOTATED_LOCATION}</ph>,\ - \ <ph name=\"USER_EMAIL_PLACEHOLDER\">${USER_EMAIL}</ph>, <ph name=\"USER_EMAIL_NAME_PLACEHOLDER\"\ - >${USER_EMAIL_NAME}</ph>, <ph name=\"USER_EMAIL_DOMAIN\">${USER_EMAIL_DOMAIN}</ph>.\ - \ Unsupported placeholder variables will not be expanded.\n\n The resulting\ - \ value after substitution of variables is considered valid if it consists only\ - \ of <ph name=\"ASCII\">ASCII</ph> printable characters and its length does not\ - \ exceed 255.\n\n Note that, for privacy reasons, this policy applies only\ - \ when communicating with a printer using <ph name=\"IPPS_PROTOCOL\">IPPS</ph>,\ - \ <ph name=\"HTTPS_PROTOCOL\">HTTPS</ph>, <ph name=\"USB_PROTOCOL\">USB</ph> or\ - \ <ph name=\"IPP_USB_PROTOCOL\">IPP-over-USB</ph> protocols. Also, note that this\ - \ policy only applies to printers that support <ph name=\"CLIENT_NAME_IPP_ATTRIBUTE\"\ - >'client-name'</ph>.\n\n If the policy is unset, set to an empty or invalid\ - \ value, an additional <ph name=\"CLIENT_INFO_PLACEHOLDER\">'client-info'</ph> will\ - \ not be added to print job requests.\n " + >'client-info'</ph> <ph name=\"IPP_PROTOCOL\">IPP</ph> (<ph name=\"INTERNET_PRINTING_PROTOCOL\"\ + >Internet Printing Protocol</ph>) <ph name=\"IPP_ATTRIBUTE\">attribute</ph> in print\ + \ jobs.\n\n Setting the policy to a string has the effect of adding an additional\ + \ <ph name=\"CLIENT_INFO_IPP_ATTRIBUTE\">'client-info'</ph> item to every print\ + \ job. The <ph name=\"CLIENT_NAME_IPP_ATTRIBUTE\">'client-name'</ph> member of the\ + \ added <ph name=\"CLIENT_INFO_IPP_ATTRIBUTE\">'client-info'</ph> item will be set\ + \ to the value of the policy after substitution of variables.\n\n Supported\ + \ variables are <ph name=\"DIRECTORY_ID_PLACEHOLDER\">${DEVICE_DIRECTORY_ID}</ph>,\ + \ <ph name=\"SERIAL_NUMBER_PLACEHOLDER\">${DEVICE_SERIAL_NUMBER}</ph>, <ph name=\"\ + ASSET_ID_PLACEHOLDER\">${DEVICE_ASSET_ID}</ph>, <ph name=\"ANNOTATED_LOCATION_PLACEHOLDER\"\ + >${DEVICE_ANNOTATED_LOCATION}</ph>. Unsupported placeholder variables will not be\ + \ substituted.\n\n The resulting value after substitution of variables is considered\ + \ valid if it consists only of <ph name=\"ASCII\">ASCII</ph> printable characters\ + \ and its length does not exceed 255.\n\n Note that, for privacy reasons, this\ + \ policy applies only when communicating with a printer using <ph name=\"IPPS_PROTOCOL\"\ + >IPPS</ph>, <ph name=\"HTTPS_PROTOCOL\">HTTPS</ph>, <ph name=\"USB_PROTOCOL\">USB</ph>\ + \ or <ph name=\"IPP_USB_PROTOCOL\">IPP-over-USB</ph> protocols. Also, note that\ + \ this policy only applies to printers that support <ph name=\"CLIENT_NAME_IPP_ATTRIBUTE\"\ + >'client-name'</ph>.\n\n The policy only applies to affiliated users.\n\n \ + \ If the policy is unset, set to an empty or invalid value, an additional <ph\ + \ name=\"CLIENT_INFO_PLACEHOLDER\">'client-info'</ph> will not be added to print\ + \ job requests.\n " device_only: true example_value: chromebook-${DEVICE_ASSET_ID} features: @@ -30,8 +31,8 @@ future_on: - chrome_os owners: -- srad@google.com - ust@google.com +- srad@google.com schema: type: string tags: []
diff --git a/components/policy/resources/templates/policy_definitions/QuickUnlock/QuickUnlockModeWhitelist.yaml b/components/policy/resources/templates/policy_definitions/QuickUnlock/QuickUnlockModeWhitelist.yaml deleted file mode 100644 index e7a210f8..0000000 --- a/components/policy/resources/templates/policy_definitions/QuickUnlock/QuickUnlockModeWhitelist.yaml +++ /dev/null
@@ -1,41 +0,0 @@ -caption: Configure allowed quick unlock modes -default_for_enterprise_users: [] -deprecated: true -desc: |- - Setting the policy controls which quick unlock modes can unlock the lock screen. - - To allow: - - * Every quick unlock mode, use ["all"] (includes modes added in the future). - - * Only PIN unlock, use ["PIN"]. - - * PIN and fingerprint, use ["PIN", "FINGERPRINT"]. - - If the policy is unset or set to an empty list, no quick unlock modes are available for managed devices. - - This policy is deprecated, please use <ph name="QUICK_UNLOCK_MODE_ALLOW_LIST_POLICY_NAME">QuickUnlockModeAllowlist</ph> instead -example_value: -- PIN -features: - dynamic_refresh: true - per_profile: true -items: -- caption: All - name: all - value: all -- caption: PIN - name: PIN - value: PIN -- caption: Fingerprint - name: FINGERPRINT - value: FINGERPRINT -owners: -- file://components/policy/resources/OWNERS -- rsorokin@chromium.org -schema: - $ref: QuickUnlockModeWhitelist -supported_on: -- chrome_os:56-100 -tags: [] -type: string-enum-list
diff --git a/components/policy/resources/templates/policy_definitions/QuickUnlock/policy_atomic_groups.yaml b/components/policy/resources/templates/policy_definitions/QuickUnlock/policy_atomic_groups.yaml index 85c4df9..a139e98 100644 --- a/components/policy/resources/templates/policy_definitions/QuickUnlock/policy_atomic_groups.yaml +++ b/components/policy/resources/templates/policy_definitions/QuickUnlock/policy_atomic_groups.yaml
@@ -9,5 +9,4 @@ caption: Quick unlock policies: - QuickUnlockModeAllowlist - - QuickUnlockModeWhitelist - QuickUnlockTimeout
diff --git a/components/policy/resources/templates/policy_definitions/SafeBrowsing/SafeBrowsingWhitelistDomains.yaml b/components/policy/resources/templates/policy_definitions/SafeBrowsing/SafeBrowsingWhitelistDomains.yaml deleted file mode 100644 index e057c15f..0000000 --- a/components/policy/resources/templates/policy_definitions/SafeBrowsing/SafeBrowsingWhitelistDomains.yaml +++ /dev/null
@@ -1,28 +0,0 @@ -caption: Configure the list of domains on which Safe Browsing will not trigger warnings. -deprecated: true -desc: |- - This policy is deprecated, please use <ph name="SAFE_BROWSING_ALLOWLIST_DOMAINS_POLICY_NAME">SafeBrowsingAllowlistDomains</ph> instead. - - Setting the policy to Enabled means Safe Browsing will trust the domains you designate. It won't check them for dangerous resources such as phishing, malware, or unwanted software. Safe Browsing's download protection service won't check downloads hosted on these domains. Its password protection service won't check for password reuse. - - Setting the policy to Disabled or leaving it unset means default Safe Browsing protection applies to all resources. - - On <ph name="MS_WIN_NAME">Microsoft® Windows®</ph>, this functionality is only available on instances that are joined to a <ph name="MS_AD_NAME">Microsoft® Active Directory®</ph> domain, running on Windows 10 Pro, or enrolled in <ph name="CHROME_BROWSER_CLOUD_MANAGEMENT_NAME">Chrome Browser Cloud Management</ph>. On <ph name="MAC_OS_NAME">macOS</ph>, this functionality is only available on instances that are managed via MDM, or joined to a domain via MCX. -example_value: -- mydomain.com -- myuniversity.edu -features: - dynamic_refresh: true - per_profile: true -owners: -- nwokedi@chromium.org -- nparker@chromium.org -schema: - items: - type: string - type: array -supported_on: -- chrome.*:68-100 -- chrome_os:68-100 -tags: [] -type: list
diff --git a/components/policy/resources/templates/policy_definitions/SafeBrowsing/policy_atomic_groups.yaml b/components/policy/resources/templates/policy_definitions/SafeBrowsing/policy_atomic_groups.yaml index 7cfbc80..2a3ef96 100644 --- a/components/policy/resources/templates/policy_definitions/SafeBrowsing/policy_atomic_groups.yaml +++ b/components/policy/resources/templates/policy_definitions/SafeBrowsing/policy_atomic_groups.yaml
@@ -10,5 +10,4 @@ - SafeBrowsingEnabled - SafeBrowsingExtendedReportingEnabled - SafeBrowsingProtectionLevel - - SafeBrowsingWhitelistDomains - SafeBrowsingAllowlistDomains
diff --git a/components/policy/resources/templates/policy_definitions/Signin/DeviceSamlLoginAuthenticationType.yaml b/components/policy/resources/templates/policy_definitions/Signin/DeviceSamlLoginAuthenticationType.yaml deleted file mode 100644 index 404789b3..0000000 --- a/components/policy/resources/templates/policy_definitions/Signin/DeviceSamlLoginAuthenticationType.yaml +++ /dev/null
@@ -1,33 +0,0 @@ -caption: SAML login authentication type -desc: |- - Configures the type of authentication for SAML logins. - - When this policy is unset or set to Default (value 0), the behavior of SAML logins is determined by the browser depending on other factors. In the most basic scenario, the user authentication and the protection of the cached user data are based on passwords manually entered by users. - - When this policy is set to ClientCertificate (value 1), client certificate authentication is used for newly added users which log in via SAML. No passwords are used for such users, and their cached local data is protected using corresponding cryptographic keys. For instance, this setting allows configuring smart card based user authentication (note that smart card middleware apps have to be installed via the DeviceLoginScreenExtensions policy). - - This policy affects only users who authenticate using SAML. -device_only: true -example_value: 0 -features: - dynamic_refresh: true -future_on: -- chrome_os -items: -- caption: Default configuration - name: Default - value: 0 -- caption: Authentication based on client certificates - name: ClientCertificate - value: 1 -owners: -- file://components/policy/resources/OWNERS -- emaxx@chromium.org -schema: - enum: - - 0 - - 1 - type: integer -tags: -- system-security -type: int-enum
diff --git a/components/policy/resources/templates/policy_definitions/Signin/DeviceUserWhitelist.yaml b/components/policy/resources/templates/policy_definitions/Signin/DeviceUserWhitelist.yaml deleted file mode 100644 index 933bd19..0000000 --- a/components/policy/resources/templates/policy_definitions/Signin/DeviceUserWhitelist.yaml +++ /dev/null
@@ -1,34 +0,0 @@ -arc_support: This policy controls who may start a <ph name="PRODUCT_OS_NAME">$2<ex>ChromiumOS</ex></ph> - session. It does not prevent users from signing in to additional Google accounts - within Android. If you want to prevent this, configure the Android-specific <ph - name="ACCOUNT_TYPES_WITH_MANAGEMENT_DISABLED_CLOUDDPC_POLICY_NAME">accountTypesWithManagementDisabled</ph> - policy as part of <ph name="ARC_POLICY_POLICY_NAME">ArcPolicy</ph>. -caption: Login user white list -deprecated: true -desc: "Defines the list of users that are allowed to login to the device. Entries\ - \ are of the form <ph name=\"USER_ALLOWLIST_ENTRY_FORMAT\">user@domain</ph>, such\ - \ as <ph name=\"USER_ALLOWLIST_ENTRY_EXAMPLE\">madmax@managedchrome.com</ph>. To\ - \ allow arbitrary users on a domain, use entries of the form <ph name=\"USER_ALLOWLIST_ENTRY_WILDCARD\"\ - >*@domain</ph>.\n\n If this policy is not configured, there are no restrictions\ - \ on which users are allowed to sign in. Note that creating new users still requires\ - \ the <ph name=\"DEVICE_ALLOW_NEW_USERS_POLICY_NAME\">DeviceAllowNewUsers</ph> policy\ - \ to be configured appropriately.\n\n This policy is deprecated, please use\ - \ <ph name=\"DEVICE_USER_ALLOWLIST_POLICY_NAME\">DeviceUserAllowlist</ph> instead.\n\ - \ " -device_only: true -example_value: -- madmax@managedchrome.com -features: - dynamic_refresh: true -owners: -- file://components/policy/resources/OWNERS -- pmarko@chromium.org -schema: - items: - type: string - sensitiveValue: true - type: array -supported_on: -- chrome_os:12-100 -tags: [] -type: list
diff --git a/components/policy/resources/templates/policy_definitions/Signin/RecoveryFactorBehavior.yaml b/components/policy/resources/templates/policy_definitions/Signin/RecoveryFactorBehavior.yaml new file mode 100644 index 0000000..5e625d0 --- /dev/null +++ b/components/policy/resources/templates/policy_definitions/Signin/RecoveryFactorBehavior.yaml
@@ -0,0 +1,34 @@ +caption: Account recovery +default: true +default_for_enterprise_users: false +desc: "Specifies whether the account recovery service is activated for your users\ + \ on <ph name=\"PRODUCT_OS_NAME\">$2<ex>Google ChromeOS</ex></ph> devices.\n\n \ + \ When the policy is enabled, the user data recovery is activated. When the\ + \ policy is disabled or not set, the user data recovery is not activated.\n \ + \ Setting the policy level to recommended lets users change the account recovery\ + \ activation through the settings page. Setting the policy level to mandatory means\ + \ users can't change the account recovery activation.\n\n On the policy value\ + \ change the update process is completed on the next login to <ph name=\"PRODUCT_OS_NAME\"\ + >$2<ex>Google ChromeOS</ex></ph> device, after the new policy value was fetched.\n\ + \n Note: This setting only applies to new accounts that get added on <ph name=\"\ + PRODUCT_OS_NAME\">$2<ex>Google ChromeOS</ex></ph> devices.\n " +example_value: true +features: + can_be_mandatory: true + can_be_recommended: true + dynamic_refresh: false + per_profile: true +future_on: +- chrome_os +items: +- caption: Activate account recovery + value: true +- caption: Deactivate account recovery + value: false +owners: +- anastasiian@chromium.org +- cros-lurs@google.com +schema: + type: boolean +tags: [] +type: main
diff --git a/components/policy/resources/templates/policy_definitions/UserAndDeviceReporting/DeviceReportXDREvents.yaml b/components/policy/resources/templates/policy_definitions/UserAndDeviceReporting/DeviceReportXDREvents.yaml new file mode 100644 index 0000000..1b7a381 --- /dev/null +++ b/components/policy/resources/templates/policy_definitions/UserAndDeviceReporting/DeviceReportXDREvents.yaml
@@ -0,0 +1,29 @@ +arc_support: This policy has no effect on the logging done by Android. +caption: Report extended detection and response (XDR) events +default: false +desc: |- + Setting the policy to True has enrolled devices report information related to extended detection and response (XDR) events. + + Setting the policy to False or leaving it unset means enrolled devices don't report extended detection and response (XDR) events. +device_only: true +example_value: false +features: + dynamic_refresh: true +future_on: +- chrome_os +items: +- caption: Report information about extended detection and response (XDR) events + value: true +- caption: Do not report information about about extended detection and response (XDR) + events + value: false +owners: +- cros-reporting-team@google.com +- jrhilke@google.com +schema: + type: boolean +supported_chrome_os_management: +- google_cloud +tags: +- admin-sharing +type: main
diff --git a/components/policy/resources/templates/policy_definitions/UserAndDeviceReporting/policy_atomic_groups.yaml b/components/policy/resources/templates/policy_definitions/UserAndDeviceReporting/policy_atomic_groups.yaml index 79bee4c1..14e1e8939 100644 --- a/components/policy/resources/templates/policy_definitions/UserAndDeviceReporting/policy_atomic_groups.yaml +++ b/components/policy/resources/templates/policy_definitions/UserAndDeviceReporting/policy_atomic_groups.yaml
@@ -38,3 +38,4 @@ - HeartbeatFrequency - LogUploadEnabled - DeviceMetricsReportingEnabled + - DeviceReportXDREvents
diff --git a/components/search/ntp_features.cc b/components/search/ntp_features.cc index ad5ad16..3be93f6 100644 --- a/components/search/ntp_features.cc +++ b/components/search/ntp_features.cc
@@ -182,6 +182,10 @@ "NtpFeedModule", base::FEATURE_DISABLED_BY_DEFAULT); +// If enabled, Google Lens image search will be shown in the NTP Realbox. +const base::Feature kNtpRealboxLensSearch{"NtpRealboxLensSearch", + base::FEATURE_DISABLED_BY_DEFAULT}; + // If enabled, recipe tasks module will be shown. BASE_FEATURE(kNtpRecipeTasksModule, "NtpRecipeTasksModule",
diff --git a/components/search/ntp_features.h b/components/search/ntp_features.h index 0832cc5..21f1dda8 100644 --- a/components/search/ntp_features.h +++ b/components/search/ntp_features.h
@@ -53,11 +53,11 @@ BASE_DECLARE_FEATURE(kNtpPhotosModuleSplitSvgOptInArtWork); BASE_DECLARE_FEATURE(kNtpFeedModule); BASE_DECLARE_FEATURE(kNtpOneGoogleBar); +BASE_DECLARE_FEATURE(kNtpRealboxLensSearch); BASE_DECLARE_FEATURE(kNtpRecipeTasksModule); BASE_DECLARE_FEATURE(kNtpRemoveScrim); BASE_DECLARE_FEATURE(kNtpSafeBrowsingModule); BASE_DECLARE_FEATURE(kNtpShortcuts); - BASE_DECLARE_FEATURE(kNtpHandleMostVisitedNavigationExplicitly); // Parameter for the CSS selector for the button elements on the OGB.
diff --git a/components/sync_preferences/pref_model_associator.cc b/components/sync_preferences/pref_model_associator.cc index cc4ebce..b20af90 100644 --- a/components/sync_preferences/pref_model_associator.cc +++ b/components/sync_preferences/pref_model_associator.cc
@@ -326,8 +326,8 @@ DCHECK(to_value.type() == base::Value::Type::LIST); base::Value result = to_value.Clone(); - for (const auto& value : from_value.GetListDeprecated()) { - if (!base::Contains(result.GetListDeprecated(), value)) { + for (const auto& value : from_value.GetList()) { + if (!base::Contains(result.GetList(), value)) { result.Append(value.Clone()); } }
diff --git a/components/sync_preferences/pref_service_syncable_unittest.cc b/components/sync_preferences/pref_service_syncable_unittest.cc index b658c8b..9be3a41e 100644 --- a/components/sync_preferences/pref_service_syncable_unittest.cc +++ b/components/sync_preferences/pref_service_syncable_unittest.cc
@@ -651,7 +651,7 @@ pref_registry_->RegisterListPref( pref_name, user_prefs::PrefRegistrySyncable::SYNCABLE_PREF); - EXPECT_TRUE(GetPreferenceValue(pref_name).GetListDeprecated().empty()); + EXPECT_TRUE(GetPreferenceValue(pref_name).GetList().empty()); EXPECT_FALSE(user_prefs_->GetValue(pref_name, nullptr)); prefs_.RemoveSyncedPrefObserver(pref_name, &observer);
diff --git a/content/app/BUILD.gn b/content/app/BUILD.gn index 4717617..faec429 100644 --- a/content/app/BUILD.gn +++ b/content/app/BUILD.gn
@@ -6,6 +6,7 @@ import("//build/config/chromeos/ui_mode.gni") import("//build/config/features.gni") import("//ppapi/buildflags/buildflags.gni") +import("//third_party/tflite/features.gni") extra_configs = [ "//build/config/compiler:wexit_time_destructors", @@ -73,6 +74,7 @@ configs += extra_configs deps = content_app_deps + [ + "//components/optimization_guide:machine_learning_tflite_buildflags", "//components/power_scheduler", "//content/browser", "//content/gpu:gpu_sources", @@ -90,6 +92,9 @@ "//chromeos/startup:constants", ] } + if (build_tflite_with_xnnpack) { + deps += [ "//third_party/cpuinfo" ] + } } source_set("app") {
diff --git a/content/app/DEPS b/content/app/DEPS index 058afd7..044a3d0 100644 --- a/content/app/DEPS +++ b/content/app/DEPS
@@ -2,6 +2,7 @@ "+chromeos/startup", "+components/discardable_memory", "+components/download", + "+components/optimization_guide", "+components/tracing/common", "+content", "+device/bluetooth", @@ -13,4 +14,5 @@ "+services/network/public/cpp/features.h", "+services/resource_coordinator/public", "+services/tracing/public/cpp", + "+third_party/cpuinfo/src/include/cpuinfo.h", ]
diff --git a/content/app/content_main_runner_impl.cc b/content/app/content_main_runner_impl.cc index 8967bb50..302fd81 100644 --- a/content/app/content_main_runner_impl.cc +++ b/content/app/content_main_runner_impl.cc
@@ -49,6 +49,7 @@ #include "build/chromeos_buildflags.h" #include "components/discardable_memory/service/discardable_shared_memory_manager.h" #include "components/download/public/common/download_task_runner.h" +#include "components/optimization_guide/machine_learning_tflite_buildflags.h" #include "components/power_scheduler/power_mode_arbiter.h" #include "components/variations/variations_ids_provider.h" #include "content/app/mojo/mojo_init.h" @@ -188,6 +189,10 @@ #include "base/fuchsia/system_info.h" #endif +#if BUILDFLAG(BUILD_TFLITE_WITH_XNNPACK) +#include "third_party/cpuinfo/src/include/cpuinfo.h" +#endif + namespace content { extern int GpuMain(MainFunctionParams); #if BUILDFLAG(ENABLE_PPAPI) @@ -427,6 +432,13 @@ #endif InitializeWebRtcModule(); +#if BUILDFLAG(BUILD_TFLITE_WITH_XNNPACK) + // cpuinfo needs to parse /proc/cpuinfo, or its equivalent. + if (!cpuinfo_initialize()) { + LOG(ERROR) << "Failed to initialize cpuinfo"; + } +#endif + // Set the android SkFontMgr for blink. We need to ensure this is done // before the sandbox is initialized to allow the font manager to access // font configuration files on disk.
diff --git a/content/browser/BUILD.gn b/content/browser/BUILD.gn index 762b186..b515606 100644 --- a/content/browser/BUILD.gn +++ b/content/browser/BUILD.gn
@@ -714,8 +714,6 @@ "code_cache/simple_lru_cache.h", "compositor/surface_utils.cc", "compositor/surface_utils.h", - "compute_pressure/pressure_quantizer.cc", - "compute_pressure/pressure_quantizer.h", "compute_pressure/pressure_service_impl.cc", "compute_pressure/pressure_service_impl.h", "contacts/contacts_manager_impl.cc",
diff --git a/content/browser/aggregation_service/aggregation_service_features.cc b/content/browser/aggregation_service/aggregation_service_features.cc index 5e014de..84578f95 100644 --- a/content/browser/aggregation_service/aggregation_service_features.cc +++ b/content/browser/aggregation_service/aggregation_service_features.cc
@@ -7,8 +7,9 @@ namespace content { // Enables the Aggregation Service. See crbug.com/1207974. -const base::Feature kPrivacySandboxAggregationService = { - "PrivacySandboxAggregationService", base::FEATURE_ENABLED_BY_DEFAULT}; +BASE_FEATURE(kPrivacySandboxAggregationService, + "PrivacySandboxAggregationService", + base::FEATURE_ENABLED_BY_DEFAULT); const base::FeatureParam<std::string> kPrivacySandboxAggregationServiceTrustedServerUrlParam{
diff --git a/content/browser/aggregation_service/aggregation_service_features.h b/content/browser/aggregation_service/aggregation_service_features.h index 6e08c60a..c3c33df 100644 --- a/content/browser/aggregation_service/aggregation_service_features.h +++ b/content/browser/aggregation_service/aggregation_service_features.h
@@ -12,7 +12,7 @@ namespace content { // Enables the Aggregation Service. See crbug.com/1207974. -extern CONTENT_EXPORT const base::Feature kPrivacySandboxAggregationService; +CONTENT_EXPORT BASE_DECLARE_FEATURE(kPrivacySandboxAggregationService); extern CONTENT_EXPORT const base::FeatureParam<std::string> kPrivacySandboxAggregationServiceTrustedServerUrlParam;
diff --git a/content/browser/android/battery_metrics.cc b/content/browser/android/battery_metrics.cc index 3f2862e2..029d02cb 100644 --- a/content/browser/android/battery_metrics.cc +++ b/content/browser/android/battery_metrics.cc
@@ -29,15 +29,17 @@ #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/blink/public/mojom/webpreferences/web_preferences.mojom.h" -const base::Feature kForegroundRadioStateCountWakeups{ - "ForegroundRadioStateCountWakeups", base::FEATURE_DISABLED_BY_DEFAULT}; +BASE_FEATURE(kForegroundRadioStateCountWakeups, + "ForegroundRadioStateCountWakeups", + base::FEATURE_DISABLED_BY_DEFAULT); // Keeps reporting of the battery metrics on the UI thread, where it may cause // jank. This is used for a holdback experiment to estimate the jank reduction // won by moving reporting to the thread pool. // TODO(eseckler): Remove once holdback experiment is complete. -const base::Feature kAndroidBatteryMetricsReportOnUIThread{ - "AndroidBatteryMetricsReportOnUIThread", base::FEATURE_DISABLED_BY_DEFAULT}; +BASE_FEATURE(kAndroidBatteryMetricsReportOnUIThread, + "AndroidBatteryMetricsReportOnUIThread", + base::FEATURE_DISABLED_BY_DEFAULT); namespace content { namespace {
diff --git a/content/browser/android/web_contents_observer_proxy.cc b/content/browser/android/web_contents_observer_proxy.cc index dafe6a1..bf49e2c 100644 --- a/content/browser/android/web_contents_observer_proxy.cc +++ b/content/browser/android/web_contents_observer_proxy.cc
@@ -32,8 +32,9 @@ namespace features { -const base::Feature kNotifyJavaSpuriouslyToMeasurePerf{ - "NotifyJavaSpuriouslyToMeasurePerf", base::FEATURE_DISABLED_BY_DEFAULT}; +BASE_FEATURE(kNotifyJavaSpuriouslyToMeasurePerf, + "NotifyJavaSpuriouslyToMeasurePerf", + base::FEATURE_DISABLED_BY_DEFAULT); } // namespace features
diff --git a/content/browser/browser_main_loop.cc b/content/browser/browser_main_loop.cc index e9267dc2..c6af082 100644 --- a/content/browser/browser_main_loop.cc +++ b/content/browser/browser_main_loop.cc
@@ -392,8 +392,9 @@ // dynamic code or modifying executable code. See comments in // sandbox/win/src/security_level.h. Only available on Windows 10 RS1 (1607, // Build 14393) onwards. -const base::Feature kBrowserDynamicCodeDisabled{ - "BrowserDynamicCodeDisabled", base::FEATURE_DISABLED_BY_DEFAULT}; +BASE_FEATURE(kBrowserDynamicCodeDisabled, + "BrowserDynamicCodeDisabled", + base::FEATURE_DISABLED_BY_DEFAULT); #endif // BUILDFLAG(IS_WIN) class OopDataDecoder : public data_decoder::ServiceProvider {
diff --git a/content/browser/cache_storage/cache_storage_scheduler.cc b/content/browser/cache_storage/cache_storage_scheduler.cc index 28cb123..0bdbf69d 100644 --- a/content/browser/cache_storage/cache_storage_scheduler.cc +++ b/content/browser/cache_storage/cache_storage_scheduler.cc
@@ -52,8 +52,9 @@ // Enables support for parallel cache_storage operations via the // "max_shared_ops" fieldtrial parameter. -const base::Feature kCacheStorageParallelOps{"CacheStorageParallelOps", - base::FEATURE_ENABLED_BY_DEFAULT}; +BASE_FEATURE(kCacheStorageParallelOps, + "CacheStorageParallelOps", + base::FEATURE_ENABLED_BY_DEFAULT); CacheStorageScheduler::CacheStorageScheduler( CacheStorageSchedulerClient client_type,
diff --git a/content/browser/cache_storage/cache_storage_scheduler.h b/content/browser/cache_storage/cache_storage_scheduler.h index bb2d902..de0fcab 100644 --- a/content/browser/cache_storage/cache_storage_scheduler.h +++ b/content/browser/cache_storage/cache_storage_scheduler.h
@@ -19,7 +19,7 @@ class CacheStorageOperation; -CONTENT_EXPORT extern const base::Feature kCacheStorageParallelOps; +CONTENT_EXPORT BASE_DECLARE_FEATURE(kCacheStorageParallelOps); // TODO(jkarlin): Support operation identification so that ops can be checked in // DCHECKs.
diff --git a/content/browser/compute_pressure/README.md b/content/browser/compute_pressure/README.md index 02bc668..721a68f 100644 --- a/content/browser/compute_pressure/README.md +++ b/content/browser/compute_pressure/README.md
@@ -17,7 +17,8 @@ implementation. The class is responsible for handling the communication between the browser process and services. -`device::PressureSample` represents the device's compute pressure state. +`device::mojom::PressureUpdate` represents the device's compute pressure update, +composed of the `device::mojom::PressureState` and the timestamp. This information is collected by `device::CpuProbe` and bubbled up by `device::PlatformCollector` to `device::PressureManagerImpl`, which broadcasts the information to the `content::PressureServiceImpl` instances. @@ -34,20 +35,13 @@ `content::PressureServiceImpl` serves the mojo connection for a frame. Each instance is owned by a `content::RenderFrameHostImpl`. The class receives -`device::mojom::PressureState` from `device::PressureManagerImpl` and +`device::mojom::PressureUpdate` from `device::PressureManagerImpl` and broadcasts the information to the `blink::PressureObserverManager` instance. -`content::PressureQuantizer` implements the quantization logic that converts -a high-entropy `device::mojom::PressureState` into a low-entropy one, which -minimizes the amount of information exposed to a Web page that uses the -Compute Pressure API. Each `content::PressureServiceImpl` uses a -`content::PressureQuantizer` instance, which stores the frame's -quantization schema and produces quantized data suitable for frame. - `blink::PressureObserver` implements bindings for the PressureObserver interface. There can be more than one PressureObserver per frame. `blink::PressureObserverManager` maintains the list of active observers. -All active observers should use the same quantization schema. The class -receives `device::mojom::PressureState` from `content::PressureServiceImpl` -and broadcasts the information to active observers. +The class receives `device::mojom::PressureUpdate` from +`content::PressureServiceImpl` and broadcasts the information to active +observers.
diff --git a/content/browser/compute_pressure/pressure_quantizer.cc b/content/browser/compute_pressure/pressure_quantizer.cc deleted file mode 100644 index d49e319b..0000000 --- a/content/browser/compute_pressure/pressure_quantizer.cc +++ /dev/null
@@ -1,126 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "content/browser/compute_pressure/pressure_quantizer.h" - -#include <vector> - -namespace content { - -PressureQuantizer::PressureQuantizer() = default; - -PressureQuantizer::~PressureQuantizer() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); -} - -// static -bool PressureQuantizer::IsValid( - const blink::mojom::PressureQuantization& quantization) { - if (quantization.cpu_utilization_thresholds.size() > - blink::mojom::kMaxPressureCpuUtilizationThresholds) { - return false; - } - if (!ValueQuantizer::IsValid(quantization.cpu_utilization_thresholds)) - return false; - - return true; -} - -bool PressureQuantizer::IsSame( - const blink::mojom::PressureQuantization& quantization) const { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(PressureQuantizer::IsValid(quantization)); - - if (!cpu_utilization_quantizer_.IsSame( - quantization.cpu_utilization_thresholds)) { - return false; - } - - return true; -} - -device::mojom::PressureState PressureQuantizer::Quantize( - device::mojom::PressureStatePtr sample) const { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - device::mojom::PressureState state; - state.cpu_utilization = - cpu_utilization_quantizer_.Quantize(sample->cpu_utilization); - - return state; -} - -void PressureQuantizer::Assign( - blink::mojom::PressureQuantizationPtr quantization) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(PressureQuantizer::IsValid(*quantization)); - - cpu_utilization_quantizer_.Assign( - std::move(quantization->cpu_utilization_thresholds)); -} - -PressureQuantizer::ValueQuantizer::ValueQuantizer() = default; - -PressureQuantizer::ValueQuantizer::~ValueQuantizer() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); -} - -// static -bool PressureQuantizer::ValueQuantizer::IsValid( - const std::vector<double>& thresholds) { - double last_threshold = 0.0; - - for (double threshold : thresholds) { - if (threshold <= 0.0 || threshold >= 1.0) - return false; - - if (threshold <= last_threshold) - return false; - - last_threshold = threshold; - } - return true; -} - -bool PressureQuantizer::ValueQuantizer::IsSame( - const std::vector<double>& thresholds) const { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(ValueQuantizer::IsValid(thresholds)); - - if (thresholds_.size() != thresholds.size()) - return false; - - for (size_t i = 0; i < thresholds_.size(); ++i) { - if (std::abs(thresholds_[i] - thresholds[i]) >= 0.00001) - return false; - } - return true; -} - -double PressureQuantizer::ValueQuantizer::Quantize(double value) const { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - double lower_bound = 0.0; - double upper_bound = 1.0; - - for (double threshold : thresholds_) { - DCHECK_GT(threshold, lower_bound) << "thresholds_ is not sorted"; - if (value < threshold) { - upper_bound = threshold; - break; - } - lower_bound = threshold; - } - - return (lower_bound + upper_bound) / 2; -} - -void PressureQuantizer::ValueQuantizer::Assign(std::vector<double> thresholds) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(ValueQuantizer::IsValid(thresholds)); - - thresholds_ = std::move(thresholds); -} - -} // namespace content
diff --git a/content/browser/compute_pressure/pressure_quantizer.h b/content/browser/compute_pressure/pressure_quantizer.h deleted file mode 100644 index d5dcb0d..0000000 --- a/content/browser/compute_pressure/pressure_quantizer.h +++ /dev/null
@@ -1,89 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_BROWSER_COMPUTE_PRESSURE_PRESSURE_QUANTIZER_H_ -#define CONTENT_BROWSER_COMPUTE_PRESSURE_PRESSURE_QUANTIZER_H_ - -#include <vector> - -#include "base/sequence_checker.h" -#include "base/thread_annotations.h" -#include "content/common/content_export.h" -#include "services/device/public/mojom/pressure_state.mojom.h" -#include "third_party/blink/public/mojom/compute_pressure/pressure_service.mojom.h" - -namespace content { - -// Quantizes compute pressure data for a frame. -// -// See blink::mojom::PressureQuantization for a descripion of the quantization -// scheme. The scheme converts a high-entropy device::mojom::PressureState -// into a low-entropy one, which minimizes the amount of information exposed -// to a Web page that uses the Compute Pressure API. -// -// This class is not thread-safe, so each instance must be used on one sequence. -class CONTENT_EXPORT PressureQuantizer { - public: - // Creates a quantizer with the single sub-interval [0, 1]. - // - // Until Assign() is called, all values will be quantized to the same value. - PressureQuantizer(); - ~PressureQuantizer(); - - PressureQuantizer(const PressureQuantizer&) = delete; - PressureQuantizer& operator=(const PressureQuantizer&) = delete; - - // True iff `quantization` is a valid pressure quantization scheme. - static bool IsValid(const blink::mojom::PressureQuantization& quantization); - - // True if this quantizer's scheme is the same as `quantization`. - // - // This is a bit more complicated than element-wise vector equality to allow - // for floating-point precision errors, such as 0.5 != 0.2 + 0.3. - // - // `quantization` must be valid. - bool IsSame(const blink::mojom::PressureQuantization& quantization) const; - - // Overwrites the quantization scheme used by this quantizer. - void Assign(blink::mojom::PressureQuantizationPtr quantization); - - // Quantizes `sample` using the current quantization scheme. - device::mojom::PressureState Quantize( - device::mojom::PressureStatePtr sample) const; - - private: - // Quantizes a single value in compute pressure data. - class ValueQuantizer { - public: - ValueQuantizer(); - ~ValueQuantizer(); - - ValueQuantizer(const ValueQuantizer&) = delete; - ValueQuantizer& operator=(const ValueQuantizer&) = delete; - - static bool IsValid(const std::vector<double>& thresholds); - bool IsSame(const std::vector<double>& thresholds) const; - double Quantize(double value) const; - void Assign(std::vector<double> thresholds); - - private: - SEQUENCE_CHECKER(sequence_checker_); - - // The array of thresholds passes the IsValid() check. - // - // This means that the array is sorted and does not include 0.0 or 1.0. An - // empty array is a valid quantizing scheme that transforms every input to - // 0.5. - std::vector<double> thresholds_ GUARDED_BY_CONTEXT(sequence_checker_); - }; - - SEQUENCE_CHECKER(sequence_checker_); - - ValueQuantizer cpu_utilization_quantizer_ - GUARDED_BY_CONTEXT(sequence_checker_); -}; - -} // namespace content - -#endif // CONTENT_BROWSER_COMPUTE_PRESSURE_PRESSURE_QUANTIZER_H_
diff --git a/content/browser/compute_pressure/pressure_quantizer_unittest.cc b/content/browser/compute_pressure/pressure_quantizer_unittest.cc deleted file mode 100644 index 148c061..0000000 --- a/content/browser/compute_pressure/pressure_quantizer_unittest.cc +++ /dev/null
@@ -1,122 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "content/browser/compute_pressure/pressure_quantizer.h" - -#include <utility> -#include <vector> - -#include "services/device/public/mojom/pressure_state.mojom.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "third_party/blink/public/mojom/compute_pressure/pressure_service.mojom.h" - -namespace content { - -using blink::mojom::PressureQuantization; -using device::mojom::PressureState; - -TEST(PressureQuantizer, IsValid_Valid) { - std::vector<PressureQuantization> valid_cases = { - PressureQuantization{}, - PressureQuantization{{0.5}}, - PressureQuantization{{0.2, 0.5, 0.8}}, - }; - - for (const auto& quantization : valid_cases) { - EXPECT_TRUE(PressureQuantizer::IsValid(quantization)); - } -} - -TEST(PressureQuantizer, IsValid_Invalid) { - std::vector<PressureQuantization> invalid_cases = { - PressureQuantization{ - {0.2, 0.3, 0.4, 0.5}}, // Too many utilization thresholds. - PressureQuantization{{0.2, 0.8, 0.5}}, // Incorrectly sorted thresholds. - PressureQuantization{{-1.0}}, // Threshold outside range. - PressureQuantization{{0.0}}, - PressureQuantization{{1.0}}, - PressureQuantization{{2.0}}, - }; - - for (const auto& quantization : invalid_cases) { - EXPECT_FALSE(PressureQuantizer::IsValid(quantization)); - } -} - -TEST(PressureQuantizer, IsSame_True) { - std::vector<std::pair<PressureQuantization, PressureQuantization>> - true_cases = { - {PressureQuantization{{0.1}}, PressureQuantization{{0.1}}}, - {PressureQuantization{{0.2, 0.5, 0.8}}, - PressureQuantization{{0.2, 0.5, 0.8}}}, - {PressureQuantization{{0.3}}, - PressureQuantization{{0.1 + 0.1 + 0.1}}}, - }; - - for (const auto& quantizations : true_cases) { - PressureQuantizer quantizer; - quantizer.Assign(quantizations.first.Clone()); - EXPECT_TRUE(quantizer.IsSame(quantizations.second)); - } -} - -TEST(PressureQuantizer, IsSame_False) { - std::vector<std::pair<PressureQuantization, PressureQuantization>> - false_cases = { - {PressureQuantization{{0.1}}, PressureQuantization{{0.2}}}, - {PressureQuantization{{0.1, 0.15}}, PressureQuantization{{0.1}}}, - {PressureQuantization{{0.1}}, PressureQuantization{{0.1, 0.15}}}, - {PressureQuantization{{0.1}}, PressureQuantization{{0.101}}}, - {PressureQuantization{{0.2, 0.5, 0.8}}, - PressureQuantization{{0.2, 0.6, 0.8}}}, - {PressureQuantization{{0.2, 0.5, 0.8}}, - PressureQuantization{{0.2, 0.5, 0.9}}}, - }; - - for (const auto& quantizations : false_cases) { - PressureQuantizer quantizer; - quantizer.Assign(quantizations.first.Clone()); - EXPECT_FALSE(quantizer.IsSame(quantizations.second)); - } -} - -TEST(PressureQuantizer, Quantize_Empty) { - PressureQuantizer quantizer; - auto empty_quantization_ptr = PressureQuantization::New(); - quantizer.Assign(std::move(empty_quantization_ptr)); - - EXPECT_EQ(PressureState{0.5}, quantizer.Quantize(PressureState{0.0}.Clone())); - EXPECT_EQ(PressureState{0.5}, quantizer.Quantize(PressureState{1.0}.Clone())); -} - -TEST(PressureQuantizer, Quantize) { - PressureQuantizer quantizer; - auto quantization_ptr = - PressureQuantization::New(std::vector<double>{0.2, 0.5, 0.8}); - quantizer.Assign(std::move(quantization_ptr)); - - std::vector<std::pair<PressureState, PressureState>> test_cases = { - {PressureState{0.0}, PressureState{0.1}}, - {PressureState{1.0}, PressureState{0.9}}, - {PressureState{0.1}, PressureState{0.1}}, - {PressureState{0.19}, PressureState{0.1}}, - {PressureState{0.21}, PressureState{0.35}}, - {PressureState{0.49}, PressureState{0.35}}, - {PressureState{0.51}, PressureState{0.65}}, - {PressureState{0.79}, PressureState{0.65}}, - {PressureState{0.81}, PressureState{0.9}}, - {PressureState{0.99}, PressureState{0.9}}, - }; - - for (const auto& test_case : test_cases) { - PressureState input = test_case.first; - PressureState expected = test_case.second; - PressureState output = quantizer.Quantize(input.Clone()); - - EXPECT_DOUBLE_EQ(expected.cpu_utilization, output.cpu_utilization) - << "Input cpu_utilization is: " << input.cpu_utilization; - } -} - -} // namespace content
diff --git a/content/browser/compute_pressure/pressure_service_impl.cc b/content/browser/compute_pressure/pressure_service_impl.cc index 25609651..c0c9252 100644 --- a/content/browser/compute_pressure/pressure_service_impl.cc +++ b/content/browser/compute_pressure/pressure_service_impl.cc
@@ -106,48 +106,17 @@ &PressureServiceImpl::ResetObserverState, base::Unretained(this))); } -void PressureServiceImpl::SetQuantization( - blink::mojom::PressureQuantizationPtr quantization, - SetQuantizationCallback callback) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - if (!remote_.is_bound() || !client_.is_bound()) { - receiver_.ReportBadMessage("Not connected to pressure service"); - return; - } - - if (!PressureQuantizer::IsValid(*quantization)) { - receiver_.ReportBadMessage("Invalid quantization"); - return; - } - - const bool quantization_changed = !quantizer_.IsSame(*quantization); - if (quantization_changed) { - ResetTimestampAndState(); - quantizer_.Assign(std::move(quantization)); - } - auto status = quantization_changed - ? blink::mojom::SetQuantizationStatus::kChanged - : blink::mojom::SetQuantizationStatus::kUnchanged; - std::move(callback).Run(status); -} - void PressureServiceImpl::PressureStateChanged( - device::mojom::PressureStatePtr state, - base::Time timestamp) { + device::mojom::PressureUpdatePtr update) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - device::mojom::PressureState quantized_state = - quantizer_.Quantize(std::move(state)); - // TODO(jsbell): Rate-limit observers in non-visible frames instead of // cutting off their updates completely. - if (timestamp - last_reported_timestamp_ < visible_observer_rate_limit_) + if (last_reported_update_ && + update->timestamp - last_reported_update_->timestamp < + visible_observer_rate_limit_) { return; - - // No need to send an update if previous value is similar. - if (last_reported_state_ == quantized_state) - return; + } if (!render_frame_host().IsActive()) { // TODO(jsbell): Is it safe to disconnect observers in this state? @@ -161,10 +130,8 @@ return; } - last_reported_timestamp_ = timestamp; - last_reported_state_ = quantized_state; - - observer_->OnUpdate(quantized_state.Clone()); + last_reported_update_ = update.Clone(); + observer_->OnUpdate(update.Clone()); } void PressureServiceImpl::OnObserverRemoteDisconnected() { @@ -199,18 +166,9 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); observer_.reset(); - ResetTimestampAndState(); -} - -void PressureServiceImpl::ResetTimestampAndState() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - // Makes sure that rate-limiting can't be bypassed by changing the - // quantization scheme often. - last_reported_timestamp_ = base::Time::Now(); // Setting to an invalid value, so any state is considered an update. - last_reported_state_ = device::mojom::PressureState(-1); + last_reported_update_ = nullptr; } DOCUMENT_USER_DATA_KEY_IMPL(PressureServiceImpl);
diff --git a/content/browser/compute_pressure/pressure_service_impl.h b/content/browser/compute_pressure/pressure_service_impl.h index 29047ce..e4b0937 100644 --- a/content/browser/compute_pressure/pressure_service_impl.h +++ b/content/browser/compute_pressure/pressure_service_impl.h
@@ -9,13 +9,12 @@ #include "base/sequence_checker.h" #include "base/thread_annotations.h" #include "base/time/time.h" -#include "content/browser/compute_pressure/pressure_quantizer.h" #include "content/common/content_export.h" #include "content/public/browser/document_user_data.h" #include "mojo/public/cpp/bindings/receiver.h" #include "mojo/public/cpp/bindings/remote.h" #include "services/device/public/mojom/pressure_manager.mojom.h" -#include "services/device/public/mojom/pressure_state.mojom.h" +#include "services/device/public/mojom/pressure_update.mojom.h" #include "third_party/blink/public/mojom/compute_pressure/pressure_service.mojom.h" namespace content { @@ -50,12 +49,9 @@ void BindObserver( mojo::PendingRemote<blink::mojom::PressureObserver> observer, BindObserverCallback callback) override; - void SetQuantization(blink::mojom::PressureQuantizationPtr quantization, - SetQuantizationCallback callback) override; // device::mojom::PressureClient implementation. - void PressureStateChanged(device::mojom::PressureStatePtr state, - base::Time timestamp) override; + void PressureStateChanged(device::mojom::PressureUpdatePtr update) override; private: PressureServiceImpl(RenderFrameHost* render_frame_host, @@ -70,30 +66,19 @@ // Resets the state used to dispatch updates to observer. void ResetObserverState(); - // Called when the quantizing scheme changes. - void ResetTimestampAndState(); - SEQUENCE_CHECKER(sequence_checker_); // The minimum delay between two Update() calls for observers belonging to // the frame. const base::TimeDelta visible_observer_rate_limit_; - // Implements the quantizing scheme used for all the frame's observers. - PressureQuantizer quantizer_ GUARDED_BY_CONTEXT(sequence_checker_); - - // The (quantized) sample that was last reported to this frame's observers. + // The update that was last reported to this frame's observers. // // Stored to avoid sending updates when the underlying compute pressure state // changes, but quantization produces the same values that were reported in // the last update. - device::mojom::PressureState last_reported_state_ - GUARDED_BY_CONTEXT(sequence_checker_); - - // The last time the frame's observers received an update. - // - // Stored to implement rate-limiting. - base::Time last_reported_timestamp_ GUARDED_BY_CONTEXT(sequence_checker_); + device::mojom::PressureUpdatePtr last_reported_update_ + GUARDED_BY_CONTEXT(sequence_checker_) = nullptr; // Callback from |receiver_| is passed to |remote_| and the Receiver // should be destroyed first so that the callback is invalidated before
diff --git a/content/browser/compute_pressure/pressure_service_impl_unittest.cc b/content/browser/compute_pressure/pressure_service_impl_unittest.cc index 7dbc177..8905958 100644 --- a/content/browser/compute_pressure/pressure_service_impl_unittest.cc +++ b/content/browser/compute_pressure/pressure_service_impl_unittest.cc
@@ -18,7 +18,6 @@ #include "mojo/public/cpp/test_support/test_utils.h" #include "services/device/public/cpp/test/scoped_pressure_manager_overrider.h" #include "services/device/public/mojom/pressure_manager.mojom.h" -#include "services/device/public/mojom/pressure_state.mojom.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/mojom/compute_pressure/pressure_service.mojom.h" @@ -26,8 +25,8 @@ namespace content { -using blink::mojom::PressureQuantization; using device::mojom::PressureState; +using device::mojom::PressureUpdate; namespace { @@ -53,13 +52,6 @@ return future.Get(); } - blink::mojom::SetQuantizationStatus SetQuantization( - const PressureQuantization& quantization) { - base::test::TestFuture<blink::mojom::SetQuantizationStatus> future; - service_.SetQuantization(quantization.Clone(), future.GetCallback()); - return future.Get(); - } - private: // The reference is immutable, so accessing it is thread-safe. The referenced // blink::mojom::PressureService implementation is called synchronously, @@ -79,7 +71,7 @@ FakePressureObserver& operator=(const FakePressureObserver&) = delete; // blink::mojom::PressureObserver implementation. - void OnUpdate(device::mojom::PressureStatePtr state) override { + void OnUpdate(device::mojom::PressureUpdatePtr state) override { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); updates_.push_back(*state); @@ -89,7 +81,7 @@ } } - std::vector<PressureState>& updates() { + std::vector<PressureUpdate>& updates() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); return updates_; } @@ -128,7 +120,7 @@ private: SEQUENCE_CHECKER(sequence_checker_); - std::vector<PressureState> updates_ GUARDED_BY_CONTEXT(sequence_checker_); + std::vector<PressureUpdate> updates_ GUARDED_BY_CONTEXT(sequence_checker_); // Used to implement WaitForUpdate(). base::OnceClosure update_callback_ GUARDED_BY_CONTEXT(sequence_checker_); @@ -175,8 +167,6 @@ protected: const GURL kTestUrl{"https://example.com/compute_pressure.html"}; const GURL kInsecureUrl{"http://example.com/compute_pressure.html"}; - // Quantization scheme used in most tests. - const PressureQuantization kQuantization{{0.2, 0.5, 0.8}}; base::test::ScopedFeatureList scoped_feature_list_; @@ -191,15 +181,13 @@ ASSERT_EQ(pressure_service_impl_sync_->BindObserver( observer.BindNewPipeAndPassRemote()), blink::mojom::PressureStatus::kOk); - ASSERT_EQ(pressure_service_impl_sync_->SetQuantization(kQuantization), - blink::mojom::SetQuantizationStatus::kChanged); const base::Time time = base::Time::Now() + kRateLimit; - const PressureState state{0.42}; - pressure_manager_overrider_->UpdateClients(state, time); + PressureUpdate update(PressureState::kNominal, time); + pressure_manager_overrider_->UpdateClients(update); observer.WaitForUpdate(); ASSERT_EQ(observer.updates().size(), 1u); - EXPECT_EQ(observer.updates()[0], PressureState{0.35}); + EXPECT_EQ(observer.updates()[0], update); } TEST_F(PressureServiceImplTest, UpdateRateLimiting) { @@ -207,121 +195,22 @@ ASSERT_EQ(pressure_service_impl_sync_->BindObserver( observer.BindNewPipeAndPassRemote()), blink::mojom::PressureStatus::kOk); - ASSERT_EQ(pressure_service_impl_sync_->SetQuantization(kQuantization), - blink::mojom::SetQuantizationStatus::kChanged); const base::Time time = base::Time::Now(); - const PressureState state1{0.42}; - pressure_manager_overrider_->UpdateClients(state1, time + kRateLimit); + PressureUpdate update1(PressureState::kNominal, time + kRateLimit); + pressure_manager_overrider_->UpdateClients(update1); observer.WaitForUpdate(); observer.updates().clear(); // The first update should be blocked due to rate-limiting. - const PressureState state2{1.0}; - pressure_manager_overrider_->UpdateClients(state2, time + kRateLimit * 1.5); - const PressureState state3{0.0}; - pressure_manager_overrider_->UpdateClients(state3, time + kRateLimit * 2); + PressureUpdate update2(PressureState::kCritical, time + kRateLimit * 1.5); + pressure_manager_overrider_->UpdateClients(update2); + PressureUpdate update3(PressureState::kFair, time + kRateLimit * 2); + pressure_manager_overrider_->UpdateClients(update3); observer.WaitForUpdate(); ASSERT_EQ(observer.updates().size(), 1u); - EXPECT_EQ(observer.updates()[0], PressureState{0.1}); -} - -TEST_F(PressureServiceImplTest, NoCallbackInvoked_SameBucket) { - FakePressureObserver observer; - ASSERT_EQ(pressure_service_impl_sync_->BindObserver( - observer.BindNewPipeAndPassRemote()), - blink::mojom::PressureStatus::kOk); - ASSERT_EQ(pressure_service_impl_sync_->SetQuantization(kQuantization), - blink::mojom::SetQuantizationStatus::kChanged); - - const base::Time time = base::Time::Now() + kRateLimit; - const PressureState state1{0.42}; - pressure_manager_overrider_->UpdateClients(state1, time); - observer.WaitForUpdate(); - ASSERT_EQ(observer.updates().size(), 1u); - EXPECT_EQ(observer.updates()[0], PressureState{0.35}); - - // The first update should be discarded due to same bucket - const PressureState state2{0.37}; - pressure_manager_overrider_->UpdateClients(state2, time + kRateLimit); - const PressureState state3{0.52}; - pressure_manager_overrider_->UpdateClients(state3, time + kRateLimit * 2); - observer.WaitForUpdate(); - ASSERT_EQ(observer.updates().size(), 2u); - EXPECT_EQ(observer.updates()[1], PressureState{0.65}); -} - -TEST_F(PressureServiceImplTest, BindRateLimiting) { - const base::Time before_add = base::Time::Now(); - - FakePressureObserver observer; - ASSERT_EQ(pressure_service_impl_sync_->BindObserver( - observer.BindNewPipeAndPassRemote()), - blink::mojom::PressureStatus::kOk); - ASSERT_EQ(pressure_service_impl_sync_->SetQuantization(kQuantization), - blink::mojom::SetQuantizationStatus::kChanged); - - const base::Time after_add = base::Time::Now(); - - ASSERT_LE(after_add - before_add, base::Milliseconds(500)) - << "test timings assume that BindObserver completes in at most 500ms"; - - // The first update should be blocked due to rate-limiting. - const PressureState state1{0.42}; - const base::Time time1 = before_add + base::Milliseconds(700); - pressure_manager_overrider_->UpdateClients(state1, time1); - const PressureState state2{0.0}; - const base::Time time2 = before_add + base::Milliseconds(1600); - pressure_manager_overrider_->UpdateClients(state2, time2); - observer.WaitForUpdate(); - - ASSERT_EQ(observer.updates().size(), 1u); - EXPECT_EQ(observer.updates()[0], PressureState{0.1}); -} - -TEST_F(PressureServiceImplTest, NewQuantization) { - const PressureState state{0.42}; - - // 0.42 would quantize as 0.4 - PressureQuantization quantization1{{0.8}}; - FakePressureObserver observer; - ASSERT_EQ(pressure_service_impl_sync_->BindObserver( - observer.BindNewPipeAndPassRemote()), - blink::mojom::PressureStatus::kOk); - ASSERT_EQ(pressure_service_impl_sync_->SetQuantization(quantization1), - blink::mojom::SetQuantizationStatus::kChanged); - - const base::Time time1 = base::Time::Now() + kRateLimit; - pressure_manager_overrider_->UpdateClients(state, time1); - observer.WaitForUpdate(); - ASSERT_EQ(observer.updates().size(), 1u); - EXPECT_EQ(observer.updates()[0], PressureState{0.4}); - observer.updates().clear(); - - // 0.42 would quantize as 0.6 - PressureQuantization quantization2{{0.2}}; - ASSERT_EQ(pressure_service_impl_sync_->SetQuantization(quantization2), - blink::mojom::SetQuantizationStatus::kChanged); - - const base::Time time2 = base::Time::Now() + kRateLimit; - pressure_manager_overrider_->UpdateClients(state, time2); - observer.WaitForUpdate(); - ASSERT_EQ(observer.updates().size(), 1u); - EXPECT_EQ(observer.updates()[0], PressureState{0.6}); - observer.updates().clear(); - - // 0.42 would quantize as 0.25 - PressureQuantization quantization3{{0.5}}; - ASSERT_EQ(pressure_service_impl_sync_->SetQuantization(quantization3), - blink::mojom::SetQuantizationStatus::kChanged); - - const base::Time time3 = base::Time::Now() + kRateLimit; - pressure_manager_overrider_->UpdateClients(state, time3); - observer.WaitForUpdate(); - ASSERT_EQ(observer.updates().size(), 1u); - EXPECT_EQ(observer.updates()[0], PressureState{0.25}); - observer.updates().clear(); + EXPECT_EQ(observer.updates()[0], update3); } TEST_F(PressureServiceImplTest, NoVisibility) { @@ -329,18 +218,16 @@ ASSERT_EQ(pressure_service_impl_sync_->BindObserver( observer.BindNewPipeAndPassRemote()), blink::mojom::PressureStatus::kOk); - ASSERT_EQ(pressure_service_impl_sync_->SetQuantization(kQuantization), - blink::mojom::SetQuantizationStatus::kChanged); const base::Time time = base::Time::Now(); test_rvh()->SimulateWasHidden(); // The first two updates should be blocked due to invisibility. - const PressureState state1{0.0}; - pressure_manager_overrider_->UpdateClients(state1, time + kRateLimit); - const PressureState state2{1.0}; - pressure_manager_overrider_->UpdateClients(state2, time + kRateLimit * 2); + PressureUpdate update1(PressureState::kNominal, time + kRateLimit); + pressure_manager_overrider_->UpdateClients(update1); + PressureUpdate update2(PressureState::kCritical, time + kRateLimit * 2); + pressure_manager_overrider_->UpdateClients(update2); task_environment()->RunUntilIdle(); test_rvh()->SimulateWasShown(); @@ -348,43 +235,12 @@ // The third update should be dispatched. It should not be rate-limited by the // time proximity to the second update, because the second update is not // dispatched. - const PressureState state3{1.0}; - pressure_manager_overrider_->UpdateClients(state3, time + kRateLimit * 2.5); + PressureUpdate update3(PressureState::kFair, time + kRateLimit * 2.5); + pressure_manager_overrider_->UpdateClients(update3); observer.WaitForUpdate(); ASSERT_EQ(observer.updates().size(), 1u); - EXPECT_EQ(observer.updates()[0], PressureState{0.9}); -} - -TEST_F(PressureServiceImplTest, InvalidQuantization) { - FakePressureObserver observer; - PressureQuantization invalid_quantization{{-1.0}}; - ASSERT_EQ(pressure_service_impl_sync_->BindObserver( - observer.BindNewPipeAndPassRemote()), - blink::mojom::PressureStatus::kOk); - ASSERT_EQ(pressure_service_impl_sync_->SetQuantization(kQuantization), - blink::mojom::SetQuantizationStatus::kChanged); - - const base::Time time = base::Time::Now(); - - const PressureState state1{0.0}; - pressure_manager_overrider_->UpdateClients(state1, time + kRateLimit); - observer.WaitForUpdate(); - - { - mojo::test::BadMessageObserver bad_message_observer; - pressure_service_->SetQuantization(invalid_quantization.Clone(), - base::DoNothing()); - EXPECT_EQ("Invalid quantization", bad_message_observer.WaitForBadMessage()); - } - - const PressureState state2{1.0}; - pressure_manager_overrider_->UpdateClients(state2, time + kRateLimit * 2); - observer.WaitForUpdate(); - - ASSERT_EQ(observer.updates().size(), 2u); - EXPECT_THAT(observer.updates(), testing::Contains(PressureState{0.1})); - EXPECT_THAT(observer.updates(), testing::Contains(PressureState{0.9})); + EXPECT_EQ(observer.updates()[0], update3); } TEST_F(PressureServiceImplTest, BindObserver_NotSupported) {
diff --git a/content/browser/devtools/protocol/network_handler.cc b/content/browser/devtools/protocol/network_handler.cc index 9ad0ecef..fbf666f 100644 --- a/content/browser/devtools/protocol/network_handler.cc +++ b/content/browser/devtools/protocol/network_handler.cc
@@ -1860,6 +1860,35 @@ } } +String AlternateProtocolUsageToString( + net::AlternateProtocolUsage alternate_protocol_usage) { + switch (alternate_protocol_usage) { + case net::AlternateProtocolUsage::ALTERNATE_PROTOCOL_USAGE_NO_RACE: + return protocol::Network::AlternateProtocolUsageEnum:: + AlternativeJobWonWithoutRace; + case net::AlternateProtocolUsage::ALTERNATE_PROTOCOL_USAGE_WON_RACE: + return protocol::Network::AlternateProtocolUsageEnum:: + AlternativeJobWonRace; + case net::AlternateProtocolUsage:: + ALTERNATE_PROTOCOL_USAGE_MAIN_JOB_WON_RACE: + return protocol::Network::AlternateProtocolUsageEnum::MainJobWonRace; + case net::AlternateProtocolUsage::ALTERNATE_PROTOCOL_USAGE_MAPPING_MISSING: + return protocol::Network::AlternateProtocolUsageEnum::MappingMissing; + case net::AlternateProtocolUsage::ALTERNATE_PROTOCOL_USAGE_BROKEN: + return protocol::Network::AlternateProtocolUsageEnum::Broken; + case net::AlternateProtocolUsage:: + ALTERNATE_PROTOCOL_USAGE_DNS_ALPN_H3_JOB_WON_WITHOUT_RACE: + return protocol::Network::AlternateProtocolUsageEnum:: + DnsAlpnH3JobWonWithoutRace; + case net::AlternateProtocolUsage:: + ALTERNATE_PROTOCOL_USAGE_DNS_ALPN_H3_JOB_WON_RACE: + return protocol::Network::AlternateProtocolUsageEnum::DnsAlpnH3JobWonRace; + case net::AlternateProtocolUsage::ALTERNATE_PROTOCOL_USAGE_MAX: + return protocol::Network::AlternateProtocolUsageEnum::UnspecifiedReason; + } + return protocol::Network::AlternateProtocolUsageEnum::UnspecifiedReason; +} + std::unique_ptr<Network::Response> BuildResponse( const GURL& url, const network::mojom::URLResponseHeadDevToolsInfo& info) { @@ -1904,6 +1933,8 @@ } response->SetProtocol(GetProtocol(url, info)); + response->SetAlternateProtocolUsage( + AlternateProtocolUsageToString(info.alternate_protocol_usage)); response->SetRemoteIPAddress( net::HostPortPair::FromIPEndPoint(info.remote_endpoint).HostForURL()); response->SetRemotePort(info.remote_endpoint.port());
diff --git a/content/browser/indexed_db/indexed_db_bucket_state.cc b/content/browser/indexed_db/indexed_db_bucket_state.cc index 52f1ba9..10c56b3 100644 --- a/content/browser/indexed_db/indexed_db_bucket_state.cc +++ b/content/browser/indexed_db/indexed_db_bucket_state.cc
@@ -105,8 +105,9 @@ } // namespace -const base::Feature kCompactIDBOnClose{"CompactIndexedDBOnClose", - base::FEATURE_ENABLED_BY_DEFAULT}; +BASE_FEATURE(kCompactIDBOnClose, + "CompactIndexedDBOnClose", + base::FEATURE_ENABLED_BY_DEFAULT); constexpr const base::TimeDelta IndexedDBBucketState::kMaxEarliestGlobalSweepFromNow;
diff --git a/content/browser/indexed_db/indexed_db_bucket_state.h b/content/browser/indexed_db/indexed_db_bucket_state.h index 12e7c61..fcb9bb4 100644 --- a/content/browser/indexed_db/indexed_db_bucket_state.h +++ b/content/browser/indexed_db/indexed_db_bucket_state.h
@@ -36,7 +36,7 @@ // This is an emergency kill switch to use with Finch if the feature needs to be // shut off. -CONTENT_EXPORT extern const base::Feature kCompactIDBOnClose; +CONTENT_EXPORT BASE_DECLARE_FEATURE(kCompactIDBOnClose); // IndexedDBBucketState manages the per-bucket IndexedDB state, and // contains the backing store for the bucket.
diff --git a/content/browser/network_service_instance_impl.cc b/content/browser/network_service_instance_impl.cc index 9d61be6f..f85feab 100644 --- a/content/browser/network_service_instance_impl.cc +++ b/content/browser/network_service_instance_impl.cc
@@ -121,14 +121,14 @@ // On Chrome OS, the Network Service must run on the IO thread because // ProfileIOData and NetworkContext both try to set up NSS, which has to be // called from the IO thread. -const base::Feature kNetworkServiceDedicatedThread { - "NetworkServiceDedicatedThread", +BASE_FEATURE(kNetworkServiceDedicatedThread, + "NetworkServiceDedicatedThread", #if BUILDFLAG(IS_CHROMEOS) - base::FEATURE_DISABLED_BY_DEFAULT + base::FEATURE_DISABLED_BY_DEFAULT #else - base::FEATURE_ENABLED_BY_DEFAULT + base::FEATURE_ENABLED_BY_DEFAULT #endif -}; +); base::Thread& GetNetworkServiceDedicatedThread() { static base::NoDestructor<base::Thread> thread{"NetworkService"};
diff --git a/content/browser/preloading/prefetch/prefetch_features.cc b/content/browser/preloading/prefetch/prefetch_features.cc index e23ca92..4ac0c29 100644 --- a/content/browser/preloading/prefetch/prefetch_features.cc +++ b/content/browser/preloading/prefetch/prefetch_features.cc
@@ -6,7 +6,8 @@ namespace content::features { -const base::Feature kPrefetchUseContentRefactor{ - "PrefetchUseContentRefactor", base::FEATURE_DISABLED_BY_DEFAULT}; +BASE_FEATURE(kPrefetchUseContentRefactor, + "PrefetchUseContentRefactor", + base::FEATURE_DISABLED_BY_DEFAULT); } // namespace content::features
diff --git a/content/browser/preloading/prefetch/prefetch_features.h b/content/browser/preloading/prefetch/prefetch_features.h index 1e68dd6..8de5f9c 100644 --- a/content/browser/preloading/prefetch/prefetch_features.h +++ b/content/browser/preloading/prefetch/prefetch_features.h
@@ -13,7 +13,7 @@ // If enabled, then prefetch requests from speculation rules should use the code // in content/browser/preloading/prefetch/ instead of // chrome/browser/preloadingprefetch/prefetch_proxy/. -extern CONTENT_EXPORT const base::Feature kPrefetchUseContentRefactor; +CONTENT_EXPORT BASE_DECLARE_FEATURE(kPrefetchUseContentRefactor); } // namespace content::features
diff --git a/content/browser/preloading/prerender/prerender_browsertest.cc b/content/browser/preloading/prerender/prerender_browsertest.cc index ff7b87e7..605892d 100644 --- a/content/browser/preloading/prerender/prerender_browsertest.cc +++ b/content/browser/preloading/prerender/prerender_browsertest.cc
@@ -4209,6 +4209,134 @@ EXPECT_TRUE(embedder_observer.was_activated()); } +// Tests that if the running prerender is cancelled by +// PrerenderHostRegistry::CancelHost(), the next pending prerender starts its +// navigation. +IN_PROC_BROWSER_TEST_F(PrerenderSequentialPrerenderingBrowserTest, + RunningHostCancellationStartPendingPrerender) { + net::test_server::ControllableHttpResponse response(embedded_test_server(), + "/empty.html?prerender1"); + ASSERT_TRUE(embedded_test_server()->Start()); + const GURL kInitialUrl = embedded_test_server()->GetURL("/empty.html"); + const GURL kPrerender1 = + embedded_test_server()->GetURL("/empty.html?prerender1"); + const GURL kPrerender2 = + embedded_test_server()->GetURL("/empty.html?prerender2"); + + ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl)); + + test::PrerenderHostRegistryObserver registry_observer(*web_contents_impl()); + + // Insert 2 URLs into the speculation rules at the same time. + ASSERT_TRUE(ExecJs(web_contents_impl()->GetPrimaryMainFrame(), + JsReplace( + R"( + const sc = document.createElement('script'); + sc.type = 'speculationrules'; + sc.textContent = JSON.stringify({ + prerender: [ + {source: "list", urls: [$1, $2]} + ] + }); + document.head.appendChild(sc); + )", + kPrerender1, kPrerender2))); + + registry_observer.WaitForTrigger(kPrerender2); + test::PrerenderHostObserver prerender2_observer(*web_contents(), + GetHostForUrl(kPrerender2)); + + // Stop the first prerendering initial navigation. + response.WaitForRequest(); + + // Cancel the running prerender. The next pending prerender should start upon + // this cancellation. + web_contents_impl()->GetPrerenderHostRegistry()->CancelHost( + GetHostForUrl(kPrerender1), PrerenderHost::FinalStatus::kDestroyed); + WaitForPrerenderLoadCompletion(kPrerender2); + + // Activate the page with the prerender that was pending. + NavigatePrimaryPage(kPrerender2); + prerender2_observer.WaitForActivation(); + EXPECT_EQ(web_contents()->GetLastCommittedURL(), kPrerender2); + EXPECT_TRUE(prerender2_observer.was_activated()); + + // The first prerender should be manually destroyed. + histogram_tester().ExpectBucketCount( + "Prerender.Experimental.PrerenderHostFinalStatus.SpeculationRule", + PrerenderHost::FinalStatus::kDestroyed, 1); + // The second prerender should be successfully activated. + histogram_tester().ExpectBucketCount( + "Prerender.Experimental.PrerenderHostFinalStatus.SpeculationRule", + PrerenderHost::FinalStatus::kActivated, 1); +} + +// Tests that if the running prerender is cancelled by +// PrerenderHostRegistry::OnTriggerDestroyed(), the next pending prerender +// starts its navigation. +IN_PROC_BROWSER_TEST_F(PrerenderSequentialPrerenderingBrowserTest, + SpeculationRulesUpdateStartPendingPrerender) { + net::test_server::ControllableHttpResponse response(embedded_test_server(), + "/empty.html?prerender1"); + ASSERT_TRUE(embedded_test_server()->Start()); + const GURL kInitialUrl = embedded_test_server()->GetURL("/empty.html"); + const GURL kPrerender1 = + embedded_test_server()->GetURL("/empty.html?prerender1"); + const GURL kPrerender2 = + embedded_test_server()->GetURL("/empty.html?prerender2"); + + ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl)); + + test::PrerenderHostRegistryObserver registry_observer(*web_contents_impl()); + + // Insert 2 URLs into the speculation rules in order. The prerender for + // `kPrerender1` should start first. + std::string script = R"( + let sc = document.createElement('script'); + sc.type = 'speculationrules'; + sc.id = $1; + sc.textContent = JSON.stringify({ + prerender: [ + {source: "list", urls: [$2]} + ] + }); + document.head.appendChild(sc); + )"; + ASSERT_TRUE(ExecJs(web_contents_impl()->GetPrimaryMainFrame(), + JsReplace(script, "prerender1", kPrerender1))); + ASSERT_TRUE(ExecJs(web_contents_impl()->GetPrimaryMainFrame(), + JsReplace(script, "prerender2", kPrerender2))); + + registry_observer.WaitForTrigger(kPrerender2); + test::PrerenderHostObserver prerender2_observer(*web_contents(), + GetHostForUrl(kPrerender2)); + + // Stop the first prerendering initial navigation. + response.WaitForRequest(); + + // Delete the first speculation rule. This speculation rules removal invokes + // the PrerenderHostRegistry::OnTriggerDestroyed(), and the next pending + // prerender should start upon the cancellation. + ASSERT_TRUE(ExecJs(web_contents_impl()->GetPrimaryMainFrame(), + "document.querySelector('#prerender1').remove()")); + WaitForPrerenderLoadCompletion(kPrerender2); + + // Activate the page with the prerender that was pending. + NavigatePrimaryPage(kPrerender2); + prerender2_observer.WaitForActivation(); + EXPECT_EQ(web_contents()->GetLastCommittedURL(), kPrerender2); + EXPECT_TRUE(prerender2_observer.was_activated()); + + // The first prerender should be cancelled by the trigger. + histogram_tester().ExpectBucketCount( + "Prerender.Experimental.PrerenderHostFinalStatus.SpeculationRule", + PrerenderHost::FinalStatus::kTriggerDestroyed, 1); + // The second prerender should be successfully activated. + histogram_tester().ExpectBucketCount( + "Prerender.Experimental.PrerenderHostFinalStatus.SpeculationRule", + PrerenderHost::FinalStatus::kActivated, 1); +} + IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, IsInactiveAndDisallowActivationCancelsPrerendering) { const GURL kInitialUrl = GetUrl("/empty.html");
diff --git a/content/browser/preloading/prerender/prerender_host_registry.cc b/content/browser/preloading/prerender/prerender_host_registry.cc index bf18c88..62374b0 100644 --- a/content/browser/preloading/prerender/prerender_host_registry.cc +++ b/content/browser/preloading/prerender/prerender_host_registry.cc
@@ -245,13 +245,19 @@ switch (attributes.trigger_type) { case PrerenderTriggerType::kSpeculationRule: pending_prerenders_.push_back(frame_tree_node_id); - // Start only the first PrerenderHost execution if there's no running - // prerendering. + // Start the initial prerendering navigation of the pending request in + // the head of the queue if there's no running prerender. if (running_prerender_host_id_ == RenderFrameHost::kNoFrameTreeNodeId) { - // TODO(crbug.com/1355151): Returns the starting host's id once - // starting another prerender on running prerender cancellation is - // implemented. - StartPrerendering(RenderFrameHost::kNoFrameTreeNodeId); + // No running prerender means that no other prerender is waiting in + // the pending queue, because the prerender sequence only stops when + // all the pending prerenders are started. + DCHECK_EQ(pending_prerenders_.size(), 1u); + int started_frame_tree_node_id = + StartPrerendering(RenderFrameHost::kNoFrameTreeNodeId); + DCHECK(started_frame_tree_node_id == frame_tree_node_id || + started_frame_tree_node_id == + RenderFrameHost::kNoFrameTreeNodeId); + frame_tree_node_id = started_frame_tree_node_id; } break; case PrerenderTriggerType::kEmbedder: @@ -356,12 +362,18 @@ // Remove the prerender host from the host map so that it's not used for // activation during asynchronous deletion. - // TODO(crbug.com/1355151): Start another pending prerender. std::unique_ptr<PrerenderHost> prerender_host = std::move(iter->second); prerender_host_by_frame_tree_node_id_.erase(iter); // Asynchronously delete the prerender host. ScheduleToDeleteAbandonedHost(std::move(prerender_host), final_status); + + // Start another prerender if the running prerender is cancelled. + if (running_prerender_host_id_ == frame_tree_node_id) { + running_prerender_host_id_ = RenderFrameHost::kNoFrameTreeNodeId; + StartPrerendering(RenderFrameHost::kNoFrameTreeNodeId); + } + return true; } @@ -456,9 +468,6 @@ // Look up the id in the non-reserved host map and remove it from the map if // it's found. - // - // TODO(crbug.com/1355151): Start another pending prerender if the deleted one - // is the running prerender. auto found = prerender_host_by_frame_tree_node_id_.find(frame_tree_node_id); if (found != prerender_host_by_frame_tree_node_id_.end()) { DCHECK(!base::Contains(reserved_prerender_host_by_frame_tree_node_id_, @@ -473,6 +482,12 @@ ScheduleToDeleteAbandonedHost( std::move(prerender_host), PrerenderHost::FinalStatus::kTriggerDestroyed); + + // Start another prerender if the running prerender is destroyed. + if (running_prerender_host_id_ == frame_tree_node_id) { + running_prerender_host_id_ = RenderFrameHost::kNoFrameTreeNodeId; + StartPrerendering(RenderFrameHost::kNoFrameTreeNodeId); + } } // Don't remove the host from the reserved host map. Unlike use of the
diff --git a/content/browser/renderer_host/back_forward_cache_impl.h b/content/browser/renderer_host/back_forward_cache_impl.h index d0c5417..982f06b 100644 --- a/content/browser/renderer_host/back_forward_cache_impl.h +++ b/content/browser/renderer_host/back_forward_cache_impl.h
@@ -46,33 +46,36 @@ // without enabling it. To control the URLs list by using this feature by // generating the metrics only for "allowed_websites" param. Mainly, to ensure // that metrics from the control and experiment groups are consistent. -constexpr base::Feature kRecordBackForwardCacheMetricsWithoutEnabling{ - "RecordBackForwardCacheMetricsWithoutEnabling", - base::FEATURE_DISABLED_BY_DEFAULT}; +BASE_FEATURE(kRecordBackForwardCacheMetricsWithoutEnabling, + "RecordBackForwardCacheMetricsWithoutEnabling", + base::FEATURE_DISABLED_BY_DEFAULT); // Removes the time limit for cached content. This is used on bots to identify // accidentally passing tests. -constexpr base::Feature kBackForwardCacheNoTimeEviction{ - "BackForwardCacheNoTimeEviction", base::FEATURE_DISABLED_BY_DEFAULT}; +BASE_FEATURE(kBackForwardCacheNoTimeEviction, + "BackForwardCacheNoTimeEviction", + base::FEATURE_DISABLED_BY_DEFAULT); // Allows pages with cache-control:no-store to enter the back/forward cache. // Feature params can specify whether pages with cache-control:no-store can be // restored if cookies change / if HTTPOnly cookies change. // TODO(crbug.com/1228611): Enable this feature. -const base::Feature kCacheControlNoStoreEnterBackForwardCache{ - "CacheControlNoStoreEnterBackForwardCache", - base::FEATURE_DISABLED_BY_DEFAULT}; +BASE_FEATURE(kCacheControlNoStoreEnterBackForwardCache, + "CacheControlNoStoreEnterBackForwardCache", + base::FEATURE_DISABLED_BY_DEFAULT); // Enables controlling the time to live for pages in the backforward cache. // The time to live is defined by the param 'time_to_live_seconds'; if this // param is not specified then this feature is ignored and the default is used. -const base::Feature kBackForwardCacheTimeToLiveControl{ - "BackForwardCacheTimeToLiveControl", base::FEATURE_DISABLED_BY_DEFAULT}; +BASE_FEATURE(kBackForwardCacheTimeToLiveControl, + "BackForwardCacheTimeToLiveControl", + base::FEATURE_DISABLED_BY_DEFAULT); // Allows overriding the sizes of back/forward cache. // Sizes set via this feature's parameters take precedence over others. -const base::Feature kBackForwardCacheSize{"BackForwardCacheSize", - base::FEATURE_DISABLED_BY_DEFAULT}; +BASE_FEATURE(kBackForwardCacheSize, + "BackForwardCacheSize", + base::FEATURE_DISABLED_BY_DEFAULT); // Combines a flattened list and a tree of the reasons why each document cannot // enter the back/forward cache (might be empty if it can). The tree saves the
diff --git a/content/browser/renderer_host/browsing_context_state.cc b/content/browser/renderer_host/browsing_context_state.cc index 552f3aee..8c0f8ad 100644 --- a/content/browser/renderer_host/browsing_context_state.cc +++ b/content/browser/renderer_host/browsing_context_state.cc
@@ -13,9 +13,9 @@ #include "services/network/public/mojom/web_sandbox_flags.mojom.h" namespace features { -const base::Feature kNewBrowsingContextStateOnBrowsingContextGroupSwap{ - "NewBrowsingContextStateOnBrowsingContextGroupSwap", - base::FEATURE_DISABLED_BY_DEFAULT}; +BASE_FEATURE(kNewBrowsingContextStateOnBrowsingContextGroupSwap, + "NewBrowsingContextStateOnBrowsingContextGroupSwap", + base::FEATURE_DISABLED_BY_DEFAULT); BrowsingContextStateImplementationType GetBrowsingContextMode() { if (base::FeatureList::IsEnabled(
diff --git a/content/browser/renderer_host/media/in_process_video_capture_device_launcher.cc b/content/browser/renderer_host/media/in_process_video_capture_device_launcher.cc index 1c13f65..4e510e5 100644 --- a/content/browser/renderer_host/media/in_process_video_capture_device_launcher.cc +++ b/content/browser/renderer_host/media/in_process_video_capture_device_launcher.cc
@@ -91,11 +91,13 @@ #if BUILDFLAG(ENABLE_SCREEN_CAPTURE) #if BUILDFLAG(IS_MAC) -const base::Feature kDesktopCaptureMacV2{"DesktopCaptureMacV2", - base::FEATURE_ENABLED_BY_DEFAULT}; +BASE_FEATURE(kDesktopCaptureMacV2, + "DesktopCaptureMacV2", + base::FEATURE_ENABLED_BY_DEFAULT); -const base::Feature kScreenCaptureKitMac{"ScreenCaptureKitMac", - base::FEATURE_DISABLED_BY_DEFAULT}; +BASE_FEATURE(kScreenCaptureKitMac, + "ScreenCaptureKitMac", + base::FEATURE_DISABLED_BY_DEFAULT); #endif void IncrementDesktopCaptureCounters(const DesktopMediaID& device_id) {
diff --git a/content/browser/renderer_host/navigation_request.cc b/content/browser/renderer_host/navigation_request.cc index a6a78ab..d6c7e1d 100644 --- a/content/browser/renderer_host/navigation_request.cc +++ b/content/browser/renderer_host/navigation_request.cc
@@ -194,9 +194,9 @@ // crbug.com/954271: This feature is a part of an ablation study which makes // history navigations slower. // TODO(altimin): Clean this up after the study finishes. -constexpr base::Feature kHistoryNavigationDoNotUseCacheAblationStudy{ - "HistoryNavigationDoNotUseCacheAblationStudy", - base::FEATURE_DISABLED_BY_DEFAULT}; +BASE_FEATURE(kHistoryNavigationDoNotUseCacheAblationStudy, + "HistoryNavigationDoNotUseCacheAblationStudy", + base::FEATURE_DISABLED_BY_DEFAULT); constexpr base::FeatureParam<double> kDoNotUseCacheProbability{ &kHistoryNavigationDoNotUseCacheAblationStudy, "probability", 0.0};
diff --git a/content/browser/renderer_host/render_frame_host_impl.cc b/content/browser/renderer_host/render_frame_host_impl.cc index 4cf59f34..de66dd78 100644 --- a/content/browser/renderer_host/render_frame_host_impl.cc +++ b/content/browser/renderer_host/render_frame_host_impl.cc
@@ -287,22 +287,22 @@ #endif namespace features { -const base::Feature kDisableFrameNameUpdateOnNonCurrentRenderFrameHost{ - "DisableFrameNameUpdateOnNonCurrentRenderFrameHost", - base::FEATURE_ENABLED_BY_DEFAULT}; +BASE_FEATURE(kDisableFrameNameUpdateOnNonCurrentRenderFrameHost, + "DisableFrameNameUpdateOnNonCurrentRenderFrameHost", + base::FEATURE_ENABLED_BY_DEFAULT); // Evict when accessibility events occur while in back/forward cache. Remove // once the https://crbug.com/1341507 is resolved. This crash started to happen // on Android with bfcache experiments, so we're enabling this flag only on // Android. -const base::Feature kEvictOnAXEvents { - "EvictOnAXEvents", +BASE_FEATURE(kEvictOnAXEvents, + "EvictOnAXEvents", #if BUILDFLAG(IS_ANDROID) - base::FEATURE_ENABLED_BY_DEFAULT + base::FEATURE_ENABLED_BY_DEFAULT #else - base::FEATURE_DISABLED_BY_DEFAULT + base::FEATURE_DISABLED_BY_DEFAULT #endif -}; +); } // namespace features namespace content { @@ -390,8 +390,9 @@ // // TODO(nuskos): Once we've conducted a retroactive study of chrometto // improvements clean up this feature. -const base::Feature kRenderAccessibilityHostAvoidCopying{ - "RenderAccessibilityHostAvoidCopying", base::FEATURE_ENABLED_BY_DEFAULT}; +BASE_FEATURE(kRenderAccessibilityHostAvoidCopying, + "RenderAccessibilityHostAvoidCopying", + base::FEATURE_ENABLED_BY_DEFAULT); // The next value to use for the accessibility reset token. int g_next_accessibility_reset_token = 1;
diff --git a/content/browser/renderer_host/render_frame_host_impl.h b/content/browser/renderer_host/render_frame_host_impl.h index e97d08d2..09bcb033 100644 --- a/content/browser/renderer_host/render_frame_host_impl.h +++ b/content/browser/renderer_host/render_frame_host_impl.h
@@ -205,11 +205,11 @@ // relevant BrowsingContextState) when it is not current (i.e. is in the // BackForwardCache or is pending delete). This primarily will affect the // non-legacy implementation of BrowsingContextState. -CONTENT_EXPORT extern const base::Feature - kDisableFrameNameUpdateOnNonCurrentRenderFrameHost; +CONTENT_EXPORT BASE_DECLARE_FEATURE( + kDisableFrameNameUpdateOnNonCurrentRenderFrameHost); // Feature to evict when accessibility events occur while in back/forward cache. -CONTENT_EXPORT extern const base::Feature kEvictOnAXEvents; +CONTENT_EXPORT BASE_DECLARE_FEATURE(kEvictOnAXEvents); } // namespace features namespace content {
diff --git a/content/browser/scheduler/browser_task_executor.cc b/content/browser/scheduler/browser_task_executor.cc index c495691f..fc58408 100644 --- a/content/browser/scheduler/browser_task_executor.cc +++ b/content/browser/scheduler/browser_task_executor.cc
@@ -37,8 +37,9 @@ // // TODO(nuskos): Remove this feature flag after we've done our retroactive study // of all chrometto performance improvements. -constexpr base::Feature kBrowserPrioritizeInputQueue{ - "BrowserPrioritizeInputQueue", base::FEATURE_ENABLED_BY_DEFAULT}; +BASE_FEATURE(kBrowserPrioritizeInputQueue, + "BrowserPrioritizeInputQueue", + base::FEATURE_ENABLED_BY_DEFAULT); } // namespace features
diff --git a/content/browser/scheduler/browser_ui_thread_scheduler.cc b/content/browser/scheduler/browser_ui_thread_scheduler.cc index 0a4241f..b774f4c 100644 --- a/content/browser/scheduler/browser_ui_thread_scheduler.cc +++ b/content/browser/scheduler/browser_ui_thread_scheduler.cc
@@ -44,8 +44,9 @@ // a first input event is received. Checking for native messages more frequently // incurs some overhead, but allows the browser to handle input more // consistently. -constexpr base::Feature kBrowserPrioritizeNativeWork{ - "BrowserPrioritizeNativeWork", base::FEATURE_DISABLED_BY_DEFAULT}; +BASE_FEATURE(kBrowserPrioritizeNativeWork, + "BrowserPrioritizeNativeWork", + base::FEATURE_DISABLED_BY_DEFAULT); constexpr base::FeatureParam<base::TimeDelta> kBrowserPrioritizeNativeWorkAfterInputForNMsParam{ &kBrowserPrioritizeNativeWork, "prioritize_for_next_ms",
diff --git a/content/browser/service_worker/service_worker_context_wrapper.cc b/content/browser/service_worker/service_worker_context_wrapper.cc index ee7341b6..f9acd90 100644 --- a/content/browser/service_worker/service_worker_context_wrapper.cc +++ b/content/browser/service_worker/service_worker_context_wrapper.cc
@@ -74,8 +74,9 @@ #if BUILDFLAG(IS_ANDROID) // Enables running ServiceWorkerStorageControl on IO thread instead of UI thread // on Android. -const base::Feature kServiceWorkerStorageControlOnIOThread{ - "ServiceWorkerStorageControlOnIOThread", base::FEATURE_DISABLED_BY_DEFAULT}; +BASE_FEATURE(kServiceWorkerStorageControlOnIOThread, + "ServiceWorkerStorageControlOnIOThread", + base::FEATURE_DISABLED_BY_DEFAULT); #endif void DidFindRegistrationForStartActiveWorker(
diff --git a/content/browser/service_worker/service_worker_registry.cc b/content/browser/service_worker/service_worker_registry.cc index 0510a944..ba83c714 100644 --- a/content/browser/service_worker/service_worker_registry.cc +++ b/content/browser/service_worker/service_worker_registry.cc
@@ -41,9 +41,9 @@ // When this is enabled, the browser will schedule // ServiceWorkerStorageControl's response in a kHighest priority // queue during startup. After startup, it has a normal priority. -const base::Feature kServiceWorkerStorageControlResponseQueue{ - "ServiceWorkerStorageControlResponseQueue", - base::FEATURE_DISABLED_BY_DEFAULT}; +BASE_FEATURE(kServiceWorkerStorageControlResponseQueue, + "ServiceWorkerStorageControlResponseQueue", + base::FEATURE_DISABLED_BY_DEFAULT); blink::ServiceWorkerStatusCode DatabaseStatusToStatusCode( storage::mojom::ServiceWorkerDatabaseStatus status) {
diff --git a/content/browser/startup_helper.cc b/content/browser/startup_helper.cc index 9ddd1a4..91e73e8 100644 --- a/content/browser/startup_helper.cc +++ b/content/browser/startup_helper.cc
@@ -61,8 +61,9 @@ constexpr size_t kThreadPoolOffset = 0; #endif -const base::Feature kBrowserThreadPoolAdjustment{ - "BrowserThreadPoolAdjustment", base::FEATURE_DISABLED_BY_DEFAULT}; +BASE_FEATURE(kBrowserThreadPoolAdjustment, + "BrowserThreadPoolAdjustment", + base::FEATURE_DISABLED_BY_DEFAULT); const base::FeatureParam<int> kBrowserThreadPoolMin{ &kBrowserThreadPoolAdjustment, "min", kThreadPoolDefaultMin};
diff --git a/content/child/dwrite_font_proxy/dwrite_font_proxy_win.cc b/content/child/dwrite_font_proxy/dwrite_font_proxy_win.cc index 70c24577..fddf348f 100644 --- a/content/child/dwrite_font_proxy/dwrite_font_proxy_win.cc +++ b/content/child/dwrite_font_proxy/dwrite_font_proxy_win.cc
@@ -36,8 +36,9 @@ // TODO(https://crbug.com/1089390): Remove this feature when the experiment is // complete. If the experiment shows a significant input delay improvement, // replace with a more refined mitigation for pages that access many fonts. -const base::Feature kLimitFontFamilyNamesPerRenderer{ - "LimitFontFamilyNamesPerRenderer", base::FEATURE_DISABLED_BY_DEFAULT}; +BASE_FEATURE(kLimitFontFamilyNamesPerRenderer, + "LimitFontFamilyNamesPerRenderer", + base::FEATURE_DISABLED_BY_DEFAULT); constexpr size_t kFamilyNamesLimit = 20; // Family names that opted-out from the limit enforced by
diff --git a/content/common/content_navigation_policy.cc b/content/common/content_navigation_policy.cc index b2e1187f..32ebc55 100644 --- a/content/common/content_navigation_policy.cc +++ b/content/common/content_navigation_policy.cc
@@ -14,8 +14,9 @@ #include "content/public/common/content_switches.h" namespace features { -const base::Feature kBackForwardCache_NoMemoryLimit_Trial{ - "BackForwardCache_NoMemoryLimit_Trial", base::FEATURE_ENABLED_BY_DEFAULT}; +BASE_FEATURE(kBackForwardCache_NoMemoryLimit_Trial, + "BackForwardCache_NoMemoryLimit_Trial", + base::FEATURE_ENABLED_BY_DEFAULT); } namespace content {
diff --git a/content/common/content_navigation_policy.h b/content/common/content_navigation_policy.h index 4002767..dd2ec35 100644 --- a/content/common/content_navigation_policy.h +++ b/content/common/content_navigation_policy.h
@@ -24,7 +24,7 @@ // avoiding activating the BackForwardCache experiment, and won’t include // devices that do have enough memory but have the BackForwardCache flag // disabled. -CONTENT_EXPORT extern const base::Feature kBackForwardCache_NoMemoryLimit_Trial; +CONTENT_EXPORT BASE_DECLARE_FEATURE(kBackForwardCache_NoMemoryLimit_Trial); } // namespace features namespace content {
diff --git a/content/common/features.cc b/content/common/features.cc index 69716ae..fe94125 100644 --- a/content/common/features.cc +++ b/content/common/features.cc
@@ -8,9 +8,9 @@ // Please keep features in alphabetical order. -CONSTINIT base::Feature kQueueNavigationsWhileWaitingForCommit( - "QueueNavigationsWhileWaitingForPendingCommit", - base::FEATURE_DISABLED_BY_DEFAULT); +BASE_FEATURE(kQueueNavigationsWhileWaitingForCommit, + "QueueNavigationsWhileWaitingForPendingCommit", + base::FEATURE_DISABLED_BY_DEFAULT); // Please keep features in alphabetical order.
diff --git a/content/common/features.h b/content/common/features.h index 1ee6da0..8770395 100644 --- a/content/common/features.h +++ b/content/common/features.h
@@ -15,7 +15,7 @@ // When enabled, queues navigations instead of cancelling the previous // navigation if the previous navigation is already waiting for commit. // See https://crbug.com/838348 and https://crbug.com/1220337. -extern CONSTINIT base::Feature kQueueNavigationsWhileWaitingForCommit; +BASE_DECLARE_FEATURE(kQueueNavigationsWhileWaitingForCommit); // Please keep features in alphabetical order.
diff --git a/content/common/private_aggregation_features.cc b/content/common/private_aggregation_features.cc index a093611..1d32e2f 100644 --- a/content/common/private_aggregation_features.cc +++ b/content/common/private_aggregation_features.cc
@@ -8,7 +8,8 @@ namespace content { -const base::Feature kPrivateAggregationApi = { - "PrivateAggregationApi", base::FEATURE_DISABLED_BY_DEFAULT}; +BASE_FEATURE(kPrivateAggregationApi, + "PrivateAggregationApi", + base::FEATURE_DISABLED_BY_DEFAULT); } // namespace content
diff --git a/content/common/private_aggregation_features.h b/content/common/private_aggregation_features.h index b522b65e..0821828 100644 --- a/content/common/private_aggregation_features.h +++ b/content/common/private_aggregation_features.h
@@ -13,7 +13,7 @@ // Enables the Private Aggregation API. Note that this API also requires the // `kPrivacySandboxAggregationService` to be enabled to successfully send // reports. -CONTENT_EXPORT extern const base::Feature kPrivateAggregationApi; +CONTENT_EXPORT BASE_DECLARE_FEATURE(kPrivateAggregationApi); } // namespace content
diff --git a/content/common/skia_utils.cc b/content/common/skia_utils.cc index cfb4bfbe..f8bcee8 100644 --- a/content/common/skia_utils.cc +++ b/content/common/skia_utils.cc
@@ -25,8 +25,9 @@ const size_t kImageCacheSingleAllocationByteLimit = 64 * 1024 * 1024; // Decreases the size of the font cache to 1MiB. -const base::Feature kSmallerFontCache{"SmallerFontCache", - base::FEATURE_DISABLED_BY_DEFAULT}; +BASE_FEATURE(kSmallerFontCache, + "SmallerFontCache", + base::FEATURE_DISABLED_BY_DEFAULT); } // namespace
diff --git a/content/public/browser/desktop_capture.cc b/content/public/browser/desktop_capture.cc index 2c1edcb..8ca1f99 100644 --- a/content/public/browser/desktop_capture.cc +++ b/content/public/browser/desktop_capture.cc
@@ -25,9 +25,8 @@ // Leave desktop effects enabled during WebRTC captures. options.set_disable_effects(false); #if BUILDFLAG(IS_WIN) - static constexpr base::Feature kDirectXCapturer{ - "DirectXCapturer", - base::FEATURE_ENABLED_BY_DEFAULT}; + static BASE_FEATURE(kDirectXCapturer, "DirectXCapturer", + base::FEATURE_ENABLED_BY_DEFAULT); if (base::FeatureList::IsEnabled(kDirectXCapturer)) { options.set_allow_directx_capturer(true); options.set_allow_use_magnification_api(false);
diff --git a/content/public/common/content_features.cc b/content/public/common/content_features.cc index 2111ca12..685e680 100644 --- a/content/public/common/content_features.cc +++ b/content/public/common/content_features.cc
@@ -1356,8 +1356,9 @@ // Automatically disables accessibility on Android when no assistive // technologies are present -const base::Feature kAutoDisableAccessibilityV2{ - "AutoDisableAccessibilityV2", base::FEATURE_DISABLED_BY_DEFAULT}; +BASE_FEATURE(kAutoDisableAccessibilityV2, + "AutoDisableAccessibilityV2", + base::FEATURE_DISABLED_BY_DEFAULT); // Sets moderate binding to background renderers playing media, when enabled. // Else the renderer will have strong binding.
diff --git a/content/public/common/network_service_util.cc b/content/public/common/network_service_util.cc index 10fbe905..69d84f6 100644 --- a/content/public/common/network_service_util.cc +++ b/content/public/common/network_service_util.cc
@@ -18,9 +18,9 @@ namespace { #if BUILDFLAG(IS_ANDROID) -const base::Feature kNetworkServiceOutOfProcessMemoryThreshold{ - "NetworkServiceOutOfProcessMemoryThreshold", - base::FEATURE_ENABLED_BY_DEFAULT}; +BASE_FEATURE(kNetworkServiceOutOfProcessMemoryThreshold, + "NetworkServiceOutOfProcessMemoryThreshold", + base::FEATURE_ENABLED_BY_DEFAULT); // Using 1077 rather than 1024 because 1) it helps ensure that devices with // exactly 1GB of RAM won't get included because of inaccuracies or off-by-one
diff --git a/content/test/BUILD.gn b/content/test/BUILD.gn index 450625b..ccfed63 100644 --- a/content/test/BUILD.gn +++ b/content/test/BUILD.gn
@@ -2177,7 +2177,6 @@ "../browser/client_hints/client_hints_unittest.cc", "../browser/code_cache/generated_code_cache_unittest.cc", "../browser/code_cache/simple_lru_cache_unittest.cc", - "../browser/compute_pressure/pressure_quantizer_unittest.cc", "../browser/compute_pressure/pressure_service_impl_unittest.cc", "../browser/content_index/content_index_database_unittest.cc", "../browser/content_index/content_index_service_impl_unittest.cc",
diff --git a/content/test/content_browser_test_test.cc b/content/test/content_browser_test_test.cc index 44f26e0..83383ad60 100644 --- a/content/test/content_browser_test_test.cc +++ b/content/test/content_browser_test_test.cc
@@ -323,14 +323,18 @@ namespace { -const base::Feature kTestFeatureForBrowserTest1{ - "TestFeatureForBrowserTest1", base::FEATURE_DISABLED_BY_DEFAULT}; -const base::Feature kTestFeatureForBrowserTest2{ - "TestFeatureForBrowserTest2", base::FEATURE_ENABLED_BY_DEFAULT}; -const base::Feature kTestFeatureForBrowserTest3{ - "TestFeatureForBrowserTest3", base::FEATURE_DISABLED_BY_DEFAULT}; -const base::Feature kTestFeatureForBrowserTest4{ - "TestFeatureForBrowserTest4", base::FEATURE_ENABLED_BY_DEFAULT}; +BASE_FEATURE(kTestFeatureForBrowserTest1, + "TestFeatureForBrowserTest1", + base::FEATURE_DISABLED_BY_DEFAULT); +BASE_FEATURE(kTestFeatureForBrowserTest2, + "TestFeatureForBrowserTest2", + base::FEATURE_ENABLED_BY_DEFAULT); +BASE_FEATURE(kTestFeatureForBrowserTest3, + "TestFeatureForBrowserTest3", + base::FEATURE_DISABLED_BY_DEFAULT); +BASE_FEATURE(kTestFeatureForBrowserTest4, + "TestFeatureForBrowserTest4", + base::FEATURE_ENABLED_BY_DEFAULT); } // namespace
diff --git a/content/utility/utility_main.cc b/content/utility/utility_main.cc index d29a8ba..1520e8f 100644 --- a/content/utility/utility_main.cc +++ b/content/utility/utility_main.cc
@@ -173,7 +173,7 @@ #if BUILDFLAG(ENABLE_CROS_LIBASSISTANT) case sandbox::mojom::Sandbox::kLibassistant: pre_sandbox_hook = - base::BindOnce(&chromeos::libassistant::LibassistantPreSandboxHook); + base::BindOnce(&ash::libassistant::LibassistantPreSandboxHook); break; #endif // BUILDFLAG(ENABLE_CROS_LIBASSISTANT) #endif // BUILDFLAG(IS_CHROMEOS_ASH)
diff --git a/docs/README.md b/docs/README.md index cd01d5c..cef534d 100644 --- a/docs/README.md +++ b/docs/README.md
@@ -160,10 +160,7 @@ * [Ozone Overview](ozone_overview.md) - Ozone is an abstraction layer between the window system and low level input and graphics. * [Optimizing Chrome Web UIs](optimizing_web_uis.md) - Notes on making webuis - more performant -* [Adding a new feature flag in chrome://flags](how_to_add_your_feature_flag.md) - Quick - guide to add a new feature flag to experiment your feature. -* [Guidelines for considering branch dates in project planning](release_branch_guidance.md) - + more performant* [Guidelines for considering branch dates in project planning](release_branch_guidance.md) - What to do (and not to do) around branch dates when scheduling your project work. * [WebUI Explainer](webui_explainer.md) - An explanation of C++ and JavaScript @@ -206,6 +203,14 @@ * [Code Coverage in Gerrit](testing/code_coverage_in_gerrit.md) - Per-CL code coverage in Gerrit to assist code reviews. +### Configuration Docs + +* [Configuration: Prefs, Settings, Features, Switches & Flags](configuration.md) - Explains different ways to gate a new feature. +* [Adding a new feature flag in chrome://flags](how_to_add_your_feature_flag.md) - Quick guide to add a new feature flag to experiment your feature. +* [Runtime Enabled Features](https://chromium.googlesource.com/chromium/src/+/main/third_party/blink/renderer/platform/RuntimeEnabledFeatures.md) +* [Initialization of Blink runtime features in content layer](initialize_blink_features.md) +* [Integrating a feature with the origin trials framework](origin_trials_integration.md) + ### GPU-related docs * [GPU Pixel Wrangling](gpu/pixel_wrangling.md) - Instructions for GPU pixel wrangling (the GPU sheriffing rotation).
diff --git a/docs/configuration.md b/docs/configuration.md index a4b531b..275ec59 100644 --- a/docs/configuration.md +++ b/docs/configuration.md
@@ -5,6 +5,8 @@ these are intended for use by users, some by developers, and some by system administrators. +[TOC] + ## Prefs Example: prefs::kAllowDinosaurEasterEgg aka "allow_dinosaur_easter_egg" @@ -135,10 +137,18 @@ decent litmus test for whether something should be a flag or a setting is: "will someone who can't read or write code want to change this?" +## Related Documents + +* [Chromium Feature API & Finch (Googler-only)](http://go/finch-feature-api) +* [Adding a new feature flag in chrome://flags](how_to_add_your_feature_flag.md) +* [Runtime Enabled Features](../third_party/blink/renderer/platform/RuntimeEnabledFeatures.md) +* [Initialization of Blink runtime features in content layer](initialize_blink_features.md) +* [Integrating a feature with the origin trials framework](origin_trials_integration.md) + [base-commandline]: https://cs.chromium.org/chromium/src/base/command_line.h?type=cs&l=98 [base-feature]: https://cs.chromium.org/chromium/src/base/feature_list.h?sq=package:chromium&g=0&l=53 [about-flags]: https://cs.chromium.org/chromium/src/chrome/browser/about_flags.cc [fieldtrial-config]: https://cs.chromium.org/chromium/src/testing/variations/fieldtrial_testing_config.json [flag-metadata]: https://cs.chromium.org/chromium/src/chrome/browser/flag-metadata.json [prefs]: https://www.chromium.org/developers/design-documents/preferences -[profile-register]: https://source.chromium.org/chromium/chromium/src/+/main:chrome/browser/profiles/profile.h;l=189;drc=b0378e4b67a5dbdb15acf0341ccd51acda81c8e0 \ No newline at end of file +[profile-register]: https://source.chromium.org/chromium/chromium/src/+/main:chrome/browser/profiles/profile.h;l=189;drc=b0378e4b67a5dbdb15acf0341ccd51acda81c8e0
diff --git a/docs/experiments/permissions-policy-unload.md b/docs/experiments/permissions-policy-unload.md new file mode 100644 index 0000000..c90fcb0 --- /dev/null +++ b/docs/experiments/permissions-policy-unload.md
@@ -0,0 +1,65 @@ +# Permissions-Policy: Unload + +Contact: bfcache-dev@chromium.org + +This document describes the status of the current implementation of the +[Permissions-Policy: unload feature](https://github.com/w3c/webappsec-permissions-policy/issues/444) +in Chrome, and how to enable it. + +Starting from version 107, +Chrome experimentally supports Permissions-Policy: unload. +This allows sites to prevent usage of unload event listeners. + +Note that this policy is not available by default. +Chrome plans to do an origin trial +to evaluate its effectiveness +and to allow site authors to give feedback. + +## What’s supported + +A new [permission](https://github.com/w3c/webappsec-permissions-policy/blob/main/permissions-policy-explainer.md) is added, `unload`, +which defaults to be enabled +but when disabled makes calls to `window.addEventListener("unload", callback)` +a no-op. + +## What’s not supported + + +## Activation + +The policy can be enabled in several ways. + +### Using command line flag + +Pass the `--enable-features=PermissionsPolicyUnload` command line flag. + +### Using the Chromium UI + +Enable the flag chrome://flags/#enable-experimental-web-platform-features . + +### Using Origin Trial + +The [Origin Trial](https://developer.chrome.com/blog/origin-trials/) feature is named `PermissionsPolicyUnload`. +See [feature status](https://chromestatus.com/feature/5760325231050752) to find out +if the origin trial is currently running. + +The [origin trial tutorial](https://developer.chrome.com/docs/web-platform/origin-trials/#take-part-in-an-origin-trial) describes how to participate. + +### Verifying the API is working + +In devtools, run the following piece of javascript + +```js +document.createElement("iframe").allow="unload"; +``` + +If it succeeds then the feature is enabled. +If it gives an error like +`Unrecognized feature: 'unload'.` +then the feature is not enabled. + +## Related Links + +- [Chrome Status](https://chromestatus.com/feature/5760325231050752) +- [Permissions-Policy: unload Explainer](https://github.com/fergald/docs/blob/master/explainers/permissions-policy-unload.md) +- [Permissions-Policy: Explainer](https://github.com/w3c/webappsec-permissions-policy/blob/main/permissions-policy-explainer.md)
diff --git a/docs/how_to_add_your_feature_flag.md b/docs/how_to_add_your_feature_flag.md index 089043a..fb24e4f2 100644 --- a/docs/how_to_add_your_feature_flag.md +++ b/docs/how_to_add_your_feature_flag.md
@@ -1,37 +1,69 @@ # Adding a new feature flag in chrome://flags -This document describes how to add your new feature behind a flag. See also -[Configuration](configuration.md), which gives more explanation about flags and -other options for configuring Chrome. +This document describes how to add a new Chrome feature flag visible to users +via chrome://flag UI. + +*** note +**NOTE:** It's NOT required if you don't intend to make your feature appear in +chrome://flag UI. +*** + +See also the following for definitions: +* [Configuration: Features](configuration.md#features) +* [Configuration: Flags](configuration.md#flags) ## Step 1: Adding a new `base::Feature` -This step would be different between where you want to use the flag. -For example, if you want to use the flag in src/content, you should add a base::Feature to the following files: + +This step would be different depending on where you want to use the flag: + +### To Use the Flag in `content/` Only + +Add a `base::Feature` to the following files: * [content/public/common/content_features.cc](https://cs.chromium.org/chromium/src/content/public/common/content_features.cc) * [content/public/common/content_features.h](https://cs.chromium.org/chromium/src/content/public/common/content_features.h) -If you want to use the flag in blink, you should also read -[Runtime Enable Features](https://chromium.googlesource.com/chromium/src/+/main/third_party/blink/renderer/platform/RuntimeEnabledFeatures.md). +### To Use the Flag in `third_party/blink/` (and Possibly in `content/`) -You can refer to [this CL](https://chromium-review.googlesource.com/c/554510/) and [this document](initialize_blink_features.md) -to see +Add a `base::Feature` to the following files: -1. where to add the base::Feature -[[1](https://chromium-review.googlesource.com/c/554510/8/content/public/common/content_features.cc#253)] -[[2](https://chromium-review.googlesource.com/c/554510/8/content/public/common/content_features.h)] -2. how to use it -[[1](https://chromium-review.googlesource.com/c/554510/8/content/common/service_worker/service_worker_utils.cc#153)] -3. how to wire your new base::Feature to a blink runtime feature[[1](https://chromium.googlesource.com/chromium/src/+/main/docs/initialize_blink_features.md)] -4. how to use it in blink -[[1](https://chromium-review.googlesource.com/c/554510/8/third_party/blnk/renderere/core/workers/worker_thread.cc)] +* [third_party/blink/common/features.cc](https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/common/features.cc) +* [third_party/blink/public/common/features.h](https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/public/common/features.h) + +Historically, Blink also has its own runtime feature mechanism. So if you +feature needs to be runtime-enabled, read also Blink's +[Runtime Enable Features][blink-rte] doc and +[Initialization of Blink runtime features in content layer][blink-rte-init]. + +[blink-rte]: ../third_party/blink/renderer/platform/RuntimeEnabledFeatures.md + +### Examples + +You can refer to [this CL](https://chromium-review.googlesource.com/c/554510/) +and [this document](initialize_blink_features.md) to see + +1. Where to add the `base::Feature`: + [[1](https://chromium-review.googlesource.com/c/554510/8/content/public/common/content_features.cc#253)] + [[2](https://chromium-review.googlesource.com/c/554510/8/content/public/common/content_features.h)] +2. How to use it: + [[1](https://chromium-review.googlesource.com/c/554510/8/content/common/service_worker/service_worker_utils.cc#153)] +3. How to wire your new `base::Feature` to a Blink runtime feature: + [[1][blink-rte-init]] +4. How to use it in Blink: + [[1](https://chromium-review.googlesource.com/c/554510/8/third_party/blnk/renderere/core/workers/worker_thread.cc)] Also, this patch added a virtual test for running web tests with the flag. When you add a flag, you can consider to use that. +[blink-rte-init]: initialize_blink_features.md + ## Step 2: Adding the feature flag to the chrome://flags UI. *** promo +Googlers: Read also [Chrome Feature Flag in chrome://flags](http/go/finch-feature-api#chrome-feature-flag-in-chromeflags). +*** + +*** promo **Tip:** Android WebView has its own flag UI. The WebView team recommends adding your features there too if they are supported on WebView. Follow [these steps](/android_webview/docs/developer-ui.md#Adding-your-flags-and-features-to-the-UI) @@ -47,7 +79,8 @@ * [chrome/browser/flag-metadata.json](https://cs.chromium.org/chromium/src/chrome/browser/flag-metadata.json) At first you need to add an entry to __about_flags.cc__, -__flag_descriptions.cc__ and __flag_descriptions.h__. After that, try running the following test. +__flag_descriptions.cc__ and __flag_descriptions.h__. After that, try running +the following test. ```bash # Build unit_tests @@ -58,9 +91,11 @@ ./out/Default/bin/run_unit_tests --gtest_filter=AboutFlagsHistogramTest.CheckHistograms ``` -That test will ask you to add several entries to enums.xml. After doing so, run `git cl format` -which will insert the entries in enums.xml in the correct order and run the tests again. -You can refer to [this CL](https://chromium-review.googlesource.com/c/593707) as an example. +That test will ask you to add several entries to enums.xml. After doing so, run +`git cl format` which will insert the entries in enums.xml in the correct order +and run the tests again. +You can refer to [this CL](https://chromium-review.googlesource.com/c/593707) as +an example. Finally, run the following test. @@ -70,3 +105,10 @@ That test will ask you to update the flag expiry metadata in [flag-metadata.json](https://cs.chromium.org/chromium/src/chrome/browser/flag-metadata.json). + +## Related Documents + +* [Chromium Feature API & Finch (Googler-only)](http://go/finch-feature-api) +* [Configuration: Prefs, Settings, Features, Switches & Flags](configuration.md) +* [Runtime Enabled Features](../third_party/blink/renderer/platform/RuntimeEnabledFeatures.md) +* [Initialization of Blink runtime features in content layer](initialize_blink_features.md)
diff --git a/docs/initialize_blink_features.md b/docs/initialize_blink_features.md index 219a6c5..257b3b2 100644 --- a/docs/initialize_blink_features.md +++ b/docs/initialize_blink_features.md
@@ -80,11 +80,7 @@ will call `wf::EnableNewFeatureX` to disable it only if that `switches::kNewFeatureX` exists on the command line. -### 4) Controlled by parameters from a field trial: -Add your code to the function -[SetRuntimeFeaturesFromFieldTrialParams()][SetRuntimeFeaturesFromFieldTrialParams]. - -### 5) Combination of the previous options or not covered: +### 4) Combination of the previous options or not covered: For example, you Blink feature could be controlled by both a base::Feature and a command line switch. In this case, your custom logic should live here in [`SetCustomizedRuntimeFeaturesFromCombinedArgs()`][SetCustomizedRuntimeFeaturesFromCombinedArgs]. @@ -103,4 +99,4 @@ [SetCustomizedRuntimeFeaturesFromCombinedArgs]:<https://chromium.googlesource.com/chromium/src/+/HEAD/content/child/runtime_features.cc#487> [SetRuntimeFeaturesFromChromiumFeatures]:<https://chromium.googlesource.com/chromium/src/+/HEAD/content/child/runtime_features.cc#160> [SetRuntimeFeaturesFromCommandLine]:<https://chromium.googlesource.com/chromium/src/+/HEAD/content/child/runtime_features.cc#390> -[SetRuntimeFeaturesFromFieldTrialParams]:<https://chromium.googlesource.com/chromium/src/+/HEAD/content/child/runtime_features.cc#448> \ No newline at end of file +[SetRuntimeFeaturesFromFieldTrialParams]:<https://chromium.googlesource.com/chromium/src/+/HEAD/content/child/runtime_features.cc#448>
diff --git a/docs/origin_trials_integration.md b/docs/origin_trials_integration.md index 163936a..865c8b8 100644 --- a/docs/origin_trials_integration.md +++ b/docs/origin_trials_integration.md
@@ -1,59 +1,87 @@ -# Integrating a feature with the origin trials framework +# Integrating a feature with the Origin Trials framework -To expose your feature via the origin trials framework, there are a few code +To expose your feature via the [Origin Trials framework], there are a few code changes required. +*** note +**WARNING:** This is only available for features implemented in Blink. +*** + [TOC] ## Code Changes -NOTE: You can land these code changes before requesting to run an origin trial. +*** promo +**NOTE:** You can land these code changes before requesting to run an origin +trial. These code changes make it possible to control a feature via an origin trial, but don't require an origin trial to be approved. For more on the process, see [Running an Origin Trial]. +*** -### Runtime Enabled Features +### Step 1: Add Runtime Enabled Feature in Blink for Origin Trial -First, you’ll need to configure [runtime\_enabled\_features.json5]. This is -explained in the file, but you use `origin_trial_feature_name` to associate your -runtime feature flag with a name for your origin trial. The name can be the -same as your runtime feature flag, or different. Eventually, this configured -name will be used in the origin trials developer console. You can have both -`status: experimental` and `origin_trial_feature_name` if you want your feature -to be enabled either by using the `--enable-experimental-web-platform-features` -flag **or** the origin trial. +First, you’ll need to configure [runtime\_enabled\_features.json5]. If you don't +have a Blink's [Runtime Enabled Feature] flag yet, you will need to add an entry +in this file. -You will have to change all callers of the no-argument overload of -`RuntimeEnabledFeatures::FooEnabled()` to the overload that takes a -`const FeatureContext*`. You can pass an `ExecutionContext` here -(e.g. using `ExecutionContext::From(ScriptState*)`). +The following fields of an entry are relevant: -You may have a feature that is not available on all platforms, or need to limit -the trial to specific platforms. Use `origin_trial_os: [list]` to specify which -platforms will allow the trial to be enabled. The list values are case- -insensitive, but must match one of the defined `OS_<platform>` macros (see -[build_config.h]). +- `name`: The name of your runtime enabled feature, e.g. `"MyFeature"`. +- `origin_trial_feature_name`: The name of your runtime enabled feature in the + origin trial. This can be the same as your runtime feature flag (i.e. `name` + field), or different. Eventually, this configured name will be used in the + origin trials developer console. +- `origin_trial_os`: Specifies a `[list]` of platforms where they will allow the + trial to be enabled. The list values are case-insensitive, but must match one + of the defined `OS_<platform>` macros (see [build_config.h]). +- `base_feature`: Generates a `base::Feature` in the `blink::features` + namespace. It helps to control the Origin Trial remotely. See also + [Generate a `base::Feature` instance from a Blink Feature][from blink]. + +Not specific to Origin Trial: + +- `status`: Controls when the runtime enabled feature is enabled in Blink. See + also [the Status table]. +- `base_feature_status`: Controls when the `base::Feature` defined by + `base_feature` is enabled. + +More details are explained in the json5 file and in the above linked doc. + +If the runtime enabled feature flag is [used in C++](#1-in-c), you will have to +change all callers of the no-argument overload of +`RuntimeEnabledFeatures::MyFeatureEnabled()` to the overload that takes a +`const FeatureContext*`. You can pass an `ExecutionContext` here, e.g. using +`ExecutionContext::From(ScriptState*)`. #### Examples -Flag name and trial name are the same: -``` +RuntimeEnabledFeature flag name, trial name and `base::Feature` are all the +same: + +```json { - name: "MyFeature", + name: "MyFeature", // Generates `RuntimeEnabledFeatures::MyFeatureEnabled()` origin_trial_feature_name: "MyFeature", + base_feature: "MyFeature", // Generates blink::features::kMyFeature status: "experimental", }, ``` -Flag name and trial name are different: -``` + +RuntimeEnabledFeature flag name and trial name are different: + +```json { name: "MyFeature", origin_trial_feature_name: "MyFeatureTrial", + base_feature: "MyFeature", // Generates blink::features::kMyFeature status: "experimental", }, ``` + Trial limited to specific platform: -``` json + +```json { name: "MyFeature", origin_trial_feature_name: "MyFeature", @@ -63,8 +91,9 @@ ``` #### WebView considerations -Because WebView is built as part of the `"android"` os target, it is not possible -to exclude a trial from WebView if it is enabled on Android. + +Because WebView is built as part of the `"android"` os target, it is not +possible to exclude a trial from WebView if it is enabled on Android. If the feature under trial can be enabled on WebView alongside other Android platforms, this is preferred. @@ -77,105 +106,235 @@ See http://crrev.com/c/3733267 for an example of how this can be done. -### CSS Properties - -You can also run experiment for new CSS properties with origin trial. After you -have configured your feature in [runtime\_enabled\_features.json5] as above, head -to [css\_properties.json5]. As explained in the file, you use `runtime_flag` to associate -the CSS property with the feature you just defined. This will automatically link the CSS -property to the origin trial defined in the runtime feature. It will be available -in both JavaScript (`Element.style`) and CSS (including `@supports`) when the trial -is enabled. - - -**Example:** [origin-trial-test-property] defines a test css property controlled via -runtime feature `OriginTrialsSampleAPI` and subsequently an origin trial named `Frobulate`. - -### Gating Access +### Step 2: Gating Access Once configured, there are two mechanisms to gate access to your feature behind an origin trial. You can use either mechanism, or both, as appropriate to your feature implementation. -1. A native C++ method that you can call in Blink code at runtime to expose your - feature: `bool RuntimeEnabledFeatures::MyFeatureEnabled(ExecutionContext*)` -2. An IDL attribute \[[RuntimeEnabled]\] that you can use to automatically - generate code to expose and hide JavaScript methods/attributes/objects. +#### 1) In C++ + +A native C++ method that you can call in Blink code at runtime to expose your +feature: + +```cpp +bool RuntimeEnabledFeatures::MyFeatureEnabled(ExecutionContext*) ``` + +*** note +**WARNING:** Your feature implementation must not persist the result of the +enabled check. Your code should simply call +`RuntimeEnabledFeatures::MyFeatureEnabled(ExecutionContext*)` as often as +necessary to gate access to your feature. +*** + +#### 2-1) In Web IDL + +An IDL attribute \[[RuntimeEnabled]\] that you can use to automatically generate +code to expose and hide JavaScript methods/attributes/objects. + +```cpp [RuntimeEnabled=MyFeature] partial interface Navigator { readonly attribute MyFeatureManager myFeature; } ``` -**NOTE:** Your feature implementation must not persist the result of the enabled -check. Your code should simply call -`RuntimeEnabledFeatures::MyFeatureEnabled(ExecutionContext*)` as often as -necessary to gate access to your feature. +#### 2-2) CSS Properties -**NOTE:** For CSS properties, you do not need to edit the IDL files, as the exposure -on the [CSSStyleDeclaration] is handled at runtime. +*** promo +**NOTE:** For CSS properties, you do not need to edit the IDL files, as the +exposure on the [CSSStyleDeclaration] is handled at runtime. +*** -**ISSUE:** In the rare cases where the origin trial token is added via script after -the css style declaration, the css property will be enabled and is fully functional, -however it will not appear on the [CSSStyleDeclaration] interface, i.e. not accessible -in `Element.style`. This issue is tracked in crbug/1041993. +You can also run experiment for new CSS properties with origin trial. After you +have configured your feature in [runtime\_enabled\_features.json5] as above, +head to [css\_properties.json5]. As explained in the file, you use +`runtime_flag` to associate the CSS property with the feature you just defined. +This will automatically link the CSS property to the origin trial defined in the +runtime feature. It will be available in both JavaScript (`Element.style`) and +CSS (including `@supports`) when the trial is enabled. -### Web Feature Counting +*** promo +**EXAMPLE:** [origin-trial-test-property] defines a test css property controlled +via runtime feature `OriginTrialsSampleAPI` and subsequently an origin trial +named `Frobulate`. +*** + +*** note +**ISSUE:** In the rare cases where the origin trial token is added via script +after the css style declaration, the css property will be enabled and is fully +functional, however it will not appear on the [CSSStyleDeclaration] interface, +i.e. not accessible in `Element.style`. This issue is tracked in crbug/1041993. +*** + +### Step 3: Mapping Runtime Enabled Feature to `base::Feature` (optional) + +Given the following example: + +```json +{ + name: "MyFeature", + origin_trial_feature_name: "MyFeature", + base_feature: "MyFeature", + status: "experimental", +}, +``` + +```cpp +[RuntimeEnabled=MyFeature] +interface MyFeatureAPI { + readonly attribute bool dummy; +} +``` + +```cpp +// third_party/blink/.../my_feature_api.cc +bool MyFeatureAPI::ConnectToBrowser() { + if (base::FeatureList::IsEnabled(blink::features::kMyFeature) { + // Do something + } + return false; +} +``` + +The above example shows a new feature relies on a `base::Feature` generated from +the `base_feature` definition in json file, e.g. `blink::features::kMyFeature`, +in addition to the runtime enabled feature flag `MyFeature`. +However, their values are not associated. + +In addition, due to the [limitation](#limitations), the runtime enabled feature +flag is not available in the browser process **by default**: + +> if you need to know in the browser process whether a feature should +> be enabled, then you will have to either have the renderer inform it at +> runtime, or else just assume that it's always enabled, and gate access to the +> feature from the renderer. + +*** note +**TLDR:** Turning on `MyFeature` doesn't automatically turning on +`blink::features::kMyFeature`, and vice versa. +*** + +To mitigate the issue, there are several options: + +#### Option 1: Fully Enabling `base::Feature`, e.g. `kMyFeature` + +And letting Origin Trial decides when your feature (via runtime enabled feature +flag `blink::features::MyFeature`) is available, as suggested in the above +quote. The `base::Feature` can be enabled via a remote Finch config, or by +updating the default value in C++. + +However, after the Origin Trial ends, it will be impossible to ramp up the +feature by Finch if the part controlled by `MyFeature` cannot be enabled +independently. For example, if you have a new Web API `MyFeatureAPI`, enabling +`MyFeature` will just make the IDL available to everyone without the +Blink/browser implementation. + +*** note +**Example Bug:** https://crbug.com/1360678. +*** + +#### Option 2: Setting Up a Custom Mapping + +1. Make `MyFeature` depend on `blink::features::kMyFeature` so that the feature + is not enabled if `features::kMyFeatures` is not enabled. In + [third_party/blink/renderer/core/origin_trials/origin_trial_context.cc](../third_party/blink/renderer/core/origin_trials/origin_trial_context.cc): + + ```cpp + bool OriginTrialContext::CanEnableTrialFromName(const StringView& trial_name) { + ... + if (trial_name == "MyFeature") { + return base::FeatureList::IsEnabled(blink::features::kMyFeatures); + } + } + ``` + +2. Add custom relationship for `MyFeature` and `blink::features::kMyFeature` to + handle your use case. + + Read + [**Determine how your feature is initialized: Depends on the status of a base::Feature**](initialize_blink_features.md#step-2_determine-how-your-feature-is-initialized) + first. If the mappings described there don't meet your use case, refer to + the following examples. + + In [content/child/runtime_features.cc](https://source.chromium.org/chromium/chromium/src/+/main:content/child/runtime_features.cc): + + ```cpp + void SetCustomizedRuntimeFeaturesFromCombinedArgs( + const base::CommandLine& command_line) { + // Example 1: https://bit.ly/configuring-trust-tokens + // Example 2: https://crrev.com/c/3878922/14/content/child/runtime_features.cc + } + ``` + +### Step 4: Web Feature Counting Once the feature is created, in order to run the origin trial you need to track how often users use your feature. You can do it in two ways. -#### Increment counter in your c++ code. +#### Increment counter in your c++ code 1. Add your feature counter to end of [web\_feature.mojom]: -``` -enum WebFeature { - // ... - kLastFeatureBeforeYours = 1235, - // Here, increment the last feature count before yours by 1. - kMyFeature = 1236, + ```cpp + enum WebFeature { + // ... + kLastFeatureBeforeYours = 1235, + // Here, increment the last feature count before yours by 1. + kMyFeature = 1236, - kNumberOfFeatures, // This enum value must be last. -}; -``` + kNumberOfFeatures, // This enum value must be last. + }; + ``` + 2. Run [update\_use\_counter\_feature\_enum.py] to update the UMA mapping. 3. Increment your feature counter in c++ code. -```c++ -#include "third_party/blink/renderer/platform/instrumentation/use_counter.h" -// ... + ```c++ + #include "third_party/blink/renderer/platform/instrumentation/use_counter.h" - if (RuntimeEnabledFeatures::MyFeatureEnabled(context)) { - UseCounter::Count(context, WebFeature::kMyFeature); - } -``` + // ... + + if (RuntimeEnabledFeatures::MyFeatureEnabled(context)) { + UseCounter::Count(context, WebFeature::kMyFeature); + } + ``` #### Update counter with \[Measure\] IDL attribute 1. Add \[[Measure]\] IDL attribute -``` -partial interface Navigator { - [RuntimeEnabled=MyFeature, Measure] - readonly attribute MyFeatureManager myFeature; -``` + + ```cpp + partial interface Navigator { + [RuntimeEnabled=MyFeature, Measure] + readonly attribute MyFeatureManager myFeature; + ``` 2. The code to increment your feature counter will be generated in V8 automatically. But it requires you to follow \[[Measure]\] IDL attribute naming convention when you will add your feature counter to [web\_feature.mojom]. -``` -enum WebFeature { - // ... - kLastFeatureBeforeYours = 1235, - // Here, increment the last feature count before yours by 1. - kV8Navigator_MyFeature_AttributeGetter = 1236, - kNumberOfFeatures, // This enum value must be last. -}; -``` + ```cpp + enum WebFeature { + // ... + kLastFeatureBeforeYours = 1235, + // Here, increment the last feature count before yours by 1. + kV8Navigator_MyFeature_AttributeGetter = 1236, + + kNumberOfFeatures, // This enum value must be last. + }; + ``` + +### Step 5: Add Web Tests + +When using the \[[RuntimeEnabled]\] IDL attribute, you should add web tests +to verify that the V8 bindings code is working as expected. Depending on how +your feature is exposed, you'll want tests for the exposed interfaces, as well +as tests for script-added tokens. For examples, refer to the existing tests in +[origin_trials/webexposed]. ## Limitations @@ -199,7 +358,7 @@ or else just assume that it's always enabled, and gate access to the feature from the renderer. -## Testing +## Manual Testing To test an origin trial feature during development, follow these steps: @@ -207,17 +366,17 @@ You can generate signed tokens for any origin that you need to help you test, including localhost or 127.0.0.1. Example: - ``` - tools/origin_trials/generate_token.py http://localhost:8000 MyFeature - ``` + ```bash + tools/origin_trials/generate_token.py http://localhost:8000 MyFeature + ``` There are additional flags to generate third-party tokens, set the expiry date, and control other options. See the command help for details (`--help`). For example, to generate a third-party token, with [user subset exclusion]: - ``` - tools/origin_trials/generate_token.py --is-third-party --usage-restriction=subset http://localhost:8000 MyFeature - ``` + ```bash + tools/origin_trials/generate_token.py --is-third-party --usage-restriction=subset http://localhost:8000 MyFeature + ``` 2. Copy the token from the end of the output and use it in a `<meta>` tag or an `Origin-Trial` header as described in the [Developer Guide]. @@ -225,7 +384,8 @@ 3. Run Chrome with the test public key by passing: `--origin-trial-public-key=dRCs+TocuKkocNKa0AtZ4awrt9XKH2SQCI6o4FY6BNA=` -You can also run Chrome with both the test public key and the default public key along side by passing: +You can also run Chrome with both the test public key and the default public key +along side by passing: `--origin-trial-public-key=dRCs+TocuKkocNKa0AtZ4awrt9XKH2SQCI6o4FY6BNA=,fMS4mpO6buLQ/QMd+zJmxzty/VQ6B1EUZqoCU04zoRU=` The `--origin-trial-public-key` switch is not needed with `content_shell`, as it @@ -237,8 +397,9 @@ If you cannot set command-line switches (e.g., on Chrome OS), you can also directly modify [chrome_origin_trial_policy.cc]. -To see additional information about origin trial token parsing (including reasons -for failures, or token names for successful tokens), you can add these switches: +To see additional information about origin trial token parsing (including +reasons for failures, or token names for successful tokens), you can add these +switches: `--vmodule=trial_token=2,origin_trial_context=1` @@ -247,27 +408,30 @@ `--enable-logging=stderr` +## Related Documents -### Web Tests -When using the \[RuntimeEnabled\] IDL attribute, you should add web tests -to verify that the V8 bindings code is working as expected. Depending on how -your feature is exposed, you'll want tests for the exposed interfaces, as well -as tests for script-added tokens. For examples, refer to the existing tests in -[origin_trials/webexposed]. +- [Chromium Feature API & Finch (Googler-only)](http://go/finch-feature-api) +- [Configuration: Prefs, Settings, Features, Switches & Flags](configuration.md) +- [Runtime Enabled Features](../third_party/blink/renderer/platform/RuntimeEnabledFeatures.md) +- [Initialization of Blink runtime features in content layer](initialize_blink_features.md) +[Origin Trials framework]: http://googlechrome.github.io/OriginTrials/developer-guide.html +[Runtime Enabled Features]: ../third_party/blink/renderer/platform/RuntimeEnabledFeatures.md +[from blink]: ../third_party/blink/renderer/platform/RuntimeEnabledFeatures.md#generate-a-instance-from-a-blink-feature +[the Status table]: ../third_party/blink/renderer/platform/RuntimeEnabledFeatures.md#adding-a-runtime-enabled-feature [build_config.h]: /build/build_config.h [chrome_origin_trial_policy.cc]: /chrome/common/origin_trials/chrome_origin_trial_policy.cc [generate_token.py]: /tools/origin_trials/generate_token.py [Developer Guide]: https://github.com/jpchase/OriginTrials/blob/gh-pages/developer-guide.md -[RuntimeEnabled]: /third_party/blink/renderer/bindings/IDLExtendedAttributes.md#RuntimeEnabled_i_m_a_c -[origin_trials/webexposed]: /third_party/blink/web_tests/http/tests/origin_trials/webexposed/ -[runtime\_enabled\_features.json5]: /third_party/blink/renderer/platform/runtime_enabled_features.json5 -[trial_token_unittest.cc]: /third_party/blink/common/origin_trials/trial_token_unittest.cc -[web\_feature.mojom]: /third_party/blink/public/mojom/use_counter/metrics/web_feature.mojom +[RuntimeEnabled]: ../third_party/blink/renderer/bindings/IDLExtendedAttributes.md#RuntimeEnabled_i_m_a_c +[origin_trials/webexposed]: ../third_party/blink/web_tests/http/tests/origin_trials/webexposed/ +[runtime\_enabled\_features.json5]: ../third_party/blink/renderer/platform/runtime_enabled_features.json5 +[trial_token_unittest.cc]: ../third_party/blink/common/origin_trials/trial_token_unittest.cc +[web\_feature.mojom]: ../third_party/blink/public/mojom/use_counter/metrics/web_feature.mojom [update\_use\_counter\_feature\_enum.py]: /tools/metrics/histograms/update_use_counter_feature_enum.py -[Measure]: /third_party/blink/renderer/bindings/IDLExtendedAttributes.md#Measure_i_m_a_c -[css\_properties.json5]: /third_party/blink/renderer/core/css/css_properties.json5 +[Measure]: ../third_party/blink/renderer/bindings/IDLExtendedAttributes.md#Measure_i_m_a_c +[css\_properties.json5]: ../third_party/blink/renderer/core/css/css_properties.json5 [origin-trial-test-property]: https://chromium.googlesource.com/chromium/src/+/ff2ab8b89745602c8300322c2a0158e210178c7e/third_party/blink/renderer/core/css/css_properties.json5#2635 -[CSSStyleDeclaration]: /third_party/blink/renderer/core/css/css_style_declaration.idl +[CSSStyleDeclaration]: ../third_party/blink/renderer/core/css/css_style_declaration.idl [Running an Origin Trial]: https://www.chromium.org/blink/origin-trials/running-an-origin-trial [user subset exclusion]: https://docs.google.com/document/d/1xALH9W7rWmX0FpjudhDeS2TNTEOXuPn4Tlc9VmuPdHA/edit#heading=h.myaz1twlipw
diff --git a/extensions/browser/extension_function_histogram_value.h b/extensions/browser/extension_function_histogram_value.h index 014332d..d008dad 100644 --- a/extensions/browser/extension_function_histogram_value.h +++ b/extensions/browser/extension_function_histogram_value.h
@@ -1770,6 +1770,8 @@ FILEMANAGERPRIVATE_GETDLPBLOCKEDCOMPONENTS = 1707, FILEMANAGERPRIVATE_GETDIALOGCALLER = 1708, OS_TELEMETRY_GETNONREMOVABLEBLOCKDEVICESINFO = 1709, + OS_DIAGNOSTICS_RUNDNSRESOLUTIONROUTINE = 1710, + OS_DIAGNOSTICS_RUNSIGNALSTRENGTHROUTINE = 1711, // Last entry: Add new entries above, then run: // tools/metrics/histograms/update_extension_histograms.py ENUM_BOUNDARY
diff --git a/fuchsia_web/runners/BUILD.gn b/fuchsia_web/runners/BUILD.gn index 503bbfb..e4e6a294 100644 --- a/fuchsia_web/runners/BUILD.gn +++ b/fuchsia_web/runners/BUILD.gn
@@ -216,6 +216,7 @@ test("cast_runner_integration_tests") { sources = [ + "cast/cast_runner_cfv1_shim_integration_test.cc", "cast/cast_runner_integration_test.cc", "cast/cast_runner_integration_test_base.cc", "cast/cast_runner_integration_test_base.h", @@ -242,49 +243,6 @@ "//third_party/fuchsia-sdk/sdk/pkg/scenic_cpp", "//third_party/fuchsia-sdk/sdk/pkg/sys_cpp", ] - package_deps = [ [ - "//fuchsia_web/webengine:web_engine", - "web_engine", - ] ] - additional_manifest_fragments = [ - "//build/config/fuchsia/test/fonts.shard.test-cml", - "//build/config/fuchsia/test/network.shard.test-cml", - "//fuchsia_web/runners/cast/cast_runner_integration_test.shard.test-cml", - "//third_party/fuchsia-sdk/sdk/pkg/sys/component/realm_builder_absolute.shard.cml", - "//third_party/fuchsia-sdk/sdk/pkg/vulkan/client.shard.cml", - ] -} - -test("cast_runner_integration_tests_cfv1") { - sources = [ - "cast/cast_runner_integration_test.cc", - "cast/cast_runner_integration_test_base.cc", - "cast/cast_runner_integration_test_base.h", - "cast/cast_runner_integration_test_cfv1.cc", - "common/modular/fake_component_context.cc", - "common/modular/fake_component_context.h", - ] - data = [ "cast/testdata" ] - deps = [ - ":cast_runner_core", - ":cast_runner_test_core", - "//base/test:test_support", - "//components/cast/message_port", - "//fuchsia_web/common", - "//fuchsia_web/common/test:run_all_integration_tests", - "//fuchsia_web/common/test:test_support", - "//fuchsia_web/runners/cast/test:cfv1_integration", - "//fuchsia_web/runners/common/modular", - "//net:test_support", - "//testing/gtest", - "//third_party/fuchsia-sdk/sdk/fidl/fuchsia.camera3", - "//third_party/fuchsia-sdk/sdk/fidl/fuchsia.legacymetrics", - "//third_party/fuchsia-sdk/sdk/fidl/fuchsia.media", - "//third_party/fuchsia-sdk/sdk/fidl/fuchsia.modular", - "//third_party/fuchsia-sdk/sdk/pkg/scenic_cpp", - "//third_party/fuchsia-sdk/sdk/pkg/sys_cpp", - ] - data_deps = [ ":cast_runner_core" ] package_deps = [ [ ":cast_runner_pkg", @@ -295,12 +253,13 @@ "web_engine", ], ] - use_cfv1 = true - use_cfv2 = false additional_manifest_fragments = [ - "//build/config/fuchsia/test/network_capabilities.test-cmx", - "//build/config/fuchsia/test/vulkan_capabilities.test-cmx", - "//build/config/fuchsia/test/web_engine_required_capabilities.test-cmx", + "//build/config/fuchsia/test/cfv1_launcher.shard.test-cml", + "//build/config/fuchsia/test/fonts.shard.test-cml", + "//build/config/fuchsia/test/network.shard.test-cml", + "//fuchsia_web/runners/cast/cast_runner_integration_test.shard.test-cml", + "//third_party/fuchsia-sdk/sdk/pkg/sys/component/realm_builder_absolute.shard.cml", + "//third_party/fuchsia-sdk/sdk/pkg/vulkan/client.shard.cml", ] }
diff --git a/fuchsia_web/runners/cast/cast_runner_cfv1_shim_integration_test.cc b/fuchsia_web/runners/cast/cast_runner_cfv1_shim_integration_test.cc new file mode 100644 index 0000000..745abed --- /dev/null +++ b/fuchsia_web/runners/cast/cast_runner_cfv1_shim_integration_test.cc
@@ -0,0 +1,191 @@ +// Copyright 2022 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include <fuchsia/sys/cpp/fidl.h> +#include <lib/fdio/fd.h> +#include <lib/fidl/cpp/interface_request.h> +#include <lib/sys/cpp/component_context.h> +#include <lib/sys/cpp/outgoing_directory.h> +#include <lib/sys/cpp/service_directory.h> +#include <unistd.h> +#include <zircon/processargs.h> + +#include <utility> +#include <vector> + +#include "base/auto_reset.h" +#include "base/callback.h" +#include "base/command_line.h" +#include "base/fuchsia/fuchsia_logging.h" +#include "base/fuchsia/process_context.h" +#include "base/fuchsia/scoped_service_publisher.h" +#include "base/fuchsia/test_component_controller.h" +#include "base/location.h" +#include "base/run_loop.h" +#include "base/test/bind.h" +#include "base/test/scoped_run_loop_timeout.h" +#include "base/test/task_environment.h" +#include "base/test/test_timeouts.h" +#include "fuchsia_web/runners/cast/cast_runner_switches.h" +#include "net/test/embedded_test_server/default_handlers.h" +#include "net/test/embedded_test_server/embedded_test_server.h" +#include "testing/gtest/include/gtest/gtest.h" + +class CastRunnerCfv1ShimIntegrationTest : public ::testing::Test { + protected: + CastRunnerCfv1ShimIntegrationTest() + : fake_runner_publisher_( + &services_for_runner_, + [this](fidl::InterfaceRequest<fuchsia::sys::Runner> request) { + received_requests_.push_back(std::move(request)); + if (on_request_received_) + on_request_received_.Run(); + }, + "fuchsia.sys.Runner-cast") {} + + void SetUp() override { + cast_runner_services_ = StartCfv1Shim(); + + // Connect to the CastRunner's fuchsia.sys.Runner interface. + cast_runner_shim_ = cast_runner_services_->Connect<fuchsia::sys::Runner>(); + cast_runner_shim_.set_error_handler([](zx_status_t status) { + ZX_LOG(ERROR, status) << "CastRunner closed channel."; + ADD_FAILURE(); + }); + + static constexpr base::StringPiece kTestServerRoot( + "fuchsia_web/runners/cast/testdata"); + test_server_.ServeFilesFromSourceDirectory(kTestServerRoot); + net::test_server::RegisterDefaultHandlers(&test_server_); + ASSERT_TRUE(test_server_.Start()); + } + + void TearDown() override { + // Unbind the Runner channel, to prevent it from triggering an error when + // the CastRunner and WebEngine are torn down. + cast_runner_shim_.Unbind(); + } + + void RunUntilRequestsReceived(size_t expected_count) { + base::RunLoop run_loop; + base::AutoReset reset(&on_request_received_, + base::BindLambdaForTesting([&]() { + if (received_requests_.size() == expected_count) + run_loop.Quit(); + })); + run_loop.Run(); + } + + ::fuchsia::sys::ComponentControllerPtr& controller_ptr() { + return controller_.ptr(); + } + ::fuchsia::sys::RunnerPtr& cast_runner_shim_ptr() { + return cast_runner_shim_; + } + + std::vector<fidl::InterfaceRequest<fuchsia::sys::Runner>> received_requests_; + + private: + std::unique_ptr<sys::ServiceDirectory> StartCfv1Shim() { + fuchsia::sys::LaunchInfo launch_info; + launch_info.url = + "fuchsia-pkg://fuchsia.com/cast_runner#meta/cast_runner.cmx"; + + // Clone stderr from the current process to CastRunner and ask it to + // redirect all logs to stderr. + launch_info.err = fuchsia::sys::FileDescriptor::New(); + launch_info.err->type0 = PA_FD; + zx_status_t status = fdio_fd_clone( + STDERR_FILENO, launch_info.err->handle0.reset_and_get_address()); + ZX_CHECK(status == ZX_OK, status); + + base::CommandLine command_line(base::CommandLine::NO_PROGRAM); + command_line.AppendSwitch(kDisableVulkanForTestsSwitch); + command_line.AppendSwitchASCII("enable-logging", "stderr"); + + // Add all switches and arguments, skipping the program. + launch_info.arguments.emplace(std::vector<std::string>( + command_line.argv().begin() + 1, command_line.argv().end())); + + auto additional_services = std::make_unique<fuchsia::sys::ServiceList>(); + auto* svc_dir = services_for_runner_.GetOrCreateDirectory("svc"); + additional_services->names.push_back("fuchsia.sys.Runner-cast"); + + fuchsia::io::DirectoryHandle svc_dir_handle; + svc_dir->Serve(fuchsia::io::OpenFlags::RIGHT_READABLE | + fuchsia::io::OpenFlags::RIGHT_WRITABLE, + svc_dir_handle.NewRequest().TakeChannel()); + additional_services->host_directory = svc_dir_handle.TakeChannel(); + + launch_info.additional_services = std::move(additional_services); + + fuchsia::io::DirectoryHandle cast_runner_services_dir; + launch_info.directory_request = + cast_runner_services_dir.NewRequest().TakeChannel(); + + fuchsia::sys::LauncherPtr launcher; + base::ComponentContextForProcess()->svc()->Connect(launcher.NewRequest()); + launcher->CreateComponent(std::move(launch_info), + controller_.ptr().NewRequest()); + return std::make_unique<sys::ServiceDirectory>( + std::move(cast_runner_services_dir)); + } + + base::test::SingleThreadTaskEnvironment task_environment_{ + base::test::SingleThreadTaskEnvironment::MainThreadType::IO}; + net::EmbeddedTestServer test_server_; + + // TODO(https://crbug.com/1168538): Override the RunLoop timeout set by + // |task_environment_| to allow for the very high variability in web.Context + // launch times. + const base::test::ScopedRunLoopTimeout scoped_timeout_{ + FROM_HERE, TestTimeouts::action_max_timeout()}; + + std::unique_ptr<sys::ServiceDirectory> cast_runner_services_; + fuchsia::sys::RunnerPtr cast_runner_shim_; + base::TestComponentController controller_; + + // Directory used to publish test ContextProvider to CastRunner. + sys::OutgoingDirectory services_for_runner_; + base::ScopedServicePublisher<fuchsia::sys::Runner> fake_runner_publisher_; + base::RepeatingClosure on_request_received_; +}; + +// Ensure that when running in CFv1 "shim" mode, all connection attempts are +// trivially redirected to a fuchsia.sys.Runner-cast service capability in +// the shim Runner's environment. +TEST_F(CastRunnerCfv1ShimIntegrationTest, ProxiesConnect) { + ASSERT_EQ(received_requests_.size(), 0u); + + // The test constructor launched the CastRunner, configured as CFv1 shim, + // and immediately connected to it. That should result in two requests via the + // additional-services, which will be handled by |fake_runner_publisher_| + // as soon as the message loop is allowed to pump events. + // The first request is from the Runner shim itself, to allow it to monitor + // whether the service capability is still valid. + // The second is the test's connection to the shim Runner. + RunUntilRequestsReceived(2u); +} + +// Ensure that CFv1 "shim" mode tears down the Runner component if the +// underlying service capability disconnects it. This is required in order to +// have the shim correctly reflect instability in the real Runner, to the CFv1 +// framework. +TEST_F(CastRunnerCfv1ShimIntegrationTest, ExitOnFailure) { + // |cast_runner_shim_| is expected to disconnect, so remove the error handler. + cast_runner_shim_ptr().set_error_handler([](zx_status_t) {}); + + // Wait for the two incoming Runner connections. + RunUntilRequestsReceived(2u); + + // Close the two connections, and expect the Runner to self-terminate. + received_requests_.clear(); + base::RunLoop loop; + controller_ptr().set_error_handler( + [quit_loop = loop.QuitClosure()](zx_status_t status) { + EXPECT_EQ(status, ZX_ERR_PEER_CLOSED); + quit_loop.Run(); + }); + loop.Run(); +}
diff --git a/fuchsia_web/runners/cast/cast_runner_integration_test_base.h b/fuchsia_web/runners/cast/cast_runner_integration_test_base.h index 81a2678..40b7aa0 100644 --- a/fuchsia_web/runners/cast/cast_runner_integration_test_base.h +++ b/fuchsia_web/runners/cast/cast_runner_integration_test_base.h
@@ -19,27 +19,16 @@ #include "base/test/task_environment.h" #include "base/test/test_timeouts.h" #include "fuchsia_web/runners/cast/test/cast_runner_features.h" +#include "fuchsia_web/runners/cast/test/cast_runner_launcher.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "testing/gtest/include/gtest/gtest.h" -#if defined(USE_CFV1_LAUNCHER) -#include "fuchsia_web/runners/cast/test/cast_runner_launcher_v1.h" // nogncheck -#else -#include "fuchsia_web/runners/cast/test/cast_runner_launcher_v2.h" // nogncheck -#endif - // The base class for cast runner integration tests; templated on the type of // launcher used to start the component. This allows the same tests to be used // under both component framework v1 (using fuchsia.sys.Launcher) and v2 // (using component_testing::RealmBuilder). class CastRunnerIntegrationTest : public testing::Test { public: -#if defined(USE_CFV1_LAUNCHER) - using Launcher = test::CastRunnerLauncherV1; -#else - using Launcher = test::CastRunnerLauncherV2; -#endif - CastRunnerIntegrationTest(const CastRunnerIntegrationTest&) = delete; CastRunnerIntegrationTest& operator=(const CastRunnerIntegrationTest&) = delete; @@ -54,7 +43,9 @@ void SetUp() override; void TearDown() override; - Launcher& cast_runner_launcher() { return cast_runner_launcher_; } + test::CastRunnerLauncher& cast_runner_launcher() { + return cast_runner_launcher_; + } net::EmbeddedTestServer& test_server() { return test_server_; } fuchsia::sys::RunnerPtr& cast_runner() { return cast_runner_; } const sys::ServiceDirectory& cast_runner_services() const { @@ -72,7 +63,7 @@ const base::test::ScopedRunLoopTimeout scoped_timeout_{ FROM_HERE, TestTimeouts::action_max_timeout()}; - Launcher cast_runner_launcher_; + test::CastRunnerLauncher cast_runner_launcher_; fuchsia::sys::RunnerPtr cast_runner_;
diff --git a/fuchsia_web/runners/cast/cast_runner_integration_test_cfv1.cc b/fuchsia_web/runners/cast/cast_runner_integration_test_cfv1.cc deleted file mode 100644 index 5019ef3b..0000000 --- a/fuchsia_web/runners/cast/cast_runner_integration_test_cfv1.cc +++ /dev/null
@@ -1,86 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <fuchsia/sys/cpp/fidl.h> -#include <lib/fidl/cpp/interface_request.h> - -#include <utility> -#include <vector> - -#include "base/auto_reset.h" -#include "base/callback.h" -#include "base/fuchsia/scoped_service_publisher.h" -#include "base/run_loop.h" -#include "base/test/bind.h" -#include "fuchsia_web/runners/cast/cast_runner_integration_test_base.h" -#include "testing/gtest/include/gtest/gtest.h" - -class CastRunnerCfv1ShimIntegrationTest : public CastRunnerIntegrationTest { - public: - CastRunnerCfv1ShimIntegrationTest() - : CastRunnerIntegrationTest(test::kCastRunnerFeaturesCfv1Shim), - fake_runner_publisher_( - &cast_runner_launcher().services_for_runner(), - [this](fidl::InterfaceRequest<fuchsia::sys::Runner> request) { - received_requests_.push_back(std::move(request)); - if (on_request_received_) - on_request_received_.Run(); - }, - "fuchsia.sys.Runner-cast") {} - - void RunUntilRequestsReceived(size_t expected_count) { - base::RunLoop run_loop; - base::AutoReset reset(&on_request_received_, - base::BindLambdaForTesting([&]() { - if (received_requests_.size() == expected_count) - run_loop.Quit(); - })); - run_loop.Run(); - } - - protected: - std::vector<fidl::InterfaceRequest<fuchsia::sys::Runner>> received_requests_; - base::RepeatingClosure on_request_received_; - - private: - base::ScopedServicePublisher<fuchsia::sys::Runner> fake_runner_publisher_; -}; - -// Ensure that when running in CFv1 "shim" mode, all connection attempts are -// trivially redirected to a fuchsia.sys.Runner-cast service capability in -// the shim Runner's environment. -TEST_F(CastRunnerCfv1ShimIntegrationTest, ProxiesConnect) { - ASSERT_EQ(received_requests_.size(), 0u); - - // The test constructor launched the CastRunner, configured as CFv1 shim, - // and immediately connected to it. That should result in two requests via the - // additional-services, which will be handled by |fake_runner_publisher_| - // as soon as the message loop is allowed to pump events. - // The first request is from the Runner shim itself, to allow it to monitor - // whether the service capability is still valid. - // The second is the test's connection to the shim Runner. - RunUntilRequestsReceived(2u); -} - -// Ensure that CFv1 "shim" mode tears down the Runner component if the -// underlying service capability disconnects it. This is required in order to -// have the shim correctly reflect instability in the real Runner, to the CFv1 -// framework. -TEST_F(CastRunnerCfv1ShimIntegrationTest, ExitOnFailure) { - // |cast_runner_| is expected to disconnect, so remove the error handler. - cast_runner().set_error_handler([](zx_status_t) {}); - - // Wait for the two incoming Runner connections. - RunUntilRequestsReceived(2u); - - // Close the two connections, and expect the Runner to self-terminate. - received_requests_.clear(); - base::RunLoop loop; - cast_runner_launcher().controller_ptr().set_error_handler( - [quit_loop = loop.QuitClosure()](zx_status_t status) { - EXPECT_EQ(status, ZX_ERR_PEER_CLOSED); - quit_loop.Run(); - }); - loop.Run(); -}
diff --git a/fuchsia_web/runners/cast/main.cc b/fuchsia_web/runners/cast/main.cc index 2141bda..f11487a0 100644 --- a/fuchsia_web/runners/cast/main.cc +++ b/fuchsia_web/runners/cast/main.cc
@@ -39,9 +39,6 @@ // Config-data key to enable the fuchsia.web.FrameHost provider component. constexpr char kFrameHostConfigKey[] = "enable-frame-host-component"; -// Config-data key to run the CFv1 runner as a shim to the CFv2 runner. -constexpr char kRunCfv1ShimConfigKey[] = "enable-cfv1-shim"; - // Returns the value of |config_key| or false if it is not set. bool GetConfigBool(base::StringPiece config_key) { const absl::optional<base::Value>& config = @@ -111,9 +108,7 @@ LogComponentStartWithVersion("cast_runner"); - if (!enable_cfv2 && (base::CommandLine::ForCurrentProcess()->HasSwitch( - kRunCfv1ShimConfigKey) || - GetConfigBool(kRunCfv1ShimConfigKey))) { + if (!enable_cfv2) { return Cfv1ToCfv2RunnerProxyMain(); } @@ -136,11 +131,8 @@ data_reset_binding(outgoing_directory, &runner); // Allow web containers to be debugged, by end-to-end tests. - // Only allow this under CFv2, which requires explicit capability routing. - absl::optional<base::ScopedServiceBinding<fuchsia::web::Debug>> debug_binding; - if (enable_cfv2) { - debug_binding.emplace(outgoing_directory, web_instance_host.debug_api()); - } + base::ScopedServiceBinding<fuchsia::web::Debug> debug_binding( + outgoing_directory, web_instance_host.debug_api()); if (command_line->HasSwitch(kDisableVulkanForTestsSwitch)) { runner.set_disable_vulkan_for_test(); // IN-TEST @@ -162,11 +154,7 @@ outgoing_directory->ServeFromStartupInfo(); base::RunLoop run_loop; - absl::optional<base::ProcessLifecycle> process_lifecycle; - - if (enable_cfv2) { - process_lifecycle.emplace(run_loop.QuitClosure()); - } + base::ProcessLifecycle process_lifecycle(run_loop.QuitClosure()); run_loop.Run();
diff --git a/fuchsia_web/runners/cast/test/BUILD.gn b/fuchsia_web/runners/cast/test/BUILD.gn index f4b9e7a..95c3923 100644 --- a/fuchsia_web/runners/cast/test/BUILD.gn +++ b/fuchsia_web/runners/cast/test/BUILD.gn
@@ -4,19 +4,15 @@ assert(is_fuchsia) -config("cfv1_config") { - defines = [ "USE_CFV1_LAUNCHER" ] -} - source_set("integration") { testonly = true public = [ "cast_runner_features.h", - "cast_runner_launcher_v2.h", + "cast_runner_launcher.h", ] sources = [ "cast_runner_features.cc", - "cast_runner_launcher_v2.cc", + "cast_runner_launcher.cc", ] public_deps = [ "//fuchsia_web/common/test:test_support", @@ -46,28 +42,3 @@ "//third_party/fuchsia-sdk/sdk/pkg/fdio", ] } - -source_set("cfv1_integration") { - testonly = true - public = [ - "cast_runner_features.h", - "cast_runner_launcher_v1.h", - ] - sources = [ - "cast_runner_features.cc", - "cast_runner_launcher_v1.cc", - ] - public_deps = [ - "//base/test:test_support", - "//third_party/fuchsia-sdk/sdk/fidl/fuchsia.sys", - "//third_party/fuchsia-sdk/sdk/pkg/sys_cpp", - ] - public_configs = [ ":cfv1_config" ] - deps = [ - "//base", - "//fuchsia_web/runners:cast_runner_core", - "//media/fuchsia/audio:test_support", - "//third_party/fuchsia-sdk/sdk/fidl/fuchsia.io", - "//third_party/fuchsia-sdk/sdk/pkg/fdio", - ] -}
diff --git a/fuchsia_web/runners/cast/test/DEPS b/fuchsia_web/runners/cast/test/DEPS index 22190ad..11ddeb2 100644 --- a/fuchsia_web/runners/cast/test/DEPS +++ b/fuchsia_web/runners/cast/test/DEPS
@@ -1,4 +1,3 @@ include_rules = [ - "+media/fuchsia/audio/fake_audio_device_enumerator.h", "+media/fuchsia/audio/fake_audio_device_enumerator_local_component.h", ]
diff --git a/fuchsia_web/runners/cast/test/cast_runner_features.cc b/fuchsia_web/runners/cast/test/cast_runner_features.cc index 3d89d918..ddf3b6d 100644 --- a/fuchsia_web/runners/cast/test/cast_runner_features.cc +++ b/fuchsia_web/runners/cast/test/cast_runner_features.cc
@@ -18,11 +18,6 @@ command_line.AppendSwitch(kDisableVulkanForTestsSwitch); if (features & kCastRunnerFeaturesFrameHost) command_line.AppendSwitch(kEnableFrameHostComponentForTestsSwitch); -#if defined(USE_CFV1_LAUNCHER) - static constexpr char kEnableCfv1Shim[] = "enable-cfv1-shim"; - if (features & kCastRunnerFeaturesCfv1Shim) - command_line.AppendSwitch(kEnableCfv1Shim); -#endif return command_line; }
diff --git a/fuchsia_web/runners/cast/test/cast_runner_features.h b/fuchsia_web/runners/cast/test/cast_runner_features.h index 8b5fcb2..600ff33 100644 --- a/fuchsia_web/runners/cast/test/cast_runner_features.h +++ b/fuchsia_web/runners/cast/test/cast_runner_features.h
@@ -23,9 +23,6 @@ kCastRunnerFeaturesVulkan = 1U << 1, kCastRunnerFeaturesFrameHost = 1U << 2, kCastRunnerFeaturesFakeAudioDeviceEnumerator = 1U << 3, -#if defined(USE_CFV1_LAUNCHER) - kCastRunnerFeaturesCfv1Shim = 1U << 4, -#endif }; // Returns a command line for launching cast_runner with the given `features`.
diff --git a/fuchsia_web/runners/cast/test/cast_runner_launcher_v2.cc b/fuchsia_web/runners/cast/test/cast_runner_launcher.cc similarity index 93% rename from fuchsia_web/runners/cast/test/cast_runner_launcher_v2.cc rename to fuchsia_web/runners/cast/test/cast_runner_launcher.cc index 22ec5298..aff7b74 100644 --- a/fuchsia_web/runners/cast/test/cast_runner_launcher_v2.cc +++ b/fuchsia_web/runners/cast/test/cast_runner_launcher.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 "fuchsia_web/runners/cast/test/cast_runner_launcher_v2.h" +#include "fuchsia_web/runners/cast/test/cast_runner_launcher.h" #include <fuchsia/buildinfo/cpp/fidl.h> #include <fuchsia/fonts/cpp/fidl.h> @@ -34,12 +34,12 @@ namespace test { -CastRunnerLauncherV2::CastRunnerLauncherV2(CastRunnerFeatures runner_features) +CastRunnerLauncher::CastRunnerLauncher(CastRunnerFeatures runner_features) : runner_features_(runner_features) {} -CastRunnerLauncherV2::~CastRunnerLauncherV2() = default; +CastRunnerLauncher::~CastRunnerLauncher() = default; -std::unique_ptr<sys::ServiceDirectory> CastRunnerLauncherV2::StartCastRunner() { +std::unique_ptr<sys::ServiceDirectory> CastRunnerLauncher::StartCastRunner() { auto realm_builder = RealmBuilder::Create(); static constexpr char kCastRunnerService[] = "cast_runner";
diff --git a/fuchsia_web/runners/cast/test/cast_runner_launcher_v2.h b/fuchsia_web/runners/cast/test/cast_runner_launcher.h similarity index 66% rename from fuchsia_web/runners/cast/test/cast_runner_launcher_v2.h rename to fuchsia_web/runners/cast/test/cast_runner_launcher.h index bc81aec..7b405fd 100644 --- a/fuchsia_web/runners/cast/test/cast_runner_launcher_v2.h +++ b/fuchsia_web/runners/cast/test/cast_runner_launcher.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 FUCHSIA_WEB_RUNNERS_CAST_TEST_CAST_RUNNER_LAUNCHER_V2_H_ -#define FUCHSIA_WEB_RUNNERS_CAST_TEST_CAST_RUNNER_LAUNCHER_V2_H_ +#ifndef FUCHSIA_WEB_RUNNERS_CAST_TEST_CAST_RUNNER_LAUNCHER_H_ +#define FUCHSIA_WEB_RUNNERS_CAST_TEST_CAST_RUNNER_LAUNCHER_H_ #include <lib/sys/component/cpp/testing/realm_builder.h> #include <lib/sys/cpp/service_directory.h> @@ -19,14 +19,13 @@ namespace test { // A launcher for CastRunnerIntegrationTestBase that uses -// component_testing.RealmBuilder to start the cast runner component. This is -// for use with the CFv2 variant of the integration tests. -class CastRunnerLauncherV2 { +// component_testing.RealmBuilder to start the cast runner component. +class CastRunnerLauncher { public: - explicit CastRunnerLauncherV2(CastRunnerFeatures runner_features); - CastRunnerLauncherV2(const CastRunnerLauncherV2&) = delete; - CastRunnerLauncherV2& operator=(const CastRunnerLauncherV2&) = delete; - ~CastRunnerLauncherV2(); + explicit CastRunnerLauncher(CastRunnerFeatures runner_features); + CastRunnerLauncher(const CastRunnerLauncher&) = delete; + CastRunnerLauncher& operator=(const CastRunnerLauncher&) = delete; + ~CastRunnerLauncher(); std::unique_ptr<sys::ServiceDirectory> StartCastRunner(); @@ -40,4 +39,4 @@ } // namespace test -#endif // FUCHSIA_WEB_RUNNERS_CAST_TEST_CAST_RUNNER_LAUNCHER_V2_H_ +#endif // FUCHSIA_WEB_RUNNERS_CAST_TEST_CAST_RUNNER_LAUNCHER_H_
diff --git a/fuchsia_web/runners/cast/test/cast_runner_launcher_v1.cc b/fuchsia_web/runners/cast/test/cast_runner_launcher_v1.cc deleted file mode 100644 index 10021ec..0000000 --- a/fuchsia_web/runners/cast/test/cast_runner_launcher_v1.cc +++ /dev/null
@@ -1,83 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "fuchsia_web/runners/cast/test/cast_runner_launcher_v1.h" - -#include <fuchsia/io/cpp/fidl.h> -#include <fuchsia/sys/cpp/fidl.h> -#include <lib/fdio/fd.h> -#include <lib/sys/cpp/component_context.h> -#include <unistd.h> -#include <zircon/processargs.h> - -#include <memory> -#include <string> -#include <utility> -#include <vector> - -#include "base/command_line.h" -#include "base/fuchsia/fuchsia_logging.h" -#include "base/fuchsia/process_context.h" -#include "media/fuchsia/audio/fake_audio_device_enumerator.h" - -namespace test { - -CastRunnerLauncherV1::CastRunnerLauncherV1(CastRunnerFeatures runner_features) - : runner_features_(runner_features) {} - -CastRunnerLauncherV1::~CastRunnerLauncherV1() = default; - -std::unique_ptr<sys::ServiceDirectory> CastRunnerLauncherV1::StartCastRunner() { - fuchsia::sys::LaunchInfo launch_info; - launch_info.url = - "fuchsia-pkg://fuchsia.com/cast_runner#meta/cast_runner.cmx"; - - // Clone stderr from the current process to CastRunner and ask it to - // redirect all logs to stderr. - launch_info.err = fuchsia::sys::FileDescriptor::New(); - launch_info.err->type0 = PA_FD; - zx_status_t status = fdio_fd_clone( - STDERR_FILENO, launch_info.err->handle0.reset_and_get_address()); - ZX_CHECK(status == ZX_OK, status); - - base::CommandLine command_line(CommandLineFromFeatures(runner_features_)); - command_line.AppendSwitchASCII("enable-logging", "stderr"); - - // Add all switches and arguments, skipping the program. - launch_info.arguments.emplace(std::vector<std::string>( - command_line.argv().begin() + 1, command_line.argv().end())); - - auto additional_services = std::make_unique<fuchsia::sys::ServiceList>(); - auto* svc_dir = services_for_runner().GetOrCreateDirectory("svc"); - if (runner_features_ & kCastRunnerFeaturesFakeAudioDeviceEnumerator) { - fake_audio_device_enumerator_ = - std::make_unique<media::FakeAudioDeviceEnumerator>(svc_dir); - additional_services->names.push_back( - fuchsia::media::AudioDeviceEnumerator::Name_); - } - if (runner_features_ & kCastRunnerFeaturesCfv1Shim) { - additional_services->names.push_back("fuchsia.sys.Runner-cast"); - } - - fuchsia::io::DirectoryHandle svc_dir_handle; - svc_dir->Serve(fuchsia::io::OpenFlags::RIGHT_READABLE | - fuchsia::io::OpenFlags::RIGHT_WRITABLE, - svc_dir_handle.NewRequest().TakeChannel()); - additional_services->host_directory = svc_dir_handle.TakeChannel(); - - launch_info.additional_services = std::move(additional_services); - - fuchsia::io::DirectoryHandle cast_runner_services_dir; - launch_info.directory_request = - cast_runner_services_dir.NewRequest().TakeChannel(); - - fuchsia::sys::LauncherPtr launcher; - base::ComponentContextForProcess()->svc()->Connect(launcher.NewRequest()); - launcher->CreateComponent(std::move(launch_info), - controller_.ptr().NewRequest()); - return std::make_unique<sys::ServiceDirectory>( - std::move(cast_runner_services_dir)); -} - -} // namespace test
diff --git a/fuchsia_web/runners/cast/test/cast_runner_launcher_v1.h b/fuchsia_web/runners/cast/test/cast_runner_launcher_v1.h deleted file mode 100644 index 5ae56fe..0000000 --- a/fuchsia_web/runners/cast/test/cast_runner_launcher_v1.h +++ /dev/null
@@ -1,64 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef FUCHSIA_WEB_RUNNERS_CAST_TEST_CAST_RUNNER_LAUNCHER_V1_H_ -#define FUCHSIA_WEB_RUNNERS_CAST_TEST_CAST_RUNNER_LAUNCHER_V1_H_ - -#include <fuchsia/sys/cpp/fidl.h> -#include <lib/sys/cpp/outgoing_directory.h> -#include <lib/sys/cpp/service_directory.h> - -#include <memory> - -#include "base/fuchsia/test_component_controller.h" -#include "fuchsia_web/runners/cast/test/cast_runner_features.h" - -namespace media { -class FakeAudioDeviceEnumerator; -} - -namespace test { - -// A launcher for CastRunnerIntegrationTestBase that uses fuchsia.sys.Launcher -// to start the cast runner component. This is for use with the CFv1 variant of -// the integration tests. -class CastRunnerLauncherV1 { - public: - // Creates an instance that will launch cast_runner.cmx with the features - // indicated in the `runner_features` bitmask. This can be used, for example, - // to provide a fake AudioDeviceEnumerator to the runner. - explicit CastRunnerLauncherV1(CastRunnerFeatures runner_features); - CastRunnerLauncherV1(const CastRunnerLauncherV1&) = delete; - CastRunnerLauncherV1& operator=(const CastRunnerLauncherV1&) = delete; - ~CastRunnerLauncherV1(); - - std::unique_ptr<sys::ServiceDirectory> StartCastRunner(); - - ::fuchsia::sys::ComponentControllerPtr& controller_ptr() { - return controller_.ptr(); - } - - // Returns the outgoing directory for services given to the runner. Services - // must be added before calling StartCastRunner(). - sys::OutgoingDirectory& services_for_runner() { return services_for_runner_; } - - private: - const CastRunnerFeatures runner_features_; - - base::TestComponentController controller_; - - // Directory used to publish test ContextProvider to CastRunner. Some tests - // restart ContextProvider, so we can't pass the services directory from - // ContextProvider to CastRunner directly. - sys::OutgoingDirectory services_for_runner_; - - // A fake for fuchsia.media.AudioDeviceEnumerator that is provided to the - // runner upon request via `runner_features`. - std::unique_ptr<media::FakeAudioDeviceEnumerator> - fake_audio_device_enumerator_; -}; - -} // namespace test - -#endif // FUCHSIA_WEB_RUNNERS_CAST_TEST_CAST_RUNNER_LAUNCHER_V1_H_
diff --git a/infra/config/generated/luci/cr-buildbucket.cfg b/infra/config/generated/luci/cr-buildbucket.cfg index a97ed44e..f0cd9f1 100644 --- a/infra/config/generated/luci/cr-buildbucket.cfg +++ b/infra/config/generated/luci/cr-buildbucket.cfg
@@ -2835,6 +2835,10 @@ build_numbers: YES service_account: "chromium-ci-builder@chops-service-accounts.iam.gserviceaccount.com" experiments { + key: "luci.buildbucket.omit_python2" + value: 100 + } + experiments { key: "luci.recipes.use_python3" value: 100 } @@ -2918,6 +2922,10 @@ build_numbers: YES service_account: "chromium-ci-builder@chops-service-accounts.iam.gserviceaccount.com" experiments { + key: "luci.buildbucket.omit_python2" + value: 100 + } + experiments { key: "luci.recipes.use_python3" value: 100 } @@ -3001,6 +3009,10 @@ build_numbers: YES service_account: "chromium-ci-builder@chops-service-accounts.iam.gserviceaccount.com" experiments { + key: "luci.buildbucket.omit_python2" + value: 100 + } + experiments { key: "luci.recipes.use_python3" value: 100 } @@ -3084,6 +3096,10 @@ build_numbers: YES service_account: "chromium-ci-builder@chops-service-accounts.iam.gserviceaccount.com" experiments { + key: "luci.buildbucket.omit_python2" + value: 100 + } + experiments { key: "luci.recipes.use_python3" value: 100 } @@ -7253,6 +7269,10 @@ build_numbers: YES service_account: "chromium-ci-builder@chops-service-accounts.iam.gserviceaccount.com" experiments { + key: "luci.buildbucket.omit_python2" + value: 100 + } + experiments { key: "luci.recipes.use_python3" value: 100 } @@ -7328,6 +7348,10 @@ build_numbers: YES service_account: "chromium-ci-builder@chops-service-accounts.iam.gserviceaccount.com" experiments { + key: "luci.buildbucket.omit_python2" + value: 100 + } + experiments { key: "luci.recipes.use_python3" value: 100 } @@ -9623,6 +9647,10 @@ build_numbers: YES service_account: "chromium-ci-builder@chops-service-accounts.iam.gserviceaccount.com" experiments { + key: "luci.buildbucket.omit_python2" + value: 100 + } + experiments { key: "luci.recipes.use_python3" value: 100 } @@ -11120,6 +11148,10 @@ build_numbers: YES service_account: "chromium-ci-builder@chops-service-accounts.iam.gserviceaccount.com" experiments { + key: "luci.buildbucket.omit_python2" + value: 100 + } + experiments { key: "luci.recipes.use_python3" value: 100 } @@ -11203,6 +11235,10 @@ build_numbers: YES service_account: "chromium-ci-builder@chops-service-accounts.iam.gserviceaccount.com" experiments { + key: "luci.buildbucket.omit_python2" + value: 100 + } + experiments { key: "luci.recipes.use_python3" value: 100 } @@ -11286,6 +11322,10 @@ build_numbers: YES service_account: "chromium-ci-builder@chops-service-accounts.iam.gserviceaccount.com" experiments { + key: "luci.buildbucket.omit_python2" + value: 100 + } + experiments { key: "luci.recipes.use_python3" value: 100 } @@ -13434,6 +13474,10 @@ build_numbers: YES service_account: "chromium-ci-builder@chops-service-accounts.iam.gserviceaccount.com" experiments { + key: "luci.buildbucket.omit_python2" + value: 100 + } + experiments { key: "luci.recipes.use_python3" value: 100 } @@ -13527,6 +13571,10 @@ build_numbers: YES service_account: "chromium-ci-builder@chops-service-accounts.iam.gserviceaccount.com" experiments { + key: "luci.buildbucket.omit_python2" + value: 100 + } + experiments { key: "luci.recipes.use_python3" value: 100 } @@ -13610,6 +13658,10 @@ build_numbers: YES service_account: "chromium-ci-builder@chops-service-accounts.iam.gserviceaccount.com" experiments { + key: "luci.buildbucket.omit_python2" + value: 100 + } + experiments { key: "luci.recipes.use_python3" value: 100 } @@ -17213,6 +17265,10 @@ build_numbers: YES service_account: "chromium-ci-builder@chops-service-accounts.iam.gserviceaccount.com" experiments { + key: "luci.buildbucket.omit_python2" + value: 100 + } + experiments { key: "luci.recipes.use_python3" value: 100 } @@ -36652,6 +36708,10 @@ build_numbers: YES service_account: "chromium-ci-builder@chops-service-accounts.iam.gserviceaccount.com" experiments { + key: "luci.buildbucket.omit_python2" + value: 100 + } + experiments { key: "luci.recipes.use_python3" value: 100 } @@ -37710,6 +37770,10 @@ build_numbers: YES service_account: "chromium-ci-builder@chops-service-accounts.iam.gserviceaccount.com" experiments { + key: "luci.buildbucket.omit_python2" + value: 100 + } + experiments { key: "luci.recipes.use_python3" value: 100 } @@ -37874,6 +37938,10 @@ build_numbers: YES service_account: "chromium-ci-builder@chops-service-accounts.iam.gserviceaccount.com" experiments { + key: "luci.buildbucket.omit_python2" + value: 100 + } + experiments { key: "luci.recipes.use_python3" value: 100 }
diff --git a/infra/config/subprojects/chromium/ci/chromium.linux.star b/infra/config/subprojects/chromium/ci/chromium.linux.star index 10e60b1..9ecc450 100644 --- a/infra/config/subprojects/chromium/ci/chromium.linux.star +++ b/infra/config/subprojects/chromium/ci/chromium.linux.star
@@ -24,9 +24,6 @@ service_account = ci.DEFAULT_SERVICE_ACCOUNT, sheriff_rotations = sheriff_rotations.CHROMIUM, tree_closing = True, - - # TODO(crbug.com/1362440): remove this. - omit_python2 = False, ) consoles.console_view(
diff --git a/ios/chrome/browser/link_to_text/link_to_text_java_script_feature.mm b/ios/chrome/browser/link_to_text/link_to_text_java_script_feature.mm index 1f35ef15..daf0914 100644 --- a/ios/chrome/browser/link_to_text/link_to_text_java_script_feature.mm +++ b/ios/chrome/browser/link_to_text/link_to_text_java_script_feature.mm
@@ -6,6 +6,7 @@ #import "base/barrier_callback.h" #import "base/no_destructor.h" +#import "base/ranges/algorithm.h" #import "base/timer/elapsed_timer.h" #import "components/shared_highlighting/core/common/disabled_sites.h" #import "components/shared_highlighting/core/common/shared_highlighting_features.h" @@ -146,9 +147,9 @@ DCHECK(!parsed_responses.empty()); // First, see if we succeeded in any frame. - auto success_response = std::find_if( - parsed_responses.begin(), parsed_responses.end(), - [](LinkToTextResponse* response) { return response.payload != nil; }); + auto success_response = base::ranges::find_if_not( + parsed_responses, + [](LinkToTextResponse* response) { return response.payload == nil; }); if (success_response != parsed_responses.end()) { std::move(final_callback).Run(*success_response); return; @@ -157,10 +158,9 @@ // If not, look for a frame where we failed with an error other than Incorrect // Selector. There should be at most one of these (since every frame with no // user selection should return Incorrect Selector). - auto error_response = std::find_if( - parsed_responses.begin(), parsed_responses.end(), - [](LinkToTextResponse* response) { - return [response error].value() != + auto error_response = base::ranges::find_if_not( + parsed_responses, [](LinkToTextResponse* response) { + return [response error].value() == shared_highlighting::LinkGenerationError::kIncorrectSelector; }); if (error_response != parsed_responses.end()) {
diff --git a/ios/chrome/browser/providers/context_menu/chromium_context_menu.mm b/ios/chrome/browser/providers/context_menu/chromium_context_menu.mm index bac2934..9de96aec8 100644 --- a/ios/chrome/browser/providers/context_menu/chromium_context_menu.mm +++ b/ios/chrome/browser/providers/context_menu/chromium_context_menu.mm
@@ -19,5 +19,17 @@ return nil; } +NSTextCheckingType GetHandledIntentTypes(web::WebState* web_state) { + return 0; +} + +NSArray<CRWContextMenuItem*>* GetContextMenuElementsToAdd( + web::WebState* web_state, + NSTextCheckingResult* match, + NSString* text, + UIViewController* presenting_view_controller) { + return @[]; +} + } // namespace provider } // namespace ios
diff --git a/ios/chrome/browser/providers/signin/chromium_trusted_vault.mm b/ios/chrome/browser/providers/signin/chromium_trusted_vault.mm index 9f1db360..643d0ba 100644 --- a/ios/chrome/browser/providers/signin/chromium_trusted_vault.mm +++ b/ios/chrome/browser/providers/signin/chromium_trusted_vault.mm
@@ -24,17 +24,17 @@ // TrustedVaultClientBackend implementation. void AddObserver(Observer* observer) final; void RemoveObserver(Observer* observer) final; - void FetchKeys(ChromeIdentity* chrome_identity, + void FetchKeys(id<SystemIdentity> identity, KeyFetchedCallback callback) final; - void MarkLocalKeysAsStale(ChromeIdentity* chrome_identity, + void MarkLocalKeysAsStale(id<SystemIdentity> identity, base::OnceClosure callback) final; void GetDegradedRecoverabilityStatus( - ChromeIdentity* chrome_identity, + id<SystemIdentity> identity, base::OnceCallback<void(bool)> callback) final; - void Reauthentication(ChromeIdentity* chrome_identity, + void Reauthentication(id<SystemIdentity> identity, UIViewController* presenting_view_controller, CompletionBlock callback) final; - void FixDegradedRecoverability(ChromeIdentity* chrome_identity, + void FixDegradedRecoverability(id<SystemIdentity> identity, UIViewController* presenting_view_controller, CompletionBlock callback) final; void CancelDialog(BOOL animated, ProceduralBlock callback) final; @@ -48,33 +48,32 @@ // Do nothing. } -void ChromiumTrustedVaultClientBackend::FetchKeys( - ChromeIdentity* chrome_identity, - KeyFetchedCallback callback) { +void ChromiumTrustedVaultClientBackend::FetchKeys(id<SystemIdentity> identity, + KeyFetchedCallback callback) { NOTREACHED(); } void ChromiumTrustedVaultClientBackend::MarkLocalKeysAsStale( - ChromeIdentity* chrome_identity, + id<SystemIdentity> identity, base::OnceClosure callback) { NOTREACHED(); } void ChromiumTrustedVaultClientBackend::GetDegradedRecoverabilityStatus( - ChromeIdentity* chrome_identity, + id<SystemIdentity> identity, base::OnceCallback<void(bool)> callback) { NOTREACHED(); } void ChromiumTrustedVaultClientBackend::Reauthentication( - ChromeIdentity* chrome_identity, + id<SystemIdentity> identity, UIViewController* presenting_view_controller, CompletionBlock callback) { NOTREACHED(); } void ChromiumTrustedVaultClientBackend::FixDegradedRecoverability( - ChromeIdentity* chrome_identity, + id<SystemIdentity> identity, UIViewController* presenting_view_controller, CompletionBlock callback) { NOTREACHED();
diff --git a/ios/chrome/browser/safe_browsing/chrome_password_protection_service.mm b/ios/chrome/browser/safe_browsing/chrome_password_protection_service.mm index 99dc0f2..cb1a4a7 100644 --- a/ios/chrome/browser/safe_browsing/chrome_password_protection_service.mm +++ b/ios/chrome/browser/safe_browsing/chrome_password_protection_service.mm
@@ -12,6 +12,7 @@ #import "base/metrics/user_metrics.h" #import "base/metrics/user_metrics_action.h" #import "base/notreached.h" +#import "base/ranges/algorithm.h" #import "base/strings/utf_string_conversions.h" #import "base/time/time.h" #import "components/keyed_service/core/service_access_type.h" @@ -396,14 +397,13 @@ return AccountInfo(); std::vector<CoreAccountInfo> signed_in_accounts = identity_manager->GetAccountsWithRefreshTokens(); - auto account_iterator = - std::find_if(signed_in_accounts.begin(), signed_in_accounts.end(), - [username](const auto& account) { - return password_manager::AreUsernamesSame( - account.email, - /*is_username1_gaia_account=*/true, username, - /*is_username2_gaia_account=*/true); - }); + auto account_iterator = base::ranges::find_if( + signed_in_accounts, [username](const auto& account) { + return password_manager::AreUsernamesSame( + account.email, + /*is_username1_gaia_account=*/true, username, + /*is_username2_gaia_account=*/true); + }); if (account_iterator == signed_in_accounts.end()) return AccountInfo();
diff --git a/ios/chrome/browser/signin/BUILD.gn b/ios/chrome/browser/signin/BUILD.gn index 134be8b37..55cb39e 100644 --- a/ios/chrome/browser/signin/BUILD.gn +++ b/ios/chrome/browser/signin/BUILD.gn
@@ -166,7 +166,6 @@ "//base", "//components/keyed_service/core", "//components/sync/driver", - "//ios/public/provider/chrome/browser/signin", "//ios/public/provider/chrome/browser/signin:signin_sso_api", ] frameworks = [
diff --git a/ios/chrome/browser/signin/trusted_vault_client_backend.h b/ios/chrome/browser/signin/trusted_vault_client_backend.h index bbe702e0..dc1e40e3 100644 --- a/ios/chrome/browser/signin/trusted_vault_client_backend.h +++ b/ios/chrome/browser/signin/trusted_vault_client_backend.h
@@ -14,7 +14,6 @@ #include "components/keyed_service/core/keyed_service.h" #include "components/sync/driver/trusted_vault_client.h" -@class ChromeIdentity; @protocol SystemIdentity; // Abstract class to manage shared keys. @@ -45,40 +44,30 @@ // Asynchronously fetches the shared keys for `identity` and invokes // `callback` with the fetched keys. - virtual void FetchKeys(ChromeIdentity* chrome_identity, - KeyFetchedCallback callback); virtual void FetchKeys(id<SystemIdentity> identity, - KeyFetchedCallback callback); + KeyFetchedCallback callback) = 0; // Invoked when the result of FetchKeys() contains keys that are not // up-to-date. During the execution, before `callback` is invoked, the // behavior is unspecified if FetchKeys() is invoked, that is, FetchKeys() // may or may not treat existing keys as stale (only guaranteed upon // completion of MarkLocalKeysAsStale()). - virtual void MarkLocalKeysAsStale(ChromeIdentity* chrome_identity, - base::OnceClosure callback); virtual void MarkLocalKeysAsStale(id<SystemIdentity> identity, - base::OnceClosure callback); + base::OnceClosure callback) = 0; // Returns whether recoverability of the keys is degraded and user action is // required to add a new method. virtual void GetDegradedRecoverabilityStatus( - ChromeIdentity* chrome_identity, - base::OnceCallback<void(bool)> callback); - virtual void GetDegradedRecoverabilityStatus( id<SystemIdentity> identity, - base::OnceCallback<void(bool)> callback); + base::OnceCallback<void(bool)> callback) = 0; // Presents the trusted vault key reauthentication UI for `identity` for the // purpose of extending the set of keys returned via FetchKeys(). Once the // reauth is done and the UI is dismissed, `callback` is called. `callback` is // not called if the reauthentication is canceled. - virtual void Reauthentication(ChromeIdentity* chrome_identity, - UIViewController* presenting_view_controller, - CompletionBlock callback); virtual void Reauthentication(id<SystemIdentity> identity, UIViewController* presenting_view_controller, - CompletionBlock callback); + CompletionBlock callback) = 0; // Presents the trusted vault key reauthentication UI for `identity` for the // purpose of improving recoverability as returned via @@ -86,13 +75,9 @@ // dismissed, `callback` is called. `callback` is not called if the // reauthentication is canceled. virtual void FixDegradedRecoverability( - ChromeIdentity* chrome_identity, - UIViewController* presenting_view_controller, - CompletionBlock callback); - virtual void FixDegradedRecoverability( id<SystemIdentity> identity, UIViewController* presenting_view_controller, - CompletionBlock callback); + CompletionBlock callback) = 0; // Cancels the presented trusted vault reauthentication UI, triggered via // either Reauthentication() or via
diff --git a/ios/chrome/browser/signin/trusted_vault_client_backend.mm b/ios/chrome/browser/signin/trusted_vault_client_backend.mm index d1a1f56a..9964c875 100644 --- a/ios/chrome/browser/signin/trusted_vault_client_backend.mm +++ b/ios/chrome/browser/signin/trusted_vault_client_backend.mm
@@ -4,10 +4,6 @@ #import "ios/chrome/browser/signin/trusted_vault_client_backend.h" -#import "base/callback.h" -#import "base/notreached.h" -#import "ios/public/provider/chrome/browser/signin/chrome_identity.h" - #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support." #endif @@ -15,70 +11,3 @@ TrustedVaultClientBackend::TrustedVaultClientBackend() = default; TrustedVaultClientBackend::~TrustedVaultClientBackend() = default; - -void TrustedVaultClientBackend::FetchKeys(ChromeIdentity* chrome_identity, - KeyFetchedCallback callback) { - FetchKeys(static_cast<id<SystemIdentity>>(chrome_identity), - std::move(callback)); -} - -void TrustedVaultClientBackend::FetchKeys(id<SystemIdentity> identity, - KeyFetchedCallback callback) { - NOTREACHED(); -} - -void TrustedVaultClientBackend::MarkLocalKeysAsStale( - ChromeIdentity* chrome_identity, - base::OnceClosure callback) { - MarkLocalKeysAsStale(static_cast<id<SystemIdentity>>(chrome_identity), - std::move(callback)); -} - -void TrustedVaultClientBackend::MarkLocalKeysAsStale( - id<SystemIdentity> identity, - base::OnceClosure callback) { - NOTREACHED(); -} - -void TrustedVaultClientBackend::GetDegradedRecoverabilityStatus( - ChromeIdentity* chrome_identity, - base::OnceCallback<void(bool)> callback) { - GetDegradedRecoverabilityStatus( - static_cast<id<SystemIdentity>>(chrome_identity), std::move(callback)); -} - -void TrustedVaultClientBackend::GetDegradedRecoverabilityStatus( - id<SystemIdentity> identity, - base::OnceCallback<void(bool)> callback) { - NOTREACHED(); -} - -void TrustedVaultClientBackend::Reauthentication( - ChromeIdentity* chrome_identity, - UIViewController* presenting_view_controller, - CompletionBlock callback) { - Reauthentication(static_cast<id<SystemIdentity>>(chrome_identity), - presenting_view_controller, std::move(callback)); -} - -void TrustedVaultClientBackend::Reauthentication( - id<SystemIdentity> identity, - UIViewController* presenting_view_controller, - CompletionBlock callback) { - NOTREACHED(); -} - -void TrustedVaultClientBackend::FixDegradedRecoverability( - ChromeIdentity* chrome_identity, - UIViewController* presenting_view_controller, - CompletionBlock callback) { - FixDegradedRecoverability(static_cast<id<SystemIdentity>>(chrome_identity), - presenting_view_controller, std::move(callback)); -} - -void TrustedVaultClientBackend::FixDegradedRecoverability( - id<SystemIdentity> identity, - UIViewController* presenting_view_controller, - CompletionBlock callback) { - NOTREACHED(); -}
diff --git a/ios/chrome/browser/tabs/tab_helper_util.mm b/ios/chrome/browser/tabs/tab_helper_util.mm index 0da7492d..cb0cfae 100644 --- a/ios/chrome/browser/tabs/tab_helper_util.mm +++ b/ios/chrome/browser/tabs/tab_helper_util.mm
@@ -156,7 +156,8 @@ BreadcrumbManagerTabHelper::CreateForWebState(web_state); } - if (base::FeatureList::IsEnabled(web::features::kEnableWebPageAnnotations)) { + if (base::FeatureList::IsEnabled(web::features::kEnableWebPageAnnotations) && + !is_off_the_record) { AnnotationsTabHelper::CreateForWebState(web_state); }
diff --git a/ios/chrome/browser/ui/commands/browser_coordinator_commands.h b/ios/chrome/browser/ui/commands/browser_coordinator_commands.h index 51a462f..5099d5e 100644 --- a/ios/chrome/browser/ui/commands/browser_coordinator_commands.h +++ b/ios/chrome/browser/ui/commands/browser_coordinator_commands.h
@@ -59,7 +59,7 @@ // devices. - (void)showSendTabToSelfUI:(const GURL&)url title:(NSString*)title; -// Hides the dialog shown by showSendTabToSelfUI(). +// Hides the dialog shown by -showSendTabToSelfUI:. - (void)hideSendTabToSelfUI; // Shows the online help page in a tab.
diff --git a/ios/chrome/browser/ui/reading_list/reading_list_egtest.mm b/ios/chrome/browser/ui/reading_list/reading_list_egtest.mm index 6c697075..c23126c 100644 --- a/ios/chrome/browser/ui/reading_list/reading_list_egtest.mm +++ b/ios/chrome/browser/ui/reading_list/reading_list_egtest.mm
@@ -1019,7 +1019,13 @@ // Marks all read entries as unread, when there is a lot of entries. This is to // prevent crbug.com/1013708 from regressing. -- (void)testMarkAllUnreadLotOfEntry { +// TODO(crbug.com/1366621): Flaky on iOS Simulator +#if TARGET_IPHONE_SIMULATOR +#define MAYBE_testMarkAllUnreadLotOfEntry DISABLED_testMarkAllUnreadLotOfEntry +#else +#define MAYBE_testMarkAllUnreadLotOfEntry testMarkAllUnreadLotOfEntry +#endif +- (void)MAYBE_testMarkAllUnreadLotOfEntry { AddLotOfEntriesAndEnterEdit(); AssertToolbarMarkButtonText(IDS_IOS_READING_LIST_MARK_ALL_BUTTON);
diff --git a/ios/chrome/browser/ui/recent_tabs/recent_tabs_table_view_controller.mm b/ios/chrome/browser/ui/recent_tabs/recent_tabs_table_view_controller.mm index 15313a43..5893f4c 100644 --- a/ios/chrome/browser/ui/recent_tabs/recent_tabs_table_view_controller.mm +++ b/ios/chrome/browser/ui/recent_tabs/recent_tabs_table_view_controller.mm
@@ -1157,7 +1157,11 @@ base::mac::ObjCCastStrict<TableViewSigninPromoCell>(cell); signinPromoCell.signinPromoView.imageView.hidden = YES; signinPromoCell.signinPromoView.textLabel.hidden = YES; + // Disable animations when setting the background color to prevent flash on + // rotation. + [UIView setAnimationsEnabled:NO]; signinPromoCell.backgroundColor = nil; + [UIView setAnimationsEnabled:YES]; } // Retrieve favicons for closed tabs and remote sessions. if (itemTypeSelected == ItemTypeRecentlyClosed ||
diff --git a/ios/chrome/browser/ui/settings/search_engine_table_view_controller.mm b/ios/chrome/browser/ui/settings/search_engine_table_view_controller.mm index b5cb28e5..578f8c5 100644 --- a/ios/chrome/browser/ui/settings/search_engine_table_view_controller.mm +++ b/ios/chrome/browser/ui/settings/search_engine_table_view_controller.mm
@@ -10,6 +10,7 @@ #import "base/metrics/histogram_macros.h" #import "base/metrics/user_metrics.h" #import "base/metrics/user_metrics_action.h" +#import "base/ranges/algorithm.h" #import "base/strings/sys_string_conversions.h" #import "components/password_manager/core/common/password_manager_features.h" #import "components/search_engines/template_url_service.h" @@ -456,10 +457,9 @@ }); // Keep the search engines visited within `kMaxVisitAge` and erase others. - const base::Time cutoff = base::Time::Now() - kMaxVisitAge; - auto cutBegin = std::find_if(begin, pivot, [cutoff](const TemplateURL* url) { - return url->last_visited() < cutoff; - }); + auto cutBegin = base::ranges::lower_bound( + begin, pivot, base::Time::Now() - kMaxVisitAge, + base::ranges::greater_equal(), &TemplateURL::last_visited); _secondList.erase(cutBegin, end); }
diff --git a/ios/chrome/browser/ui/table_view/cells/table_view_illustrated_item.mm b/ios/chrome/browser/ui/table_view/cells/table_view_illustrated_item.mm index a42e12e..4b972d4 100644 --- a/ios/chrome/browser/ui/table_view/cells/table_view_illustrated_item.mm +++ b/ios/chrome/browser/ui/table_view/cells/table_view_illustrated_item.mm
@@ -69,7 +69,11 @@ } else { cell.button.hidden = YES; } + // Disable animations when setting the background color to prevent flash on + // rotation. + [UIView setAnimationsEnabled:NO]; cell.backgroundColor = nil; + [UIView setAnimationsEnabled:YES]; if (styler.cellTitleColor) { cell.titleLabel.textColor = styler.cellTitleColor;
diff --git a/ios/chrome/browser/ui/webui/policy/policy_ui_handler.h b/ios/chrome/browser/ui/webui/policy/policy_ui_handler.h index 6517d5e6..7065e251f 100644 --- a/ios/chrome/browser/ui/webui/policy/policy_ui_handler.h +++ b/ios/chrome/browser/ui/webui/policy/policy_ui_handler.h
@@ -8,6 +8,7 @@ #include <memory> #include "base/memory/weak_ptr.h" +#include "base/scoped_observation.h" #include "base/values.h" #include "components/policy/core/browser/webui/policy_status_provider.h" #include "components/policy/core/common/policy_service.h" @@ -24,6 +25,7 @@ // The JavaScript message handler for the chrome://policy page. class PolicyUIHandler : public web::WebUIIOSMessageHandler, public policy::PolicyService::Observer, + public policy::PolicyStatusProvider::Observer, public policy::SchemaRegistry::Observer { public: PolicyUIHandler(); @@ -42,6 +44,9 @@ const policy::PolicyMap& previous, const policy::PolicyMap& current) override; + // policy::PolicyValueProvider::Observer implementation. + void OnPolicyStatusChanged() override; + // policy::SchemaRegistry::Observer. void OnSchemaRegistryUpdated(bool has_new_schemas) override; @@ -85,6 +90,10 @@ // Provider that supply status dictionary for machine policy, std::unique_ptr<policy::PolicyStatusProvider> machine_status_provider_; + base::ScopedObservation<policy::PolicyStatusProvider, + policy::PolicyStatusProvider::Observer> + machine_status_provider_observation_{this}; + // Vends WeakPtrs for this object. base::WeakPtrFactory<PolicyUIHandler> weak_factory_{this}; };
diff --git a/ios/chrome/browser/ui/webui/policy/policy_ui_handler.mm b/ios/chrome/browser/ui/webui/policy/policy_ui_handler.mm index f5243ee..dc170cc4 100644 --- a/ios/chrome/browser/ui/webui/policy/policy_ui_handler.mm +++ b/ios/chrome/browser/ui/webui/policy/policy_ui_handler.mm
@@ -119,14 +119,13 @@ new policy::MachineLevelUserCloudPolicyContext( {dmTokenStorage->RetrieveEnrollmentToken(), dmTokenStorage->RetrieveClientId(), lastCloudReportSent})); + machine_status_provider_observation_.Observe( + machine_status_provider_.get()); } if (!machine_status_provider_) machine_status_provider_ = std::make_unique<policy::PolicyStatusProvider>(); - machine_status_provider_->SetStatusChangeCallback(base::BindRepeating( - &PolicyUIHandler::SendStatus, base::Unretained(this))); - GetPolicyService()->AddObserver(policy::POLICY_DOMAIN_CHROME, this); ChromeBrowserState* browser_state = @@ -180,6 +179,10 @@ SendPolicies(); } +void PolicyUIHandler::OnPolicyStatusChanged() { + SendStatus(); +} + base::Value::Dict PolicyUIHandler::GetPolicyNames() const { ChromeBrowserState* browser_state = ChromeBrowserState::FromWebUIIOS(web_ui());
diff --git a/ios/chrome/browser/web/annotations/BUILD.gn b/ios/chrome/browser/web/annotations/BUILD.gn index 5bd4fed..868a396 100644 --- a/ios/chrome/browser/web/annotations/BUILD.gn +++ b/ios/chrome/browser/web/annotations/BUILD.gn
@@ -10,6 +10,7 @@ deps = [ "//base", "//components/shared_highlighting/ios", + "//ios/public/provider/chrome/browser/context_menu:context_menu_api", "//ios/web/annotations", "//ios/web/common", "//ios/web/public",
diff --git a/ios/chrome/browser/web/annotations/annotations_tab_helper.h b/ios/chrome/browser/web/annotations/annotations_tab_helper.h index d68018d2..53a8a18 100644 --- a/ios/chrome/browser/web/annotations/annotations_tab_helper.h +++ b/ios/chrome/browser/web/annotations/annotations_tab_helper.h
@@ -57,8 +57,7 @@ explicit AnnotationsTabHelper(web::WebState* web_state); // Receiver for text classifier extracted intents. Must run on main thread. - void ApplyDeferredProcessing(web::WebState* web_state, - absl::optional<base::Value> deferred); + void ApplyDeferredProcessing(absl::optional<base::Value> deferred); UIViewController* base_view_controller_ = nil;
diff --git a/ios/chrome/browser/web/annotations/annotations_tab_helper.mm b/ios/chrome/browser/web/annotations/annotations_tab_helper.mm index 29f36b6d..b8a55f1 100644 --- a/ios/chrome/browser/web/annotations/annotations_tab_helper.mm +++ b/ios/chrome/browser/web/annotations/annotations_tab_helper.mm
@@ -9,9 +9,11 @@ #import "base/strings/utf_string_conversions.h" #import "base/task/thread_pool.h" #import "base/threading/scoped_blocking_call.h" +#import "ios/public/provider/chrome/browser/context_menu/context_menu_api.h" #import "ios/web/annotations/annotations_text_manager.h" #import "ios/web/annotations/annotations_utils.h" #import "ios/web/common/url_scheme_util.h" +#import "ios/web/public/browser_state.h" #import "ios/web/public/js_messaging/web_frame.h" #import "ios/web/public/js_messaging/web_frame_util.h" #import "ios/web/public/navigation/navigation_context.h" @@ -43,25 +45,28 @@ // Applies text classifier to extract intents in the given text. Returns // a `base::Value::List` of annotations (see i/w/a/annotations_utils.h). // This runs in the thread pool. -absl::optional<base::Value> ApplyDataExtractor(const std::string& text) { +absl::optional<base::Value> ApplyDataExtractor( + const std::string& text, + NSTextCheckingType handled_types) { base::ScopedBlockingCall scoped_blocking_call(FROM_HERE, base::BlockingType::WILL_BLOCK); - // TODO(crbug.com/1350974): move to provider if (text.empty()) { return absl::nullopt; } + // TODO(crbug.com/1350974): phone doesn't have a ui to set the flag for now. + handled_types |= NSTextCheckingTypePhoneNumber; + NSString* source = base::SysUTF8ToNSString(text); NSError* error = nil; - NSDataDetector* detector = [NSDataDetector - dataDetectorWithTypes:NSTextCheckingTypeDate | NSTextCheckingTypeAddress | - NSTextCheckingTypePhoneNumber - error:&error]; + NSDataDetector* detector = [NSDataDetector dataDetectorWithTypes:handled_types + error:&error]; if (error) { return absl::nullopt; } + // TODO(crbug.com/1350974): move extracting to provider __block base::Value::List parsed; auto match_handler = ^(NSTextCheckingResult* match, NSMatchingFlags flags, BOOL* stop) { @@ -122,13 +127,16 @@ void AnnotationsTabHelper::OnTextExtracted(web::WebState* web_state, const std::string& text) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + DCHECK_EQ(web_state_, web_state); + base::ThreadPool::PostTaskAndReplyWithResult( FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, - base::BindOnce(&ApplyDataExtractor, text), + base::BindOnce(&ApplyDataExtractor, text, + ios::provider::GetHandledIntentTypes(web_state)), base::BindOnce(&AnnotationsTabHelper::ApplyDeferredProcessing, - weak_factory_.GetWeakPtr(), web_state_)); + weak_factory_.GetWeakPtr())); } void AnnotationsTabHelper::OnDecorated(web::WebState* web_state, @@ -150,47 +158,21 @@ return; } - NSMutableArray* items = [[NSMutableArray alloc] init]; - if (match.resultType == NSTextCheckingTypeDate) { - [items addObject:[CRWContextMenuItem - itemWithID:@"addToGoogleCalendar" - title:@"Add to Google Calendar" - action:^{ - // TODO(crbug.com/1350974): execute - }]]; - } else if (match.resultType == NSTextCheckingTypeAddress) { - [items addObject:[CRWContextMenuItem - itemWithID:@"showMiniMap" - title:@"Show Mini Map" - action:^{ - // TODO(crbug.com/1350974): execute - }]]; - } else if (match.resultType == NSTextCheckingTypePhoneNumber) { - [items addObject:[CRWContextMenuItem - itemWithID:@"callPhoneNumber" - title:@"Call Phone Number" - action:^{ - // TODO(crbug.com/1350974): execute - }]]; + NSArray<CRWContextMenuItem*>* items = + ios::provider::GetContextMenuElementsToAdd(web_state, match, + base::SysUTF8ToNSString(text), + base_view_controller_); + + if (items.count) { + [web_state_->GetWebViewProxy() showMenuWithItems:items rect:rect]; } - - [items - addObject:[CRWContextMenuItem itemWithID:@"copyDate" - title:@"Copy" - action:^{ - // TODO(crbug.com/1350974): execute - }]]; - - [web_state_->GetWebViewProxy() showMenuWithItems:items rect:rect]; } #pragma mark - Private Methods void AnnotationsTabHelper::ApplyDeferredProcessing( - web::WebState* web_state, absl::optional<base::Value> deferred) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK_EQ(web_state_, web_state); if (GetMainFrame(web_state_) && deferred) { auto* manager = web::AnnotationsTextManager::FromWebState(web_state_);
diff --git a/ios/chrome/common/ui/promo_style/promo_style_view_controller.h b/ios/chrome/common/ui/promo_style/promo_style_view_controller.h index e2b0898..2b4b1a5 100644 --- a/ios/chrome/common/ui/promo_style/promo_style_view_controller.h +++ b/ios/chrome/common/ui/promo_style/promo_style_view_controller.h
@@ -37,6 +37,14 @@ // When set to YES, the banner is hidden. Defaults to NO. @property(nonatomic, assign) BOOL shouldHideBanner; +// When set to `YES`, an avatar image view is shown. This value has to be set +// before the view is loaded. Defaults to NO. +// See `avatarImage` to set the avatar image. +@property(nonatomic, assign) BOOL hasAvatarImage; + +// Sets the avatar image. Needs to `hasAvatarImage` to `YES` before. +@property(nonatomic, strong) UIImage* avatarImage; + // The label of the headline below the image. Must be set before the view is // loaded. This is declared public so the accessibility can be enabled. @property(nonatomic, strong) UILabel* titleLabel;
diff --git a/ios/chrome/common/ui/promo_style/promo_style_view_controller.mm b/ios/chrome/common/ui/promo_style/promo_style_view_controller.mm index 4677e8db..c4c05d8 100644 --- a/ios/chrome/common/ui/promo_style/promo_style_view_controller.mm +++ b/ios/chrome/common/ui/promo_style/promo_style_view_controller.mm
@@ -26,6 +26,9 @@ namespace { constexpr CGFloat kDefaultMargin = 16; +// TODO(crbug.com/1363812): Need to adjust the value. +constexpr CGFloat kFullAvatarImagerUpperMargin = 40; +constexpr CGFloat kFullAvatarImagerBottomMargin = 24; constexpr CGFloat kTitleHorizontalMargin = 18; constexpr CGFloat kActionsBottomMargin = 10; constexpr CGFloat kTallBannerMultiplier = 0.35; @@ -36,6 +39,8 @@ constexpr CGFloat kPreviousContentVisibleOnScroll = 0.15; constexpr CGFloat kSeparatorHeight = 1; constexpr CGFloat kLearnMoreButtonSide = 40; +constexpr CGFloat kAvatarImageSize = 48; +constexpr CGFloat kFullAvatarImageSize = 60; } // namespace @@ -48,6 +53,10 @@ @property(nonatomic, strong) UIImageView* imageView; // UIView that wraps the scrollable content. @property(nonatomic, strong) UIView* scrollContentView; +// This view contains the avatar image with a shadow background image behind. +@property(nonatomic, strong) UIView* fullAvatarImageView; +// This view contains only the avatar image. +@property(nonatomic, strong) UIImageView* avatarImageView; @property(nonatomic, strong) UILabel* subtitleLabel; @property(nonatomic, strong) UITextView* disclaimerView; @property(nonatomic, strong) UIStackView* actionStackView; @@ -117,6 +126,10 @@ self.scrollContentView = [[UIView alloc] init]; self.scrollContentView.translatesAutoresizingMaskIntoConstraints = NO; [self.scrollContentView addSubview:self.imageView]; + if (self.hasAvatarImage) { + [self.scrollContentView addSubview:self.fullAvatarImageView]; + [self.fullAvatarImageView addSubview:self.avatarImageView]; + } [self.scrollContentView addSubview:self.titleLabel]; [self.scrollContentView addSubview:self.subtitleLabel]; [self.view addLayoutGuide:subtitleMarginLayoutGuide]; @@ -215,8 +228,6 @@ // Labels contraints. Attach them to the top of the scroll content view, and // center them horizontally. - [self.titleLabel.topAnchor - constraintEqualToAnchor:self.imageView.bottomAnchor], [self.titleLabel.centerXAnchor constraintEqualToAnchor:self.scrollContentView.centerXAnchor], [self.titleLabel.widthAnchor @@ -252,6 +263,36 @@ constraintEqualToAnchor:widthLayoutGuide.trailingAnchor], ]]; + if (self.hasAvatarImage) { + [NSLayoutConstraint activateConstraints:@[ + [self.fullAvatarImageView.topAnchor + constraintEqualToAnchor:self.imageView.bottomAnchor + constant:kFullAvatarImagerUpperMargin], + [self.titleLabel.topAnchor + constraintEqualToAnchor:self.fullAvatarImageView.bottomAnchor + constant:kFullAvatarImagerBottomMargin], + [self.fullAvatarImageView.centerXAnchor + constraintEqualToAnchor:self.scrollContentView.centerXAnchor], + [self.fullAvatarImageView.centerXAnchor + constraintEqualToAnchor:self.avatarImageView.centerXAnchor], + [self.fullAvatarImageView.centerYAnchor + constraintEqualToAnchor:self.avatarImageView.centerYAnchor], + [self.fullAvatarImageView.widthAnchor + constraintEqualToConstant:kFullAvatarImageSize], + [self.fullAvatarImageView.heightAnchor + constraintEqualToConstant:kFullAvatarImageSize], + [self.avatarImageView.widthAnchor + constraintEqualToConstant:kAvatarImageSize], + [self.avatarImageView.heightAnchor + constraintEqualToConstant:kAvatarImageSize], + ]]; + } else { + [NSLayoutConstraint activateConstraints:@[ + [self.titleLabel.topAnchor + constraintEqualToAnchor:self.imageView.bottomAnchor], + ]]; + } + [self setupBannerConstraints]; self.buttonsVerticalAnchorConstraints = @[ @@ -444,6 +485,35 @@ return _imageView; } +- (UIView*)fullAvatarImageView { + if (!_fullAvatarImageView) { + DCHECK(self.hasAvatarImage); + // TODO(crbug.com/1363812): Add a background image. + _fullAvatarImageView = [[UIImageView alloc] init]; + _fullAvatarImageView.clipsToBounds = YES; + _fullAvatarImageView.translatesAutoresizingMaskIntoConstraints = NO; + } + return _fullAvatarImageView; +} + +- (UIImageView*)avatarImageView { + if (!_avatarImageView) { + DCHECK(self.hasAvatarImage); + _avatarImageView = [[UIImageView alloc] initWithImage:self.avatarImage]; + _avatarImageView.clipsToBounds = YES; + _avatarImageView.translatesAutoresizingMaskIntoConstraints = NO; + _avatarImageView.layer.cornerRadius = kAvatarImageSize / 2.; + } + return _avatarImageView; +} + +- (void)setAvatarImage:(UIImage*)avatarImage { + _avatarImage = avatarImage; + if (self.hasAvatarImage) { + self.avatarImageView.image = avatarImage; + } +} + - (UILabel*)titleLabel { if (!_titleLabel) { _titleLabel = [[UILabel alloc] init]; @@ -668,6 +738,9 @@ } - (UIImage*)bannerImage { + if (self.shouldHideBanner && !self.bannerName) { + return [[UIImage alloc] init]; + } return [UIImage imageNamed:self.bannerName]; }
diff --git a/ios/chrome/test/providers/context_menu/test_context_menu.mm b/ios/chrome/test/providers/context_menu/test_context_menu.mm index 623e63f9..a4ebb13 100644 --- a/ios/chrome/test/providers/context_menu/test_context_menu.mm +++ b/ios/chrome/test/providers/context_menu/test_context_menu.mm
@@ -18,5 +18,18 @@ UIViewController* presenting_view_controller) { return nil; } + +NSTextCheckingType GetHandledIntentTypes(web::WebState* web_state) { + return 0; +} + +NSArray<CRWContextMenuItem*>* GetContextMenuElementsToAdd( + web::WebState* web_state, + NSTextCheckingResult* match, + NSString* text, + UIViewController* presenting_view_controller) { + return nil; +} + } // namespace provider } // namespace ios
diff --git a/ios/chrome/test/providers/signin/fake_trusted_vault_client_backend.h b/ios/chrome/test/providers/signin/fake_trusted_vault_client_backend.h index 773c3f2..3c93e5fc 100644 --- a/ios/chrome/test/providers/signin/fake_trusted_vault_client_backend.h +++ b/ios/chrome/test/providers/signin/fake_trusted_vault_client_backend.h
@@ -18,17 +18,17 @@ // TrustedVaultClientBackend implementation. void AddObserver(Observer* observer) final; void RemoveObserver(Observer* observer) final; - void FetchKeys(ChromeIdentity* chrome_identity, + void FetchKeys(id<SystemIdentity> identity, KeyFetchedCallback callback) final; - void MarkLocalKeysAsStale(ChromeIdentity* chrome_identity, + void MarkLocalKeysAsStale(id<SystemIdentity> identity, base::OnceClosure callback) final; void GetDegradedRecoverabilityStatus( - ChromeIdentity* chrome_identity, + id<SystemIdentity> identity, base::OnceCallback<void(bool)> callback) final; - void Reauthentication(ChromeIdentity* chrome_identity, + void Reauthentication(id<SystemIdentity> identity, UIViewController* presenting_view_controller, CompletionBlock callback) final; - void FixDegradedRecoverability(ChromeIdentity* chrome_identity, + void FixDegradedRecoverability(id<SystemIdentity> identity, UIViewController* presenting_view_controller, CompletionBlock callback) final; void CancelDialog(BOOL animated, ProceduralBlock callback) final;
diff --git a/ios/chrome/test/providers/signin/fake_trusted_vault_client_backend.mm b/ios/chrome/test/providers/signin/fake_trusted_vault_client_backend.mm index 647cbaf..e8e964d7 100644 --- a/ios/chrome/test/providers/signin/fake_trusted_vault_client_backend.mm +++ b/ios/chrome/test/providers/signin/fake_trusted_vault_client_backend.mm
@@ -72,25 +72,25 @@ // Do nothing. } -void FakeTrustedVaultClientBackend::FetchKeys(ChromeIdentity* chrome_identity, +void FakeTrustedVaultClientBackend::FetchKeys(id<SystemIdentity> identity, KeyFetchedCallback callback) { // Do nothing. } void FakeTrustedVaultClientBackend::MarkLocalKeysAsStale( - ChromeIdentity* chrome_identity, + id<SystemIdentity> identity, base::OnceClosure callback) { // Do nothing. } void FakeTrustedVaultClientBackend::GetDegradedRecoverabilityStatus( - ChromeIdentity* chrome_identity, + id<SystemIdentity> identity, base::OnceCallback<void(bool)> callback) { // Do nothing. } void FakeTrustedVaultClientBackend::Reauthentication( - ChromeIdentity* chrome_identity, + id<SystemIdentity> identity, UIViewController* presenting_view_controller, CompletionBlock callback) { DCHECK(!view_controller_); @@ -102,7 +102,7 @@ } void FakeTrustedVaultClientBackend::FixDegradedRecoverability( - ChromeIdentity* chrome_identity, + id<SystemIdentity> identity, UIViewController* presenting_view_controller, CompletionBlock callback) { // Do nothing.
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 3c39125..1419b80 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 @@ -4aaadea629b633b3d1380d07aa9bb3102fdf4043 \ No newline at end of file +4a5254b558e0fe5b7379b9bab075cd884f172fd5 \ 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 cec4b29..95fda7f 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 @@ -2c85e739263cc1dc4cf2ebed626ba6292fde20f1 \ No newline at end of file +c622b687bf2cb50a248d7e6bdc835d466cd51025 \ 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 ff1af0e..67c43398 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 @@ -975b626610e40b610b1ae5e8e018198458a6273f \ No newline at end of file +7eaf9420b737873befc6b8866fb7419e5f5e8250 \ 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 16f34d1a..2b447ba9 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 @@ -428a29d462bd1b8b77712c653eb9643ab5d9f013 \ No newline at end of file +362b021199e6030ff9140cfc919210ce443f7877 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/chrome_test_internal_dynamic_framework.ios.zip.sha1 b/ios/google_internal/frameworks/chrome_test_internal_dynamic_framework.ios.zip.sha1 index 6531631..fed5b63 100644 --- a/ios/google_internal/frameworks/chrome_test_internal_dynamic_framework.ios.zip.sha1 +++ b/ios/google_internal/frameworks/chrome_test_internal_dynamic_framework.ios.zip.sha1
@@ -1 +1 @@ -3071e19bff2caee243de3a2f49c2fb637d804538 \ No newline at end of file +9ef36c730efa0ed9eabd625bb5e9f7b4e3afe41d \ No newline at end of file
diff --git a/ios/google_internal/frameworks/chrome_test_internal_dynamic_framework.iossimulator.zip.sha1 b/ios/google_internal/frameworks/chrome_test_internal_dynamic_framework.iossimulator.zip.sha1 index 7dcd80a8..bef0e84 100644 --- a/ios/google_internal/frameworks/chrome_test_internal_dynamic_framework.iossimulator.zip.sha1 +++ b/ios/google_internal/frameworks/chrome_test_internal_dynamic_framework.iossimulator.zip.sha1
@@ -1 +1 @@ -aeb00f778906835e50da14f0414c3492f8ee4920 \ No newline at end of file +e1a05d52557ddaf5723f0eba578f0ff76a99ce75 \ 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 380e5e3..9e7c6e19 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 @@ -0dcd3cbf37365de798144fca6622cd13cbca7dac \ No newline at end of file +25bc5412f3f29c288b0442f34b04c72191df5f5e \ 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 4de15528e..caa5efb 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 @@ -9482aa5cbc15969bf477f7ce10276664225a6474 \ No newline at end of file +b021f63b057242c0bd8c763db301ef8030222a18 \ 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 a18b104..436c5f3 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 @@ -e03bbf2e3771ca4dc43ba6c20374614bc24f8aee \ No newline at end of file +ed3c29f149e8ed13fdc963fbe68a36c386858dfb \ 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 64f7b53..7c0d174 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 @@ -2ca951e52af3031f5ac1a45f85d93f19c047935b \ No newline at end of file +6cfdd27bc1540ee00d91ee7d99474cd52602e1a5 \ 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 2e2dbb55..c9ba14cb 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 @@ -1d338aed50c2f2c72476eb7e7e5920977f7dc7d6 \ No newline at end of file +e442ec6f7c18adae183d1b3e7811bf698978cb74 \ 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 5350a9c..2ea9c69 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 @@ -4c81914931f1d00a9ba18f97172aaa950556a721 \ No newline at end of file +ad93539128a6cb87d3044a1d73172a972bc58a54 \ No newline at end of file
diff --git a/ios/public/provider/chrome/browser/context_menu/context_menu_api.h b/ios/public/provider/chrome/browser/context_menu/context_menu_api.h index f9d969e..b201cd8c 100644 --- a/ios/public/provider/chrome/browser/context_menu/context_menu_api.h +++ b/ios/public/provider/chrome/browser/context_menu/context_menu_api.h
@@ -8,6 +8,7 @@ #import <UIKit/UIKit.h> #import "ios/web/public/ui/context_menu_params.h" +#import "ios/web/public/ui/crw_context_menu_item.h" class ChromeBrowserState; @@ -37,6 +38,18 @@ web::ContextMenuParams params, UIViewController* presenting_view_controller); +// Returns set of `NSTextCheckingType` representing the intent types that +// can be handled by the provider, for the given `web_state`. +NSTextCheckingType GetHandledIntentTypes(web::WebState* web_state); + +// Returns `CRWContextMenuItem` items for the given `match`, for the given +// `web_state`. +NSArray<CRWContextMenuItem*>* GetContextMenuElementsToAdd( + web::WebState* web_state, + NSTextCheckingResult* match, + NSString* text, + UIViewController* presenting_view_controller); + } // namespace provider } // namespace ios
diff --git a/ios/web/annotations/resources/annotations.ts b/ios/web/annotations/resources/annotations.ts index fa40eb3..5db6cae 100644 --- a/ios/web/annotations/resources/annotations.ts +++ b/ios/web/annotations/resources/annotations.ts
@@ -31,7 +31,7 @@ text: string; /** Annotation type. */ type: string; - /** A passed in string that will be sent back to obj in click handler. */ + /** A passed in string that will be sent back to obj in tap handler. */ data: string; } @@ -44,7 +44,8 @@ class Replacement { constructor( public index: number, public left: number, public right: number, - public text: string, public type: string, public data: string) {} + public text: string, public type: string, public annotationText: string, + public data: string) {} } /** @@ -67,6 +68,37 @@ constructor(public node: Node|WeakRef<Node>, public index: number) {} } +/** + * Monitors DOM mutations between instance construction until a call to + * `stopObserving`. + */ +class MutationsDuringClickTracker { + mutationCount = 0; + mutationObserver: MutationObserver; + + // Constructs a new instance given an `initialEvent` and starts listening for + // changes to the DOM. + constructor(private readonly initialEvent: Event) { + this.mutationObserver = + new MutationObserver((mutationList: MutationRecord[]) => { + this.mutationCount += mutationList.length; + }); + this.mutationObserver.observe( + document, {attributes: false, childList: true, subtree: true}); + } + + // Returns true if event matches the event passed at construction, it wasn't + // prevented and no DOM mutations occurred. + hasPreventativeActivity(event: Event): boolean { + return event !== this.initialEvent || event.defaultPrevented || + this.mutationCount > 0; + } + + stopObserving(): void { + this.mutationObserver?.disconnect(); + } +} + // Used by the `enumerateTextNodes` function below. const NON_TEXT_NODE_NAMES = new Set([ 'SCRIPT', 'NOSCRIPT', 'STYLE', 'EMBED', 'OBJECT', 'TEXTAREA', 'IFRAME', @@ -120,6 +152,9 @@ let failures = 0; decorations = []; + // Last checks when bubbling up event. + document.addEventListener('click', handleTopTap.bind(document)); + removeOverlappingAnnotations(annotations); // Reparse page finding annotations and styling them. @@ -174,7 +209,7 @@ } replacements.push(new Replacement( annotationIndex, left, right, nodeText, annotation.type, - annotation.data)); + annotation.text, annotation.data)); // If annotation is completed, move to next annotation and retry on // this node to fit more annotations if needed. if (end <= index + length) { @@ -350,9 +385,44 @@ return ''.concat(...parts); } -function handleClick(event: Event) { - const annotation = event.currentTarget as HTMLElement; +let mutationDuringClickObserver: MutationsDuringClickTracker|null; +// Initiates a `mutationDuringClickObserver` that will be checked at document +// level tab handler (`handleTopTap`), where it will be decided if any action +// bubbling to objc is required (i.e. no DOM change occurs). +function handleTap(event: Event) { + mutationDuringClickObserver = new MutationsDuringClickTracker(event); +} + +// Monitors taps at the top, document level. This checks if it is tap +// triggered by an annotation and if no DOM mutation have happened while the +// event is bubbling up. If it's the case, the annotation callback is called. +function handleTopTap(event: Event) { + // Nothing happened to the page between `handleTap` and `handleTopTap`. + if (event.target instanceof HTMLElement && + event.target.tagName === 'CHROME_ANNOTATION' && + mutationDuringClickObserver && + !mutationDuringClickObserver.hasPreventativeActivity(event)) { + const annotation = event.target; + + highlightAnnotation(annotation); + + sendWebKitMessage('annotations', { + command: 'annotations.onClick', + data: annotation.dataset['data'], + rect: rectFromElement(annotation), + text: annotation.dataset['annotation'], + }); + } + mutationDuringClickObserver?.stopObserving(); + mutationDuringClickObserver = null; +} + +/** + * Highlights all elements related to the annotation of which `annotation` is an + * element of. + */ +function highlightAnnotation(annotation: HTMLElement) { // Using webkit edit selection kills a second tapping on the element and also // causes a merge with the edit menu in some circumstance. // Using custom highlight instead. @@ -368,13 +438,6 @@ } } } - - sendWebKitMessage('annotations', { - command: 'annotations.onClick', - data: annotation.dataset['data'], - rect: rectFromElement(annotation), - text: `"${annotation.innerText}"`, - }); } /** @@ -426,10 +489,11 @@ const element = document.createElement('chrome_annotation'); element.setAttribute('data-index', '' + replacement.index); element.setAttribute('data-data', replacement.data); + element.setAttribute('data-annotation', replacement.annotationText); element.innerText = replacement.text; element.style.cssText = decorationStyles; element.style.borderBottomColor = textColor; - element.addEventListener('click', handleClick.bind(element), true); + element.addEventListener('click', handleTap.bind(element), true); parts.push(element); cursor = replacement.right; }
diff --git a/ios/web/webui/crw_web_ui_scheme_handler.mm b/ios/web/webui/crw_web_ui_scheme_handler.mm index 74462d8..bf9d5a7 100644 --- a/ios/web/webui/crw_web_ui_scheme_handler.mm +++ b/ios/web/webui/crw_web_ui_scheme_handler.mm
@@ -7,6 +7,7 @@ #import <map> #import "base/files/file_path.h" +#import "base/ranges/algorithm.h" #import "ios/web/webui/url_fetcher_block_adapter.h" #import "ios/web/webui/web_ui_ios_controller_factory_registry.h" #import "net/base/mac/url_conversions.h" @@ -118,11 +119,12 @@ // Removes `fetcher` from map of active fetchers. - (void)removeFetcher:(web::URLFetcherBlockAdapter*)fetcher { - _map.erase(std::find_if( - _map.begin(), _map.end(), - [fetcher](const std::pair<const id<WKURLSchemeTask>, - std::unique_ptr<web::URLFetcherBlockAdapter>>& - entry) { return entry.second.get() == fetcher; })); + _map.erase(base::ranges::find( + _map, fetcher, + [](const std::pair<const id<WKURLSchemeTask>, + std::unique_ptr<web::URLFetcherBlockAdapter>>& entry) { + return entry.second.get(); + })); } @end
diff --git a/media/filters/ffmpeg_audio_decoder.cc b/media/filters/ffmpeg_audio_decoder.cc index b06865a..be65001 100644 --- a/media/filters/ffmpeg_audio_decoder.cc +++ b/media/filters/ffmpeg_audio_decoder.cc
@@ -175,6 +175,8 @@ } else { packet->data = const_cast<uint8_t*>(buffer.data()); packet->size = buffer.data_size(); + packet->pts = + ConvertToTimeBase(codec_context_->time_base, buffer.timestamp()); DCHECK(packet->data); DCHECK_GT(packet->size, 0);
diff --git a/media/gpu/vaapi/test/vp9_decoder.cc b/media/gpu/vaapi/test/vp9_decoder.cc index 79e52e0..e75b1bc 100644 --- a/media/gpu/vaapi/test/vp9_decoder.cc +++ b/media/gpu/vaapi/test/vp9_decoder.cc
@@ -133,14 +133,14 @@ GetFormatForProfile(profile)); } - // [Re]create context for decode. // A resolution change may occur on a frame that is neither keyframe nor - // intra-only, i.e. may refer to earlier frames. If the earlier referred frame - // is larger than the new frame, consequently, do *not* recreate the context. - // See also - // https://cgit.freedesktop.org/gstreamer/gstreamer-vaapi/tree/gst-libs/gst/vaapi/gstvaapidecoder_vp9.c?h=1.18#n652 - if (!va_context_ || va_context_->size().width() < size.width() || - va_context_->size().height() < size.height()) { + // intra-only, i.e. may refer to earlier frames. But vaDestroyContext() + // cleans up internal states of a driver and makes the driver unable to + // reference the earlier frames. Therefore, we don't destroy and recreate + // |va_context_| in non keyframe. + if (!va_context_ || (frame_hdr.IsKeyframe() && + (va_context_->size().width() < size.width() || + va_context_->size().height() < size.height()))) { va_context_ = std::make_unique<ScopedVAContext>(va_device_, *va_config_, size); }
diff --git a/net/cert/cert_verify_proc_builtin_unittest.cc b/net/cert/cert_verify_proc_builtin_unittest.cc index e556fe0..3223edc 100644 --- a/net/cert/cert_verify_proc_builtin_unittest.cc +++ b/net/cert/cert_verify_proc_builtin_unittest.cc
@@ -640,7 +640,7 @@ namespace { -// Returns a TLV to use as an invalid signature algorithm when building a cert. +// Returns a TLV to use as an unknown signature algorithm when building a cert. // The specific contents are as follows (the OID is from // https://davidben.net/oid): // @@ -648,7 +648,7 @@ // OBJECT_IDENTIFIER { 1.2.840.113554.4.1.72585.0 } // NULL {} // } -std::string InvalidSignatureAlgorithmTLV() { +std::string UnknownSignatureAlgorithmTLV() { const uint8_t kInvalidSignatureAlgorithmTLV[] = { 0x30, 0x10, 0x06, 0x0c, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x12, 0x04, 0x01, 0x84, 0xb7, 0x09, 0x00, 0x05, 0x00}; @@ -656,13 +656,26 @@ std::end(kInvalidSignatureAlgorithmTLV)); } +// Returns a TLV to use as an invalid signature algorithm when building a cert. +// This is a SEQUENCE so that it will pass the ParseCertificate code +// and fail inside ParseSignatureAlgorithm. +// SEQUENCE { +// INTEGER { 42 } +// } +std::string InvalidSignatureAlgorithmTLV() { + const uint8_t kInvalidSignatureAlgorithmTLV[] = {0x30, 0x03, 0x02, 0x01, + 0x2a}; + return std::string(std::begin(kInvalidSignatureAlgorithmTLV), + std::end(kInvalidSignatureAlgorithmTLV)); +} + } // namespace TEST_F(CertVerifyProcBuiltinTest, UnknownSignatureAlgorithmTarget) { std::unique_ptr<CertBuilder> leaf, intermediate, root; CreateChain(&leaf, &intermediate, &root); ASSERT_TRUE(leaf && intermediate && root); - leaf->SetSignatureAlgorithmTLV(InvalidSignatureAlgorithmTLV()); + leaf->SetSignatureAlgorithmTLV(UnknownSignatureAlgorithmTLV()); // Trust the root and build a chain to verify that includes the intermediate. ScopedTestRoot scoped_root(root->GetX509Certificate().get()); @@ -682,11 +695,37 @@ EXPECT_THAT(error, IsError(ERR_CERT_INVALID)); } +TEST_F(CertVerifyProcBuiltinTest, + UnparsableMismatchedTBSSignatureAlgorithmTarget) { + std::unique_ptr<CertBuilder> leaf, root; + CreateChain(&leaf, &root); + ASSERT_TRUE(leaf && root); + // Set only the tbsCertificate signature to an invalid value. + leaf->SetTBSSignatureAlgorithmTLV(InvalidSignatureAlgorithmTLV()); + + // Trust the root and build a chain to verify. + ScopedTestRoot scoped_root(root->GetX509Certificate().get()); + scoped_refptr<X509Certificate> chain = leaf->GetX509CertificateChain(); + ASSERT_TRUE(chain.get()); + + int flags = 0; + CertVerifyResult verify_result; + NetLogSource verify_net_log_source; + TestCompletionCallback callback; + Verify(chain.get(), "www.example.com", flags, CertificateList(), + &verify_result, &verify_net_log_source, callback.callback()); + int error = callback.WaitForResult(); + // Invalid signature algorithm in the leaf cert should result in the + // cert being invalid. + EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_INVALID); + EXPECT_THAT(error, IsError(ERR_CERT_INVALID)); +} + TEST_F(CertVerifyProcBuiltinTest, UnknownSignatureAlgorithmIntermediate) { std::unique_ptr<CertBuilder> leaf, intermediate, root; CreateChain(&leaf, &intermediate, &root); ASSERT_TRUE(leaf && intermediate && root); - intermediate->SetSignatureAlgorithmTLV(InvalidSignatureAlgorithmTLV()); + intermediate->SetSignatureAlgorithmTLV(UnknownSignatureAlgorithmTLV()); // Trust the root and build a chain to verify that includes the intermediate. ScopedTestRoot scoped_root(root->GetX509Certificate().get()); @@ -706,11 +745,38 @@ EXPECT_THAT(error, IsError(ERR_CERT_INVALID)); } +TEST_F(CertVerifyProcBuiltinTest, + UnparsableMismatchedTBSSignatureAlgorithmIntermediate) { + std::unique_ptr<CertBuilder> leaf, intermediate, root; + CreateChain(&leaf, &intermediate, &root); + ASSERT_TRUE(leaf && intermediate && root); + // Set only the tbsCertificate signature to an invalid value. + intermediate->SetTBSSignatureAlgorithmTLV(InvalidSignatureAlgorithmTLV()); + + // Trust the root and build a chain to verify that includes the intermediate. + ScopedTestRoot scoped_root(root->GetX509Certificate().get()); + scoped_refptr<X509Certificate> chain = leaf->GetX509CertificateChain(); + ASSERT_TRUE(chain.get()); + ASSERT_EQ(chain->intermediate_buffers().size(), 1U); + + int flags = 0; + CertVerifyResult verify_result; + NetLogSource verify_net_log_source; + TestCompletionCallback callback; + Verify(chain.get(), "www.example.com", flags, CertificateList(), + &verify_result, &verify_net_log_source, callback.callback()); + int error = callback.WaitForResult(); + // Invalid signature algorithm in the intermediate cert should result in the + // cert being invalid. + EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_INVALID); + EXPECT_THAT(error, IsError(ERR_CERT_INVALID)); +} + TEST_F(CertVerifyProcBuiltinTest, UnknownSignatureAlgorithmRoot) { std::unique_ptr<CertBuilder> leaf, intermediate, root; CreateChain(&leaf, &intermediate, &root); ASSERT_TRUE(leaf && intermediate && root); - root->SetSignatureAlgorithmTLV(InvalidSignatureAlgorithmTLV()); + root->SetSignatureAlgorithmTLV(UnknownSignatureAlgorithmTLV()); // Trust the root and build a chain to verify that includes the intermediate. ScopedTestRoot scoped_root(root->GetX509Certificate().get()); @@ -729,4 +795,40 @@ EXPECT_THAT(error, IsOk()); } +// This test is disabled on Android as adding the invalid root through +// ScopedTestRoot causes it to be parsed by the Java X509 code which barfs. We +// could re-enable if Chrome on Android has fully switched to the +// builtin-verifier and ScopedTestRoot no longer has Android-specific code. +#if BUILDFLAG(IS_ANDROID) +#define MAYBE_UnparsableMismatchedTBSSignatureAlgorithmRoot \ + DISABLED_UnparsableMismatchedTBSSignatureAlgorithmRoot +#else +#define MAYBE_UnparsableMismatchedTBSSignatureAlgorithmRoot \ + UnparsableMismatchedTBSSignatureAlgorithmRoot +#endif +TEST_F(CertVerifyProcBuiltinTest, + MAYBE_UnparsableMismatchedTBSSignatureAlgorithmRoot) { + std::unique_ptr<CertBuilder> leaf, intermediate, root; + CreateChain(&leaf, &intermediate, &root); + ASSERT_TRUE(leaf && intermediate && root); + // Set only the tbsCertificate signature to an invalid value. + root->SetTBSSignatureAlgorithmTLV(InvalidSignatureAlgorithmTLV()); + + // Trust the root and build a chain to verify that includes the intermediate. + ScopedTestRoot scoped_root(root->GetX509Certificate().get()); + scoped_refptr<X509Certificate> chain = leaf->GetX509CertificateChain(); + ASSERT_TRUE(chain.get()); + + int flags = 0; + CertVerifyResult verify_result; + NetLogSource verify_net_log_source; + TestCompletionCallback callback; + Verify(chain.get(), "www.example.com", flags, CertificateList(), + &verify_result, &verify_net_log_source, callback.callback()); + int error = callback.WaitForResult(); + // Invalid signature algorithm in the root cert should have no effect on + // verification. + EXPECT_THAT(error, IsOk()); +} + } // namespace net
diff --git a/net/cert/pki/verify_certificate_chain.cc b/net/cert/pki/verify_certificate_chain.cc index ed4d0cd..416cf31b 100644 --- a/net/cert/pki/verify_certificate_chain.cc +++ b/net/cert/pki/verify_certificate_chain.cc
@@ -147,12 +147,16 @@ // TODO(eroman): Add a unit-test that exercises this case. absl::optional<SignatureAlgorithm> alg1 = ParseSignatureAlgorithm(alg1_tlv, errors); - if (!alg1) + if (!alg1) { + errors->AddError(cert_errors::kUnacceptableSignatureAlgorithm); return false; + } absl::optional<SignatureAlgorithm> alg2 = ParseSignatureAlgorithm(alg2_tlv, errors); - if (!alg2) + if (!alg2) { + errors->AddError(cert_errors::kUnacceptableSignatureAlgorithm); return false; + } if (*alg1 == *alg2) { errors->AddWarning( @@ -802,8 +806,10 @@ // Check that the signature algorithms in Certificate vs TBSCertificate // match. This isn't part of RFC 5280 section 6.1.3, but is mandated by // sections 4.1.1.2 and 4.1.2.3. - if (!VerifySignatureAlgorithmsMatch(cert, errors)) + if (!VerifySignatureAlgorithmsMatch(cert, errors)) { + CHECK(errors->ContainsAnyErrorWithSeverity(CertError::SEVERITY_HIGH)); *shortcircuit_chain_validation = true; + } // Check whether this signature algorithm is allowed. if (!cert.signature_algorithm().has_value() || @@ -1283,7 +1289,7 @@ // Chains that don't start from a trusted root should short-circuit the // rest of the verification, as accumulating more errors from untrusted // certificates would not be meaningful. - DCHECK(cert_errors->ContainsAnyErrorWithSeverity( + CHECK(cert_errors->ContainsAnyErrorWithSeverity( CertError::SEVERITY_HIGH)); return; } @@ -1304,7 +1310,7 @@ // Signature errors should short-circuit the rest of the verification, as // accumulating more errors from untrusted certificates would not be // meaningful. - DCHECK( + CHECK( cert_errors->ContainsAnyErrorWithSeverity(CertError::SEVERITY_HIGH)); return; }
diff --git a/net/first_party_sets/first_party_sets_context_config.cc b/net/first_party_sets/first_party_sets_context_config.cc index 913bfab..40d6feff 100644 --- a/net/first_party_sets/first_party_sets_context_config.cc +++ b/net/first_party_sets/first_party_sets_context_config.cc
@@ -46,4 +46,19 @@ } } +bool FirstPartySetsContextConfig::Contains(const SchemefulSite& site) const { + return FindOverride(site).has_value(); +} + +bool FirstPartySetsContextConfig::ForEachCustomizationEntry( + base::FunctionRef<bool(const SchemefulSite&, + const absl::optional<FirstPartySetEntry>&)> f) + const { + for (const auto& [site, maybe_entry] : customizations_) { + if (!f(site, maybe_entry)) + return false; + } + return true; +} + } // namespace net
diff --git a/net/first_party_sets/first_party_sets_context_config.h b/net/first_party_sets/first_party_sets_context_config.h index ecc7f1d..77012ab 100644 --- a/net/first_party_sets/first_party_sets_context_config.h +++ b/net/first_party_sets/first_party_sets_context_config.h
@@ -6,6 +6,7 @@ #define NET_FIRST_PARTY_SETS_FIRST_PARTY_SETS_CONTEXT_CONFIG_H_ #include "base/containers/flat_map.h" +#include "base/functional/function_ref.h" #include "net/base/schemeful_site.h" #include "net/first_party_sets/first_party_set_entry.h" #include "third_party/abseil-cpp/absl/types/optional.h" @@ -56,6 +57,23 @@ // `aliases`. void IngestAliases(base::flat_map<SchemefulSite, SchemefulSite> aliases); + // Returns whether an override can be found for the given site in this + // context. + bool Contains(const SchemefulSite& site) const; + + // Synchronously iterate over all the override entries. Each iteration will be + // invoked with the relevant site and the override that applies to it. The + // override will be `nullopt` if it is a deletion, or `optional(entry)` if it + // is a modification of an existing entry, or an addition. + // + // Returns early if any of the iterations returns false. Returns false if + // iteration was incomplete; true if all iterations returned true. No + // guarantees are made re: iteration order. + bool ForEachCustomizationEntry( + base::FunctionRef<bool(const SchemefulSite&, + const absl::optional<FirstPartySetEntry>&)> f) + const; + private: // mojo (de)serialization needs access to private details. friend struct mojo::StructTraits<
diff --git a/net/first_party_sets/first_party_sets_context_config_unittest.cc b/net/first_party_sets/first_party_sets_context_config_unittest.cc index 3fee885..72c0520f 100644 --- a/net/first_party_sets/first_party_sets_context_config_unittest.cc +++ b/net/first_party_sets/first_party_sets_context_config_unittest.cc
@@ -60,4 +60,48 @@ EXPECT_THAT(config.FindOverride(example_cctld), Optional(Optional(entry))); } +TEST(FirstPartySetsContextConfigTest, Contains) { + SchemefulSite example(GURL("https://example.test")); + SchemefulSite decoy(GURL("https://decoy.test")); + + FirstPartySetsContextConfig config({{example, absl::nullopt}}); + + EXPECT_TRUE(config.Contains(example)); + EXPECT_FALSE(config.Contains(decoy)); +} + +TEST(FirstPartySetsContextConfigTest, ForEachCustomizationEntry_FullIteration) { + SchemefulSite example(GURL("https://example.test")); + SchemefulSite foo(GURL("https://foo.test")); + + FirstPartySetsContextConfig config( + {{example, absl::nullopt}, {foo, absl::nullopt}}); + + int count = 0; + EXPECT_TRUE(config.ForEachCustomizationEntry( + [&](const SchemefulSite& site, + const absl::optional<FirstPartySetEntry>& entry) { + ++count; + return true; + })); + EXPECT_EQ(count, 2); +} + +TEST(FirstPartySetsContextConfigTest, ForEachCustomizationEntry_EarlyReturn) { + SchemefulSite example(GURL("https://example.test")); + SchemefulSite foo(GURL("https://foo.test")); + + FirstPartySetsContextConfig config( + {{example, absl::nullopt}, {foo, absl::nullopt}}); + + int count = 0; + EXPECT_FALSE(config.ForEachCustomizationEntry( + [&](const SchemefulSite& site, + const absl::optional<FirstPartySetEntry>& entry) { + ++count; + return count < 1; + })); + EXPECT_EQ(count, 1); +} + } // namespace net
diff --git a/net/socket/tcp_client_socket.cc b/net/socket/tcp_client_socket.cc index d092f32..b411312 100644 --- a/net/socket/tcp_client_socket.cc +++ b/net/socket/tcp_client_socket.cc
@@ -28,6 +28,14 @@ namespace net { +namespace { + +void LogReadSize(int read_size) { + UMA_HISTOGRAM_COUNTS_10M("Net.TCPClientSocketReadSize", read_size); +} + +} // namespace + class NetLogWithSource; TCPClientSocket::TCPClientSocket( @@ -200,6 +208,7 @@ } else if (result > 0) { was_ever_used_ = true; total_received_bytes_ += result; + LogReadSize(result); } return result; @@ -433,6 +442,8 @@ if (was_disconnected_on_suspend_) return ERR_NETWORK_IO_SUSPENDED; + UMA_HISTOGRAM_COUNTS_10M("Net.TCPClientSocketWriteSize", buf_len); + // |socket_| is owned by this class and the callback won't be run once // |socket_| is gone. Therefore, it is safe to use base::Unretained() here. CompletionOnceCallback complete_write_callback = base::BindOnce( @@ -525,8 +536,10 @@ void TCPClientSocket::DidCompleteRead(int result) { DCHECK(!read_callback_.is_null()); - if (result > 0) + if (result > 0) { total_received_bytes_ += result; + LogReadSize(result); + } DidCompleteReadWrite(std::move(read_callback_), result); }
diff --git a/net/socket/udp_client_socket.cc b/net/socket/udp_client_socket.cc index 9da4f0f36d..8bb3c31 100644 --- a/net/socket/udp_client_socket.cc +++ b/net/socket/udp_client_socket.cc
@@ -4,6 +4,7 @@ #include "net/socket/udp_client_socket.h" +#include "base/metrics/histogram_macros.h" #include "base/task/single_thread_task_runner.h" #include "base/threading/thread_task_runner_handle.h" #include "build/build_config.h" @@ -13,6 +14,17 @@ namespace net { +namespace { + +int LogReadSize(int result) { + if (result > 0) { + UMA_HISTOGRAM_COUNTS_10M("Net.UDPClientSocketReadSize", result); + } + return result; +} + +} // namespace + UDPClientSocket::UDPClientSocket(DatagramSocket::BindType bind_type, net::NetLog* net_log, const net::NetLogSource& source, @@ -108,7 +120,8 @@ int UDPClientSocket::Read(IOBuffer* buf, int buf_len, CompletionOnceCallback callback) { - return socket_.Read(buf, buf_len, std::move(callback)); + return socket_.Read(buf, buf_len, + base::BindOnce(&LogReadSize).Then(std::move(callback))); } int UDPClientSocket::Write( @@ -116,6 +129,7 @@ int buf_len, CompletionOnceCallback callback, const NetworkTrafficAnnotationTag& traffic_annotation) { + UMA_HISTOGRAM_COUNTS_10M("Net.UDPClientSocketWriteSize", buf_len); return socket_.Write(buf, buf_len, std::move(callback), traffic_annotation); }
diff --git a/net/test/cert_builder.cc b/net/test/cert_builder.cc index b87c53b2..1f0feb1 100644 --- a/net/test/cert_builder.cc +++ b/net/test/cert_builder.cc
@@ -693,7 +693,19 @@ void CertBuilder::SetSignatureAlgorithmTLV( base::StringPiece signature_algorithm_tlv) { - signature_algorithm_tlv_ = std::string(signature_algorithm_tlv); + SetOuterSignatureAlgorithmTLV(signature_algorithm_tlv); + SetTBSSignatureAlgorithmTLV(signature_algorithm_tlv); +} + +void CertBuilder::SetOuterSignatureAlgorithmTLV( + base::StringPiece signature_algorithm_tlv) { + outer_signature_algorithm_tlv_ = std::string(signature_algorithm_tlv); + Invalidate(); +} + +void CertBuilder::SetTBSSignatureAlgorithmTLV( + base::StringPiece signature_algorithm_tlv) { + tbs_signature_algorithm_tlv_ = std::string(signature_algorithm_tlv); Invalidate(); } @@ -989,14 +1001,20 @@ signature_algorithm = DefaultSignatureAlgorithmForKey(issuer_->GetKey()); ASSERT_TRUE(signature_algorithm.has_value()); - std::string signature_algorithm_tlv = signature_algorithm_tlv_; - if (signature_algorithm_tlv.empty()) { - signature_algorithm_tlv = SignatureAlgorithmToDer(*signature_algorithm); - } + std::string signature_algorithm_tlv = + !outer_signature_algorithm_tlv_.empty() + ? outer_signature_algorithm_tlv_ + : SignatureAlgorithmToDer(*signature_algorithm); ASSERT_FALSE(signature_algorithm_tlv.empty()); + std::string tbs_signature_algorithm_tlv = + !tbs_signature_algorithm_tlv_.empty() + ? tbs_signature_algorithm_tlv_ + : SignatureAlgorithmToDer(*signature_algorithm); + ASSERT_FALSE(tbs_signature_algorithm_tlv.empty()); + std::string tbs_cert; - BuildTBSCertificate(signature_algorithm_tlv, &tbs_cert); + BuildTBSCertificate(tbs_signature_algorithm_tlv, &tbs_cert); // Sign the TBSCertificate and write the entire certificate. bssl::ScopedCBB cbb;
diff --git a/net/test/cert_builder.h b/net/test/cert_builder.h index 270d2ace..97c344af 100644 --- a/net/test/cert_builder.h +++ b/net/test/cert_builder.h
@@ -188,7 +188,8 @@ // algorithm will be used base on the signing key type. void SetSignatureAlgorithm(SignatureAlgorithm signature_algorithm); - // Sets the signature algorithm TLV to encode in the generated certificate. + // Sets both signature AlgorithmIdentifier TLVs to encode in the generated + // certificate. // This only affects the bytes written to the output - it does not affect what // algorithm is actually used to perform the signature. To set the signature // algorithm used to generate the certificate's signature, use @@ -197,6 +198,14 @@ // algorithm used to sign the certificate. void SetSignatureAlgorithmTLV(base::StringPiece signature_algorithm_tlv); + // Set only the outer Certificate signatureAlgorithm TLV. See + // SetSignatureAlgorithmTLV comment for general notes. + void SetOuterSignatureAlgorithmTLV(base::StringPiece signature_algorithm_tlv); + + // Set only the tbsCertificate signature TLV. See SetSignatureAlgorithmTLV + // comment for general notes. + void SetTBSSignatureAlgorithmTLV(base::StringPiece signature_algorithm_tlv); + void SetRandomSerialNumber(); // Sets the private key for the generated certificate to an EC key. If a key @@ -299,7 +308,8 @@ std::string validity_tlv_; std::string subject_tlv_; absl::optional<SignatureAlgorithm> signature_algorithm_; - std::string signature_algorithm_tlv_; + std::string outer_signature_algorithm_tlv_; + std::string tbs_signature_algorithm_tlv_; uint64_t serial_number_ = 0; int default_pkey_id_ = EVP_PKEY_EC;
diff --git a/remoting/host/chromeos/ash_mojom_video_consumer.cc b/remoting/host/chromeos/ash_mojom_video_consumer.cc index d1bec63..9d86dd3 100644 --- a/remoting/host/chromeos/ash_mojom_video_consumer.cc +++ b/remoting/host/chromeos/ash_mojom_video_consumer.cc
@@ -28,7 +28,7 @@ Frame& operator=(Frame&&); ~Frame(); - std::unique_ptr<webrtc::DesktopFrame> ToDesktopFrame() const; + std::unique_ptr<webrtc::DesktopFrame> ToDesktopFrame(gfx::Point origin) const; private: std::unique_ptr<SkBitmap> CreateSkBitmap() const; @@ -74,26 +74,30 @@ } std::unique_ptr<webrtc::DesktopFrame> -AshMojomVideoConsumer::Frame::ToDesktopFrame() const { +AshMojomVideoConsumer::Frame::ToDesktopFrame(gfx::Point origin) const { if (!IsValidFrame()) { return nullptr; } - int dpi = GetDpi(); + std::unique_ptr<webrtc::DesktopFrame> frame( SkiaBitmapDesktopFrame::Create(CreateSkBitmap())); - - frame->set_dpi(webrtc::DesktopVector(dpi, dpi)); + frame->set_top_left(webrtc::DesktopVector(origin.x(), origin.y())); + frame->set_dpi(webrtc::DesktopVector(GetDpi(), GetDpi())); frame->mutable_updated_region()->SetRect(GetUpdatedRect()); return frame; } webrtc::DesktopRect AshMojomVideoConsumer::Frame::GetUpdatedRect() const { - auto updated_rect = - info_->metadata.capture_update_rect.value_or(content_rect_); - return webrtc::DesktopRect::MakeLTRB(updated_rect.x(), updated_rect.y(), - updated_rect.right(), - updated_rect.bottom()); + // We must always pretend the entire frame was updated, even though the + // metadata has a |capture_update_rect| field. This is because the field + // stores the changes from the previous frame, but we can't make sure if the + // previous frame was delivered to webrtc. Hence we must mark the entire frame + // as updated, as otherwise WebRTC might not know about the areas updated in + // the previous frame. + return webrtc::DesktopRect::MakeLTRB(content_rect_.x(), content_rect_.y(), + content_rect_.right(), + content_rect_.bottom()); } int AshMojomVideoConsumer::Frame::GetDpi() const { @@ -135,12 +139,13 @@ return receiver_.BindNewPipeAndPassRemote(); } -std::unique_ptr<webrtc::DesktopFrame> AshMojomVideoConsumer::GetLatestFrame() { +std::unique_ptr<webrtc::DesktopFrame> AshMojomVideoConsumer::GetLatestFrame( + gfx::Point origin) { if (!latest_frame_) { return nullptr; } - return latest_frame_->ToDesktopFrame(); + return latest_frame_->ToDesktopFrame(origin); } void AshMojomVideoConsumer::OnFrameCaptured(
diff --git a/remoting/host/chromeos/ash_mojom_video_consumer.h b/remoting/host/chromeos/ash_mojom_video_consumer.h index 2a517051..85eb4c0 100644 --- a/remoting/host/chromeos/ash_mojom_video_consumer.h +++ b/remoting/host/chromeos/ash_mojom_video_consumer.h
@@ -9,10 +9,11 @@ #include "components/viz/host/client_frame_sink_video_capturer.h" #include "third_party/webrtc/modules/desktop_capture/desktop_frame.h" - +#include "ui/gfx/geometry/point.h" #include "ui/gfx/geometry/rect.h" namespace remoting { +using gfx::Point; using viz::mojom::FrameSinkVideoConsumerFrameCallbacks; // This class implements the FrameSinkVideoConsumer interface, binds with a @@ -27,7 +28,7 @@ mojo::PendingRemote<viz::mojom::FrameSinkVideoConsumer> Bind(); - std::unique_ptr<webrtc::DesktopFrame> GetLatestFrame(); + std::unique_ptr<webrtc::DesktopFrame> GetLatestFrame(Point origin); private: // A single frame received from the FrameSinkVideoCapturer.
diff --git a/remoting/host/chromeos/frame_sink_desktop_capturer.cc b/remoting/host/chromeos/frame_sink_desktop_capturer.cc index 4c51717..4680ddc0 100644 --- a/remoting/host/chromeos/frame_sink_desktop_capturer.cc +++ b/remoting/host/chromeos/frame_sink_desktop_capturer.cc
@@ -74,8 +74,14 @@ } void FrameSinkDesktopCapturer::CaptureFrame() { + const display::Display* source = ash_.GetDisplayForId(source_display_id_); + if (!source) { + callback_->OnCaptureResult(Result::ERROR_TEMPORARY, nullptr); + return; + } + std::unique_ptr<webrtc::DesktopFrame> frame = - video_consumer_.GetLatestFrame(); + video_consumer_.GetLatestFrame(source->bounds().origin()); if (!frame) { callback_->OnCaptureResult(Result::ERROR_TEMPORARY, nullptr); @@ -86,12 +92,21 @@ } bool FrameSinkDesktopCapturer::GetSourceList(SourceList* sources) { + NOTREACHED(); return false; } bool FrameSinkDesktopCapturer::SelectSource(SourceId id) { - // TODO(http://b/244435174): Add multimonitor Support - return false; + if (!ash_.GetDisplayForId(id)) { + return false; + } + + source_display_id_ = id; + + viz::FrameSinkId frame_sink_id = ash_.GetFrameSinkId(source_display_id_); + video_capturer_->ChangeTarget(viz::VideoCaptureTarget(frame_sink_id), + /*crop_version=*/0); + return true; } const display::Display* FrameSinkDesktopCapturer::GetSourceDisplay() {
diff --git a/remoting/host/chromeos/frame_sink_desktop_capturer_unittest.cc b/remoting/host/chromeos/frame_sink_desktop_capturer_unittest.cc index 1544fcda..23e9993a 100644 --- a/remoting/host/chromeos/frame_sink_desktop_capturer_unittest.cc +++ b/remoting/host/chromeos/frame_sink_desktop_capturer_unittest.cc
@@ -44,6 +44,7 @@ using media::VideoFrame; using media::VideoPixelFormat; using testing::Eq; +using testing::IsNull; using webrtc::DesktopCapturer; using webrtc::DesktopFrame; using webrtc::DesktopRect; @@ -53,6 +54,8 @@ namespace { constexpr int kAnyWidth = 800; constexpr int kAnyHeight = 600; + +const DisplayId kPrimarySourceId = 12345678; constexpr int kDesignLimitMaxFrames = 20; constexpr int kFramePoolCapacity = kDesignLimitMaxFrames + 1; @@ -253,7 +256,7 @@ void SetUp() override { ash_proxy().SetVideoCapturerReceiver(&video_capturer_.receiver_); - ash_proxy().AddPrimaryDisplay(); + ash_proxy().AddPrimaryDisplay(kPrimarySourceId); } void StartCapturerForTesting() { @@ -379,21 +382,18 @@ EXPECT_THAT(result.frame->dpi().y(), Eq(dpi)); } -TEST_F(FrameSinkDesktopCapturerTest, ShouldSetUpdatedRegionOfFrame) { +TEST_F(FrameSinkDesktopCapturerTest, ShouldSetUpdatedRegionToWholeFrame) { StartCapturerForTesting(); - int left = 50, top = 50, width = 250, height = 150; - - auto updated_rect = Rect(left, top, height, width); - video_capturer_.SendFrame(params().WithUpdatedRegion(updated_rect)); + Rect updated_rect{50, 50, 250, 150}; + video_capturer_.SendFrame( + params().WithSize(Size(800, 600)).WithUpdatedRegion(updated_rect)); CaptureResult result = CaptureFrame(); - auto updated_region = result.frame->updated_region(); - DesktopRegion desktop_region{ - DesktopRect::MakeLTRB(updated_rect.x(), updated_rect.y(), - updated_rect.right(), updated_rect.bottom())}; + auto expected_updated_region = result.frame->updated_region(); + DesktopRegion desktop_region{DesktopRect::MakeLTRB(0, 0, 800, 600)}; // No method to get the dimensions of updated region. - EXPECT_TRUE(updated_region.Equals(desktop_region)); + EXPECT_TRUE(expected_updated_region.Equals(desktop_region)); } TEST_F(FrameSinkDesktopCapturerTest, ShouldSetDisplayBounds) { @@ -409,4 +409,46 @@ EXPECT_EQ(frame_rect.height(), height); } +TEST_F(FrameSinkDesktopCapturerTest, ShouldUpdateSourceOnDisplayChange) { + DisplayId new_display_id = 2222; + ash_proxy().AddDisplayWithId(new_display_id); + + StartCapturerForTesting(); + const absl::optional<viz::VideoCaptureTarget> expected_target( + ash_proxy().GetFrameSinkId(new_display_id)); + + EXPECT_CALL(video_capturer_, ChangeTarget(expected_target, 0)); + bool source_updated = capturer_.SelectSource(2222); + EXPECT_TRUE(source_updated); + FlushForTesting(); + EXPECT_EQ(capturer_.GetSourceDisplay()->id(), new_display_id); +} + +TEST_F(FrameSinkDesktopCapturerTest, ShouldFailToSwitchToAnInvalidDisplay) { + StartCapturerForTesting(); + const DisplayId previous_source_id = capturer_.GetSourceDisplay()->id(); + + bool source_updated = capturer_.SelectSource(222); + + EXPECT_FALSE(source_updated); + EXPECT_EQ(capturer_.GetSourceDisplay()->id(), previous_source_id); +} + +TEST_F(FrameSinkDesktopCapturerTest, + ShouldReturnTemporaryErrorIfDisplayNotAvailable) { + StartCapturerForTesting(); + ash_proxy().AddDisplayWithId(222); + bool source_updated = capturer_.SelectSource(222); + + ash_proxy().RemoveDisplay(222); + + video_capturer_.SendFrame(); + CaptureResult result = CaptureFrame(); + + EXPECT_TRUE(source_updated); + EXPECT_THAT(result.result, + Eq(webrtc::DesktopCapturer::Result::ERROR_TEMPORARY)); + EXPECT_THAT(result.frame, IsNull()); +} + } // namespace remoting
diff --git a/remoting/host/chromeos/scoped_fake_ash_proxy.cc b/remoting/host/chromeos/scoped_fake_ash_proxy.cc index d07496ec..b21f4d5 100644 --- a/remoting/host/chromeos/scoped_fake_ash_proxy.cc +++ b/remoting/host/chromeos/scoped_fake_ash_proxy.cc
@@ -71,8 +71,9 @@ displays_.erase(it); return; } - NOTREACHED(); } + + NOTREACHED(); } ScreenshotRequest ScopedFakeAshProxy::WaitForScreenshotRequest() {
diff --git a/remoting/host/desktop_capturer_proxy.cc b/remoting/host/desktop_capturer_proxy.cc index c54de31..b78b5963 100644 --- a/remoting/host/desktop_capturer_proxy.cc +++ b/remoting/host/desktop_capturer_proxy.cc
@@ -90,7 +90,8 @@ #if BUILDFLAG(IS_CHROMEOS_ASH) if (base::FeatureList::IsEnabled( remoting::features::kEnableFrameSinkDesktopCapturerInCrd)) { - capturer_ = std::make_unique<FrameSinkDesktopCapturer>(); + capturer_ = std::make_unique<webrtc::DesktopCapturerDifferWrapper>( + std::make_unique<FrameSinkDesktopCapturer>()); } else { capturer_ = std::make_unique<webrtc::DesktopCapturerDifferWrapper>( std::make_unique<AuraDesktopCapturer>());
diff --git a/sandbox/win/src/broker_services.cc b/sandbox/win/src/broker_services.cc index a1f9d78..a7e5230 100644 --- a/sandbox/win/src/broker_services.cc +++ b/sandbox/win/src/broker_services.cc
@@ -11,6 +11,7 @@ #include <utility> #include "base/check_op.h" +#include "base/containers/contains.h" #include "base/memory/ptr_util.h" #include "base/notreached.h" #include "base/threading/platform_thread.h" @@ -185,9 +186,7 @@ // (as the key is no longer valid). We therefore check if the tracker has // already been deleted. Note that Windows may emit notifications after // 'job finished' (active process zero), so not every case is unexpected. - if (std::find_if(jobs.begin(), jobs.end(), [&](auto&& p) -> bool { - return p.get() == tracker; - }) == jobs.end()) { + if (!base::Contains(jobs, tracker, &std::unique_ptr<JobTracker>::get)) { // CHECK if job already deleted. CHECK_NE(static_cast<int>(event), JOB_OBJECT_MSG_ACTIVE_PROCESS_ZERO); // Continue to next notification otherwise.
diff --git a/services/device/compute_pressure/cpu_probe.h b/services/device/compute_pressure/cpu_probe.h index efaf0c2..3ed891fd 100644 --- a/services/device/compute_pressure/cpu_probe.h +++ b/services/device/compute_pressure/cpu_probe.h
@@ -8,6 +8,7 @@ #include <memory> #include "services/device/compute_pressure/pressure_sample.h" +#include "services/device/public/mojom/pressure_update.mojom-shared.h" namespace device {
diff --git a/services/device/compute_pressure/platform_collector.cc b/services/device/compute_pressure/platform_collector.cc index 8b77b8f..a0b6e73 100644 --- a/services/device/compute_pressure/platform_collector.cc +++ b/services/device/compute_pressure/platform_collector.cc
@@ -36,7 +36,7 @@ PlatformCollector::PlatformCollector( std::unique_ptr<CpuProbe> probe, base::TimeDelta sampling_interval, - base::RepeatingCallback<void(PressureSample)> sampling_callback) + base::RepeatingCallback<void(mojom::PressureState)> sampling_callback) : probe_task_runner_(CreateProbeTaskRunner()), probe_(std::move(probe)), sampling_interval_(sampling_interval), @@ -109,7 +109,28 @@ return; } - sampling_callback_.Run(sample); + sampling_callback_.Run(CalculateState(sample)); +} + +mojom::PressureState PlatformCollector::CalculateState( + PressureSample sample) const { + // TODO(crbug.com/1342528): A more advanced algorithm that calculates + // PressureState using PressureSample needs to be determined. + // At this moment the algorithm is the simplest possible + // with thresholds defining the state. + mojom::PressureState state = mojom::PressureState::kNominal; + if (sample.cpu_utilization < 0.3) + state = mojom::PressureState::kNominal; + else if (sample.cpu_utilization < 0.6) + state = mojom::PressureState::kFair; + else if (sample.cpu_utilization < 0.9) + state = mojom::PressureState::kSerious; + else if (sample.cpu_utilization <= 1.00) + state = mojom::PressureState::kCritical; + else + NOTREACHED() << "unexpected value: " << sample.cpu_utilization; + + return state; } } // namespace device
diff --git a/services/device/compute_pressure/platform_collector.h b/services/device/compute_pressure/platform_collector.h index 5b4bfed..d3561977 100644 --- a/services/device/compute_pressure/platform_collector.h +++ b/services/device/compute_pressure/platform_collector.h
@@ -15,6 +15,7 @@ #include "base/thread_annotations.h" #include "base/timer/timer.h" #include "services/device/compute_pressure/pressure_sample.h" +#include "services/device/public/mojom/pressure_update.mojom-shared.h" namespace device { @@ -42,7 +43,7 @@ PlatformCollector( std::unique_ptr<CpuProbe> cpu_probe, base::TimeDelta sampling_interval, - base::RepeatingCallback<void(PressureSample)> sampling_callback); + base::RepeatingCallback<void(mojom::PressureState)> sampling_callback); ~PlatformCollector(); bool has_probe() const { @@ -69,7 +70,10 @@ // Called periodically while the collector is running. void UpdateProbe(); // Called after the CpuProbe is updated. - void DidUpdateProbe(PressureSample sample); + void DidUpdateProbe(PressureSample); + + // Calculate PressureState based on PressureSample. + mojom::PressureState CalculateState(PressureSample) const; SEQUENCE_CHECKER(sequence_checker_); @@ -87,7 +91,7 @@ GUARDED_BY_CONTEXT(sequence_checker_); // Called with each sample reading. - base::RepeatingCallback<void(PressureSample)> sampling_callback_ + base::RepeatingCallback<void(mojom::PressureState)> sampling_callback_ GUARDED_BY_CONTEXT(sequence_checker_); // True if the CpuProbe state will be reported after the next update.
diff --git a/services/device/compute_pressure/platform_collector_unittest.cc b/services/device/compute_pressure/platform_collector_unittest.cc index 145c13e..08dbd4a 100644 --- a/services/device/compute_pressure/platform_collector_unittest.cc +++ b/services/device/compute_pressure/platform_collector_unittest.cc
@@ -19,7 +19,6 @@ #include "base/threading/scoped_blocking_call.h" #include "build/build_config.h" #include "services/device/compute_pressure/cpu_probe.h" -#include "services/device/compute_pressure/pressure_sample.h" #include "services/device/compute_pressure/pressure_test_support.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -52,7 +51,7 @@ return *cpu_probe; } - void CollectorCallback(PressureSample sample) { + void CollectorCallback(mojom::PressureState sample) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); samples_.push_back(sample); if (update_callback_) { @@ -71,7 +70,8 @@ std::unique_ptr<PlatformCollector> collector_; // The samples reported by the callback. - std::vector<PressureSample> samples_ GUARDED_BY_CONTEXT(sequence_checker_); + std::vector<mojom::PressureState> samples_ + GUARDED_BY_CONTEXT(sequence_checker_); private: void SetNextUpdateCallback(base::OnceClosure callback) { @@ -88,11 +88,12 @@ TEST_F(PlatformCollectorTest, EnsureStarted) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + cpu_probe().SetLastSample(PressureSample{0.9}); collector_->EnsureStarted(); WaitForUpdate(); - EXPECT_GE(samples_.size(), 1u); - EXPECT_THAT(samples_, testing::Contains(PressureSample{0.42})); + EXPECT_THAT(samples_, testing::ElementsAre(mojom::PressureState( + mojom::PressureState::kCritical))); } namespace { @@ -150,9 +151,9 @@ std::vector<PressureSample> samples = { // Value right after construction. - PressureSample{0.1}, + PressureSample{0.6}, // Value after first Update(), should be discarded. - PressureSample{0.2}, + PressureSample{0.9}, // Value after second Update(), should be reported. PressureSample{0.4}, }; @@ -166,9 +167,43 @@ collector_->EnsureStarted(); run_loop.Run(); - EXPECT_GE(samples_.size(), 1u); - EXPECT_THAT(samples_, testing::Not(testing::Contains(PressureSample{0.2}))); - EXPECT_THAT(samples_, testing::Contains(PressureSample{0.4})); + EXPECT_THAT(samples_, testing::ElementsAre( + mojom::PressureState{mojom::PressureState::kFair})); +} + +TEST_F(PlatformCollectorTest, EnsureStarted_CheckCalculateState) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + std::vector<PressureSample> samples = { + // Value right after construction. + PressureSample{0.6}, + // Value after first Update(), should be discarded. + PressureSample{0.9}, + // kNominal value after should be reported. + PressureSample{0.1}, + // kFair value should be reported. + PressureSample{0.4}, + // kSerious value should be reported. + PressureSample{0.7}, + // kCritical value should be reported. + PressureSample{0.9}, + }; + + base::RunLoop run_loop; + collector_ = std::make_unique<PlatformCollector>( + std::make_unique<StreamingCpuProbe>(samples, run_loop.QuitClosure()), + base::Milliseconds(1), + base::BindRepeating(&PlatformCollectorTest::CollectorCallback, + base::Unretained(this))); + collector_->EnsureStarted(); + run_loop.Run(); + + EXPECT_THAT(samples_, + testing::ElementsAre( + mojom::PressureState{mojom::PressureState::kNominal}, + mojom::PressureState{mojom::PressureState::kFair}, + mojom::PressureState{mojom::PressureState::kSerious}, + mojom::PressureState{mojom::PressureState::kCritical})); } TEST_F(PlatformCollectorTest, Stop_Delayed_EnsureStarted_Immediate) { @@ -179,12 +214,12 @@ collector_->Stop(); samples_.clear(); - cpu_probe().SetLastSample(PressureSample{0.25}); + cpu_probe().SetLastSample(PressureSample{0.9}); collector_->EnsureStarted(); WaitForUpdate(); - EXPECT_GE(samples_.size(), 1u); - EXPECT_THAT(samples_, testing::Contains(PressureSample{0.25})); + EXPECT_THAT(samples_, testing::ElementsAre(mojom::PressureState( + mojom::PressureState::kCritical))); } TEST_F(PlatformCollectorTest, Stop_Delayed_EnsureStarted_Delayed) { @@ -193,16 +228,15 @@ collector_->EnsureStarted(); WaitForUpdate(); collector_->Stop(); - samples_.clear(); - cpu_probe().SetLastSample(PressureSample{0.25}); + cpu_probe().SetLastSample(PressureSample{0.9}); // 10ms should be long enough to ensure that all the sampling tasks are done. base::PlatformThread::Sleep(base::Milliseconds(10)); collector_->EnsureStarted(); WaitForUpdate(); - EXPECT_GE(samples_.size(), 1u); - EXPECT_THAT(samples_, testing::Contains(PressureSample{0.25})); + EXPECT_THAT(samples_, testing::ElementsAre(mojom::PressureState( + mojom::PressureState::kCritical))); } TEST_F(PlatformCollectorTest, Stop_Immediate_EnsureStarted_Immediate) { @@ -212,12 +246,12 @@ collector_->Stop(); samples_.clear(); - cpu_probe().SetLastSample(PressureSample{0.25}); + cpu_probe().SetLastSample(PressureSample{0.9}); collector_->EnsureStarted(); WaitForUpdate(); - EXPECT_GE(samples_.size(), 1u); - EXPECT_THAT(samples_, testing::Contains(PressureSample{0.25})); + EXPECT_THAT(samples_, testing::ElementsAre(mojom::PressureState( + mojom::PressureState::kCritical))); } TEST_F(PlatformCollectorTest, Stop_Immediate_EnsureStarted_Delayed) { @@ -227,14 +261,14 @@ collector_->Stop(); samples_.clear(); - cpu_probe().SetLastSample(PressureSample{0.25}); + cpu_probe().SetLastSample(PressureSample{0.9}); // 10ms should be long enough to ensure that all the sampling tasks are done. base::PlatformThread::Sleep(base::Milliseconds(10)); collector_->EnsureStarted(); WaitForUpdate(); - EXPECT_GE(samples_.size(), 1u); - EXPECT_THAT(samples_, testing::Contains(PressureSample{0.25})); + EXPECT_THAT(samples_, testing::ElementsAre(mojom::PressureState( + mojom::PressureState::kCritical))); } } // namespace device
diff --git a/services/device/compute_pressure/pressure_manager_impl.cc b/services/device/compute_pressure/pressure_manager_impl.cc index afae5c1..0359378 100644 --- a/services/device/compute_pressure/pressure_manager_impl.cc +++ b/services/device/compute_pressure/pressure_manager_impl.cc
@@ -13,8 +13,7 @@ #include "mojo/public/cpp/bindings/pending_receiver.h" #include "services/device/compute_pressure/cpu_probe.h" #include "services/device/compute_pressure/platform_collector.h" -#include "services/device/compute_pressure/pressure_sample.h" -#include "services/device/public/mojom/pressure_state.mojom.h" +#include "services/device/public/mojom/pressure_update.mojom.h" namespace device { @@ -75,13 +74,13 @@ std::move(callback).Run(true); } -void PressureManagerImpl::UpdateClients(PressureSample sample) { +void PressureManagerImpl::UpdateClients(mojom::PressureState state) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - const mojom::PressureState state{sample.cpu_utilization}; const base::Time timestamp = base::Time::Now(); - for (auto& client : clients_) - client->PressureStateChanged(state.Clone(), timestamp); + mojom::PressureUpdate update(state, timestamp); + for (auto& client : clients_) { + client->PressureStateChanged(update.Clone()); + } } void PressureManagerImpl::OnClientRemoteDisconnected(
diff --git a/services/device/compute_pressure/pressure_manager_impl.h b/services/device/compute_pressure/pressure_manager_impl.h index be88ded6..1257563 100644 --- a/services/device/compute_pressure/pressure_manager_impl.h +++ b/services/device/compute_pressure/pressure_manager_impl.h
@@ -15,7 +15,6 @@ #include "mojo/public/cpp/bindings/receiver_set.h" #include "mojo/public/cpp/bindings/remote_set.h" #include "services/device/compute_pressure/platform_collector.h" -#include "services/device/compute_pressure/pressure_sample.h" #include "services/device/public/mojom/pressure_manager.mojom.h" namespace device { @@ -62,7 +61,7 @@ base::TimeDelta sampling_interval); // Called periodically by PlatformCollector. - void UpdateClients(PressureSample sample); + void UpdateClients(mojom::PressureState state); // Stop `collector_` once there is no client. void OnClientRemoteDisconnected(mojo::RemoteSetElementId /*id*/);
diff --git a/services/device/compute_pressure/pressure_manager_impl_unittest.cc b/services/device/compute_pressure/pressure_manager_impl_unittest.cc index 0f3e37f..e6fa3f29 100644 --- a/services/device/compute_pressure/pressure_manager_impl_unittest.cc +++ b/services/device/compute_pressure/pressure_manager_impl_unittest.cc
@@ -15,7 +15,7 @@ #include "services/device/compute_pressure/pressure_test_support.h" #include "services/device/device_service_test_base.h" #include "services/device/public/mojom/pressure_manager.mojom.h" -#include "services/device/public/mojom/pressure_state.mojom.h" +#include "services/device/public/mojom/pressure_update.mojom.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -59,19 +59,15 @@ FakePressureClient& operator=(const FakePressureClient&) = delete; // device::mojom::PressureClient implementation. - void PressureStateChanged(device::mojom::PressureStatePtr state, - base::Time timestamp) override { - updates_.emplace_back(*state, timestamp); + void PressureStateChanged(device::mojom::PressureUpdatePtr update) override { + updates_.emplace_back(*update); if (update_callback_) { std::move(update_callback_).Run(); update_callback_.Reset(); } } - const std::vector<std::pair<mojom::PressureState, base::Time>>& updates() - const { - return updates_; - } + const std::vector<mojom::PressureUpdate>& updates() const { return updates_; } void SetNextUpdateCallback(base::OnceClosure callback) { DCHECK(!update_callback_) << " already called before update received"; @@ -99,8 +95,8 @@ } private: - // Used to save pairs of PressureState and its timestamp. - std::vector<std::pair<mojom::PressureState, base::Time>> updates_; + // Used to save PressureState. + std::vector<mojom::PressureUpdate> updates_; // Used to implement WaitForUpdate(). base::OnceClosure update_callback_; @@ -146,7 +142,7 @@ client.WaitForUpdate(); ASSERT_EQ(client.updates().size(), 1u); - EXPECT_EQ(client.updates()[0].first, mojom::PressureState{0.42}); + EXPECT_EQ(client.updates()[0].state, mojom::PressureState::kFair); } TEST_F(PressureManagerImplTest, ThreeClients) { @@ -162,11 +158,11 @@ FakePressureClient::WaitForUpdates({&client1, &client2, &client3}); ASSERT_EQ(client1.updates().size(), 1u); - EXPECT_EQ(client1.updates()[0].first, mojom::PressureState{0.42}); + EXPECT_EQ(client1.updates()[0].state, mojom::PressureState::kFair); ASSERT_EQ(client2.updates().size(), 1u); - EXPECT_EQ(client2.updates()[0].first, mojom::PressureState{0.42}); + EXPECT_EQ(client2.updates()[0].state, mojom::PressureState::kFair); ASSERT_EQ(client3.updates().size(), 1u); - EXPECT_EQ(client3.updates()[0].first, mojom::PressureState{0.42}); + EXPECT_EQ(client3.updates()[0].state, mojom::PressureState::kFair); } TEST_F(PressureManagerImplTest, AddClient_NoProbe) {
diff --git a/services/device/compute_pressure/pressure_test_support.h b/services/device/compute_pressure/pressure_test_support.h index 3290bba..bdddd28f 100644 --- a/services/device/compute_pressure/pressure_test_support.h +++ b/services/device/compute_pressure/pressure_test_support.h
@@ -15,11 +15,6 @@ namespace device { -// googletest integration with PressureSample. -bool operator==(const PressureSample& lhs, const PressureSample& rhs) noexcept; - -std::ostream& operator<<(std::ostream& os, const PressureSample& sample); - // Test double for CpuProbe that always returns a predetermined value. class FakeCpuProbe : public CpuProbe { public: @@ -37,7 +32,7 @@ void SetLastSample(PressureSample sample); private: - // Bound to the sequence for Update() and LastSample(). + // Bound to the sequence for State() and LastSample(). SEQUENCE_CHECKER(sequence_checker_); base::Lock lock_;
diff --git a/services/device/public/cpp/test/scoped_pressure_manager_overrider.cc b/services/device/public/cpp/test/scoped_pressure_manager_overrider.cc index 7aca277..d4d2269 100644 --- a/services/device/public/cpp/test/scoped_pressure_manager_overrider.cc +++ b/services/device/public/cpp/test/scoped_pressure_manager_overrider.cc
@@ -6,6 +6,7 @@ #include "base/callback_helpers.h" #include "services/device/device_service.h" +#include "services/device/public/mojom/pressure_update.mojom.h" namespace device { @@ -33,10 +34,9 @@ } } -void FakePressureManager::UpdateClients(const mojom::PressureState& state, - base::Time timestamp) { +void FakePressureManager::UpdateClients(const mojom::PressureUpdate& update) { for (auto& client : clients_) - client->PressureStateChanged(state.Clone(), timestamp); + client->PressureStateChanged(update.Clone()); } void FakePressureManager::set_is_supported(bool is_supported) { @@ -54,9 +54,8 @@ } void ScopedPressureManagerOverrider::UpdateClients( - const mojom::PressureState& state, - base::Time timestamp) { - pressure_manager_->UpdateClients(state, timestamp); + const mojom::PressureUpdate& update) { + pressure_manager_->UpdateClients(update); } void ScopedPressureManagerOverrider::set_is_supported(bool is_supported) {
diff --git a/services/device/public/cpp/test/scoped_pressure_manager_overrider.h b/services/device/public/cpp/test/scoped_pressure_manager_overrider.h index ebd991e0..50f1056e 100644 --- a/services/device/public/cpp/test/scoped_pressure_manager_overrider.h +++ b/services/device/public/cpp/test/scoped_pressure_manager_overrider.h
@@ -11,7 +11,7 @@ #include "mojo/public/cpp/bindings/receiver_set.h" #include "mojo/public/cpp/bindings/remote_set.h" #include "services/device/public/mojom/pressure_manager.mojom.h" -#include "services/device/public/mojom/pressure_state.mojom.h" +#include "services/device/public/mojom/pressure_update.mojom.h" namespace device { @@ -30,7 +30,7 @@ void AddClient(mojo::PendingRemote<mojom::PressureClient> client, AddClientCallback callback) override; - void UpdateClients(const mojom::PressureState& state, base::Time timestamp); + void UpdateClients(const mojom::PressureUpdate& update); void set_is_supported(bool is_supported); @@ -50,7 +50,7 @@ ScopedPressureManagerOverrider& operator=( const ScopedPressureManagerOverrider&) = delete; - void UpdateClients(const mojom::PressureState& state, base::Time timestamp); + void UpdateClients(const mojom::PressureUpdate& update); void set_is_supported(bool is_supported);
diff --git a/services/device/public/mojom/BUILD.gn b/services/device/public/mojom/BUILD.gn index 979eec08..935a6d9 100644 --- a/services/device/public/mojom/BUILD.gn +++ b/services/device/public/mojom/BUILD.gn
@@ -25,7 +25,7 @@ "nfc_provider.mojom", "power_monitor.mojom", "pressure_manager.mojom", - "pressure_state.mojom", + "pressure_update.mojom", "public_ip_address_geolocation_provider.mojom", "screen_orientation.mojom", "screen_orientation_lock_types.mojom",
diff --git a/services/device/public/mojom/pressure_manager.mojom b/services/device/public/mojom/pressure_manager.mojom index e14e393..fe77eb1 100644 --- a/services/device/public/mojom/pressure_manager.mojom +++ b/services/device/public/mojom/pressure_manager.mojom
@@ -5,7 +5,7 @@ module device.mojom; import "mojo/public/mojom/base/time.mojom"; -import "services/device/public/mojom/pressure_state.mojom"; +import "services/device/public/mojom/pressure_update.mojom"; // This interface is used to get the PressureState. // @@ -25,5 +25,5 @@ // PressureStateChanged. interface PressureClient { // Interface used to notify PressureState changes. - PressureStateChanged(PressureState state, mojo_base.mojom.Time timestamp); + PressureStateChanged(PressureUpdate update); };
diff --git a/services/device/public/mojom/pressure_state.mojom b/services/device/public/mojom/pressure_state.mojom deleted file mode 100644 index e059500..0000000 --- a/services/device/public/mojom/pressure_state.mojom +++ /dev/null
@@ -1,13 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -module device.mojom; - -// Represents availability of compute resources. -struct PressureState { - // Average utilization of all CPU cores. - // - // Values use a scale from 0.0 (no utilization) to 1.0 (100% utilization). - double cpu_utilization; -};
diff --git a/services/device/public/mojom/pressure_update.mojom b/services/device/public/mojom/pressure_update.mojom new file mode 100644 index 0000000..802ebab --- /dev/null +++ b/services/device/public/mojom/pressure_update.mojom
@@ -0,0 +1,29 @@ +// 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. + +module device.mojom; + +import "mojo/public/mojom/base/time.mojom"; + +enum PressureState { + // Current workloads are causing minimal pressure, allowing the + // system to run at a lower clock frequency to preserve power. + kNominal, + // The system is doing fine, everything is smooth and it can + // take on additional work without issues. + kFair, + // There is some serious pressure on the system, but it is + // sustainable and the system is doing well, but it is getting + // close to its limits. + kSerious, + // The system is now about to reach its limits, but it hasn’t + // reached the limit yet. + kCritical, +}; + +// Represents availability of compute resources. +struct PressureUpdate { + PressureState state; + mojo_base.mojom.Time timestamp; +};
diff --git a/services/network/public/cpp/BUILD.gn b/services/network/public/cpp/BUILD.gn index bc61a219..20b37e13 100644 --- a/services/network/public/cpp/BUILD.gn +++ b/services/network/public/cpp/BUILD.gn
@@ -187,6 +187,8 @@ sources = [ "address_list_mojom_traits.cc", "address_list_mojom_traits.h", + "alternate_protocol_usage_mojom_traits.cc", + "alternate_protocol_usage_mojom_traits.h", "connection_endpoint_metadata_mojom_traits.cc", "connection_endpoint_metadata_mojom_traits.h", "host_resolver_endpoint_result_mojom_traits.cc",
diff --git a/services/network/public/cpp/alternate_protocol_usage_mojom_traits.cc b/services/network/public/cpp/alternate_protocol_usage_mojom_traits.cc new file mode 100644 index 0000000..5fa3783 --- /dev/null +++ b/services/network/public/cpp/alternate_protocol_usage_mojom_traits.cc
@@ -0,0 +1,67 @@ +// Copyright 2022 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "services/network/public/cpp/alternate_protocol_usage_mojom_traits.h" + +namespace mojo { + +network::mojom::AlternateProtocolUsage EnumTraits< + network::mojom::AlternateProtocolUsage, + net::AlternateProtocolUsage>::ToMojom(net::AlternateProtocolUsage input) { + switch (input) { + case net::ALTERNATE_PROTOCOL_USAGE_NO_RACE: + return network::mojom::AlternateProtocolUsage::kNoRace; + case net::ALTERNATE_PROTOCOL_USAGE_WON_RACE: + return network::mojom::AlternateProtocolUsage::kWonRace; + case net::ALTERNATE_PROTOCOL_USAGE_MAIN_JOB_WON_RACE: + return network::mojom::AlternateProtocolUsage::kMainJobWonRace; + case net::ALTERNATE_PROTOCOL_USAGE_MAPPING_MISSING: + return network::mojom::AlternateProtocolUsage::kMappingMissing; + case net::ALTERNATE_PROTOCOL_USAGE_BROKEN: + return network::mojom::AlternateProtocolUsage::kBroken; + case net::ALTERNATE_PROTOCOL_USAGE_DNS_ALPN_H3_JOB_WON_WITHOUT_RACE: + return network::mojom::AlternateProtocolUsage:: + kDnsAlpnH3JobWonWithoutRace; + case net::ALTERNATE_PROTOCOL_USAGE_DNS_ALPN_H3_JOB_WON_RACE: + return network::mojom::AlternateProtocolUsage::kDnsAlpnH3JobWonRace; + default: + return network::mojom::AlternateProtocolUsage::kUnspecifiedReason; + } +} + +bool EnumTraits<network::mojom::AlternateProtocolUsage, + net::AlternateProtocolUsage>:: + FromMojom(network::mojom::AlternateProtocolUsage input, + net::AlternateProtocolUsage* output) { + switch (input) { + case network::mojom::AlternateProtocolUsage::kNoRace: + *output = net::ALTERNATE_PROTOCOL_USAGE_NO_RACE; + return true; + case network::mojom::AlternateProtocolUsage::kWonRace: + *output = net::ALTERNATE_PROTOCOL_USAGE_WON_RACE; + return true; + case network::mojom::AlternateProtocolUsage::kMainJobWonRace: + *output = net::ALTERNATE_PROTOCOL_USAGE_MAIN_JOB_WON_RACE; + return true; + case network::mojom::AlternateProtocolUsage::kMappingMissing: + *output = net::ALTERNATE_PROTOCOL_USAGE_MAPPING_MISSING; + return true; + case network::mojom::AlternateProtocolUsage::kBroken: + *output = net::ALTERNATE_PROTOCOL_USAGE_BROKEN; + return true; + case network::mojom::AlternateProtocolUsage::kDnsAlpnH3JobWonWithoutRace: + *output = net::ALTERNATE_PROTOCOL_USAGE_DNS_ALPN_H3_JOB_WON_WITHOUT_RACE; + return true; + case network::mojom::AlternateProtocolUsage::kDnsAlpnH3JobWonRace: + *output = net::ALTERNATE_PROTOCOL_USAGE_DNS_ALPN_H3_JOB_WON_RACE; + return true; + case network::mojom::AlternateProtocolUsage::kUnspecifiedReason: + *output = net::ALTERNATE_PROTOCOL_USAGE_MAX; + return true; + default: + return false; + } +} + +} // namespace mojo \ No newline at end of file
diff --git a/services/network/public/cpp/alternate_protocol_usage_mojom_traits.h b/services/network/public/cpp/alternate_protocol_usage_mojom_traits.h new file mode 100644 index 0000000..2bdc5c1 --- /dev/null +++ b/services/network/public/cpp/alternate_protocol_usage_mojom_traits.h
@@ -0,0 +1,24 @@ +// Copyright 2022 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef SERVICES_NETWORK_PUBLIC_CPP_ALTERNATE_PROTOCOL_USAGE_MOJOM_TRAITS_H_ +#define SERVICES_NETWORK_PUBLIC_CPP_ALTERNATE_PROTOCOL_USAGE_MOJOM_TRAITS_H_ + +#include "mojo/public/cpp/bindings/enum_traits.h" +#include "net/http/alternate_protocol_usage.h" +#include "services/network/public/mojom/alternate_protocol_usage.mojom-shared.h" + +namespace mojo { +template <> +struct COMPONENT_EXPORT(NETWORK_CPP_IP_ADDRESS) + EnumTraits<network::mojom::AlternateProtocolUsage, + net::AlternateProtocolUsage> { + static network::mojom::AlternateProtocolUsage ToMojom( + net::AlternateProtocolUsage input); + static bool FromMojom(network::mojom::AlternateProtocolUsage input, + net::AlternateProtocolUsage* output); +}; +} // namespace mojo + +#endif // SERVICES_NETWORK_PUBLIC_CPP_ALTERNATE_PROTOCOL_USAGE_MOJOM_TRAITS_H_ \ No newline at end of file
diff --git a/services/network/public/cpp/devtools_observer_util.cc b/services/network/public/cpp/devtools_observer_util.cc index daedcb1..f481cbb 100644 --- a/services/network/public/cpp/devtools_observer_util.cc +++ b/services/network/public/cpp/devtools_observer_util.cc
@@ -15,9 +15,9 @@ head.response_time, head.headers, head.mime_type, head.load_timing, head.cert_status, head.encoded_data_length, head.was_in_prefetch_cache, head.was_fetched_via_service_worker, head.cache_storage_cache_name, - head.alpn_negotiated_protocol, head.was_fetched_via_spdy, - head.service_worker_response_source, head.ssl_info, head.remote_endpoint, - head.emitted_extra_info); + head.alpn_negotiated_protocol, head.alternate_protocol_usage, + head.was_fetched_via_spdy, head.service_worker_response_source, + head.ssl_info, head.remote_endpoint, head.emitted_extra_info); } mojom::URLRequestDevToolsInfoPtr ExtractDevToolsInfo(
diff --git a/services/network/public/mojom/BUILD.gn b/services/network/public/mojom/BUILD.gn index bbcebcb..da60539 100644 --- a/services/network/public/mojom/BUILD.gn +++ b/services/network/public/mojom/BUILD.gn
@@ -16,6 +16,7 @@ sources = [ "address_family.mojom", "address_list.mojom", + "alternate_protocol_usage.mojom", "connection_endpoint_metadata.mojom", "host_resolver_endpoint_result.mojom", "ip_address.mojom", @@ -71,6 +72,22 @@ "//services/network/public/cpp:ip_address_mojom_support", ] }, + { + types = [ + { + mojom = "network.mojom.AlternateProtocolUsage" + cpp = "::net::AlternateProtocolUsage" + }, + ] + traits_headers = [ + "//net/http/alternate_protocol_usage.h", + "//services/network/public/cpp/alternate_protocol_usage_mojom_traits.h", + ] + traits_public_deps = [ + "//net", + "//services/network/public/cpp:ip_address_mojom_support", + ] + }, ] cpp_typemaps = [
diff --git a/services/network/public/mojom/alternate_protocol_usage.mojom b/services/network/public/mojom/alternate_protocol_usage.mojom new file mode 100644 index 0000000..2dd258d --- /dev/null +++ b/services/network/public/mojom/alternate_protocol_usage.mojom
@@ -0,0 +1,29 @@ +// Copyright 2022 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +module network.mojom; + +// The reason why Chrome uses a specific transport protocol for HTTP semantics. +enum AlternateProtocolUsage { + // Alternate Protocol was used without racing a normal connection. + kNoRace, + // Alternate Protocol was used by winning a race with a normal connection. + kWonRace, + // Alternate Protocol was not used by losing a race with a normal connection. + kMainJobWonRace, + // Alternate Protocol was not used because no Alternate-Protocol information + // was available when the request was issued, but an Alternate-Protocol header + // was present in the response. + kMappingMissing, + // Alternate Protocol was not used because it was marked broken. + kBroken, + // HTTPS DNS protocol upgrade job was used without racing with a normal + // connection and an Alternate Protocol job. + kDnsAlpnH3JobWonWithoutRace, + // HTTPS DNS protocol upgrade job won a race with a normal connection and + // an Alternate Protocol job. + kDnsAlpnH3JobWonRace, + // When the reason is unspecified. + kUnspecifiedReason +};
diff --git a/services/network/public/mojom/devtools_observer.mojom b/services/network/public/mojom/devtools_observer.mojom index 3b6361b..a3dbf2d 100644 --- a/services/network/public/mojom/devtools_observer.mojom +++ b/services/network/public/mojom/devtools_observer.mojom
@@ -7,6 +7,7 @@ import "mojo/public/mojom/base/time.mojom"; import "mojo/public/mojom/base/unguessable_token.mojom"; import "mojo/public/mojom/base/time.mojom"; +import "services/network/public/mojom/alternate_protocol_usage.mojom"; import "services/network/public/mojom/client_security_state.mojom"; import "services/network/public/mojom/cookie_manager.mojom"; import "services/network/public/mojom/cors.mojom"; @@ -51,6 +52,7 @@ bool was_fetched_via_service_worker; string cache_storage_cache_name; string alpn_negotiated_protocol; + AlternateProtocolUsage alternate_protocol_usage; bool was_fetched_via_spdy; FetchResponseSource service_worker_response_source; SSLInfo? ssl_info;
diff --git a/services/network/public/mojom/url_response_head.mojom b/services/network/public/mojom/url_response_head.mojom index 3775a2cb..dd8e82d 100644 --- a/services/network/public/mojom/url_response_head.mojom +++ b/services/network/public/mojom/url_response_head.mojom
@@ -6,6 +6,7 @@ import "mojo/public/mojom/base/time.mojom"; import "mojo/public/mojom/base/unguessable_token.mojom"; +import "services/network/public/mojom/alternate_protocol_usage.mojom"; import "services/network/public/mojom/fetch_api.mojom"; import "services/network/public/mojom/ip_address_space.mojom"; import "services/network/public/mojom/ip_endpoint.mojom"; @@ -78,6 +79,10 @@ // ALPN protocol negotiated with the server. string alpn_negotiated_protocol; + // The reason why Chrome uses a specific transport protocol + // for HTTP semantics. + AlternateProtocolUsage alternate_protocol_usage; + // Remote address of the socket which fetched this resource. IPEndPoint remote_endpoint;
diff --git a/services/network/url_loader.cc b/services/network/url_loader.cc index cf5c26f..7e7032d 100644 --- a/services/network/url_loader.cc +++ b/services/network/url_loader.cc
@@ -1307,6 +1307,7 @@ response->was_fetched_via_spdy = response_info.was_fetched_via_spdy; response->was_alpn_negotiated = response_info.was_alpn_negotiated; response->alpn_negotiated_protocol = response_info.alpn_negotiated_protocol; + response->alternate_protocol_usage = response_info.alternate_protocol_usage; response->connection_info = response_info.connection_info; response->remote_endpoint = response_info.remote_endpoint; response->was_fetched_via_cache = url_request_->was_cached();
diff --git a/services/tracing/perfetto/privacy_filtered_fields-inl.h b/services/tracing/perfetto/privacy_filtered_fields-inl.h index 451f8e77..62feb3d 100644 --- a/services/tracing/perfetto/privacy_filtered_fields-inl.h +++ b/services/tracing/perfetto/privacy_filtered_fields-inl.h
@@ -1,4 +1,4 @@ -// Copyright 2019 The Chromium Authors +// 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. @@ -368,6 +368,10 @@ constexpr int kAndroidToolbarIndices[] = {1, 2, 3, -1}; constexpr MessageInfo kAndroidToolbar = {kAndroidToolbarIndices, nullptr}; +// Proto Message: ActiveProcesses +constexpr int kActiveProcessesIndices[] = {1, -1}; +constexpr MessageInfo kActiveProcesses = {kActiveProcessesIndices, nullptr}; + // Proto Message: TrackEvent constexpr int kTrackEventIndices[] = { 1, 2, 3, 5, 6, 9, 10, 11, 12, 16, 17, 22, @@ -375,7 +379,7 @@ 35, 36, 38, 39, 40, 41, 42, 43, 47, 48, 1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010, 1011, 1012, 1013, 1014, 1015, 1016, 1017, 1018, 1019, 1020, 1021, 1022, 1023, 1024, 1025, 1031, - 1032, 1033, 1034, 1036, 1038, 1039, 1041, -1}; + 1032, 1033, 1034, 1036, 1038, 1039, 1041, 1042, -1}; constexpr MessageInfo const* kTrackEventComplexMessages[] = { nullptr, nullptr, @@ -443,7 +447,8 @@ nullptr, &kAndroidIPC, &kChromeSqlDiagnostics, - &kAndroidToolbar}; + &kAndroidToolbar, + &kActiveProcesses}; constexpr MessageInfo kTrackEvent = {kTrackEventIndices, kTrackEventComplexMessages};
diff --git a/testing/buildbot/chromium.clang.json b/testing/buildbot/chromium.clang.json index 62f15e6..cc471b4 100644 --- a/testing/buildbot/chromium.clang.json +++ b/testing/buildbot/chromium.clang.json
@@ -1016,6 +1016,23 @@ ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, + "test": "ozone_unittests", + "test_id_prefix": "ninja://ui/ozone:ozone_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, "test": "ozone_x11_unittests", "test_id_prefix": "ninja://ui/ozone:ozone_x11_unittests/" }, @@ -8420,24 +8437,6 @@ ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, - "test": "cast_runner_integration_tests_cfv1", - "test_id_prefix": "ninja://fuchsia_web/runners:cast_runner_integration_tests_cfv1/" - }, - { - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "kvm": "1", - "os": "Ubuntu-18.04" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, "test": "cast_runner_unittests", "test_id_prefix": "ninja://fuchsia_web/runners:cast_runner_unittests/" }, @@ -10030,25 +10029,6 @@ ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, - "test": "cast_runner_integration_tests_cfv1", - "test_id_prefix": "ninja://fuchsia_web/runners:cast_runner_integration_tests_cfv1/" - }, - { - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "arm64", - "inside_docker": "1", - "os": "Ubuntu-20.04" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, "test": "cast_runner_unittests", "test_id_prefix": "ninja://fuchsia_web/runners:cast_runner_unittests/" }, @@ -11956,6 +11936,23 @@ ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, + "test": "ozone_unittests", + "test_id_prefix": "ninja://ui/ozone:ozone_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, "test": "ozone_x11_unittests", "test_id_prefix": "ninja://ui/ozone:ozone_x11_unittests/" }, @@ -13674,6 +13671,26 @@ ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, + "test": "ozone_unittests", + "test_id_prefix": "ninja://ui/ozone:ozone_unittests/" + }, + { + "args": [ + "--test-launcher-print-test-stdio=always" + ], + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, "test": "ozone_x11_unittests", "test_id_prefix": "ninja://ui/ozone:ozone_x11_unittests/" }, @@ -15299,6 +15316,23 @@ ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, + "test": "ozone_unittests", + "test_id_prefix": "ninja://ui/ozone:ozone_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, "test": "ozone_x11_unittests", "test_id_prefix": "ninja://ui/ozone:ozone_x11_unittests/" }, @@ -16880,6 +16914,24 @@ ], "service_account": "chrome-tester@chops-service-accounts.iam.gserviceaccount.com" }, + "test": "ozone_unittests", + "test_id_prefix": "ninja://ui/ozone:ozone_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04", + "pool": "chrome.tests" + } + ], + "service_account": "chrome-tester@chops-service-accounts.iam.gserviceaccount.com" + }, "test": "ozone_x11_unittests", "test_id_prefix": "ninja://ui/ozone:ozone_x11_unittests/" }, @@ -19142,6 +19194,23 @@ ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, + "test": "ozone_unittests", + "test_id_prefix": "ninja://ui/ozone:ozone_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, "test": "ozone_x11_unittests", "test_id_prefix": "ninja://ui/ozone:ozone_x11_unittests/" }, @@ -20682,6 +20751,23 @@ ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, + "test": "ozone_unittests", + "test_id_prefix": "ninja://ui/ozone:ozone_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, "test": "ozone_x11_unittests", "test_id_prefix": "ninja://ui/ozone:ozone_x11_unittests/" },
diff --git a/testing/buildbot/chromium.fuchsia.fyi.json b/testing/buildbot/chromium.fuchsia.fyi.json index 4055cfdd..aa5a4cd 100644 --- a/testing/buildbot/chromium.fuchsia.fyi.json +++ b/testing/buildbot/chromium.fuchsia.fyi.json
@@ -288,25 +288,6 @@ ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, - "test": "cast_runner_integration_tests_cfv1", - "test_id_prefix": "ninja://fuchsia_web/runners:cast_runner_integration_tests_cfv1/" - }, - { - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "arm64", - "inside_docker": "1", - "os": "Ubuntu-20.04" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, "test": "cast_runner_unittests", "test_id_prefix": "ninja://fuchsia_web/runners:cast_runner_unittests/" }, @@ -1488,25 +1469,6 @@ ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, - "test": "cast_runner_integration_tests_cfv1", - "test_id_prefix": "ninja://fuchsia_web/runners:cast_runner_integration_tests_cfv1/" - }, - { - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "arm64", - "inside_docker": "1", - "os": "Ubuntu-20.04" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, "test": "cast_runner_unittests", "test_id_prefix": "ninja://fuchsia_web/runners:cast_runner_unittests/" }, @@ -2688,25 +2650,6 @@ ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, - "test": "cast_runner_integration_tests_cfv1", - "test_id_prefix": "ninja://fuchsia_web/runners:cast_runner_integration_tests_cfv1/" - }, - { - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "arm64", - "inside_docker": "1", - "os": "Ubuntu-20.04" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, "test": "cast_runner_unittests", "test_id_prefix": "ninja://fuchsia_web/runners:cast_runner_unittests/" }, @@ -3859,24 +3802,6 @@ ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, - "test": "cast_runner_integration_tests_cfv1", - "test_id_prefix": "ninja://fuchsia_web/runners:cast_runner_integration_tests_cfv1/" - }, - { - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "kvm": "1", - "os": "Ubuntu-18.04" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, "test": "cast_runner_unittests", "test_id_prefix": "ninja://fuchsia_web/runners:cast_runner_unittests/" }, @@ -5179,24 +5104,6 @@ ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, - "test": "cast_runner_integration_tests_cfv1", - "test_id_prefix": "ninja://fuchsia_web/runners:cast_runner_integration_tests_cfv1/" - }, - { - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "kvm": "1", - "os": "Ubuntu-18.04" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, "test": "cast_runner_unittests", "test_id_prefix": "ninja://fuchsia_web/runners:cast_runner_unittests/" }, @@ -6486,24 +6393,6 @@ ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, - "test": "cast_runner_integration_tests_cfv1", - "test_id_prefix": "ninja://fuchsia_web/runners:cast_runner_integration_tests_cfv1/" - }, - { - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "kvm": "1", - "os": "Ubuntu-18.04" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, "test": "cast_runner_unittests", "test_id_prefix": "ninja://fuchsia_web/runners:cast_runner_unittests/" }, @@ -8010,24 +7899,6 @@ ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, - "test": "cast_runner_integration_tests_cfv1", - "test_id_prefix": "ninja://fuchsia_web/runners:cast_runner_integration_tests_cfv1/" - }, - { - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "kvm": "1", - "os": "Ubuntu-18.04" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, "test": "cast_runner_unittests", "test_id_prefix": "ninja://fuchsia_web/runners:cast_runner_unittests/" },
diff --git a/testing/buildbot/chromium.fuchsia.json b/testing/buildbot/chromium.fuchsia.json index 55838e2..2b42813 100644 --- a/testing/buildbot/chromium.fuchsia.json +++ b/testing/buildbot/chromium.fuchsia.json
@@ -288,25 +288,6 @@ ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, - "test": "cast_runner_integration_tests_cfv1", - "test_id_prefix": "ninja://fuchsia_web/runners:cast_runner_integration_tests_cfv1/" - }, - { - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "arm64", - "inside_docker": "1", - "os": "Ubuntu-20.04" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, "test": "cast_runner_unittests", "test_id_prefix": "ninja://fuchsia_web/runners:cast_runner_unittests/" }, @@ -1473,24 +1454,6 @@ ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, - "test": "cast_runner_integration_tests_cfv1", - "test_id_prefix": "ninja://fuchsia_web/runners:cast_runner_integration_tests_cfv1/" - }, - { - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "kvm": "1", - "os": "Ubuntu-18.04" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, "test": "cast_runner_unittests", "test_id_prefix": "ninja://fuchsia_web/runners:cast_runner_unittests/" },
diff --git a/testing/buildbot/chromium.fyi.json b/testing/buildbot/chromium.fyi.json index ad8d7e7..9180e4f5 100644 --- a/testing/buildbot/chromium.fyi.json +++ b/testing/buildbot/chromium.fyi.json
@@ -1136,6 +1136,23 @@ ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, + "test": "ozone_unittests", + "test_id_prefix": "ninja://ui/ozone:ozone_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, "test": "ozone_x11_unittests", "test_id_prefix": "ninja://ui/ozone:ozone_x11_unittests/" }, @@ -5115,6 +5132,29 @@ "hard_timeout": 7200, "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, + "test": "ozone_unittests", + "test_id_prefix": "ninja://ui/ozone:ozone_unittests/" + }, + { + "args": [ + "--test-launcher-print-test-stdio=always" + ], + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Ubuntu-20.04" + } + ], + "expiration": 10800, + "hard_timeout": 7200, + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, "test": "ozone_x11_unittests", "test_id_prefix": "ninja://ui/ozone:ozone_x11_unittests/" }, @@ -6811,6 +6851,24 @@ ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, + "test": "ozone_unittests", + "test_id_prefix": "ninja://ui/ozone:ozone_unittests/" + }, + { + "isolate_profile_data": true, + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, "test": "ozone_x11_unittests", "test_id_prefix": "ninja://ui/ozone:ozone_x11_unittests/" }, @@ -25652,29 +25710,6 @@ ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, - "test": "cast_runner_integration_tests_cfv1", - "test_id_prefix": "ninja://fuchsia_web/runners:cast_runner_integration_tests_cfv1/" - }, - { - "args": [ - "--ram-size-mb=16384", - "--code-coverage", - "--code-coverage-dir=${ISOLATED_OUTDIR}" - ], - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "os": "Ubuntu-18.04" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, "test": "cast_runner_unittests", "test_id_prefix": "ninja://fuchsia_web/runners:cast_runner_unittests/" }, @@ -27235,25 +27270,6 @@ ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, - "test": "cast_runner_integration_tests_cfv1", - "test_id_prefix": "ninja://fuchsia_web/runners:cast_runner_integration_tests_cfv1/" - }, - { - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "arm64", - "inside_docker": "1", - "os": "Ubuntu-20.04" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, "test": "cast_runner_unittests", "test_id_prefix": "ninja://fuchsia_web/runners:cast_runner_unittests/" }, @@ -28601,26 +28617,6 @@ ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, - "test": "cast_runner_integration_tests_cfv1", - "test_id_prefix": "ninja://fuchsia_web/runners:cast_runner_integration_tests_cfv1/" - }, - { - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "arm64", - "inside_docker": "1", - "os": "Ubuntu-20.04", - "pool": "chromium.tests.fuchsia" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, "test": "cast_runner_unittests", "test_id_prefix": "ninja://fuchsia_web/runners:cast_runner_unittests/" }, @@ -30068,24 +30064,6 @@ ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, - "test": "cast_runner_integration_tests_cfv1", - "test_id_prefix": "ninja://fuchsia_web/runners:cast_runner_integration_tests_cfv1/" - }, - { - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "kvm": "1", - "os": "Ubuntu-18.04" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, "test": "cast_runner_unittests", "test_id_prefix": "ninja://fuchsia_web/runners:cast_runner_unittests/" }, @@ -98745,6 +98723,27 @@ ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, + "test": "ozone_unittests", + "test_id_prefix": "ninja://ui/ozone:ozone_unittests/" + }, + { + "args": [ + "--enable-features=PartitionAllocBackupRefPtr:enabled-processes/non-renderer" + ], + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Ubuntu-18.04" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, "test": "ozone_x11_unittests", "test_id_prefix": "ninja://ui/ozone:ozone_x11_unittests/" }, @@ -104566,6 +104565,24 @@ ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, + "test": "ozone_unittests", + "test_id_prefix": "ninja://ui/ozone:ozone_unittests/" + }, + { + "isolate_profile_data": true, + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, "test": "ozone_x11_unittests", "test_id_prefix": "ninja://ui/ozone:ozone_x11_unittests/" }, @@ -112474,6 +112491,26 @@ "expiration": 43200, "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, + "test": "ozone_unittests", + "test_id_prefix": "ninja://ui/ozone:ozone_unittests/" + }, + { + "isolate_profile_data": true, + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04", + "pool": "chromium.tests.no-external-ip" + } + ], + "expiration": 43200, + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, "test": "ozone_x11_unittests", "test_id_prefix": "ninja://ui/ozone:ozone_x11_unittests/" },
diff --git a/testing/buildbot/chromium.linux.json b/testing/buildbot/chromium.linux.json index 6173da29..31b2b03 100644 --- a/testing/buildbot/chromium.linux.json +++ b/testing/buildbot/chromium.linux.json
@@ -2971,6 +2971,24 @@ ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, + "test": "ozone_unittests", + "test_id_prefix": "ninja://ui/ozone:ozone_unittests/" + }, + { + "isolate_profile_data": true, + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, "test": "ozone_x11_unittests", "test_id_prefix": "ninja://ui/ozone:ozone_x11_unittests/" }, @@ -5435,6 +5453,28 @@ ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, + "test": "ozone_unittests", + "test_id_prefix": "ninja://ui/ozone:ozone_unittests/" + }, + { + "args": [ + "--no-xvfb", + "--use-weston", + "--ozone-platform=wayland" + ], + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, "test": "pdf_unittests", "test_id_prefix": "ninja://pdf:pdf_unittests/" }, @@ -7048,6 +7088,23 @@ ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, + "test": "ozone_unittests", + "test_id_prefix": "ninja://ui/ozone:ozone_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, "test": "ozone_x11_unittests", "test_id_prefix": "ninja://ui/ozone:ozone_x11_unittests/" },
diff --git a/testing/buildbot/chromium.memory.json b/testing/buildbot/chromium.memory.json index 660f72d9..169ede6 100644 --- a/testing/buildbot/chromium.memory.json +++ b/testing/buildbot/chromium.memory.json
@@ -1220,6 +1220,26 @@ ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, + "test": "ozone_unittests", + "test_id_prefix": "ninja://ui/ozone:ozone_unittests/" + }, + { + "args": [ + "--test-launcher-print-test-stdio=always" + ], + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, "test": "ozone_x11_unittests", "test_id_prefix": "ninja://ui/ozone:ozone_x11_unittests/" }, @@ -3008,6 +3028,26 @@ ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, + "test": "ozone_unittests", + "test_id_prefix": "ninja://ui/ozone:ozone_unittests/" + }, + { + "args": [ + "--test-launcher-print-test-stdio=always" + ], + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, "test": "ozone_x11_unittests", "test_id_prefix": "ninja://ui/ozone:ozone_x11_unittests/" }, @@ -4700,6 +4740,23 @@ ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, + "test": "ozone_unittests", + "test_id_prefix": "ninja://ui/ozone:ozone_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, "test": "ozone_x11_unittests", "test_id_prefix": "ninja://ui/ozone:ozone_x11_unittests/" }, @@ -10238,6 +10295,27 @@ ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, + "test": "ozone_unittests", + "test_id_prefix": "ninja://ui/ozone:ozone_unittests/" + }, + { + "args": [ + "--test-launcher-print-test-stdio=always" + ], + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Ubuntu-16.04" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, "test": "ozone_x11_unittests", "test_id_prefix": "ninja://ui/ozone:ozone_x11_unittests/" }, @@ -12018,6 +12096,26 @@ ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, + "test": "ozone_unittests", + "test_id_prefix": "ninja://ui/ozone:ozone_unittests/" + }, + { + "args": [ + "--test-launcher-print-test-stdio=always" + ], + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, "test": "ozone_x11_unittests", "test_id_prefix": "ninja://ui/ozone:ozone_x11_unittests/" }, @@ -22466,6 +22564,23 @@ ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, + "test": "ozone_unittests", + "test_id_prefix": "ninja://ui/ozone:ozone_unittests/" + }, + { + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, "test": "ozone_x11_unittests", "test_id_prefix": "ninja://ui/ozone:ozone_x11_unittests/" },
diff --git a/testing/buildbot/gn_isolate_map.pyl b/testing/buildbot/gn_isolate_map.pyl index 725dca0..83dfa29 100644 --- a/testing/buildbot/gn_isolate_map.pyl +++ b/testing/buildbot/gn_isolate_map.pyl
@@ -327,10 +327,6 @@ "label": "//fuchsia_web/runners:cast_runner_integration_tests", "type": "console_test_launcher", }, - "cast_runner_integration_tests_cfv1": { - "label": "//fuchsia_web/runners:cast_runner_integration_tests_cfv1", - "type": "console_test_launcher", - }, "cast_runner_pkg":{ "label": "//fuchsia_web/runners:cast_runner_pkg", "type": "additional_compile_target",
diff --git a/testing/buildbot/test_suites.pyl b/testing/buildbot/test_suites.pyl index 17826aa0..158a454 100644 --- a/testing/buildbot/test_suites.pyl +++ b/testing/buildbot/test_suites.pyl
@@ -997,6 +997,7 @@ }, 'chromium_gtests_for_linux_only': { + 'ozone_unittests': {}, 'ozone_x11_unittests': {}, }, @@ -4826,7 +4827,6 @@ 'web_engine_gtests': { 'cast_runner_browsertests': {}, 'cast_runner_integration_tests': {}, - 'cast_runner_integration_tests_cfv1': {}, 'cast_runner_unittests': {}, 'web_engine_browsertests': {}, 'web_engine_integration_tests': {
diff --git a/third_party/android_deps/BUILD.gn b/third_party/android_deps/BUILD.gn index 16f6e08..104afd8 100644 --- a/third_party/android_deps/BUILD.gn +++ b/third_party/android_deps/BUILD.gn
@@ -957,10 +957,10 @@ deps = [ ":com_google_errorprone_error_prone_annotations_java", ":com_google_protobuf_protobuf_javalite_java", - ":guava_android_java", - ":material_design_java", ":org_checkerframework_checker_qual_java", ":org_jsoup_jsoup_java", + "//third_party/android_deps:guava_android_java", + "//third_party/android_deps:material_design_java", "//third_party/androidx:androidx_core_core_java", "//third_party/androidx:androidx_test_services_storage_java", "//third_party/hamcrest:hamcrest_core_java",
diff --git a/third_party/android_deps/buildSrc/src/main/groovy/BuildConfigGenerator.groovy b/third_party/android_deps/buildSrc/src/main/groovy/BuildConfigGenerator.groovy index 17db9c1..054b7d9 100644 --- a/third_party/android_deps/buildSrc/src/main/groovy/BuildConfigGenerator.groovy +++ b/third_party/android_deps/buildSrc/src/main/groovy/BuildConfigGenerator.groovy
@@ -482,13 +482,13 @@ depsStr += "\"${existingLib}\"," } } else if (dep.id == 'com_google_android_material_material') { - // Material design is pulled in via doubledown, should - // use the variable instead of the real target. - depsStr += '":material_design_java",' + // Material design is pulled in via doubledown, should use the + // alias instead of the real target. + depsStr += "\"//third_party/android_deps:material_design_java\"," } else if (dep.id == 'com_google_guava_guava_android') { - // guava is pulled in via doubledown, and should - // use the variable instead of the real target. - depsStr += '":guava_android_java",' + // guava is pulled in via doubledown, and should use the alias + // instead of the real target. + depsStr += "\"//third_party/android_deps:guava_android_java\"," } else if (excludeDependency(dep)) { String thirdPartyDir = (dep.id.startsWith('androidx')) ? 'androidx' : 'android_deps' depsStr += "\"//third_party/${thirdPartyDir}:${depTargetName}\","
diff --git a/third_party/blink/public/devtools_protocol/browser_protocol.pdl b/third_party/blink/public/devtools_protocol/browser_protocol.pdl index f33b092..8fd2703 100644 --- a/third_party/blink/public/devtools_protocol/browser_protocol.pdl +++ b/third_party/blink/public/devtools_protocol/browser_protocol.pdl
@@ -5256,6 +5256,30 @@ # Type "send-redemption-record" in the Trust Token API. Signing + # The reason why Chrome uses a specific transport protocol for HTTP semantics. + experimental type AlternateProtocolUsage extends string + enum + # Alternate Protocol was used without racing a normal connection. + alternativeJobWonWithoutRace + # Alternate Protocol was used by winning a race with a normal connection. + alternativeJobWonRace + # Alternate Protocol was not used by losing a race with a normal connection. + mainJobWonRace + # Alternate Protocol was not used because no Alternate-Protocol information + # was available when the request was issued, but an Alternate-Protocol header + # was present in the response. + mappingMissing + # Alternate Protocol was not used because it was marked broken. + broken + # HTTPS DNS protocol upgrade job was used without racing with a normal + # connection and an Alternate Protocol job. + dnsAlpnH3JobWonWithoutRace + # HTTPS DNS protocol upgrade job won a race with a normal connection and + # an Alternate Protocol job. + dnsAlpnH3JobWonRace + # When the reason is unspecified. + unspecifiedReason + # HTTP response data. type Response extends object properties @@ -5301,6 +5325,8 @@ optional string cacheStorageCacheName # Protocol used to fetch this request. optional string protocol + # The reason why Chrome uses a specific transport protocol for HTTP semantics. + experimental optional AlternateProtocolUsage alternateProtocolUsage # Security state of the request resource. Security.SecurityState securityState # Security details for the request.
diff --git a/third_party/blink/public/mojom/compute_pressure/pressure_service.mojom b/third_party/blink/public/mojom/compute_pressure/pressure_service.mojom index d5a421a..95415e7 100644 --- a/third_party/blink/public/mojom/compute_pressure/pressure_service.mojom +++ b/third_party/blink/public/mojom/compute_pressure/pressure_service.mojom
@@ -4,42 +4,20 @@ module blink.mojom; -import "services/device/public/mojom/pressure_state.mojom"; - -// Specifies a quantization scheme for the data in a PressureState. -// -// Each array of thresholds subdivides the interval [0.0, 1.0]. The array must -// not contain the 0.0 and 1.0 values, as they are implied. For example, the -// array {0.2, 0.5, 0.8} specifies the sub-intervals [0.0, 0.2], [0.2, 0.5], -// [0.5, 0.8], and [0.8, 1.0]. The thresholds in an array must be sorted. -// -// A value is quantized by replacing it with the center of the interval that it -// falls in. For example, a CPU utilization quantizing scheme that matches the -// example above would report a CPU utilization value of 0.51 as 0.65. This is -// because 0.51 falls in the sub-interval [0.5, 0.8], and the center of that -// interval is 0.65, the average of 0.5 and 0.8. -struct PressureQuantization { - array<double> cpu_utilization_thresholds; -}; - -// The maximum size of PressureQuantization.cpu_utilization_thresholds. -const int32 kMaxPressureCpuUtilizationThresholds = 3; +import "services/device/public/mojom/pressure_update.mojom"; // Implemented by renderers to receive compute pressure info from the browser. // -// The values in the PressureState reported to the renderer are always -// quantized according to a PressureQuantization scheme. interface PressureObserver { // Called in the following circumstances. // // 1. Once after an observer is created. - // 2. When the (quantized) PressureState differs from the previously - // reported state. + // 2. When the PressureState differs from the previously reported state. // // Updates to an observer are rate-limited. Observers that belong to visible // pages receive updates at most once a second, while other observers are // limited to at most one update in 10 seconds. - OnUpdate(device.mojom.PressureState state); + OnUpdate(device.mojom.PressureUpdate update); }; // Result of PressureService.BindObserver(). @@ -59,39 +37,15 @@ kSecurityError, }; -// Result of PressureService.SetQuantization(). -enum SetQuantizationStatus { - // A valid but same PressureQuantization is used. - kUnchanged, - - // A valid but different PressureQuantization is used. - kChanged, -}; - // The interface is implemented in the browser and consumed by renderers. The // interface is only accessible to frames (and not workers). Each frame that // accesses the API creates a separate connection. interface PressureService { // Subscribes to updates on the device's PressureState. // - // If `status` is kOk, SetQuantization() should be called to set - // quantization scheme and the reported state will be quantized - // according to the quantization scheme. - // // `observer` is active (eligible for notifications) as soon as - // SetQuantization() completes. Observation is stopped by + // binding completes. Observation is stopped by // disconnecting the mojo pipe. BindObserver(pending_remote<PressureObserver> observer) => (PressureStatus status); - - // All active observers belonging to a frame use the same `quantization` - // scheme. If `quantization` differs from the scheme used by active observers - // belonging to the same frame, the conflict is resolved by stopping all the - // frame's pre-existing active observers and call SetQuantization() to set - // the new `quantization`. In other words, after SetQuantization() completes, - // the newly created observer will be the only active observer. - // - // `quantization` must be a valid quantization scheme. - SetQuantization(PressureQuantization quantization) - => (SetQuantizationStatus status); };
diff --git a/third_party/blink/public/platform/web_url_response.h b/third_party/blink/public/platform/web_url_response.h index 08274b1..c9d3e61 100644 --- a/third_party/blink/public/platform/web_url_response.h +++ b/third_party/blink/public/platform/web_url_response.h
@@ -47,6 +47,7 @@ namespace network { namespace mojom { +enum class AlternateProtocolUsage; enum class FetchResponseSource; enum class FetchResponseType : int32_t; enum class IPAddressSpace : int32_t; @@ -218,6 +219,7 @@ void SetWasAlpnNegotiated(bool); WebString AlpnNegotiatedProtocol() const; void SetAlpnNegotiatedProtocol(const WebString&); + void SetAlternateProtocolUsage(net::AlternateProtocolUsage); bool HasAuthorizationCoveredByWildcardOnPreflight() const; void SetHasAuthorizationCoveredByWildcardOnPreflight(bool);
diff --git a/third_party/blink/renderer/bindings/generated_in_modules.gni b/third_party/blink/renderer/bindings/generated_in_modules.gni index 7b283c4d..a5f93af 100644 --- a/third_party/blink/renderer/bindings/generated_in_modules.gni +++ b/third_party/blink/renderer/bindings/generated_in_modules.gni
@@ -1320,8 +1320,12 @@ "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_presentation_connection_close_reason.h", "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_presentation_connection_state.cc", "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_presentation_connection_state.h", + "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_presentation_source_type.cc", + "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_presentation_source_type.h", "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_pressure_source.cc", "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_pressure_source.h", + "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_pressure_state.cc", + "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_pressure_state.h", "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_public_key_credential_type.cc", "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_public_key_credential_type.h", "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_push_encryption_key_name.cc",
diff --git a/third_party/blink/renderer/core/clipboard/data_transfer.cc b/third_party/blink/renderer/core/clipboard/data_transfer.cc index 13f5a14..114cab3 100644 --- a/third_party/blink/renderer/core/clipboard/data_transfer.cc +++ b/third_party/blink/renderer/core/clipboard/data_transfer.cc
@@ -318,6 +318,7 @@ void DataTransfer::OnItemListChanged() { data_store_item_list_changed_ = true; + files_->clear(); } Vector<String> DataTransfer::types() { @@ -329,19 +330,23 @@ } FileList* DataTransfer::files() const { - auto* files = MakeGarbageCollected<FileList>(); - if (!CanReadData()) - return files; + if (!CanReadData()) { + files_->clear(); + return files_; + } + + if (!files_->IsEmpty()) + return files_; for (uint32_t i = 0; i < data_object_->length(); ++i) { if (data_object_->Item(i)->Kind() == DataObjectItem::kFileKind) { Blob* blob = data_object_->Item(i)->GetAsFile(); if (auto* file = DynamicTo<File>(blob)) - files->Append(file); + files_->Append(file); } } - return files; + return files_; } void DataTransfer::setDragImage(Element* image, int x, int y) { @@ -602,7 +607,8 @@ effect_allowed_("uninitialized"), transfer_type_(type), data_object_(data_object), - data_store_item_list_changed_(true) { + data_store_item_list_changed_(true), + files_(MakeGarbageCollected<FileList>()) { data_object_->AddObserver(this); } @@ -643,6 +649,7 @@ visitor->Trace(data_object_); visitor->Trace(drag_image_); visitor->Trace(drag_image_element_); + visitor->Trace(files_); ScriptWrappable::Trace(visitor); }
diff --git a/third_party/blink/renderer/core/clipboard/data_transfer.h b/third_party/blink/renderer/core/clipboard/data_transfer.h index f2c077d..991c0bc 100644 --- a/third_party/blink/renderer/core/clipboard/data_transfer.h +++ b/third_party/blink/renderer/core/clipboard/data_transfer.h
@@ -177,6 +177,7 @@ gfx::Point drag_loc_; Member<ImageResourceContent> drag_image_; Member<Node> drag_image_element_; + Member<FileList> files_; }; } // namespace blink
diff --git a/third_party/blink/renderer/core/css/rule_feature_set.cc b/third_party/blink/renderer/core/css/rule_feature_set.cc index d64da0a4d..bf2f2ffc 100644 --- a/third_party/blink/renderer/core/css/rule_feature_set.cc +++ b/third_party/blink/renderer/core/css/rule_feature_set.cc
@@ -417,23 +417,6 @@ } } -RuleFeatureSet::~RuleFeatureSet() { - metadata_.Clear(); - class_invalidation_sets_.clear(); - attribute_invalidation_sets_.clear(); - id_invalidation_sets_.clear(); - pseudo_invalidation_sets_.clear(); - universal_sibling_invalidation_set_ = nullptr; - nth_invalidation_set_ = nullptr; - classes_in_has_argument_.clear(); - attributes_in_has_argument_.clear(); - ids_in_has_argument_.clear(); - tag_names_in_has_argument_.clear(); - universal_in_has_argument_ = false; - not_pseudo_in_has_argument_ = false; - pseudos_in_has_argument_.clear(); -} - bool RuleFeatureSet::operator==(const RuleFeatureSet& other) const { return metadata_ == other.metadata_ && InvalidationSetMapsEqual<AtomicString>( @@ -560,7 +543,7 @@ ExtractInvalidationSetFeaturesFromCompound( *selector, scope_features, kSubject, /* for_logical_combination_in_has */ false); - descendant_features.Add(scope_features); + descendant_features.Merge(scope_features); } } } @@ -841,7 +824,7 @@ if (!all_sub_selectors_have_features) continue; if (complex_features.HasFeatures()) - any_features.Add(complex_features); + any_features.Merge(complex_features); else all_sub_selectors_have_features = false; } @@ -1553,8 +1536,7 @@ metadata) == kSelectorNeverMatches) { return kSelectorNeverMatches; } - - metadata_.Add(metadata); + metadata_.Merge(metadata); UpdateInvalidationSets(selector, style_scope); return kSelectorMayMatch; @@ -1640,7 +1622,7 @@ return kSelectorMayMatch; } -void RuleFeatureSet::FeatureMetadata::Add(const FeatureMetadata& other) { +void RuleFeatureSet::FeatureMetadata::Merge(const FeatureMetadata& other) { uses_first_line_rules |= other.uses_first_line_rules; uses_window_inactive_selector |= other.uses_window_inactive_selector; max_direct_adjacent_selectors = std::max(max_direct_adjacent_selectors, @@ -1686,7 +1668,7 @@ if (other.metadata_.invalidates_parts) metadata_.invalidates_parts = true; - metadata_.Add(other.metadata_); + metadata_.Merge(other.metadata_); media_query_result_flags_.Add(other.media_query_result_flags_); for (const auto& class_name : other.classes_in_has_argument_) @@ -2013,7 +1995,7 @@ return pseudos_in_has_argument_.Contains(pseudo_type); } -void RuleFeatureSet::InvalidationSetFeatures::Add( +void RuleFeatureSet::InvalidationSetFeatures::Merge( const InvalidationSetFeatures& other) { classes.AppendVector(other.classes); attributes.AppendVector(other.attributes); @@ -2047,7 +2029,7 @@ unsigned other_size = other.Size(); if (size == 0 || (1 <= other_size && other_size < size)) { ClearFeatures(); - Add(other); + Merge(other); } }
diff --git a/third_party/blink/renderer/core/css/rule_feature_set.h b/third_party/blink/renderer/core/css/rule_feature_set.h index 9b0ccfe6..5e3aef88 100644 --- a/third_party/blink/renderer/core/css/rule_feature_set.h +++ b/third_party/blink/renderer/core/css/rule_feature_set.h
@@ -27,12 +27,10 @@ #include "third_party/blink/renderer/core/css/css_selector.h" #include "third_party/blink/renderer/core/css/invalidation/invalidation_flags.h" #include "third_party/blink/renderer/core/css/invalidation/invalidation_set.h" -#include "third_party/blink/renderer/core/css/media_query_evaluator.h" #include "third_party/blink/renderer/core/css/resolver/media_query_result.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/hash_set.h" -#include "third_party/blink/renderer/platform/wtf/text/atomic_string_hash.h" namespace blink { @@ -53,7 +51,6 @@ RuleFeatureSet() = default; RuleFeatureSet(const RuleFeatureSet&) = delete; RuleFeatureSet& operator=(const RuleFeatureSet&) = delete; - ~RuleFeatureSet(); bool operator==(const RuleFeatureSet&) const; bool operator!=(const RuleFeatureSet& o) const { return !(*this == o); } @@ -216,7 +213,7 @@ struct FeatureMetadata { DISALLOW_NEW(); - void Add(const FeatureMetadata& other); + void Merge(const FeatureMetadata& other); void Clear(); bool operator==(const FeatureMetadata&) const; bool operator!=(const FeatureMetadata& o) const { return !(*this == o); } @@ -256,7 +253,7 @@ struct InvalidationSetFeatures { DISALLOW_NEW(); - void Add(const InvalidationSetFeatures& other); + void Merge(const InvalidationSetFeatures& other); bool HasFeatures() const; bool HasIdClassOrAttribute() const;
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 d342f0e..c486ed0 100644 --- a/third_party/blink/renderer/core/inspector/inspector_network_agent.cc +++ b/third_party/blink/renderer/core/inspector/inspector_network_agent.cc
@@ -922,6 +922,35 @@ return result; } +String AlternateProtocolUsageToString( + net::AlternateProtocolUsage alternate_protocol_usage) { + switch (alternate_protocol_usage) { + case net::AlternateProtocolUsage::ALTERNATE_PROTOCOL_USAGE_NO_RACE: + return protocol::Network::AlternateProtocolUsageEnum:: + AlternativeJobWonWithoutRace; + case net::AlternateProtocolUsage::ALTERNATE_PROTOCOL_USAGE_WON_RACE: + return protocol::Network::AlternateProtocolUsageEnum:: + AlternativeJobWonRace; + case net::AlternateProtocolUsage:: + ALTERNATE_PROTOCOL_USAGE_MAIN_JOB_WON_RACE: + return protocol::Network::AlternateProtocolUsageEnum::MainJobWonRace; + case net::AlternateProtocolUsage::ALTERNATE_PROTOCOL_USAGE_MAPPING_MISSING: + return protocol::Network::AlternateProtocolUsageEnum::MappingMissing; + case net::AlternateProtocolUsage::ALTERNATE_PROTOCOL_USAGE_BROKEN: + return protocol::Network::AlternateProtocolUsageEnum::Broken; + case net::AlternateProtocolUsage:: + ALTERNATE_PROTOCOL_USAGE_DNS_ALPN_H3_JOB_WON_WITHOUT_RACE: + return protocol::Network::AlternateProtocolUsageEnum:: + DnsAlpnH3JobWonWithoutRace; + case net::AlternateProtocolUsage:: + ALTERNATE_PROTOCOL_USAGE_DNS_ALPN_H3_JOB_WON_RACE: + return protocol::Network::AlternateProtocolUsageEnum::DnsAlpnH3JobWonRace; + case net::AlternateProtocolUsage::ALTERNATE_PROTOCOL_USAGE_MAX: + return protocol::Network::AlternateProtocolUsageEnum::UnspecifiedReason; + } + return protocol::Network::AlternateProtocolUsageEnum::UnspecifiedReason; +} + static std::unique_ptr<protocol::Network::Response> BuildObjectForResourceResponse(const ResourceResponse& response, const Resource* cached_resource = nullptr, @@ -1023,6 +1052,8 @@ } } response_object->setProtocol(protocol); + response_object->setAlternateProtocolUsage( + AlternateProtocolUsageToString(response.AlternateProtocolUsage())); const absl::optional<net::SSLInfo>& ssl_info = response.GetSSLInfo(); if (ssl_info.has_value()) {
diff --git a/third_party/blink/renderer/core/layout/ng/ng_length_utils.cc b/third_party/blink/renderer/core/layout/ng/ng_length_utils.cc index e9a5085..977a3973 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_length_utils.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_length_utils.cc
@@ -73,6 +73,9 @@ if (length.IsFillAvailable()) return constraint_space.AvailableSize().inline_size == kIndefiniteSize; + if (length.IsFitContent()) + return constraint_space.AvailableSize().inline_size == kIndefiniteSize; + return false; } @@ -141,25 +144,19 @@ case Length::kMinIntrinsic: case Length::kFitContent: { DCHECK(min_max_sizes.has_value()); + if (length.IsMinContent() || length.IsMinIntrinsic()) + return min_max_sizes->min_size; + if (length.IsMaxContent()) + return min_max_sizes->max_size; + LayoutUnit available_size = constraint_space.AvailableSize().inline_size; - LayoutUnit value; - // TODO(ikilpatrick): The |IsFitContent()| might not be correct for a - // max-size, e.g. "max-width: fit-content". - if (length.IsMinContent() || length.IsMinIntrinsic() || - (length.IsFitContent() && available_size == kIndefiniteSize)) { - value = min_max_sizes->min_size; - } else if (length.IsMaxContent()) { - value = min_max_sizes->max_size; - } else { - DCHECK_GE(available_size, LayoutUnit()); - if (override_available_size != kIndefiniteSize) - available_size = override_available_size; - NGBoxStrut margins = ComputeMarginsForSelf(constraint_space, style); - LayoutUnit fill_available = - (available_size - margins.InlineSum()).ClampNegativeToZero(); - value = min_max_sizes->ShrinkToFit(fill_available); - } - return value; + DCHECK_GE(available_size, LayoutUnit()); + if (override_available_size != kIndefiniteSize) + available_size = override_available_size; + NGBoxStrut margins = ComputeMarginsForSelf(constraint_space, style); + LayoutUnit fill_available = + (available_size - margins.InlineSum()).ClampNegativeToZero(); + return min_max_sizes->ShrinkToFit(fill_available); } case Length::kDeviceWidth: case Length::kDeviceHeight: @@ -552,10 +549,12 @@ if (LIKELY(extent == kIndefiniteSize)) { if (logical_width.IsAuto()) { - logical_width = (space.IsInlineAutoBehaviorStretch() && - space.AvailableSize().inline_size != kIndefiniteSize) - ? Length::FillAvailable() - : Length::FitContent(); + if (space.AvailableSize().inline_size == kIndefiniteSize) + logical_width = Length::MinContent(); + else if (space.IsInlineAutoBehaviorStretch()) + logical_width = Length::FillAvailable(); + else + logical_width = Length::FitContent(); } extent = ResolveMainInlineLength(space, style, border_padding, MinMaxSizesFunc, logical_width);
diff --git a/third_party/blink/renderer/core/svg/svg_length_context.cc b/third_party/blink/renderer/core/svg/svg_length_context.cc index 14ab7b42..abe6a17 100644 --- a/third_party/blink/renderer/core/svg/svg_length_context.cc +++ b/third_party/blink/renderer/core/svg/svg_length_context.cc
@@ -29,6 +29,7 @@ #include "third_party/blink/renderer/core/css/css_to_length_conversion_data.h" #include "third_party/blink/renderer/core/dom/node_computed_style.h" #include "third_party/blink/renderer/core/frame/local_frame_view.h" +#include "third_party/blink/renderer/core/layout/adjust_for_absolute_zoom.h" #include "third_party/blink/renderer/core/layout/layout_object.h" #include "third_party/blink/renderer/core/style/computed_style.h" #include "third_party/blink/renderer/core/svg/svg_length.h" @@ -485,13 +486,15 @@ } float SVGLengthContext::ConvertValueFromUserUnitsToLHS(float value) const { - // TODO(crbug.com/937104): Implement. - return 0; + const ComputedStyle* style = ComputedStyleForLengthResolving(context_); + return value / AdjustForAbsoluteZoom::AdjustFloat(style->ComputedLineHeight(), + *style); } float SVGLengthContext::ConvertValueFromLHSToUserUnits(float value) const { - // TODO(crbug.com/937104): Implement. - return 0; + const ComputedStyle* style = ComputedStyleForLengthResolving(context_); + return value * AdjustForAbsoluteZoom::AdjustFloat(style->ComputedLineHeight(), + *style); } float SVGLengthContext::ConvertValueFromUserUnitsToEXS(float value) const {
diff --git a/third_party/blink/renderer/modules/accessibility/inspector_accessibility_agent.cc b/third_party/blink/renderer/modules/accessibility/inspector_accessibility_agent.cc index eea309ca..f29a57e5 100644 --- a/third_party/blink/renderer/modules/accessibility/inspector_accessibility_agent.cc +++ b/third_party/blink/renderer/modules/accessibility/inspector_accessibility_agent.cc
@@ -1047,10 +1047,6 @@ vector.emplace_back(std::move(query)); queries_.insert(&document, std::move(vector)); } - // The agent might not be enabled because querying is allowed without - // enabling the Accessibility domain. Therefore, we register the agent - // with the cache to receive the AXReadyCallback. - cache.AddInspectorAgent(this); // ScheduleVisualUpdate() ensures the lifecycle doesn't get stalled, // and therefore ensures we get the AXReadyCallback callback as soon as a11y // is clean again. @@ -1318,9 +1314,6 @@ void InspectorAccessibilityAgent::RetainAXContextForDocument( Document* document) { - if (!enabled_.Get()) { - return; - } if (!document_to_context_map_.Contains(document)) { auto context = std::make_unique<AXContext>(*document, ui::kAXModeComplete); auto& cache = To<AXObjectCacheImpl>(context->GetAXObjectCache());
diff --git a/third_party/blink/renderer/modules/compute_pressure/pressure_observer.cc b/third_party/blink/renderer/modules/compute_pressure/pressure_observer.cc index 629b68c..abf7b95 100644 --- a/third_party/blink/renderer/modules/compute_pressure/pressure_observer.cc +++ b/third_party/blink/renderer/modules/compute_pressure/pressure_observer.cc
@@ -19,76 +19,17 @@ namespace blink { PressureObserver::PressureObserver(V8PressureUpdateCallback* observer_callback, - PressureObserverOptions* normalized_options) - : observer_callback_(observer_callback), - normalized_options_(normalized_options) {} + PressureObserverOptions* options) + // TODO(crbug.com/1356529): sampleRate in PressureObserverOptions needs to + // be processed and passed to lower stacks for compute pressure + // implementation. + : observer_callback_(observer_callback), options_(options) {} PressureObserver::~PressureObserver() = default; -namespace { - -// Validates a sorted array that specifies a quantization scheme. -// -// Returns false if the array is not a valid quantization scheme. -// `exception_state` is populated in this case. -bool ValidateThresholds(const Vector<double>& thresholds, - ExceptionState& exception_state) { - double previous_threshold = 0.0; - - for (double threshold : thresholds) { - if (threshold <= 0.0) { - exception_state.ThrowTypeError("Thresholds must be greater than 0.0"); - return false; - } - - if (threshold >= 1.0) { - exception_state.ThrowTypeError("Thresholds must be less than 1.0"); - return false; - } - - DCHECK_GE(threshold, previous_threshold) << "the thresholds are not sorted"; - if (threshold == previous_threshold) { - exception_state.ThrowTypeError("Thresholds must be different"); - return false; - } - previous_threshold = threshold; - } - return true; -} - -bool NormalizeObserverOptions(PressureObserverOptions& options, - ExceptionState& exception_state) { - Vector<double> cpu_utilization_thresholds = - options.cpuUtilizationThresholds(); - if (cpu_utilization_thresholds.size() > - mojom::blink::kMaxPressureCpuUtilizationThresholds) { - cpu_utilization_thresholds.resize( - mojom::blink::kMaxPressureCpuUtilizationThresholds); - } - std::sort(cpu_utilization_thresholds.begin(), - cpu_utilization_thresholds.end()); - if (!ValidateThresholds(cpu_utilization_thresholds, exception_state)) { - DCHECK(exception_state.HadException()); - return false; - } - options.setCpuUtilizationThresholds(cpu_utilization_thresholds); - - return true; -} - -} // namespace - // static PressureObserver* PressureObserver::Create(V8PressureUpdateCallback* callback, - PressureObserverOptions* options, - ExceptionState& exception_state) { - // TODO(crbug.com/1306803): Remove this check whenever bucketing is not - // anymore in use. - if (!NormalizeObserverOptions(*options, exception_state)) { - DCHECK(exception_state.HadException()); - return nullptr; - } - + PressureObserverOptions* options) { return MakeGarbageCollected<PressureObserver>(callback, options); } @@ -151,15 +92,26 @@ void PressureObserver::Trace(blink::Visitor* visitor) const { visitor->Trace(manager_); - visitor->Trace(normalized_options_); + visitor->Trace(options_); visitor->Trace(observer_callback_); + for (const auto& last_record : last_record_map_) + visitor->Trace(last_record); visitor->Trace(records_); ScriptWrappable::Trace(visitor); } -void PressureObserver::OnUpdate(device::mojom::blink::PressureStatePtr state) { +void PressureObserver::OnUpdate(V8PressureSource::Enum source, + V8PressureState::Enum state, + DOMHighResTimeStamp timestamp) { + if (!HasChangeInData(source, state)) + return; + auto* record = PressureRecord::Create(); - record->setCpuUtilization(state->cpu_utilization); + record->setSource(V8PressureSource(source)); + record->setState(V8PressureState(state)); + record->setTime(timestamp); + + last_record_map_[static_cast<size_t>(source)] = record; // This should happen infrequently since `records_` is supposed // to be emptied at every callback invoking or takeRecords(). @@ -168,7 +120,6 @@ records_.push_back(record); DCHECK_LE(records_.size(), kMaxQueuedRecords); - observer_callback_->InvokeAndReportException(this, record, this); } @@ -179,4 +130,11 @@ return records; } +// https://wicg.github.io/compute-pressure/#dfn-has-change-in-data +bool PressureObserver::HasChangeInData(V8PressureSource::Enum source, + V8PressureState::Enum state) const { + const auto& last_record = last_record_map_[static_cast<size_t>(source)]; + return last_record ? last_record->state() != state : true; +} + } // namespace blink
diff --git a/third_party/blink/renderer/modules/compute_pressure/pressure_observer.h b/third_party/blink/renderer/modules/compute_pressure/pressure_observer.h index 79667bc..432129cb 100644 --- a/third_party/blink/renderer/modules/compute_pressure/pressure_observer.h +++ b/third_party/blink/renderer/modules/compute_pressure/pressure_observer.h
@@ -5,9 +5,11 @@ #ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_COMPUTE_PRESSURE_PRESSURE_OBSERVER_H_ #define THIRD_PARTY_BLINK_RENDERER_MODULES_COMPUTE_PRESSURE_PRESSURE_OBSERVER_H_ -#include "services/device/public/mojom/pressure_state.mojom-blink.h" +#include "services/device/public/mojom/pressure_manager.mojom-blink.h" +#include "services/device/public/mojom/pressure_update.mojom-blink.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_pressure_record.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_pressure_update_callback.h" +#include "third_party/blink/renderer/core/dom/dom_high_res_time_stamp.h" #include "third_party/blink/renderer/core/execution_context/execution_context.h" #include "third_party/blink/renderer/platform/bindings/script_wrappable.h" #include "third_party/blink/renderer/platform/heap/garbage_collected.h" @@ -33,13 +35,11 @@ DEFINE_WRAPPERTYPEINFO(); public: - PressureObserver(V8PressureUpdateCallback* observer_callback, - PressureObserverOptions* normalized_options); + PressureObserver(V8PressureUpdateCallback*, PressureObserverOptions*); ~PressureObserver() override; static PressureObserver* Create(V8PressureUpdateCallback*, - PressureObserverOptions*, - ExceptionState&); + PressureObserverOptions*); // PressureObserver IDL implementation. ScriptPromise observe(ScriptState*, V8PressureSource, ExceptionState&); @@ -55,21 +55,26 @@ void Trace(blink::Visitor*) const override; // Called by PressureObserverManager. - void OnUpdate(device::mojom::blink::PressureStatePtr state); - - const PressureObserverOptions* normalized_options() const { - return normalized_options_; - } + void OnUpdate(V8PressureSource::Enum, + V8PressureState::Enum, + DOMHighResTimeStamp); private: + // Verifies if there is data change in between last update and new one. + bool HasChangeInData(V8PressureSource::Enum, V8PressureState::Enum) const; + // Manages registered observer list for each source. WeakMember<PressureObserverManager> manager_; // The callback that receives pressure state updates. Member<V8PressureUpdateCallback> observer_callback_; - // The quantization scheme for this observer. - Member<PressureObserverOptions> normalized_options_; + // Options for the observer. + Member<PressureObserverOptions> options_; + + // The last valid record received from the observer manager. + // Stored to avoid sending updates whenever the new record is the same. + Member<PressureRecord> last_record_map_[V8PressureSource::kEnumSize]; // Last received records from the platform collector. // The records are only collected when there is a change in the status.
diff --git a/third_party/blink/renderer/modules/compute_pressure/pressure_observer.idl b/third_party/blink/renderer/modules/compute_pressure/pressure_observer.idl index 7a411f6..b3dd4171 100644 --- a/third_party/blink/renderer/modules/compute_pressure/pressure_observer.idl +++ b/third_party/blink/renderer/modules/compute_pressure/pressure_observer.idl
@@ -14,7 +14,6 @@ SecureContext ] interface PressureObserver { [ - RaisesException, MeasureAs=PressureObserver_Constructor ] constructor(PressureUpdateCallback callback, optional PressureObserverOptions options = {});
diff --git a/third_party/blink/renderer/modules/compute_pressure/pressure_observer_manager.cc b/third_party/blink/renderer/modules/compute_pressure/pressure_observer_manager.cc index 1f41e9b..2aa043d 100644 --- a/third_party/blink/renderer/modules/compute_pressure/pressure_observer_manager.cc +++ b/third_party/blink/renderer/modules/compute_pressure/pressure_observer_manager.cc
@@ -13,8 +13,27 @@ #include "third_party/blink/renderer/platform/wtf/functional.h" #include "third_party/blink/renderer/platform/wtf/vector.h" +using device::mojom::blink::PressureState; + namespace blink { +namespace { + +V8PressureState::Enum PressureStateToV8PressureState(PressureState state) { + switch (state) { + case PressureState::kNominal: + return V8PressureState::Enum::kNominal; + case PressureState::kFair: + return V8PressureState::Enum::kFair; + case PressureState::kSerious: + return V8PressureState::Enum::kSerious; + case PressureState::kCritical: + return V8PressureState::Enum::kCritical; + } +} + +} // namespace + // static const char PressureObserverManager::kSupplementName[] = "PressureObserverManager"; @@ -54,7 +73,7 @@ registering_observers_[source_index].insert(observer); auto* resolver = MakeGarbageCollected<ScriptPromiseResolver>( script_state, exception_state.GetContext()); - + ScriptPromise promise = resolver->Promise(); EnsureServiceConnection(); if (!receiver_.is_bound()) { // Not connected to the browser process yet. Make the binding. @@ -68,17 +87,10 @@ receiver_.set_disconnect_handler(WTF::BindOnce( &PressureObserverManager::Reset, WrapWeakPersistent(this))); } else { - // Already connected to the browser process, just change the quantization - // options if necessary. - auto mojo_options = mojom::blink::PressureQuantization::New( - observer->normalized_options()->cpuUtilizationThresholds()); - pressure_service_->SetQuantization( - std::move(mojo_options), - resolver->WrapCallbackInScriptScope(WTF::BindOnce( - &PressureObserverManager::DidSetQuantization, - WrapWeakPersistent(this), source, WrapPersistent(observer)))); + DidBindObserver(source, observer, resolver, + mojom::blink::PressureStatus::kOk); } - return resolver->Promise(); + return promise; } void PressureObserverManager::RemoveObserver( @@ -117,7 +129,7 @@ } void PressureObserverManager::OnUpdate( - device::mojom::blink::PressureStatePtr state) { + device::mojom::blink::PressureUpdatePtr update) { // TODO(crbug.com/1342184): Consider other sources. // For now, "cpu" is the only source. const wtf_size_t source_index = @@ -127,12 +139,14 @@ // to safely iterate. HeapVector<Member<blink::PressureObserver>> observers; CopyToVector(registered_observers_[source_index], observers); - for (const auto& observer : observers) - observer->OnUpdate(state.Clone()); - - // Last reported state is saved for next registered observer - // if next upcoming state is filtered by the browser. - last_reported_state_ = state.Clone(); + for (const auto& observer : observers) { + // TODO(crbug.com/1342184): Consider other sources. + // For now, "cpu" is the only source. + observer->OnUpdate( + V8PressureSource::Enum::kCpu, + PressureStateToV8PressureState(update->state), + static_cast<DOMHighResTimeStamp>(update->timestamp.ToDoubleT())); + } } void PressureObserverManager::Trace(blink::Visitor* visitor) const { @@ -203,13 +217,10 @@ switch (status) { case mojom::blink::PressureStatus::kOk: { - auto mojo_options = mojom::blink::PressureQuantization::New( - observer->normalized_options()->cpuUtilizationThresholds()); - pressure_service_->SetQuantization( - std::move(mojo_options), - resolver->WrapCallbackInScriptScope(WTF::BindOnce( - &PressureObserverManager::DidSetQuantization, - WrapWeakPersistent(this), source, WrapPersistent(observer)))); + const wtf_size_t source_index = static_cast<wtf_size_t>(source.AsEnum()); + registering_observers_[source_index].erase(observer); + registered_observers_[source_index].insert(observer); + resolver->Resolve(); break; } case mojom::blink::PressureStatus::kNotSupported: { @@ -228,34 +239,4 @@ } } -void PressureObserverManager::DidSetQuantization( - V8PressureSource source, - blink::PressureObserver* observer, - ScriptPromiseResolver* resolver, - mojom::blink::SetQuantizationStatus status) { - // unobserve/disconnect may be called before this method was called. - if (!IsRegistering(source, observer)) { - resolver->Resolve(); - return; - } - - const wtf_size_t source_index = static_cast<wtf_size_t>(source.AsEnum()); - registering_observers_[source_index].erase(observer); - - switch (status) { - case mojom::blink::SetQuantizationStatus::kChanged: - // Clear registered observers, and register latest observer. - registered_observers_[source_index].clear(); - registered_observers_[source_index].insert(observer); - resolver->Resolve(); - break; - case mojom::blink::SetQuantizationStatus::kUnchanged: - registered_observers_[source_index].insert(observer); - resolver->Resolve(); - if (last_reported_state_) - observer->OnUpdate(last_reported_state_.Clone()); - break; - } -} - } // namespace blink
diff --git a/third_party/blink/renderer/modules/compute_pressure/pressure_observer_manager.h b/third_party/blink/renderer/modules/compute_pressure/pressure_observer_manager.h index bdc67d0..b3947064 100644 --- a/third_party/blink/renderer/modules/compute_pressure/pressure_observer_manager.h +++ b/third_party/blink/renderer/modules/compute_pressure/pressure_observer_manager.h
@@ -52,7 +52,7 @@ void ContextLifecycleStateChanged(mojom::blink::FrameLifecycleState) override; // mojom::blink::PressureObserver implementation. - void OnUpdate(device::mojom::blink::PressureStatePtr) override; + void OnUpdate(device::mojom::blink::PressureUpdatePtr) override; // GarbageCollected implementation. void Trace(Visitor*) const override; @@ -75,16 +75,8 @@ ScriptPromiseResolver*, mojom::blink::PressureStatus); - void DidSetQuantization(V8PressureSource, - blink::PressureObserver*, - ScriptPromiseResolver*, - mojom::blink::SetQuantizationStatus); - constexpr static size_t kPressureSourceSize = V8PressureSource::kEnumSize; - // Copy of the last reported state from the platform collector. - device::mojom::blink::PressureStatePtr last_reported_state_ = nullptr; - // Connection to the browser-side implementation. HeapMojoRemote<mojom::blink::PressureService> pressure_service_;
diff --git a/third_party/blink/renderer/modules/compute_pressure/pressure_observer_options.idl b/third_party/blink/renderer/modules/compute_pressure/pressure_observer_options.idl index 2c6f389..6e8323f 100644 --- a/third_party/blink/renderer/modules/compute_pressure/pressure_observer_options.idl +++ b/third_party/blink/renderer/modules/compute_pressure/pressure_observer_options.idl
@@ -7,5 +7,5 @@ Exposed=Window, SecureContext ] dictionary PressureObserverOptions { - sequence<double> cpuUtilizationThresholds = []; + double sampleRate; };
diff --git a/third_party/blink/renderer/modules/compute_pressure/pressure_record.idl b/third_party/blink/renderer/modules/compute_pressure/pressure_record.idl index 25201916..654733c 100644 --- a/third_party/blink/renderer/modules/compute_pressure/pressure_record.idl +++ b/third_party/blink/renderer/modules/compute_pressure/pressure_record.idl
@@ -2,12 +2,21 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +// https://wicg.github.io/compute-pressure/#dom-pressurestate +enum PressureState { + "nominal", + "fair", + "serious", + "critical" +}; + // https://wicg.github.io/compute-pressure/#dom-pressurerecord [ Exposed=Window, SecureContext ] dictionary PressureRecord { - // TODO(crbug.com/1308316): Remove cpuUtilization when switching - // to new API. - double cpuUtilization; + PressureSource source; + PressureState state; + DOMHighResTimeStamp time; + // TODO(crbug.com/1356191): Implement factors. };
diff --git a/third_party/blink/renderer/modules/presentation/presentation_request.cc b/third_party/blink/renderer/modules/presentation/presentation_request.cc index ec11b96..c86d97ac 100644 --- a/third_party/blink/renderer/modules/presentation/presentation_request.cc +++ b/third_party/blink/renderer/modules/presentation/presentation_request.cc
@@ -8,6 +8,7 @@ #include "third_party/blink/renderer/bindings/core/v8/script_promise.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h" +#include "third_party/blink/renderer/bindings/modules/v8/v8_capture_latency.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_presentation_source.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_union_presentationsource_usvstring.h" #include "third_party/blink/renderer/core/dom/dom_exception.h" @@ -36,6 +37,50 @@ url.ProtocolIs("cast-dial"); } +int GetPlayoutDelay(const PresentationSource& source) { + if (!source.hasLatencyHint()) { + return 400; + } + switch (source.latencyHint()->AsEnum()) { + case V8CaptureLatency::Enum::kLow: + return 200; + case V8CaptureLatency::Enum::kDefault: + return 400; + case V8CaptureLatency::Enum::kHigh: + return 800; + } +} + +KURL CreateMirroringUrl(const PresentationSource& source) { + int capture_audio = !source.hasAudioPlayback() || + (source.audioPlayback()->AsEnum() == + V8AudioPlaybackDestination::Enum::kReceiver) + ? 1 + : 0; + int playout_delay = GetPlayoutDelay(source); + // TODO(crbug.com/1267372): Instead of converting a mirroring source into a + // URL with a hardcoded Cast receiver app ID, pass the source object directly + // to the embedder. + return KURL( + String::Format("cast:0F5096E8?streamingCaptureAudio=%d&" + "streamingTargetPlayoutDelayMillis=%d", + capture_audio, playout_delay)); +} + +KURL CreateUrlFromSource(const ExecutionContext& execution_context, + const PresentationSource& source) { + if (!source.hasType()) { + return KURL(); + } + switch (source.type().AsEnum()) { + case V8PresentationSourceType::Enum::kUrl: + return source.hasUrl() ? KURL(execution_context.Url(), source.url()) + : KURL(); + case V8PresentationSourceType::Enum::kMirroring: + return CreateMirroringUrl(source); + } +} + } // anonymous namespace // static @@ -68,9 +113,22 @@ Vector<KURL> parsed_urls; for (const auto& source : sources) { if (source->IsPresentationSource()) { - exception_state.ThrowDOMException(DOMExceptionCode::kNotSupportedError, - "You must pass in valid URL strings."); - return nullptr; + if (!RuntimeEnabledFeatures::SiteInitiatedMirroringEnabled()) { + exception_state.ThrowDOMException( + DOMExceptionCode::kNotSupportedError, + "You must pass in valid URL strings."); + return nullptr; + } + const KURL source_url = CreateUrlFromSource( + *execution_context, *source->GetAsPresentationSource()); + if (!source_url.IsValid()) { + exception_state.ThrowDOMException( + DOMExceptionCode::kNotSupportedError, + "You must pass in valid presentation sources."); + return nullptr; + } + parsed_urls.push_back(source_url); + continue; } DCHECK(source->IsUSVString()); const String& url = source->GetAsUSVString();
diff --git a/third_party/blink/renderer/modules/presentation/presentation_request_test.cc b/third_party/blink/renderer/modules/presentation/presentation_request_test.cc index 9e72fd2..170c27f 100644 --- a/third_party/blink/renderer/modules/presentation/presentation_request_test.cc +++ b/third_party/blink/renderer/modules/presentation/presentation_request_test.cc
@@ -10,22 +10,27 @@ #include "third_party/blink/renderer/bindings/modules/v8/v8_union_presentationsource_usvstring.h" #include "third_party/blink/renderer/core/execution_context/security_context.h" #include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h" #include "third_party/blink/renderer/platform/weborigin/kurl.h" #include "third_party/blink/renderer/platform/weborigin/security_origin.h" namespace blink { namespace { -HeapVector<Member<V8UnionPresentationSourceOrUSVString>> -CreatePresentationSources(const WTF::Vector<String>& urls) { - HeapVector<Member<V8UnionPresentationSourceOrUSVString>> sources; - for (const String& url : urls) { - PresentationSource* source = PresentationSource::Create(); - source->setUrl(url); - sources.push_back( - MakeGarbageCollected<V8UnionPresentationSourceOrUSVString>(source)); - } - return sources; +Member<V8UnionPresentationSourceOrUSVString> CreatePresentationSource( + const String& url) { + PresentationSource* source = PresentationSource::Create(); + source->setType(V8PresentationSourceType::Enum::kUrl); + source->setUrl(url); + return MakeGarbageCollected<V8UnionPresentationSourceOrUSVString>(source); +} + +Member<V8UnionPresentationSourceOrUSVString> CreateMirroringSource() { + PresentationSource* source = PresentationSource::Create(); + source->setType(V8PresentationSourceType::Enum::kMirroring); + source->setAudioPlayback(V8AudioPlaybackDestination::Enum::kReceiver); + source->setLatencyHint(V8CaptureLatency::Enum::kDefault); + return MakeGarbageCollected<V8UnionPresentationSourceOrUSVString>(source); } HeapVector<Member<V8UnionPresentationSourceOrUSVString>> CreateUrlSources( @@ -167,15 +172,48 @@ scope.GetExceptionState().CodeAs<DOMExceptionCode>()); } +// If the site-initiated mirroring feature is disabled, then we do not allow +// the PresentationSource specialization of V8UnionPresentationSourceOrUSVString +// to be used to create a PresentationRequest. TEST(PresentationRequestTest, TestPresentationSourceNotAllowed) { + ScopedSiteInitiatedMirroringForTest site_initiated_mirroring_enabled{false}; V8TestingScope scope; - PresentationRequest::Create( + PresentationRequest::Create(scope.GetExecutionContext(), + {CreatePresentationSource("https://example.com")}, + scope.GetExceptionState()); + EXPECT_TRUE(scope.GetExceptionState().HadException()); + EXPECT_EQ(DOMExceptionCode::kNotSupportedError, + scope.GetExceptionState().CodeAs<DOMExceptionCode>()); +} + +TEST(PresentationRequestTest, TestPresentationSourcesInConstructor) { + ScopedSiteInitiatedMirroringForTest site_initiated_mirroring_enabled{true}; + V8TestingScope scope; + PresentationRequest* request = PresentationRequest::Create( scope.GetExecutionContext(), - CreatePresentationSources({"https://example.com"}), + {CreatePresentationSource("https://example.com"), + CreateMirroringSource()}, scope.GetExceptionState()); - // Currently we do not allow the PresentationSource specialization of - // V8UnionPresentationSourceOrUSVString to be used to create a - // PresentationRequest. + CHECK(request); + ASSERT_FALSE(scope.GetExceptionState().HadException()); + EXPECT_EQ(static_cast<size_t>(2), request->Urls().size()); + EXPECT_TRUE(request->Urls()[0].IsValid()); + EXPECT_EQ("https://example.com/", request->Urls()[0].GetString()); + EXPECT_TRUE(request->Urls()[1].IsValid()); + // TODO(crbug.com/1267372): This makes a lot of assumptions about the + // hardcoded URL in presentation_request.cc that should be removed. + EXPECT_EQ( + "cast:0F5096E8?streamingCaptureAudio=1&streamingTargetPlayoutDelayMillis=" + "400", + request->Urls()[1].GetString()); +} + +TEST(PresentationRequestTest, TestInvalidPresentationSource) { + ScopedSiteInitiatedMirroringForTest site_initiated_mirroring_enabled{true}; + V8TestingScope scope; + PresentationRequest::Create(scope.GetExecutionContext(), + {CreatePresentationSource("invalid_url")}, + scope.GetExceptionState()); EXPECT_TRUE(scope.GetExceptionState().HadException()); EXPECT_EQ(DOMExceptionCode::kNotSupportedError, scope.GetExceptionState().CodeAs<DOMExceptionCode>());
diff --git a/third_party/blink/renderer/modules/presentation/presentation_source.idl b/third_party/blink/renderer/modules/presentation/presentation_source.idl index 249372a..151cdee9 100644 --- a/third_party/blink/renderer/modules/presentation/presentation_source.idl +++ b/third_party/blink/renderer/modules/presentation/presentation_source.idl
@@ -27,9 +27,21 @@ "controller", }; +// TODO(crbug.com/600726): Set RuntimeEnabled here if support is ever added for +// enums (currently it is a no-op). +enum PresentationSourceType { + "url", + "mirroring", +}; + [RuntimeEnabled=SiteInitiatedMirroring] dictionary PresentationSource { - required USVString url; - CaptureLatency latencyHint; - AudioPlaybackDestination audioPlayback; + required PresentationSourceType type; + + // Used if `type` is "url". + USVString? url; + + // Used if `type` is "mirroring". + CaptureLatency? latencyHint; + AudioPlaybackDestination? audioPlayback; };
diff --git a/third_party/blink/renderer/platform/exported/web_url_response.cc b/third_party/blink/renderer/platform/exported/web_url_response.cc index d1c3cf3..484d147 100644 --- a/third_party/blink/renderer/platform/exported/web_url_response.cc +++ b/third_party/blink/renderer/platform/exported/web_url_response.cc
@@ -415,6 +415,11 @@ resource_response_->SetAlpnNegotiatedProtocol(alpn_negotiated_protocol); } +void WebURLResponse::SetAlternateProtocolUsage( + const net::AlternateProtocolUsage alternate_protocol_usage) { + resource_response_->SetAlternateProtocolUsage(alternate_protocol_usage); +} + bool WebURLResponse::HasAuthorizationCoveredByWildcardOnPreflight() const { return resource_response_->HasAuthorizationCoveredByWildcardOnPreflight(); }
diff --git a/third_party/blink/renderer/platform/loader/fetch/resource_response.h b/third_party/blink/renderer/platform/loader/fetch/resource_response.h index 9c6c8308..0d3b9dbf 100644 --- a/third_party/blink/renderer/platform/loader/fetch/resource_response.h +++ b/third_party/blink/renderer/platform/loader/fetch/resource_response.h
@@ -34,6 +34,7 @@ #include "base/time/time.h" #include "net/base/ip_endpoint.h" #include "net/ssl/ssl_info.h" +#include "services/network/public/mojom/alternate_protocol_usage.mojom-shared.h" #include "services/network/public/mojom/cross_origin_embedder_policy.mojom-shared.h" #include "services/network/public/mojom/fetch_api.mojom-shared.h" #include "services/network/public/mojom/ip_address_space.mojom-shared.h" @@ -326,6 +327,13 @@ alpn_negotiated_protocol_ = value; } + net::AlternateProtocolUsage AlternateProtocolUsage() const { + return alternate_protocol_usage_; + } + void SetAlternateProtocolUsage(net::AlternateProtocolUsage value) { + alternate_protocol_usage_ = value; + } + net::HttpResponseInfo::ConnectionInfo ConnectionInfo() const { return connection_info_; } @@ -596,6 +604,10 @@ // ALPN negotiated protocol of the socket which fetched this resource. AtomicString alpn_negotiated_protocol_; + // The reason why Chrome uses a specific transport protocol for HTTP + // semantics. + net::AlternateProtocolUsage alternate_protocol_usage_; + // Information about the type of connection used to fetch this resource. net::HttpResponseInfo::ConnectionInfo connection_info_ = net::HttpResponseInfo::ConnectionInfo::CONNECTION_INFO_UNKNOWN;
diff --git a/third_party/blink/renderer/platform/loader/fetch/url_loader/web_url_loader.cc b/third_party/blink/renderer/platform/loader/fetch/url_loader/web_url_loader.cc index 5ee674fe..6452fb5 100644 --- a/third_party/blink/renderer/platform/loader/fetch/url_loader/web_url_loader.cc +++ b/third_party/blink/renderer/platform/loader/fetch/url_loader/web_url_loader.cc
@@ -736,6 +736,7 @@ response->SetWasAlpnNegotiated(head.was_alpn_negotiated); response->SetAlpnNegotiatedProtocol( WebString::FromUTF8(head.alpn_negotiated_protocol)); + response->SetAlternateProtocolUsage(head.alternate_protocol_usage); response->SetHasAuthorizationCoveredByWildcardOnPreflight( head.has_authorization_covered_by_wildcard_on_preflight); response->SetWasAlternateProtocolAvailable(
diff --git a/third_party/blink/web_tests/NeverFixTests b/third_party/blink/web_tests/NeverFixTests index 51225f2..92259eca 100644 --- a/third_party/blink/web_tests/NeverFixTests +++ b/third_party/blink/web_tests/NeverFixTests
@@ -1782,7 +1782,6 @@ crbug.com/626703 [ Win ] external/wpt/html/editing/dnd/events/historical-manual.html [ Skip ] # Remove from virtual tests when ComputePressure is turned on by default. -crbug.com/1196419 external/wpt/compute-pressure/compute_pressure_arguments.tentative.https.window.html [ Skip ] crbug.com/1196419 external/wpt/compute-pressure/compute_pressure_basic.tentative.https.window.html [ Skip ] crbug.com/1196419 external/wpt/compute-pressure/compute_pressure_detached_iframe.tentative.https.html [ Skip ] crbug.com/1196419 external/wpt/compute-pressure/compute_pressure_different_quantizations_across_iframes.tentative.https.window.html [ Skip ] @@ -1790,14 +1789,13 @@ crbug.com/1196419 external/wpt/compute-pressure/compute_pressure_disconnect.tentative.https.window.html [ Skip ] crbug.com/1196419 external/wpt/compute-pressure/compute_pressure_disconnect_idempotent.tentative.https.window.html [ Skip ] crbug.com/1196419 external/wpt/compute-pressure/compute_pressure_disconnect_immediately.tentative.https.window.html [ Skip ] +crbug.com/1196419 external/wpt/compute-pressure/compute_pressure_duplicate_updates.tentative.https.window.html [ Skip ] crbug.com/1196419 external/wpt/compute-pressure/compute_pressure_multiple_across_iframes.tentative.https.window.html [ Skip ] crbug.com/1196419 external/wpt/compute-pressure/compute_pressure_multiple.tentative.https.window.html [ Skip ] crbug.com/1196419 external/wpt/compute-pressure/compute_pressure_observe_idempotent.tentative.https.window.html [ Skip ] crbug.com/1196419 external/wpt/compute-pressure/compute_pressure_observe_unobserve_failure.tentative.https.window.html [ Skip ] crbug.com/1196419 external/wpt/compute-pressure/compute_pressure_supported_sources.tentative.https.window.html [ Skip ] crbug.com/1196419 external/wpt/compute-pressure/compute_pressure_take_records.tentative.https.window.html [ Skip ] -crbug.com/1196419 external/wpt/compute-pressure/compute_pressure_values.tentative.https.window.html [ Skip ] -crbug.com/1196419 virtual/compute-pressure/external/wpt/compute-pressure/compute_pressure_arguments.tentative.https.window.html [ Pass ] crbug.com/1196419 virtual/compute-pressure/external/wpt/compute-pressure/compute_pressure_basic.tentative.https.window.html [ Pass ] crbug.com/1196419 virtual/compute-pressure/external/wpt/compute-pressure/compute_pressure_detached_iframe.tentative.https.html [ Pass ] crbug.com/1196419 virtual/compute-pressure/external/wpt/compute-pressure/compute_pressure_different_quantizations_across_iframes.tentative.https.window.html [ Pass ] @@ -1805,13 +1803,13 @@ crbug.com/1196419 virtual/compute-pressure/external/wpt/compute-pressure/compute_pressure_disconnect.tentative.https.window.html [ Pass ] crbug.com/1196419 virtual/compute-pressure/external/wpt/compute-pressure/compute_pressure_disconnect_idempotent.tentative.https.window.html [ Pass ] crbug.com/1196419 virtual/compute-pressure/external/wpt/compute-pressure/compute_pressure_disconnect_immediately.tentative.https.window.html [ Pass ] +crbug.com/1196419 virtual/compute-pressure/external/wpt/compute-pressure/compute_pressure_duplicate_updates.tentative.https.window.html [ Pass ] crbug.com/1196419 virtual/compute-pressure/external/wpt/compute-pressure/compute_pressure_multiple_across_iframes.tentative.https.window.html [ Pass ] crbug.com/1196419 virtual/compute-pressure/external/wpt/compute-pressure/compute_pressure_multiple.tentative.https.window.html [ Pass ] crbug.com/1196419 virtual/compute-pressure/external/wpt/compute-pressure/compute_pressure_observe_idempotent.tentative.https.window.html [ Pass ] crbug.com/1196419 virtual/compute-pressure/external/wpt/compute-pressure/compute_pressure_observe_unobserve_failure.tentative.https.window.html [ Pass ] crbug.com/1196419 virtual/compute-pressure/external/wpt/compute-pressure/compute_pressure_supported_sources.tentative.https.window.html [ Pass ] crbug.com/1196419 virtual/compute-pressure/external/wpt/compute-pressure/compute_pressure_take_records.tentative.https.window.html [ Pass ] -crbug.com/1196419 virtual/compute-pressure/external/wpt/compute-pressure/compute_pressure_values.tentative.https.window.html [ Pass ] # text-orientation:upright crbug.com/1005518 external/wpt/css/css-writing-modes/table-progression-vlr-003.html [ Skip ]
diff --git a/third_party/blink/web_tests/TestExpectations b/third_party/blink/web_tests/TestExpectations index e0c3a524..d37eb6c 100644 --- a/third_party/blink/web_tests/TestExpectations +++ b/third_party/blink/web_tests/TestExpectations
@@ -1359,8 +1359,6 @@ crbug.com/240765 external/wpt/css/css-flexbox/intrinsic-size/col-wrap-008.html [ Failure ] crbug.com/240765 external/wpt/css/css-flexbox/intrinsic-size/col-wrap-009.html [ Failure ] crbug.com/240765 external/wpt/css/css-flexbox/intrinsic-size/row-wrap-001.html [ Failure ] -crbug.com/240765 external/wpt/css/css-flexbox/flex-item-transferred-sizes-padding-border-sizing.html [ Failure ] -crbug.com/240765 external/wpt/css/css-flexbox/flex-item-transferred-sizes-padding-content-sizing.html [ Failure ] # These require css-align-3 positional keywords that Blink doesn't yet support for flexbox. crbug.com/1011718 external/wpt/css/css-flexbox/flexbox-safe-overflow-position-001.html [ Failure ] @@ -7125,6 +7123,9 @@ # Sheriff 2022-09-09 crbug.com/1361956 [ Linux ] fast/dom/Element/scrollTop-scrollLeft-body.html [ Pass Timeout ] +# Investigate timeouts on bots +crbug.com/1366717 http/tests/inspector-protocol/storage/indexed-db-storage-key-track-untrack.js [ Failure Pass ] + # Disable PendingBeaconAPI related internal tests tentatively until it is # fully launched. # The ones defined in VirtualTestSuites are run instead.
diff --git a/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_8.json b/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_8.json index 456e1bc..8e21831 100644 --- a/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_8.json +++ b/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_8.json
@@ -15727,7 +15727,14 @@ }, "window-placement": { "fullscreen-companion-window-manual.tentative.https.html": [ - "4548b3ebfb3376a66e4e4c22714b8883551a9f46", + "eca205b2bf5c222e079cd61895c379cd3f13e96e", + [ + null, + {} + ] + ], + "multi-screen-fullscreen-manual.tentative.https.html": [ + "620cd6e507d9dbe8f3f43c59ae973733d7c78cd8", [ null, {} @@ -258031,7 +258038,7 @@ [] ], "fedcm-network-requests.sub.https.html.sub.headers": [ - "d1d80d2f139724a1c3a0a307948fbc9981321f1c", + "c521de644a9c40dda0ca1cb402a28666dc45e283", [] ], "federatedcredential-framed-get.sub.https-expected.txt": [ @@ -304706,7 +304713,7 @@ "non-cancelable-when-passive": { "resources": { "scrolling.js": [ - "43c693857928da167be4d0b163abde5acf2ede69", + "1d898d8c7959c26e7e9932b67b3757d0be9fe3dc", [] ], "touching.js": [ @@ -307970,7 +307977,7 @@ [] ], "event-timing-test-utils.js": [ - "7aa51b0131d551c120f8d71bf7b2d3ff17fc7b51", + "ab3f110c72d48b22e1a2350176647b322eaabeb7", [] ], "slow-image.py": [ @@ -311648,6 +311655,14 @@ "12cf0e36d35303a5936a5a1f0fba87083b219262", [] ], + "FileSystemFileHandle-move.https.any-expected.txt": [ + "241c8e224b89700d369bdc2be5a0b7352158462b", + [] + ], + "FileSystemFileHandle-move.https.any.worker-expected.txt": [ + "241c8e224b89700d369bdc2be5a0b7352158462b", + [] + ], "META.yml": [ "23d7765cdfa39689ef72ae6a0beb15b8b4292ecd", [] @@ -311784,7 +311799,7 @@ [] ], "FileSystemFileHandle-move.js": [ - "a3be9f49afd85ddd47578ba8138c9c4f1bc5b09a", + "55a254c6e89fd2d8a7924d0953479247d85311e8", [] ], "FileSystemSyncAccessHandle-flush.js": [ @@ -324123,10 +324138,6 @@ } }, "the-input-element": { - "files-expected.txt": [ - "ae5e06959e69fbe081996f1d91445cd6f477f681", - [] - ], "hidden-charset-case-sensitive-child.html": [ "92c9981a1123454af8462cea7840a099721109a0", [] @@ -337412,6 +337423,10 @@ "7674eb0ab835a1b02541a28b4ed9084e61b2e088", [] ], + "fragments-expected.txt": [ + "3b584d2684ee96c7a53deb4246f26015120a6cf0", + [] + ], "iframe-same-origin-ref.html": [ "142db741efe4502da48e1b2bc94e25cacd77d7fc", [] @@ -351424,7 +351439,7 @@ ], "resources": { "helpers.js": [ - "886098923d80e801dce753eecc91f723291bc87c", + "8ce685401ade49ac33c3f2c4e0cb63a34d4f9b15", [] ] } @@ -403370,6 +403385,13 @@ {} ] ], + "auto-010.html": [ + "021612a3aeb286f68ce2f3c896d620b75800f235", + [ + null, + {} + ] + ], "contain-intrinsic-size-028.html": [ "15e8e0e89108b112bc113d6090946307379f53e7", [ @@ -419444,7 +419466,7 @@ ], "non-cancelable-when-passive": { "non-passive-mousewheel-event-listener-on-body.html": [ - "4c40291aa0a7159f3f5569f8535730fa4b20f52f", + "e3be8dac7497603bf84e4fa2971ec6fea68768de", [ null, { @@ -419453,7 +419475,7 @@ ] ], "non-passive-mousewheel-event-listener-on-div.html": [ - "a37276b4227bd0076ca6efb776a54aeac4ffc264", + "345e8188788cedc7ad2440b28d8cebb715fdf093", [ null, { @@ -419462,7 +419484,7 @@ ] ], "non-passive-mousewheel-event-listener-on-document.html": [ - "cdbfd2346fa276871f68e8e3b2ca3a0c5c413e19", + "acca8a65dfe38b22b70ac2c2b9fc862aea2e1b15", [ null, { @@ -419471,7 +419493,7 @@ ] ], "non-passive-mousewheel-event-listener-on-root.html": [ - "c7e818e094b9b5e19f3c1fccf29662458276ba9e", + "6009ec8101db15e197a54180fff89e898b05a15e", [ null, { @@ -419480,7 +419502,7 @@ ] ], "non-passive-mousewheel-event-listener-on-window.html": [ - "6a394a2c544b793e49d392ceedbcf6e43dc89a39", + "a1aa7b32872936cec3be5ebc21de11ed65a8aa69", [ null, { @@ -419489,7 +419511,7 @@ ] ], "non-passive-touchmove-event-listener-on-body.html": [ - "d2e84de6be51dcd5a162654461269d998bf1f8cb", + "f417bdd0a6681712d9dbb8189b5bd7e18fbe96c4", [ null, { @@ -419498,7 +419520,7 @@ ] ], "non-passive-touchmove-event-listener-on-div.html": [ - "9f026ee22b60de25ca3f08b88354d33c254ee49f", + "11c9345407566d006ab73ee542a45233b27d0616", [ null, { @@ -419507,7 +419529,7 @@ ] ], "non-passive-touchmove-event-listener-on-document.html": [ - "b5b27b4f006d4176c2ea892f30eb4e54d98df7b7", + "8b95a8d492be36bcd1aced7b03ddaf7b0ecdb4ee", [ null, { @@ -419516,7 +419538,7 @@ ] ], "non-passive-touchmove-event-listener-on-root.html": [ - "c2f42cc19357f5064debc72fb17cc0be57fd8fc5", + "c41ab72bd8c645b12525f2fe9391a0baab0ae228", [ null, { @@ -419525,7 +419547,7 @@ ] ], "non-passive-touchmove-event-listener-on-window.html": [ - "dee076f9643a171113b195183d242a1ca751659e", + "3d6675c56615ebe7b51076576169cdd0e1c73510", [ null, { @@ -419534,7 +419556,7 @@ ] ], "non-passive-touchstart-event-listener-on-body.html": [ - "f4c22461017ff71ccef2ea14649bf66b305c8096", + "f6e6ecb06d9c557a55a2ee026adf050cac189fea", [ null, { @@ -419543,7 +419565,7 @@ ] ], "non-passive-touchstart-event-listener-on-div.html": [ - "ba050c0364c3993ae02e83971daff70232d702ef", + "2e7c6e6b3b6992c0f1f85c94df9afe092a316277", [ null, { @@ -419552,7 +419574,7 @@ ] ], "non-passive-touchstart-event-listener-on-document.html": [ - "a1da298e6eaa34fc227a96ce134c3d1608ef96f2", + "22fcbdc322ca27e12d0e6c152182510fbbdde4e3", [ null, { @@ -419561,7 +419583,7 @@ ] ], "non-passive-touchstart-event-listener-on-root.html": [ - "38bcf9b8a170aa03293f4399b561076f3d51cf15", + "56c51349a04f3875d38cab2a00cc5183fe1d2f9d", [ null, { @@ -419570,7 +419592,7 @@ ] ], "non-passive-touchstart-event-listener-on-window.html": [ - "3642af2bf9174afe67eacae34f340c2eb01dabf2", + "4e9d424a9ded160d8dc2b7267f9fd7472557add0", [ null, { @@ -419579,7 +419601,7 @@ ] ], "non-passive-wheel-event-listener-on-body.html": [ - "3a573407856e0e4dce8d35bd11ecff7dd74fcbe8", + "7545b98275f4741afedc64101ded0070a6ac5618", [ null, { @@ -419588,7 +419610,7 @@ ] ], "non-passive-wheel-event-listener-on-div.html": [ - "05b655ff9bccbcc0c0cfa4203ddc8d8a4bcecc00", + "8884e136368c86f81b2f4eecb0b9b4e02af41e54", [ null, { @@ -419597,7 +419619,7 @@ ] ], "non-passive-wheel-event-listener-on-document.html": [ - "6e19c832dc437532aa7923b5caa16485aafa7594", + "de6009ee3d1ba57ce75aa27ca7eb7137ae31f096", [ null, { @@ -419606,7 +419628,7 @@ ] ], "non-passive-wheel-event-listener-on-root.html": [ - "26279cbc7e0527da888380df8f2168382dc9674e", + "562635a84af797debaf53a9bedd1bd0308195733", [ null, { @@ -419615,7 +419637,7 @@ ] ], "non-passive-wheel-event-listener-on-window.html": [ - "f428e4851c1f33196b61f3ef1a5445f4982e92ba", + "75ef3b3c40d55f038670d0d8bfeac4342e257c05", [ null, { @@ -419624,7 +419646,7 @@ ] ], "passive-mousewheel-event-listener-on-body.html": [ - "1c94592482653a81dc423d42350f7659c3b3f52d", + "24f76197183fb4d650e0f26ca82762c45bb0636a", [ null, { @@ -419633,7 +419655,7 @@ ] ], "passive-mousewheel-event-listener-on-div.html": [ - "2edf612b7e0fc777caa234b0d4cb50322a37ee1e", + "b3a16e5fda4e42d5a5185b8ba4df2851a0b82b1a", [ null, { @@ -419642,7 +419664,7 @@ ] ], "passive-mousewheel-event-listener-on-document.html": [ - "4027f3fccebe7e7be62753ff362b967721faf891", + "9c0796e5501a2897e51479ebf4ce3563939a14e6", [ null, { @@ -419651,7 +419673,7 @@ ] ], "passive-mousewheel-event-listener-on-root.html": [ - "40ef488e6bf1d66edc138671edf25abf343957ea", + "20f1b9856dbd99331ffa4cb4612a4527f5fbec29", [ null, { @@ -419660,7 +419682,7 @@ ] ], "passive-mousewheel-event-listener-on-window.html": [ - "6609c2a2d7470925b792f6e64158c1f0a8c8b251", + "bed62cd86eca182e4295fd358b92194be25e5c62", [ null, { @@ -419669,7 +419691,7 @@ ] ], "passive-touchmove-event-listener-on-body.html": [ - "8077d1b033d3a9c6eba928885e8d864f93a7cd51", + "2349bad258343449b216176f7a1776ff961f0b48", [ null, { @@ -419678,7 +419700,7 @@ ] ], "passive-touchmove-event-listener-on-div.html": [ - "057474f8135cfc06e891973cb7d378659ffb1d76", + "a61b34851e99ae5a50117ac3ad17fcf55a3dbcfa", [ null, { @@ -419687,7 +419709,7 @@ ] ], "passive-touchmove-event-listener-on-document.html": [ - "60b17de63b285c6294424329be05b3fbafc4b57e", + "b49971b5b0145ec63b939d8a1effc48dfc082c65", [ null, { @@ -419696,7 +419718,7 @@ ] ], "passive-touchmove-event-listener-on-root.html": [ - "853992048987a1c25977dcd60d2df0ae6e75d28b", + "b851704590086366a3c88c0eed27926e9d6851af", [ null, { @@ -419705,7 +419727,7 @@ ] ], "passive-touchmove-event-listener-on-window.html": [ - "3e1d0d4e9eefb67ba1d351c5cee36ebb77d795cb", + "351d6ace84593511032b08b1fae6e2657a3e7a18", [ null, { @@ -419714,7 +419736,7 @@ ] ], "passive-touchstart-event-listener-on-body.html": [ - "63dd68d25605d4c4c886615575aea84abfc3784b", + "c3d2b577fd8c661005c390ac14712e5170526ede", [ null, { @@ -419723,7 +419745,7 @@ ] ], "passive-touchstart-event-listener-on-div.html": [ - "f9aba60fd0b4781e9823243ca1472be370448b4b", + "103e7f0d233a6059049e4957ae13cf67c8ebb504", [ null, { @@ -419732,7 +419754,7 @@ ] ], "passive-touchstart-event-listener-on-document.html": [ - "011b87f7b7fab5ade50f4c33521e2d9e44f2253e", + "2e4de2405fb2fb44e3eef85b2c081e5d86e3455f", [ null, { @@ -419741,7 +419763,7 @@ ] ], "passive-touchstart-event-listener-on-root.html": [ - "f2db44a360f2abeddee05c671f0abdeca3a07b13", + "0f52e9a16fe67c99ae7eea2d9d103b7fe6870cf1", [ null, { @@ -419750,7 +419772,7 @@ ] ], "passive-touchstart-event-listener-on-window.html": [ - "e8d83cdc5c4738507a44267f49e6bded03cd8f5a", + "c47af8101f2b7bc953e6118c1af74ce2a6798ea8", [ null, { @@ -419759,7 +419781,7 @@ ] ], "passive-wheel-event-listener-on-body.html": [ - "82de4bd332641be3874341ea3e1e6364056635dd", + "09873a9192aa3b59a2e19a5156a3994c921fafe0", [ null, { @@ -419768,7 +419790,7 @@ ] ], "passive-wheel-event-listener-on-div.html": [ - "906c5e2d8f96d9d2e05ed2bc522ff11703da5927", + "d29c573cdf8bc6ee9d8a69751dca9fa955ba7e4d", [ null, { @@ -419777,7 +419799,7 @@ ] ], "passive-wheel-event-listener-on-document.html": [ - "9512313259b62d22c0c5ed8069eac2fd8c10072b", + "b080f8331abd3f3eef40691b3398b79b724782d1", [ null, { @@ -419786,7 +419808,7 @@ ] ], "passive-wheel-event-listener-on-root.html": [ - "fe5d6d7915808cf8f659ffd67e97a25a10c37798", + "f4e35a791622b97fcdcc56e8fd951e9dda691536", [ null, { @@ -419795,7 +419817,7 @@ ] ], "passive-wheel-event-listener-on-window.html": [ - "0107c1f01fef06bcde29e5631a0d294ae86076ef", + "eb2a6f33286e4a9ae964c036b4b14a28a7728786", [ null, { @@ -437143,6 +437165,24 @@ } ] ], + "keydown.html": [ + "fd814e12b49e87e9cf7312c2007c8359cae075b4", + [ + null, + { + "testdriver": true + } + ] + ], + "keyup.html": [ + "0ec3670de012e9cc8cda6fb510b033dd161d1bde", + [ + null, + { + "testdriver": true + } + ] + ], "large-duration-threshold.html": [ "5665d42d3345742f5364b085b2c137156652e212", [ @@ -509944,7 +509984,7 @@ ] ], "mediasource-is-type-supported.html": [ - "22fe3d6c47157a282b12b00093c7793fa20b7869", + "93b067c6926fe46a48fedb1a6af808bf8f71470c", [ null, {} @@ -536104,6 +536144,13 @@ {} ] ], + "fragments.html": [ + "bba94db88e265413a491f945c9e379e876ff9e18", + [ + null, + {} + ] + ], "idlharness.window.js": [ "2d459b0b1263682f0f3472d4bf706b8b735dbccc", [ @@ -588703,7 +588750,7 @@ }, "window-placement": { "multi-screen-window-open.tentative.https.html": [ - "73622407a7ad188c6348124d77f39cd639f5854a", + "297c6f486c3899e39837e10276d29864e619bcb2", [ null, {
diff --git a/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_arguments.tentative.https.window.js b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_arguments.tentative.https.window.js deleted file mode 100644 index 0c391a2a..0000000 --- a/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_arguments.tentative.https.window.js +++ /dev/null
@@ -1,44 +0,0 @@ -'use strict'; - -for (const property of ['cpuUtilizationThresholds']) { - for (const out_of_range_value of [-1.0, 0.0, 1.0, 2.0]) { - test(t => { - const callback = () => {}; - - const options = { - cpuUtilizationThresholds: [0.5] }; - options[property] = [out_of_range_value]; - - assert_throws_js(TypeError, () => { - new PressureObserver(callback, options); - }); - }, `PressureObserver constructor throws when ${property} ` + - `is [${out_of_range_value}]`); - } - - for (const valid_value of [0.05, 0.1, 0.2, 0.5, 0.9, 0.95]) { - test(t => { - const callback = () => {}; - - const options = { - cpuUtilizationThresholds: [0.5] }; - options[property] = [valid_value]; - - const observer = new PressureObserver(callback, options); - assert_true(observer instanceof PressureObserver); - }, `PressureObserver constructor accepts ${property} value ` + - `[${valid_value}]`); - } -} - -test(t => { - const callback = () => {}; - - - assert_throws_js(TypeError, () => { - new PressureObserver( - callback, - { cpuUtilizationThresholds: [0.5, 0.5] }); - }); -}, 'PressureObserver constructor throws when cpuUtilizationThresholds ' + - 'has duplicates');
diff --git a/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_basic.tentative.https.window.js b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_basic.tentative.https.window.js index 7c939ba..2f463e5 100644 --- a/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_basic.tentative.https.window.js +++ b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_basic.tentative.https.window.js
@@ -1,39 +1,9 @@ 'use strict'; promise_test(async t => { - // The quantization thresholds and the quantized values that they lead to can - // be represented exactly in floating-point, so === comparison works. - - const update = await new Promise((resolve, reject) => { - const observer = new PressureObserver( - resolve, {cpuUtilizationThresholds: [0.5]}); + await new Promise((resolve, reject) => { + const observer = new PressureObserver(resolve, {sampleRate: 1.0}); t.add_cleanup(() => observer.disconnect()); observer.observe('cpu').catch(reject); }); - - assert_equals(typeof update.cpuUtilization, 'number'); - assert_greater_than_equal(update.cpuUtilization, 0.0, 'cpuUtilization range'); - assert_less_than_equal(update.cpuUtilization, 1.0, 'cpuUtilization range'); - assert_in_array(update.cpuUtilization, [0.25, 0.75], - 'cpuUtilization quantization'); }, 'An active PressureObserver calls its callback at least once'); - -promise_test(async t => { - const observer1_updates = []; - const update = await new Promise(async resolve => { - const observer1 = new PressureObserver( - update => {observer1_updates.push(update)}, - {cpuUtilizationThresholds: [0.5]}); - await observer1.observe('cpu'); - - const observer2 = - new PressureObserver(resolve, {cpuUtilizationThresholds: [0.5]}); - await observer2.observe('cpu'); - }); - - assert_in_array( - update.cpuUtilization, [0.25, 0.75], 'cpuUtilization quantization') - assert_in_array( - observer1_updates[0].cpuUtilization, [0.25, 0.75], - 'cpuUtilization quantization'); -}, 'Same quantization should also update second observer');
diff --git a/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_basic_async.tentative.https.window.js b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_basic_async.tentative.https.window.js index 17c12222..a67f27c 100644 --- a/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_basic_async.tentative.https.window.js +++ b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_basic_async.tentative.https.window.js
@@ -26,11 +26,13 @@ const update = await new Promise(async resolve => { const observer = new PressureObserver(resolve); await observer.observe('cpu'); - - mockPressureService.setPressureState({cpuUtilization: 0.5}); + mockPressureService.setPressureUpdate('critical'); mockPressureService.sendUpdate(); }); - assert_equals(update.cpuUtilization, 0.5); + assert_equals(update.state, 'critical'); + assert_equals(update.source, 'cpu'); + assert_equals(typeof update.time, 'number'); + }, 'Basic functionality test'); pressure_test((t, mockPressureService) => { @@ -40,7 +42,7 @@ observer.observe('cpu'); observer.unobserve('cpu'); - mockPressureService.setPressureState({cpuUtilization: 0.5}); + mockPressureService.setPressureUpdate('critical'); mockPressureService.sendUpdate(); return new Promise(resolve => t.step_timeout(resolve, 1000)); @@ -59,41 +61,8 @@ await Promise.all(observePromises); - mockPressureService.setPressureState({cpuUtilization: 0.5}); + mockPressureService.setPressureUpdate('critical'); mockPressureService.sendUpdate(); return Promise.all(callbackPromises); }, 'Calling observe() multiple times works'); - -pressure_test(async (t, mockPressureService) => { - const update = await new Promise(async resolve => { - const observer1 = - new PressureObserver(resolve, {cpuUtilizationThresholds: [0.5]}); - await observer1.observe('cpu'); - - const observer2 = - new PressureObserver(() => {}, {cpuUtilizationThresholds: [0.5]}); - await observer2.observe('cpu'); - - mockPressureService.setPressureState({cpuUtilization: 0.5}); - mockPressureService.sendUpdate(); - }); - - assert_equals(update.cpuUtilization, 0.5); -}, 'Same quantization should not stop other observers'); - -pressure_test(async (t, mockPressureService) => { - const observer1 = new PressureObserver(() => { - assert_unreached('The observer callback should not be called'); - }, {cpuUtilizationThresholds: [0.5]}); - await observer1.observe('cpu'); - - const observer2 = - new PressureObserver(() => {}, {cpuUtilizationThresholds: [0.3]}); - await observer2.observe('cpu'); - - mockPressureService.setPressureState({cpuUtilization: 0.5}); - mockPressureService.sendUpdate(); - - await new Promise(resolve => t.step_timeout(resolve, 1000)); -}, 'Different quantization should stop other observers');
diff --git a/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_detached_iframe.tentative.https.html b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_detached_iframe.tentative.https.html index 7522b3f1..e1639e8f 100644 --- a/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_detached_iframe.tentative.https.html +++ b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_detached_iframe.tentative.https.html
@@ -23,7 +23,7 @@ const observer = new frame_window.PressureObserver( () => {}, - {cpuUtilizationThresholds: [0.5]}); + {sampleRate: 1}); const iframe_DOMException = frame_window.DOMException; iframe.remove(); @@ -40,7 +40,7 @@ const observer = new frame_window.PressureObserver( () => {}, - {cpuUtilizationThresholds: [0.5]}); + {sampleRate: 1}); await observer.observe('cpu'); @@ -57,7 +57,7 @@ const observer = new frame_window.PressureObserver( () => {}, - {cpuUtilizationThresholds: [0.5]}); + {sampleRate: 1}); const iframe_DOMException = frame_window.DOMException; // await is intentionally not used here. We want to remove the iframe while @@ -70,12 +70,12 @@ // call in the removed iframe's PressureObserver. const update = await new Promise((resolve, reject) => { const observer = new PressureObserver( - resolve, {cpuUtilizationThresholds: [0.5]}); + resolve, {sampleRate: 1}); t.add_cleanup(() => observer.disconnect()); observer.observe('cpu').catch(reject); }); - assert_in_array(update.cpuUtilization, [0.25, 0.75], - 'cpuUtilization quantization'); + assert_in_array(update.state, ['nominal', 'fair', 'serious', 'critical'], + 'cpu pressure state'); }, 'Detaching frame while PressureObserver.observe() settles'); </script>
diff --git a/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_different_quantizations.tentative.https.window.js b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_different_quantizations.tentative.https.window.js deleted file mode 100644 index 8fe2794..0000000 --- a/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_different_quantizations.tentative.https.window.js +++ /dev/null
@@ -1,74 +0,0 @@ -'use strict'; - -promise_test(async t => { - const observer1_updates = []; - const observer1 = new PressureObserver( - update => { observer1_updates.push(update); }, - {cpuUtilizationThresholds: [0.5]}); - t.add_cleanup(() => observer1.disconnect()); - // Ensure that observer1's quantization scheme gets registered as the frame's - // scheme before observer2 starts. - await observer1.observe('cpu'); - - const observer2_updates = []; - await new Promise((resolve, reject) => { - const observer2 = new PressureObserver( - update => { - observer2_updates.push(update); - resolve(); - }, - {cpuUtilizationThresholds: [0.25]}); - t.add_cleanup(() => observer2.disconnect()); - observer2.observe('cpu').catch(reject); - }); - - // observer2 uses a different quantization scheme than observer1. After - // observer2.observe() completes, observer1 should no longer be active. - // - // The check below assumes that observer2.observe() completes before the - // browser dispatches any update for observer1. This assumption is highly - // likely to be true, because there should be a 1-second delay between - // observer1.observe() and the first update that observer1 would receive. - assert_equals( - observer1_updates.length, 0, - 'observer2.observe() should have stopped observer1; the two observers ' + - 'have different quantization schemes'); - - assert_equals(observer2_updates.length, 1); - assert_in_array(observer2_updates[0].cpuUtilization, [0.125, 0.625], - 'cpuUtilization quantization'); - - // Go through one more update cycle so any (incorrect) update for observer1 - // makes it through the IPC queues. - observer1_updates.length = 0; - observer2_updates.length = 0; - - const observer3_updates = []; - await new Promise((resolve, reject) => { - const observer3 = new PressureObserver( - update => { - observer3_updates.push(update); - resolve(); - }, - {cpuUtilizationThresholds: [0.75]}); - t.add_cleanup(() => observer3.disconnect()); - observer3.observe('cpu').catch(reject); - }); - - assert_equals( - observer1_updates.length, 0, - 'observer2.observe() should have stopped observer1; the two observers ' + - 'have different quantization schemes'); - - // observer3 uses a different quantization scheme than observer2. So, - // observer3.observe() should stop observer2. - assert_equals( - observer2_updates.length, 0, - 'observer3.observe() should have stopped observer2; the two observers ' + - 'have different quantization schemes'); - - assert_equals(observer3_updates.length, 1); - assert_in_array(observer3_updates[0].cpuUtilization, [0.375, 0.875], - 'cpuUtilization quantization'); -}, 'PressureObserver with a new quantization schema stops all ' + - 'other active observers in the same frame');
diff --git a/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_different_quantizations_across_iframes.tentative.https.window-expected.txt b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_different_quantizations_across_iframes.tentative.https.window-expected.txt deleted file mode 100644 index 4f67fa3..0000000 --- a/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_different_quantizations_across_iframes.tentative.https.window-expected.txt +++ /dev/null
@@ -1,4 +0,0 @@ -This is a testharness.js-based test. -FAIL PressureObserver with a new quantization schema stops all other active observers assert_equals: observer2.observe() should have stopped observer1; the two observers have different quantization schemes expected 0 but got 1 -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_different_quantizations_across_iframes.tentative.https.window.js b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_different_quantizations_across_iframes.tentative.https.window.js deleted file mode 100644 index e1816a1..0000000 --- a/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_different_quantizations_across_iframes.tentative.https.window.js +++ /dev/null
@@ -1,82 +0,0 @@ -'use strict'; - -promise_test(async t => { - const observer1_updates = []; - const observer1 = new PressureObserver( - update => { observer1_updates.push(update); }, - {cpuUtilizationThresholds: [0.5]}); - t.add_cleanup(() => observer1.disconnect()); - // Ensure that observer1's quantization scheme gets registered as the origin's - // scheme before observer2 starts. - await observer1.observe('cpu'); - - // iframe numbers are aligned with observer numbers. The first observer is in - // the main frame, so there is no iframe1. - const iframe2 = document.createElement('iframe'); - document.body.appendChild(iframe2); - - const observer2_updates = []; - await new Promise((resolve, reject) => { - const observer2 = new iframe2.contentWindow.PressureObserver( - update => { - observer2_updates.push(update); - resolve(); - }, - {cpuUtilizationThresholds: [0.25]}); - t.add_cleanup(() => observer2.disconnect()); - observer2.observe('cpu').catch(reject); - }); - - // observer2 uses a different quantization scheme than observer1. After - // observer2.observe() completes, observer1 should no longer be active. - // - // The check below assumes that observer2.observe() completes before the - // browser dispatches any update for observer1. This assumption is highly - // likely to be true, because there should be a 1-second delay between - // observer1.observe() and the first update that observer1 would receive. - assert_equals( - observer1_updates.length, 0, - 'observer2.observe() should have stopped observer1; the two observers ' + - 'have different quantization schemes'); - - assert_equals(observer2_updates.length, 1); - assert_in_array(observer2_updates[0].cpuUtilization, [0.125, 0.625], - 'cpuUtilization quantization'); - - // Go through one more update cycle so any (incorrect) update for observer1 - // makes it through the IPC queues. - observer1_updates.length = 0; - observer2_updates.length = 0; - - const iframe3 = document.createElement('iframe'); - document.body.appendChild(iframe3); - - const observer3_updates = []; - await new Promise((resolve, reject) => { - const observer3 = new iframe3.contentWindow.PressureObserver( - update => { - observer3_updates.push(update); - resolve(); - }, - {cpuUtilizationThresholds: [0.75]}); - t.add_cleanup(() => observer3.disconnect()); - observer3.observe('cpu').catch(reject); - }); - - assert_equals( - observer1_updates.length, 0, - 'observer2.observe() should have stopped observer1; the two observers ' + - 'have different quantization schemes'); - - // observer3 uses a different quantization scheme than observer2. So, - // observer3.observe() should stop observer2. - assert_equals( - observer2_updates.length, 0, - 'observer3.observe() should have stopped observer2; the two observers ' + - 'have different quantization schemes'); - - assert_equals(observer3_updates.length, 1); - assert_in_array(observer3_updates[0].cpuUtilization, [0.375, 0.875], - 'cpuUtilization quantization'); -}, 'PressureObserver with a new quantization schema stops all ' + - 'other active observers');
diff --git a/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_disconnect.tentative.https.window.js b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_disconnect.tentative.https.window.js index b39af20..f6e5c313 100644 --- a/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_disconnect.tentative.https.window.js +++ b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_disconnect.tentative.https.window.js
@@ -4,7 +4,7 @@ const observer1_updates = []; const observer1 = new PressureObserver(update => { observer1_updates.push(update); - }, {cpuUtilizationThresholds: [0.5]}); + }, {sampleRate: 1.0}); t.add_cleanup(() => observer1.disconnect()); // Ensure that observer1's schema gets registered before observer2 starts. await observer1.observe('cpu'); @@ -15,7 +15,7 @@ const observer2 = new PressureObserver(update => { observer2_updates.push(update); resolve(); - }, {cpuUtilizationThresholds: [0.5]}); + }, {sampleRate: 1.0}); t.add_cleanup(() => observer2.disconnect()); observer2.observe('cpu').catch(reject); }); @@ -26,28 +26,6 @@ assert_equals(observer2_updates.length, 1); assert_in_array( - observer2_updates[0].cpuUtilization, [0.25, 0.75], - 'cpuUtilization quantization'); - - // Go through one more update cycle so any (incorrect) update for observer1 - // makes it through the IPC queues. - - const observer3_updates = []; - await new Promise((resolve, reject) => { - const observer3 = new PressureObserver(update => { - observer3_updates.push(update); - resolve(); - }, {cpuUtilizationThresholds: [0.75]}); - t.add_cleanup(() => observer3.disconnect()); - observer3.observe('cpu').catch(reject); - }); - - assert_equals( - observer1_updates.length, 0, - 'disconnected observers should not receive callbacks'); - - assert_equals(observer3_updates.length, 1); - assert_in_array( - observer3_updates[0].cpuUtilization, [0.375, 0.875], - 'cpuUtilization quantization'); + observer2_updates[0].state, ['nominal', 'fair', 'serious', 'critical'], + 'cpu pressure state'); }, 'Stopped PressureObserver do not receive updates');
diff --git a/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_disconnect_idempotent.tentative.https.window.js b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_disconnect_idempotent.tentative.https.window.js index 10e3ad6..b2ae22f1 100644 --- a/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_disconnect_idempotent.tentative.https.window.js +++ b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_disconnect_idempotent.tentative.https.window.js
@@ -4,7 +4,7 @@ const observer1_updates = []; const observer1 = new PressureObserver(update => { observer1_updates.push(update); - }, {cpuUtilizationThresholds: [0.5]}); + }, {sampleRate: 1}); t.add_cleanup(() => observer1.disconnect()); // Ensure that observer1's schema gets registered before observer2 starts. observer1.observe('cpu'); @@ -15,7 +15,7 @@ const observer2 = new PressureObserver(update => { observer2_updates.push(update); resolve(); - }, {cpuUtilizationThresholds: [0.5]}); + }, {sampleRate: 1}); t.add_cleanup(() => observer2.disconnect()); observer2.observe('cpu').catch(reject); }); @@ -26,28 +26,6 @@ assert_equals(observer2_updates.length, 1); assert_in_array( - observer2_updates[0].cpuUtilization, [0.25, 0.75], - 'cpuUtilization quantization'); - - // Go through one more update cycle so any (incorrect) update for observer1 - // makes it through the IPC queues. - - const observer3_updates = []; - await new Promise((resolve, reject) => { - const observer3 = new PressureObserver(update => { - observer3_updates.push(update); - resolve(); - }, {cpuUtilizationThresholds: [0.75]}); - t.add_cleanup(() => observer3.disconnect()); - observer3.observe('cpu').catch(reject); - }); - - assert_equals( - observer1_updates.length, 0, - 'stopped observers should not receive callbacks'); - - assert_equals(observer3_updates.length, 1); - assert_in_array( - observer3_updates[0].cpuUtilization, [0.375, 0.875], - 'cpuUtilization quantization'); + observer2_updates[0].state, ['nominal', 'fair', 'serious', 'critical'], + 'cpu pressure state'); }, 'Stopped PressureObserver do not receive updates');
diff --git a/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_disconnect_immediately.tentative.https.window.js b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_disconnect_immediately.tentative.https.window.js index 10e3ad6..cb5ab2d5 100644 --- a/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_disconnect_immediately.tentative.https.window.js +++ b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_disconnect_immediately.tentative.https.window.js
@@ -4,7 +4,7 @@ const observer1_updates = []; const observer1 = new PressureObserver(update => { observer1_updates.push(update); - }, {cpuUtilizationThresholds: [0.5]}); + }, {sampleRate: 1.0}); t.add_cleanup(() => observer1.disconnect()); // Ensure that observer1's schema gets registered before observer2 starts. observer1.observe('cpu'); @@ -15,7 +15,7 @@ const observer2 = new PressureObserver(update => { observer2_updates.push(update); resolve(); - }, {cpuUtilizationThresholds: [0.5]}); + }, {sampleRate: 1.0}); t.add_cleanup(() => observer2.disconnect()); observer2.observe('cpu').catch(reject); }); @@ -26,28 +26,6 @@ assert_equals(observer2_updates.length, 1); assert_in_array( - observer2_updates[0].cpuUtilization, [0.25, 0.75], - 'cpuUtilization quantization'); - - // Go through one more update cycle so any (incorrect) update for observer1 - // makes it through the IPC queues. - - const observer3_updates = []; - await new Promise((resolve, reject) => { - const observer3 = new PressureObserver(update => { - observer3_updates.push(update); - resolve(); - }, {cpuUtilizationThresholds: [0.75]}); - t.add_cleanup(() => observer3.disconnect()); - observer3.observe('cpu').catch(reject); - }); - - assert_equals( - observer1_updates.length, 0, - 'stopped observers should not receive callbacks'); - - assert_equals(observer3_updates.length, 1); - assert_in_array( - observer3_updates[0].cpuUtilization, [0.375, 0.875], - 'cpuUtilization quantization'); + observer2_updates[0].state, ['nominal', 'fair', 'serious', 'critical'], + 'cpu pressure state'); }, 'Stopped PressureObserver do not receive updates');
diff --git a/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_duplicate_updates.tentative.https.window.js b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_duplicate_updates.tentative.https.window.js new file mode 100644 index 0000000..30e06ed --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_duplicate_updates.tentative.https.window.js
@@ -0,0 +1,27 @@ +// META: script=/resources/test-only-api.js +// META: script=resources/pressure-helpers.js + +'use strict'; + +pressure_test(async (t, mockPressureService) => { + const pressureUpdates = await new Promise(async resolve => { + const updates = []; + let n = 0; + const observer = new PressureObserver(update => { + updates.push(update); + if (++n === 2) + resolve(updates); + }, {sampleRate: 1.0}); + await observer.observe('cpu'); + + mockPressureService.setPressureUpdate('critical'); + mockPressureService.sendUpdate(); + mockPressureService.setPressureUpdate('critical'); + mockPressureService.sendUpdate(); + mockPressureService.setPressureUpdate('nominal'); + mockPressureService.sendUpdate(); + }); + assert_equals(pressureUpdates.length, 2); + assert_equals(pressureUpdates[0].state, 'critical'); + assert_equals(pressureUpdates[1].state, 'nominal'); +}, 'Updates that fail the "has change in data" test are discarded.');
diff --git a/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_multiple.tentative.https.window.js b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_multiple.tentative.https.window.js index fef47e3..16ddb3c0 100644 --- a/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_multiple.tentative.https.window.js +++ b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_multiple.tentative.https.window.js
@@ -2,22 +2,19 @@ promise_test(async t => { const update1_promise = new Promise((resolve, reject) => { - const observer = new PressureObserver( - resolve, {cpuUtilizationThresholds: [0.5]}); + const observer = new PressureObserver(resolve, {sampleRate: 1.0}); t.add_cleanup(() => observer.disconnect()); observer.observe('cpu').catch(reject); }); const update2_promise = new Promise((resolve, reject) => { - const observer = new PressureObserver( - resolve, {cpuUtilizationThresholds: [0.5]}); + const observer = new PressureObserver(resolve, {sampleRate: 1.0}); t.add_cleanup(() => observer.disconnect()); observer.observe('cpu').catch(reject); }); const update3_promise = new Promise((resolve, reject) => { - const observer = new PressureObserver( - resolve, {cpuUtilizationThresholds: [0.5]}); + const observer = new PressureObserver(resolve, {sampleRate: 1.0}); t.add_cleanup(() => observer.disconnect()); observer.observe('cpu').catch(reject); }); @@ -26,8 +23,8 @@ await Promise.all([update1_promise, update2_promise, update3_promise]); for (const update of [update1, update2, update3]) { - assert_in_array(update.cpuUtilization, [0.25, 0.75], - 'cpuUtilization quantization'); + assert_in_array( + update.state, ['nominal', 'fair', 'serious', 'critical'], + 'cpu pressure state'); } -}, 'Three PressureObserver instances with the same quantization ' + - 'schema receive updates'); +}, 'Three PressureObserver instances receive updates');
diff --git a/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_multiple_across_iframes.tentative.https.window.js b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_multiple_across_iframes.tentative.https.window.js index dff994c..7377337 100644 --- a/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_multiple_across_iframes.tentative.https.window.js +++ b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_multiple_across_iframes.tentative.https.window.js
@@ -2,20 +2,19 @@ promise_test(async t => { const update1_promise = new Promise((resolve, reject) => { - const observer = new PressureObserver( - resolve, {cpuUtilizationThresholds: [0.5]}); + const observer = new PressureObserver(resolve, {sampleRate: 1.0}); t.add_cleanup(() => observer.disconnect()); observer.observe('cpu').catch(reject); }); - // iframe numbers are aligned with observer numbers. The first observer is in - // the main frame, so there is no iframe1. + // iframe numbers are aligned with observer numbers. The first observer is + // in the main frame, so there is no iframe1. const iframe2 = document.createElement('iframe'); document.body.appendChild(iframe2); const update2_promise = new Promise((resolve, reject) => { - const observer = new iframe2.contentWindow.PressureObserver( - resolve, {cpuUtilizationThresholds: [0.5]}); + const observer = + new iframe2.contentWindow.PressureObserver(resolve, {sampleRate: 1.0}); t.add_cleanup(() => observer.disconnect()); observer.observe('cpu').catch(reject); }); @@ -24,8 +23,8 @@ document.body.appendChild(iframe3); const update3_promise = new Promise((resolve, reject) => { - const observer = new iframe3.contentWindow.PressureObserver( - resolve, {cpuUtilizationThresholds: [0.5]}); + const observer = + new iframe3.contentWindow.PressureObserver(resolve, {sampleRate: 1.0}); t.add_cleanup(() => observer.disconnect()); observer.observe('cpu').catch(reject); }); @@ -34,8 +33,8 @@ await Promise.all([update1_promise, update2_promise, update3_promise]); for (const update of [update1, update2, update3]) { - assert_in_array(update.cpuUtilization, [0.25, 0.75], - 'cpuUtilization quantization'); + assert_in_array( + update.state, ['nominal', 'fair', 'serious', 'critical'], + 'cpu pressure state'); } -}, 'Three PressureObserver instances in different iframes, but with ' + - 'the same quantization schema, receive updates'); +}, 'Three PressureObserver instances, in different iframes, receive updates');
diff --git a/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_observe_idempotent.tentative.https.window.js b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_observe_idempotent.tentative.https.window.js index 925f73a3..86d26e1 100644 --- a/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_observe_idempotent.tentative.https.window.js +++ b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_observe_idempotent.tentative.https.window.js
@@ -1,22 +1,16 @@ 'use strict'; promise_test(async t => { - // The quantization thresholds and the quantized values that they lead to can - // be represented exactly in floating-point, so === comparison works. - const update = await new Promise((resolve, reject) => { - const observer = new PressureObserver( - resolve, {cpuUtilizationThresholds: [0.5]}); + const observer = new PressureObserver(resolve, {sampleRate: 1.0}); t.add_cleanup(() => observer.disconnect()); observer.observe('cpu').catch(reject); observer.observe('cpu').catch(reject); observer.observe('cpu').catch(reject); }); - assert_equals(typeof update.cpuUtilization, 'number'); - assert_greater_than_equal(update.cpuUtilization, 0.0, 'cpuUtilization range'); - assert_less_than_equal(update.cpuUtilization, 1.0, 'cpuUtilization range'); - assert_in_array(update.cpuUtilization, [0.25, 0.75], - 'cpuUtilization quantization'); + assert_equals(typeof update.state, 'string'); + assert_in_array( + update.state, ['nominal', 'fair', 'serious', 'critical'], + 'cpu pressure state'); }, 'PressureObserver.observe() is idempotent'); -
diff --git a/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_observe_unobserve_failure.tentative.https.window.js b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_observe_unobserve_failure.tentative.https.window.js index 7d6e94c..69fe125 100644 --- a/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_observe_unobserve_failure.tentative.https.window.js +++ b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_observe_unobserve_failure.tentative.https.window.js
@@ -2,16 +2,14 @@ promise_test(async t => { const observer = new PressureObserver( - t.unreached_func('oops should not end up here'), - {cpuUtilizationThresholds: [0.1, 0.5]}); + t.unreached_func('oops should not end up here'), {sampleRate: 1.0}); t.add_cleanup(() => observer.disconnect()); await promise_rejects_js(t, TypeError, observer.observe('random')); }, 'PressureObserver.observe() requires a valid source'); test(function(t) { const observer = new PressureObserver( - t.unreached_func('oops should not end up here'), - {cpuUtilizationThresholds: [0.1, 0.5]}); + t.unreached_func('oops should not end up here'), {sampleRate: 1.0}); t.add_cleanup(() => observer.disconnect()); assert_throws_js(TypeError, () => { observer.unobserve('random');
diff --git a/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_take_records.tentative.https.window.js b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_take_records.tentative.https.window.js index c6da8f61..ce5e835b 100644 --- a/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_take_records.tentative.https.window.js +++ b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_take_records.tentative.https.window.js
@@ -1,9 +1,12 @@ +// META: script=/resources/test-only-api.js +// META: script=resources/pressure-helpers.js + 'use strict'; test(t => { const observer = new PressureObserver( t.unreached_func('This callback should not have been called.'), - {cpuUtilizationThresholds: [0.25]}); + {sampleRate: 1.0}); const records = observer.takeRecords(); assert_equals(records.length, 0, 'No record before observe'); @@ -11,16 +14,15 @@ promise_test(async t => { let observer; - const record = await new Promise((resolve, reject) => { - observer = new PressureObserver( - resolve, - {cpuUtilizationThresholds: [0.25]}); + const update = await new Promise(async resolve => { + observer = new PressureObserver(resolve, {sampleRate: 1.0}); t.add_cleanup(() => observer.disconnect()); - observer.observe('cpu').catch(reject); - }); + await observer.observe('cpu'); + }); assert_in_array( - record.cpuUtilization, [0.125, 0.625], 'cpuUtilization quantization'); + update.state, ['nominal', 'fair', 'serious', 'critical'], + 'cpu presure state'); const records = observer.takeRecords(); assert_equals(records.length, 0, 'No record available');
diff --git a/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_values.tentative.https.window.js b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_values.tentative.https.window.js deleted file mode 100644 index b51a3e3..0000000 --- a/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_values.tentative.https.window.js +++ /dev/null
@@ -1,17 +0,0 @@ -'use strict'; - -promise_test(async t => { - // The quantization thresholds and the quantized values that they lead to can - // be represented exactly in floating-point, so === comparison works. - - const update = await new Promise((resolve, reject) => { - const observer = new PressureObserver( - resolve, - {cpuUtilizationThresholds: [0.25]}); - t.add_cleanup(() => observer.disconnect()); - observer.observe('cpu').catch(reject); - }); - - assert_in_array( - update.cpuUtilization, [0.125, 0.625], 'cpuUtilization quantization'); -}, 'PressureObserver quantizes utilization and speed separately');
diff --git a/third_party/blink/web_tests/external/wpt/css/css-sizing/contain-intrinsic-size/auto-010.html b/third_party/blink/web_tests/external/wpt/css/css-sizing/contain-intrinsic-size/auto-010.html new file mode 100644 index 0000000..021612a --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-sizing/contain-intrinsic-size/auto-010.html
@@ -0,0 +1,90 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<title>Last remembered size</title> +<link rel="author" title="Oriol Brufau" href="mailto:obrufau@igalia.com"> +<link rel="help" href="https://drafts.csswg.org/css-sizing-4/#last-remembered"> +<link rel="help" href="https://drafts.csswg.org/css-sizing-4/#intrinsic-size-override"> +<link rel="help" href="https://drafts.csswg.org/css-contain-2/#content-visibility"> +<link rel="help" href="https://drafts.csswg.org/css-multicol-1/"> +<link rel="help" href="https://github.com/w3c/csswg-drafts/issues/7598"> +<meta name="assert" content="Tests that the last remembered size takes all fragments into account." /> + +<style> +#wrapper { + column-width: 100px; + width: max-content; + height: 100px; +} +#target { + width: max-content; + height: max-content; + background: orange; +} +#target::before { + content: ""; + display: block; +} +.content-50-150::before { + width: 50px; + height: 150px; +} +.content-50-175::before { + width: 50px; + height: 175px; +} +.content-skip { + content-visibility: hidden; +} +.cis-auto { + contain-intrinsic-size: auto 1px; +} +</style> + +<div id="log"></div> + +<div id="wrapper"> + <div id="target"></div> +</div> + +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script> +const target = document.getElementById("target"); + +function checkSizes(expectedSizes, msg) { + const rects = target.getClientRects(); + assert_equals(rects.length, expectedSizes.length, msg + " - fragments"); + for (let i = 0; i < rects.length; ++i) { + assert_equals(rects[i].width, expectedSizes[i][0], `${msg} - fragment #${i+1} width`); + assert_equals(rects[i].height, expectedSizes[i][1], `${msg} - fragment #${i+1} height`); + } +} + +function nextRendering() { + return new Promise(resolve => { + requestAnimationFrame(() => requestAnimationFrame(() => resolve())); + }); +} + +promise_test(async function() { + target.className = "cis-auto content-50-150"; + checkSizes([[50, 100], [50, 50]], "Sizing normally"); + + await nextRendering(); + target.className = "cis-auto content-skip"; + checkSizes([[50, 150]], "Using last remembered size"); +}, "Last remembered size supports multiple fragments"); + +promise_test(async function() { + target.className = "cis-auto content-50-150"; + checkSizes([[50, 100], [50, 50]], "Sizing normally"); + + await nextRendering(); + target.className = "cis-auto content-50-175"; + checkSizes([[50, 100], [50, 75]], "Sizing normally with new size"); + + await nextRendering(); + target.className = "cis-auto content-skip"; + checkSizes([[50, 175]], "Using updated last remembered size"); +}, "Last remembered size is updated when 2nd fragment changes size"); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-sizing/fit-content-contribution-001.html b/third_party/blink/web_tests/external/wpt/css/css-sizing/fit-content-contribution-001.html new file mode 100644 index 0000000..efe3d49f --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-sizing/fit-content-contribution-001.html
@@ -0,0 +1,36 @@ +<!DOCTYPE html> +<link rel="help" + href="https://drafts.csswg.org/css-sizing-3/#valdef-width-fit-content-length-percentage"> +<link rel="match" href="../reference/ref-filled-green-100px-square.xht" /> +<meta name="assert" + content="max-width: fit-content works when there is no definite available size. Chrome 105 treated fit-content as min-content in this scenario."> +<style> + #reference-overlapped-red { + position: absolute; + background-color: red; + width: 100px; + height: 100px; + z-index: -1; + } + + .word { + float: left; + width: 50px; + } + +</style> + +<p>Test passes if there is a filled green square and <strong>no red</strong>. +</p> + +<div id="reference-overlapped-red"></div> + +<div style="width: 100px;"> + <div style="float: left; height: 100px; background: green;"> + <div style="max-width: fit-content;"> + <div class="word"></div> + <div class="word"></div> + <div class="word"></div> + </div> + </div> +</div>
diff --git a/third_party/blink/web_tests/external/wpt/fs/FileSystemFileHandle-move.https.any-expected.txt b/third_party/blink/web_tests/external/wpt/fs/FileSystemFileHandle-move.https.any-expected.txt new file mode 100644 index 0000000..241c8e22 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/fs/FileSystemFileHandle-move.https.any-expected.txt
@@ -0,0 +1,24 @@ +This is a testharness.js-based test. +PASS move(name) to rename a file +PASS move(name) to rename a file the same name +PASS move("") to rename a file fails +PASS move(name) can be called multiple times +PASS move(name) with a name with a trailing period should fail +PASS move(name) with a name with invalid characters should fail +PASS move(name) while the file has an open writable fails +FAIL move(name) while the destination file has an open writable fails assert_unreached: Should have rejected: undefined Reached unreachable code +PASS move(dir, name) to rename a file +PASS move(dir, name) to rename a file the same name +PASS move(dir) to move a file to a new directory +PASS move(dir, "") to move a file to a new directory +PASS move(dir, name) to move a file to a new directory +PASS move(dir) can be called multiple times +PASS move(dir, "") can be called multiple times +PASS move(dir, name) can be called multiple times +PASS move(dir, name) with a name with invalid characters should fail +PASS move(dir) while the file has an open writable fails +PASS move(dir, name) while the file has an open writable fails +FAIL move(dir) while the destination file has an open writable fails assert_unreached: Should have rejected: undefined Reached unreachable code +FAIL move(dir, name) while the destination file has an open writable fails assert_unreached: Should have rejected: undefined Reached unreachable code +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/fs/FileSystemFileHandle-move.https.any.worker-expected.txt b/third_party/blink/web_tests/external/wpt/fs/FileSystemFileHandle-move.https.any.worker-expected.txt new file mode 100644 index 0000000..241c8e22 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/fs/FileSystemFileHandle-move.https.any.worker-expected.txt
@@ -0,0 +1,24 @@ +This is a testharness.js-based test. +PASS move(name) to rename a file +PASS move(name) to rename a file the same name +PASS move("") to rename a file fails +PASS move(name) can be called multiple times +PASS move(name) with a name with a trailing period should fail +PASS move(name) with a name with invalid characters should fail +PASS move(name) while the file has an open writable fails +FAIL move(name) while the destination file has an open writable fails assert_unreached: Should have rejected: undefined Reached unreachable code +PASS move(dir, name) to rename a file +PASS move(dir, name) to rename a file the same name +PASS move(dir) to move a file to a new directory +PASS move(dir, "") to move a file to a new directory +PASS move(dir, name) to move a file to a new directory +PASS move(dir) can be called multiple times +PASS move(dir, "") can be called multiple times +PASS move(dir, name) can be called multiple times +PASS move(dir, name) with a name with invalid characters should fail +PASS move(dir) while the file has an open writable fails +PASS move(dir, name) while the file has an open writable fails +FAIL move(dir) while the destination file has an open writable fails assert_unreached: Should have rejected: undefined Reached unreachable code +FAIL move(dir, name) while the destination file has an open writable fails assert_unreached: Should have rejected: undefined Reached unreachable code +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/fs/script-tests/FileSystemFileHandle-move.js b/third_party/blink/web_tests/external/wpt/fs/script-tests/FileSystemFileHandle-move.js index a3be9f4..55a254c 100644 --- a/third_party/blink/web_tests/external/wpt/fs/script-tests/FileSystemFileHandle-move.js +++ b/third_party/blink/web_tests/external/wpt/fs/script-tests/FileSystemFileHandle-move.js
@@ -86,10 +86,11 @@ await promise_rejects_dom( t, 'NoModificationAllowedError', handle.move('file-after')); - // Can move handle once the writable is closed. + // Can't move handle once the writable is closed. await stream.close(); - await handle.move('file-after'); - assert_array_equals(await getSortedDirectoryEntries(root), ['file-after']); + await promise_rejects_dom( + t, 'NoModificationAllowedError', handle.move('file-after')); + assert_array_equals(await getSortedDirectoryEntries(root), ['file-before']); }, 'move(name) while the destination file has an open writable fails'); @@ -308,15 +309,11 @@ // Assert the file is still in the source directory. assert_array_equals(await getSortedDirectoryEntries(dir_src), ['file']); - // Can move handle once the writable is closed. + // Can't move handle once the writable is closed. await stream.close(); - await file.move(dir_dest); - assert_array_equals( - await getSortedDirectoryEntries(root), ['dir-dest/', 'dir-src/']); - assert_array_equals(await getSortedDirectoryEntries(dir_src), []); - assert_array_equals(await getSortedDirectoryEntries(dir_dest), ['file']); - assert_equals(await getFileContents(file), 'abc'); - assert_equals(await getFileSize(file), 3); + await promise_rejects_dom( + t, 'NoModificationAllowedError', file.move(dir_dest)); + assert_array_equals(await getSortedDirectoryEntries(dir_src), ['file']); }, 'move(dir) while the destination file has an open writable fails'); directory_test(async (t, root) => { @@ -336,13 +333,12 @@ // Assert the file is still in the source directory. assert_array_equals(await getSortedDirectoryEntries(dir_src), ['file-src']); - // Can move handle once the writable is closed. + // Can't move handle once the writable is closed. await stream.close(); - await file.move(dir_dest, 'file-dest'); - assert_array_equals( - await getSortedDirectoryEntries(root), ['dir-dest/', 'dir-src/']); - assert_array_equals(await getSortedDirectoryEntries(dir_src), []); - assert_array_equals(await getSortedDirectoryEntries(dir_dest), ['file-dest']); + await promise_rejects_dom( + t, 'NoModificationAllowedError', file.move(dir_dest, 'file-dest')); + // Assert the file is still in the source directory. + assert_array_equals(await getSortedDirectoryEntries(dir_src), ['file-src']); assert_equals(await getFileContents(file), 'abc'); assert_equals(await getFileSize(file), 3); }, 'move(dir, name) while the destination file has an open writable fails');
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/forms/the-input-element/files-expected.txt b/third_party/blink/web_tests/external/wpt/html/semantics/forms/the-input-element/files-expected.txt deleted file mode 100644 index ae5e069..0000000 --- a/third_party/blink/web_tests/external/wpt/html/semantics/forms/the-input-element/files-expected.txt +++ /dev/null
@@ -1,27 +0,0 @@ -This is a testharness.js-based test. -PASS files for input type=hidden -PASS files for input type=text -PASS files for input type=search -PASS files for input type=tel -PASS files for input type=url -PASS files for input type=email -PASS files for input type=password -PASS files for input type=date -PASS files for input type=month -PASS files for input type=week -PASS files for input type=time -PASS files for input type=datetime-local -PASS files for input type=number -PASS files for input type=range -PASS files for input type=color -PASS files for input type=checkbox -PASS files for input type=radio -PASS files for input type=submit -PASS files for input type=image -PASS files for input type=reset -PASS files for input type=button -PASS files for input type=file -PASS setting <input type=file>.files -FAIL setting <input type=file>.files from DataTransfer assert_equals: FileList can be shared across input / DataTransfer expected object "[object FileList]" but got object "[object FileList]" -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/external/wpt/media-source/mediasource-is-type-supported.html b/third_party/blink/web_tests/external/wpt/media-source/mediasource-is-type-supported.html index 22fe3d6c..93b067c 100644 --- a/third_party/blink/web_tests/external/wpt/media-source/mediasource-is-type-supported.html +++ b/third_party/blink/web_tests/external/wpt/media-source/mediasource-is-type-supported.html
@@ -96,7 +96,9 @@ 'video/mp4;codecs="mp4a.40.2 , avc1.4d001e "', 'video/mp4;codecs="avc1.4d001e,mp4a.40.5"', 'audio/mp4;codecs="Opus"', - 'video/mp4;codecs="Opus"' + 'video/mp4;codecs="Opus"', + 'audio/mp4;codecs="fLaC"', + 'video/mp4;codecs="fLaC"' ], true, 'Test valid MP4 type'); </script>
diff --git a/third_party/blink/web_tests/external/wpt/resize-observer/fragments-expected.txt b/third_party/blink/web_tests/external/wpt/resize-observer/fragments-expected.txt new file mode 100644 index 0000000..3b584d26 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/resize-observer/fragments-expected.txt
@@ -0,0 +1,8 @@ +This is a testharness.js-based test. +PASS Single fragment +FAIL Adding 2nd fragment assert_equals: number of fragments expected 2 but got 1 +FAIL Resizing 2nd fragment assert_equals: number of fragments expected 2 but got 1 +FAIL Resizing all fragments assert_equals: number of fragments expected 2 but got 1 +PASS Removing 2nd fragment +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/resize-observer/fragments.html b/third_party/blink/web_tests/external/wpt/resize-observer/fragments.html new file mode 100644 index 0000000..bba94db --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/resize-observer/fragments.html
@@ -0,0 +1,115 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<title>ResizeObserver with multiple fragments</title> +<link rel="author" title="Oriol Brufau" href="mailto:obrufau@igalia.com"> +<link rel="help" href="https://drafts.csswg.org/resize-observer-1/"> +<link rel="help" href="https://github.com/w3c/csswg-drafts/issues/3673"> +<meta name="assert" content="Tests ResizeObserver supports multiple fragments." /> + +<style> +#wrapper { + column-width: 100px; + width: max-content; + height: 100px; + margin: 10px; +} +#target { + outline: solid; + background: orange; +} +.w50 { + width: 50px; +} +.w75 { + width: 75px; +} +.h100 { + height: 100px; +} +.h150 { + height: 150px; +} +.h175 { + height: 175px; +} +</style> + +<div id="log"></div> + +<div id="wrapper"> + <div id="target"></div> +</div> + +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script> +const target = document.getElementById("target"); + +const nextSizes = (() => { + let callback = null; + new ResizeObserver((entries) => { + if (callback) { + callback(entries[0].contentBoxSize); + callback = null; + } + }).observe(target); + return () => { + if (callback) { + throw "Already awaiting another notification"; + } + return new Promise((resolve, reject) => { + callback = resolve; + requestAnimationFrame(() => { + requestAnimationFrame(() => { + reject("Missing ResizeObserver notification"); + callback = null; + }); + }); + }); + }; +})(); + +function checkSizes(className, expectedSizes, msg) { + promise_test(async () => { + await new Promise(requestAnimationFrame); + target.className = className; + let sizes; + try { + sizes = await nextSizes(); + } catch (error) { + assert_unreached(error); + } + assert_equals(sizes.length, expectedSizes.length, "number of fragments"); + for (let i = 0; i < sizes.length; ++i) { + assert_equals(sizes[i].inlineSize, expectedSizes[i][0], `fragment #${i+1} inline size`); + assert_equals(sizes[i].blockSize, expectedSizes[i][1], `fragment #${i+1} block size`); + } + }, msg); +} + +checkSizes( + "w50 h100", + [[50, 100]], + "Single fragment" +); +checkSizes( + "w50 h150", + [[50, 100], [50, 50]], + "Adding 2nd fragment" +); +checkSizes( + "w50 h175", + [[50, 100], [50, 75]], + "Resizing 2nd fragment" +); +checkSizes( + "w75 h175", + [[75, 100], [75, 75]], + "Resizing all fragments" +); +checkSizes( + "w75 h100", + [[75, 100]], + "Removing 2nd fragment" +); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/resources/chromium/mock-pressure-service.js b/third_party/blink/web_tests/external/wpt/resources/chromium/mock-pressure-service.js index e8a21ac..47fc3c3 100644 --- a/third_party/blink/web_tests/external/wpt/resources/chromium/mock-pressure-service.js +++ b/third_party/blink/web_tests/external/wpt/resources/chromium/mock-pressure-service.js
@@ -1,4 +1,5 @@ -import {PressureService, PressureServiceReceiver, PressureStatus, SetQuantizationStatus} from '/gen/third_party/blink/public/mojom/compute_pressure/pressure_service.mojom.m.js' +import {PressureState} from '/gen/services/device/public/mojom/pressure_update.mojom.m.js' +import {PressureService, PressureServiceReceiver, PressureStatus} from '/gen/third_party/blink/public/mojom/compute_pressure/pressure_service.mojom.m.js' class MockPressureService { constructor() { @@ -9,6 +10,10 @@ this.receiver_.$.bindHandle(e.handle); }; this.reset(); + this.mojomStateType_ = new Map([ + ['nominal', PressureState.kNominal], ['fair', PressureState.kFair], + ['serious', PressureState.kSerious], ['critical', PressureState.kCritical] + ]); } start() { @@ -26,8 +31,7 @@ reset() { this.observer_ = null; - this.pressureState_ = null; - this.quantization_ = null; + this.pressureUpdate_ = null; this.pressureStatus_ = PressureStatus.kOk; } @@ -40,42 +44,20 @@ return {status: this.pressureStatus_}; } - isSameQuantization(quantization) { - if (this.quantization_ === null) - return false; - - if (quantization.cpuUtilizationThresholds.length != - this.quantization_.cpuUtilizationThresholds.length) { - return false; - } - - for (let i = 0; i < quantization.cpuUtilizationThresholds.length; i++) { - if (quantization.cpuUtilizationThresholds[i] != - this.quantization_.cpuUtilizationThresholds[i]) { - return false; - } - } - - return true; - } - - async setQuantization(quantization) { - if (this.isSameQuantization(quantization)) { - return {status: SetQuantizationStatus.kUnchanged}; - } else { - this.quantization_ = quantization; - return {status: SetQuantizationStatus.kChanged}; - } - } - sendUpdate() { - if (this.pressureState_ === null || this.observer_ === null) + if (this.pressureUpdate_ === null || this.observer_ === null) return; - this.observer_.onUpdate(this.pressureState_); + this.observer_.onUpdate(this.pressureUpdate_); } - setPressureState(value) { - this.pressureState_ = value; + setPressureUpdate(state) { + if (!this.mojomStateType_.has(state)) + throw new Error(`PressureState '${state}' is invalid`); + + this.pressureUpdate_ = { + state: this.mojomStateType_.get(state), + timestamp: window.performance.timeOrigin + }; } setExpectedFailure(expectedException) {
diff --git a/third_party/blink/web_tests/external/wpt/svg/types/scripted/SVGLength-ic.html b/third_party/blink/web_tests/external/wpt/svg/types/scripted/SVGLength-ic.html index ed8a6364..583a964 100644 --- a/third_party/blink/web_tests/external/wpt/svg/types/scripted/SVGLength-ic.html +++ b/third_party/blink/web_tests/external/wpt/svg/types/scripted/SVGLength-ic.html
@@ -13,7 +13,7 @@ test(() => { assert_equals(ic_length.unitType, SVGLength.SVG_LENGTHTYPE_UNKNOWN); - assert_equals(ic_length.value, ref_width); + assert_equals(ic_length.value, ref_width); }, "ic unit in SVGLength"); test(() => {
diff --git a/third_party/blink/web_tests/external/wpt/svg/types/scripted/SVGLength-lh.html b/third_party/blink/web_tests/external/wpt/svg/types/scripted/SVGLength-lh.html new file mode 100644 index 0000000..023d04fb --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/svg/types/scripted/SVGLength-lh.html
@@ -0,0 +1,23 @@ +<!DOCTYPE HTML> +<title>SVGLength with 'lh' unit</title> +<link rel="help" href="https://www.w3.org/TR/SVG/types.html#InterfaceSVGLength"> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<div id="lh_ref" style="font-family:initial; font-size:20px; width:10lh"></div> +<svg> + <text id="lh_test" x="10lh" style="font-family:initial; font-size:20px"></text> +</svg> +<script> + let ref_width = lh_ref.offsetWidth; + let lh_length = lh_test.x.baseVal[0]; + + test(() => { + assert_equals(lh_length.unitType, SVGLength.SVG_LENGTHTYPE_UNKNOWN); + assert_equals(lh_length.value, ref_width); + }, "lh unit in SVGLength"); + + test(() => { + lh_length.value = ref_width * 2; + assert_equals(lh_length.valueInSpecifiedUnits, 20); + }, "Convert back to lh from new user unit value"); +</script>
diff --git a/third_party/blink/web_tests/flag-specific/disable-layout-ng/external/wpt/css/css-sizing/contain-intrinsic-size/auto-010-expected.txt b/third_party/blink/web_tests/flag-specific/disable-layout-ng/external/wpt/css/css-sizing/contain-intrinsic-size/auto-010-expected.txt new file mode 100644 index 0000000..c9ddbcd --- /dev/null +++ b/third_party/blink/web_tests/flag-specific/disable-layout-ng/external/wpt/css/css-sizing/contain-intrinsic-size/auto-010-expected.txt
@@ -0,0 +1,5 @@ +This is a testharness.js-based test. +FAIL Last remembered size supports multiple fragments assert_equals: Using last remembered size - fragments expected 1 but got 2 +FAIL Last remembered size is updated when 2nd fragment changes size assert_equals: Using updated last remembered size - fragments expected 1 but got 2 +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/http/tests/inspector-protocol/storage/indexed-db-storage-key-track-untrack.js b/third_party/blink/web_tests/http/tests/inspector-protocol/storage/indexed-db-storage-key-track-untrack.js index 6a47ee4..adefa1b 100644 --- a/third_party/blink/web_tests/http/tests/inspector-protocol/storage/indexed-db-storage-key-track-untrack.js +++ b/third_party/blink/web_tests/http/tests/inspector-protocol/storage/indexed-db-storage-key-track-untrack.js
@@ -4,6 +4,8 @@ await dp.Page.enable(); + testRunner.startDumpingProtocolMessages(); + const frameId = (await dp.Page.getResourceTree()).result.frameTree.frame.id; const storageKey = (await dp.Storage.getStorageKeyForFrame({ frameId: frameId
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index 3b12e0c..a8fae89 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -7238,8 +7238,8 @@ <int value="56" label="Local suggestion of a deduped server card filled (once)"/> <int value="57" - label="Autofilled field was cleared by JavaScript immediately after - fill (once)"/> + label="Autofilled field was cleared by JavaScript within + kLimitBeforeRefill (1s) after being filled (once)"/> </enum> <enum name="AutofillFormSubmittedState"> @@ -35622,6 +35622,8 @@ <int value="1707" label="FILEMANAGERPRIVATE_GETDLPBLOCKEDCOMPONENTS"/> <int value="1708" label="FILEMANAGERPRIVATE_GETDIALOGCALLER"/> <int value="1709" label="OS_TELEMETRY_GETNONREMOVABLEBLOCKDEVICESINFO"/> + <int value="1710" label="OS_DIAGNOSTICS_RUNDNSRESOLUTIONROUTINE"/> + <int value="1711" label="OS_DIAGNOSTICS_RUNSIGNALSTRENGTHROUTINE"/> </enum> <enum name="ExtensionIconState"> @@ -56591,6 +56593,7 @@ <int value="-1992999120" label="composite-after-paint"/> <int value="-1992488524" label="AutofillAcrossIframes:disabled"/> <int value="-1991935790" label="ShareCrowLaunchTab:enabled"/> + <int value="-1990678808" label="SafetyCheckUnusedSitePermissions:disabled"/> <int value="-1990614981" label="StoragePressureUI:disabled"/> <int value="-1990238241" label="ChromeOSHWVBREncoding:enabled"/> <int value="-1989747818" label="TabStripKeyboardFocus:disabled"/> @@ -58121,6 +58124,7 @@ <int value="-1089665395" label="HTMLParamElementUrlSupport:enabled"/> <int value="-1088804127" label="DuetTabStripIntegrationAndroid:disabled"/> <int value="-1087409065" label="RoundedDisplay:enabled"/> + <int value="-1087109069" label="SafetyCheckNotificationPermissions:enabled"/> <int value="-1086987072" label="NearbySharingSelfShareAutoAccept:enabled"/> <int value="-1086728979" label="kids-management-url-classification:enabled"/> <int value="-1086656172" @@ -59496,6 +59500,7 @@ label="AutofillHighlightOnlyChangedValuesInPreviewMode:enabled"/> <int value="-245342115" label="PermissionChip:enabled"/> <int value="-242836432" label="EnableFakeKeyboardHeuristic:disabled"/> + <int value="-242441279" label="SafetyCheckUnusedSitePermissions:enabled"/> <int value="-242431978" label="StartSurfaceRefactor:enabled"/> <int value="-241353344" label="MidiManagerWinrt:disabled"/> <int value="-240531943" label="ContextualSearchRankerQuery:disabled"/> @@ -61996,6 +62001,7 @@ <int value="1289433604" label="RecoverFromNeverSaveAndroid:enabled"/> <int value="1289495171" label="AssistantBetterOnboarding:disabled"/> <int value="1289670142" label="ArcAccountRestrictions:disabled"/> + <int value="1290343279" label="SafetyCheckNotificationPermissions:disabled"/> <int value="1290904214" label="DiagnosticsAppNavigation:enabled"/> <int value="1291257442" label="TabsInCBD:disabled"/> <int value="1291761696" label="CCTModuleDexLoading:disabled"/> @@ -71603,6 +71609,7 @@ <int value="151" label="ARC Low Disk Space Pre-stop"/> <int value="152" label="ARC Low Disk Space Post-stop"/> <int value="153" label="Multi capture started"/> + <int value="154" label="PrivacyHubCamera"/> </enum> <enum name="NotificationDatabaseStatus">
diff --git a/tools/metrics/histograms/metadata/browser/histograms.xml b/tools/metrics/histograms/metadata/browser/histograms.xml index f337287..08f7131 100644 --- a/tools/metrics/histograms/metadata/browser/histograms.xml +++ b/tools/metrics/histograms/metadata/browser/histograms.xml
@@ -104,6 +104,7 @@ <variant name=".CameraApp"/> <variant name=".Ent"/> <variant name=".General"/> + <variant name=".GeneralCamera"/> <variant name=".MediaAppPdf"/> <variant name=".OnboardingExperience"/> <variant name=".Performance"/>
diff --git a/tools/metrics/histograms/metadata/net/histograms.xml b/tools/metrics/histograms/metadata/net/histograms.xml index 951469f..5a84e53 100644 --- a/tools/metrics/histograms/metadata/net/histograms.xml +++ b/tools/metrics/histograms/metadata/net/histograms.xml
@@ -4949,6 +4949,26 @@ </summary> </histogram> +<histogram name="Net.TCPClientSocketReadSize" units="bytes" + expires_after="2023-05-11"> + <owner>stefanoduo@google.com</owner> + <owner>src/net/OWNERS</owner> + <summary> + The amount of bytes written in the IOBuffer passed to + TCPClientSocket::Read{IfReady}. + </summary> +</histogram> + +<histogram name="Net.TCPClientSocketWriteSize" units="bytes" + expires_after="2023-05-11"> + <owner>stefanoduo@google.com</owner> + <owner>src/net/OWNERS</owner> + <summary> + The amount of bytes contained in the IOBuffer passed to + TCPClientSocket::Write. + </summary> +</histogram> + <histogram name="Net.TcpConnectAttempt.Latency.Error" units="ms" expires_after="2023-01-15"> <owner>bashi@chromium.org</owner> @@ -5086,6 +5106,25 @@ </summary> </histogram> +<histogram name="Net.UDPClientSocketReadSize" units="bytes" + expires_after="2023-05-11"> + <owner>stefanoduo@google.com</owner> + <owner>src/net/OWNERS</owner> + <summary> + The amount of bytes written in the IOBuffer passed to UDPClientSocket::Read. + </summary> +</histogram> + +<histogram name="Net.UDPClientSocketWriteSize" units="bytes" + expires_after="2023-05-11"> + <owner>stefanoduo@google.com</owner> + <owner>src/net/OWNERS</owner> + <summary> + The amount of bytes contained in the IOBuffer passed to + UDPClientSocket::Write. + </summary> +</histogram> + <histogram name="Net.UdpSocketRandomBindErrorCode" enum="NetErrorCodes" expires_after="M77"> <owner>mgersh@chromium.org</owner>
diff --git a/tools/metrics/histograms/metadata/sync/histograms.xml b/tools/metrics/histograms/metadata/sync/histograms.xml index 18835eb..be62570 100644 --- a/tools/metrics/histograms/metadata/sync/histograms.xml +++ b/tools/metrics/histograms/metadata/sync/histograms.xml
@@ -103,7 +103,7 @@ </histogram> <histogram name="Sync.BookmarkEntityReuploadNeeded.On{UpdateType}" - enum="Boolean" expires_after="2022-10-30"> + enum="Boolean" expires_after="2023-10-30"> <owner>rushans@google.com</owner> <owner>mastiz@chromium.org</owner> <component>Services>Sync</component>
diff --git a/tools/perf/core/perfetto_binary_roller/binary_deps.json b/tools/perf/core/perfetto_binary_roller/binary_deps.json index 8fd020fe..948798f4 100644 --- a/tools/perf/core/perfetto_binary_roller/binary_deps.json +++ b/tools/perf/core/perfetto_binary_roller/binary_deps.json
@@ -13,16 +13,16 @@ "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/linux_arm/49b4b5dcbc312d8d2c3751cf29238b8efeb4e494/trace_processor_shell" }, "mac": { - "hash": "ef8f48de5e54c1aae1298115d04e68c8abfadf4c", - "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/mac/3a9f96aecc5ffe0b5a9d6d540653468f0b215842/trace_processor_shell" + "hash": "e70c16ef443d6ccc40ca62dda01fd34b97bb4d4b", + "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/mac/b2829a1f2f115581d5ab091770e7c1878c243b82/trace_processor_shell" }, "mac_arm64": { "hash": "e1ad4861384b06d911a65f035317914b8cc975c6", "full_remote_path": "perfetto-luci-artifacts/v25.0/mac-arm64/trace_processor_shell" }, "linux": { - "hash": "03f2a7d05c23c72113d5e02088863f980a573f1c", - "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/linux/40b17af5c58d2777097eef8fb8a7d61c8419af7b/trace_processor_shell" + "hash": "f61258a631ee16e80c85db40ecc8292b86a2d48c", + "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/linux/b2829a1f2f115581d5ab091770e7c1878c243b82/trace_processor_shell" } }, "power_profile.sql": {
diff --git a/ui/ozone/platform/wayland/common/wayland_object.h b/ui/ozone/platform/wayland/common/wayland_object.h index dd82b214..de2b33a 100644 --- a/ui/ozone/platform/wayland/common/wayland_object.h +++ b/ui/ozone/platform/wayland/common/wayland_object.h
@@ -10,6 +10,12 @@ #include "base/check.h" #include "ui/ozone/platform/wayland/common/wayland.h" +#define CHROME_WAYLAND_CHECK_VERSION(x, y, z) \ + (WAYLAND_VERSION_MAJOR > x || \ + (WAYLAND_VERSION_MAJOR == x && WAYLAND_VERSION_MINOR > y) || \ + (WAYLAND_VERSION_MAJOR == x && WAYLAND_VERSION_MINOR == y && \ + WAYLAND_VERSION_MICRO >= z)) + struct wl_proxy; namespace ui {
diff --git a/ui/ozone/platform/wayland/host/wayland_output.cc b/ui/ozone/platform/wayland/host/wayland_output.cc index e6d5c580..d679365 100644 --- a/ui/ozone/platform/wayland/host/wayland_output.cc +++ b/ui/ozone/platform/wayland/host/wayland_output.cc
@@ -23,9 +23,9 @@ namespace ui { namespace { -// TODO(crbug.com/1279681): support newer versions. constexpr uint32_t kMinVersion = 2; -} +constexpr uint32_t kMaxVersion = 4; +} // namespace // static constexpr char WaylandOutput::kInterfaceName[]; @@ -38,11 +38,12 @@ uint32_t version) { DCHECK_EQ(interface, kInterfaceName); - if (!wl::CanBind(interface, version, kMinVersion, kMinVersion)) { + if (!wl::CanBind(interface, version, kMinVersion, kMaxVersion)) { return; } - auto output = wl::Bind<wl_output>(registry, name, kMinVersion); + auto output = + wl::Bind<wl_output>(registry, name, std::min(version, kMaxVersion)); if (!output) { LOG(ERROR) << "Failed to bind to wl_output global"; return; @@ -90,10 +91,15 @@ DCHECK(!delegate_); delegate_ = delegate; static constexpr wl_output_listener output_listener = { - &OutputHandleGeometry, - &OutputHandleMode, - &OutputHandleDone, - &OutputHandleScale, + &OutputHandleGeometry, + &OutputHandleMode, + &OutputHandleDone, + &OutputHandleScale, +#if CHROME_WAYLAND_CHECK_VERSION(1, 20, 0) + // since protocol version 4 and Wayland version 1.20 + &OutputHandleName, + &OutputHandleDescription, +#endif }; wl_output_add_listener(output_.get(), &output_listener, this); } @@ -213,4 +219,20 @@ wayland_output->scale_factor_ = factor; } +#if CHROME_WAYLAND_CHECK_VERSION(1, 20, 0) +// static +void WaylandOutput::OutputHandleName(void* data, + struct wl_output* wl_output, + const char* name) { + NOTIMPLEMENTED_LOG_ONCE(); +} + +// static +void WaylandOutput::OutputHandleDescription(void* data, + struct wl_output* wl_output, + const char* description) { + NOTIMPLEMENTED_LOG_ONCE(); +} +#endif + } // namespace ui
diff --git a/ui/ozone/platform/wayland/host/wayland_output.h b/ui/ozone/platform/wayland/host/wayland_output.h index 6f72318..c2b8abb 100644 --- a/ui/ozone/platform/wayland/host/wayland_output.h +++ b/ui/ozone/platform/wayland/host/wayland_output.h
@@ -122,6 +122,14 @@ static void OutputHandleScale(void* data, struct wl_output* wl_output, int32_t factor); +#if CHROME_WAYLAND_CHECK_VERSION(1, 20, 0) + static void OutputHandleName(void* data, + struct wl_output* wl_output, + const char* name); + static void OutputHandleDescription(void* data, + struct wl_output* wl_output, + const char* description); +#endif const Id output_id_ = 0; wl::Object<wl_output> output_;
diff --git a/ui/views/window/non_client_view.cc b/ui/views/window/non_client_view.cc index 38c6a8f..ac55b96 100644 --- a/ui/views/window/non_client_view.cc +++ b/ui/views/window/non_client_view.cc
@@ -242,10 +242,6 @@ frame_view_->SizeConstraintsChanged(); } -void NonClientView::SetAccessibleName(const std::u16string& name) { - accessible_name_ = name; -} - gfx::Size NonClientView::CalculatePreferredSize() const { // TODO(pkasting): This should probably be made to look similar to // GetMinimumSize() below. This will require implementing GetPreferredSize() @@ -278,8 +274,8 @@ } void NonClientView::GetAccessibleNodeData(ui::AXNodeData* node_data) { + // TODO(crbug.com/1366294): Should this be pruned from the accessibility tree? node_data->role = ax::mojom::Role::kClient; - node_data->SetName(accessible_name_); } View* NonClientView::GetTooltipHandlerForPoint(const gfx::Point& point) {
diff --git a/ui/views/window/non_client_view.h b/ui/views/window/non_client_view.h index 42c3cff1..e7bded9 100644 --- a/ui/views/window/non_client_view.h +++ b/ui/views/window/non_client_view.h
@@ -209,9 +209,6 @@ // Get/Set client_view property. ClientView* client_view() const { return client_view_; } - // Set the accessible name of this view. - void SetAccessibleName(const std::u16string& name); - // NonClientView, View overrides: gfx::Size CalculatePreferredSize() const override; gfx::Size GetMinimumSize() const override; @@ -242,9 +239,6 @@ // The overlay view, when non-NULL and visible, takes up the entire widget and // is placed on top of the ClientView and NonClientFrameView. raw_ptr<View> overlay_view_ = nullptr; - - // The accessible name of this view. - std::u16string accessible_name_; }; BEGIN_VIEW_BUILDER(VIEWS_EXPORT, NonClientFrameView, View)